[x86] Initial improvements to the new shuffle lowering for v16i8
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
523     setOperationAction(ISD::FP32_TO_FP16, MVT::i16, Expand);
524   }
525
526   if (Subtarget->hasPOPCNT()) {
527     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
528   } else {
529     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
530     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
531     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
532     if (Subtarget->is64Bit())
533       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
534   }
535
536   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
537
538   if (!Subtarget->hasMOVBE())
539     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
540
541   // These should be promoted to a larger select which is supported.
542   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
543   // X86 wants to expand cmov itself.
544   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
545   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
546   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
547   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
548   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
549   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
550   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
551   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
552   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
555   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
556   if (Subtarget->is64Bit()) {
557     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
558     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
559   }
560   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
561   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
562   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
563   // support continuation, user-level threading, and etc.. As a result, no
564   // other SjLj exception interfaces are implemented and please don't build
565   // your own exception handling based on them.
566   // LLVM/Clang supports zero-cost DWARF exception handling.
567   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
568   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
569
570   // Darwin ABI issue.
571   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
572   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
573   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
574   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
575   if (Subtarget->is64Bit())
576     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
577   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
578   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
579   if (Subtarget->is64Bit()) {
580     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
581     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
582     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
583     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
584     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
585   }
586   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
587   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
588   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
589   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
592     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
593     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
594   }
595
596   if (Subtarget->hasSSE1())
597     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
598
599   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
600
601   // Expand certain atomics
602   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
603     MVT VT = IntVTs[i];
604     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
605     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
606     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
607   }
608
609   if (Subtarget->hasCmpxchg16b()) {
610     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
611   }
612
613   // FIXME - use subtarget debug flags
614   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
615       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
616     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
617   }
618
619   if (Subtarget->is64Bit()) {
620     setExceptionPointerRegister(X86::RAX);
621     setExceptionSelectorRegister(X86::RDX);
622   } else {
623     setExceptionPointerRegister(X86::EAX);
624     setExceptionSelectorRegister(X86::EDX);
625   }
626   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
627   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
628
629   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
630   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
631
632   setOperationAction(ISD::TRAP, MVT::Other, Legal);
633   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
634
635   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
636   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
637   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
638   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
639     // TargetInfo::X86_64ABIBuiltinVaList
640     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
641     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
642   } else {
643     // TargetInfo::CharPtrBuiltinVaList
644     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
645     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
646   }
647
648   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
649   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
650
651   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
652                      MVT::i64 : MVT::i32, Custom);
653
654   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
655     // f32 and f64 use SSE.
656     // Set up the FP register classes.
657     addRegisterClass(MVT::f32, &X86::FR32RegClass);
658     addRegisterClass(MVT::f64, &X86::FR64RegClass);
659
660     // Use ANDPD to simulate FABS.
661     setOperationAction(ISD::FABS , MVT::f64, Custom);
662     setOperationAction(ISD::FABS , MVT::f32, Custom);
663
664     // Use XORP to simulate FNEG.
665     setOperationAction(ISD::FNEG , MVT::f64, Custom);
666     setOperationAction(ISD::FNEG , MVT::f32, Custom);
667
668     // Use ANDPD and ORPD to simulate FCOPYSIGN.
669     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
670     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
671
672     // Lower this to FGETSIGNx86 plus an AND.
673     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
674     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
675
676     // We don't support sin/cos/fmod
677     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
678     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
679     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
680     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
681     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
682     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
683
684     // Expand FP immediates into loads from the stack, except for the special
685     // cases we handle.
686     addLegalFPImmediate(APFloat(+0.0)); // xorpd
687     addLegalFPImmediate(APFloat(+0.0f)); // xorps
688   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
689     // Use SSE for f32, x87 for f64.
690     // Set up the FP register classes.
691     addRegisterClass(MVT::f32, &X86::FR32RegClass);
692     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
693
694     // Use ANDPS to simulate FABS.
695     setOperationAction(ISD::FABS , MVT::f32, Custom);
696
697     // Use XORP to simulate FNEG.
698     setOperationAction(ISD::FNEG , MVT::f32, Custom);
699
700     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
701
702     // Use ANDPS and ORPS to simulate FCOPYSIGN.
703     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
704     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
705
706     // We don't support sin/cos/fmod
707     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
708     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
709     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
710
711     // Special cases we handle for FP constants.
712     addLegalFPImmediate(APFloat(+0.0f)); // xorps
713     addLegalFPImmediate(APFloat(+0.0)); // FLD0
714     addLegalFPImmediate(APFloat(+1.0)); // FLD1
715     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
716     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
717
718     if (!TM.Options.UnsafeFPMath) {
719       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
720       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
721       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
722     }
723   } else if (!TM.Options.UseSoftFloat) {
724     // f32 and f64 in x87.
725     // Set up the FP register classes.
726     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
727     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
728
729     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
730     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
731     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
732     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
733
734     if (!TM.Options.UnsafeFPMath) {
735       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
736       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
737       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
738       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
739       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
740       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
741     }
742     addLegalFPImmediate(APFloat(+0.0)); // FLD0
743     addLegalFPImmediate(APFloat(+1.0)); // FLD1
744     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
745     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
746     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
747     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
748     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
749     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
750   }
751
752   // We don't support FMA.
753   setOperationAction(ISD::FMA, MVT::f64, Expand);
754   setOperationAction(ISD::FMA, MVT::f32, Expand);
755
756   // Long double always uses X87.
757   if (!TM.Options.UseSoftFloat) {
758     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
759     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
760     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
761     {
762       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
763       addLegalFPImmediate(TmpFlt);  // FLD0
764       TmpFlt.changeSign();
765       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
766
767       bool ignored;
768       APFloat TmpFlt2(+1.0);
769       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
770                       &ignored);
771       addLegalFPImmediate(TmpFlt2);  // FLD1
772       TmpFlt2.changeSign();
773       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
774     }
775
776     if (!TM.Options.UnsafeFPMath) {
777       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
778       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
779       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
780     }
781
782     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
783     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
784     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
785     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
786     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
787     setOperationAction(ISD::FMA, MVT::f80, Expand);
788   }
789
790   // Always use a library call for pow.
791   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
792   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
793   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
794
795   setOperationAction(ISD::FLOG, MVT::f80, Expand);
796   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
797   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
798   setOperationAction(ISD::FEXP, MVT::f80, Expand);
799   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
800
801   // First set operation action for all vector types to either promote
802   // (for widening) or expand (for scalarization). Then we will selectively
803   // turn on ones that can be effectively codegen'd.
804   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
805            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
806     MVT VT = (MVT::SimpleValueType)i;
807     setOperationAction(ISD::ADD , VT, Expand);
808     setOperationAction(ISD::SUB , VT, Expand);
809     setOperationAction(ISD::FADD, VT, Expand);
810     setOperationAction(ISD::FNEG, VT, Expand);
811     setOperationAction(ISD::FSUB, VT, Expand);
812     setOperationAction(ISD::MUL , VT, Expand);
813     setOperationAction(ISD::FMUL, VT, Expand);
814     setOperationAction(ISD::SDIV, VT, Expand);
815     setOperationAction(ISD::UDIV, VT, Expand);
816     setOperationAction(ISD::FDIV, VT, Expand);
817     setOperationAction(ISD::SREM, VT, Expand);
818     setOperationAction(ISD::UREM, VT, Expand);
819     setOperationAction(ISD::LOAD, VT, Expand);
820     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
822     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
823     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
824     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::FABS, VT, Expand);
826     setOperationAction(ISD::FSIN, VT, Expand);
827     setOperationAction(ISD::FSINCOS, VT, Expand);
828     setOperationAction(ISD::FCOS, VT, Expand);
829     setOperationAction(ISD::FSINCOS, VT, Expand);
830     setOperationAction(ISD::FREM, VT, Expand);
831     setOperationAction(ISD::FMA,  VT, Expand);
832     setOperationAction(ISD::FPOWI, VT, Expand);
833     setOperationAction(ISD::FSQRT, VT, Expand);
834     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
835     setOperationAction(ISD::FFLOOR, VT, Expand);
836     setOperationAction(ISD::FCEIL, VT, Expand);
837     setOperationAction(ISD::FTRUNC, VT, Expand);
838     setOperationAction(ISD::FRINT, VT, Expand);
839     setOperationAction(ISD::FNEARBYINT, VT, Expand);
840     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841     setOperationAction(ISD::MULHS, VT, Expand);
842     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
843     setOperationAction(ISD::MULHU, VT, Expand);
844     setOperationAction(ISD::SDIVREM, VT, Expand);
845     setOperationAction(ISD::UDIVREM, VT, Expand);
846     setOperationAction(ISD::FPOW, VT, Expand);
847     setOperationAction(ISD::CTPOP, VT, Expand);
848     setOperationAction(ISD::CTTZ, VT, Expand);
849     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
850     setOperationAction(ISD::CTLZ, VT, Expand);
851     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
852     setOperationAction(ISD::SHL, VT, Expand);
853     setOperationAction(ISD::SRA, VT, Expand);
854     setOperationAction(ISD::SRL, VT, Expand);
855     setOperationAction(ISD::ROTL, VT, Expand);
856     setOperationAction(ISD::ROTR, VT, Expand);
857     setOperationAction(ISD::BSWAP, VT, Expand);
858     setOperationAction(ISD::SETCC, VT, Expand);
859     setOperationAction(ISD::FLOG, VT, Expand);
860     setOperationAction(ISD::FLOG2, VT, Expand);
861     setOperationAction(ISD::FLOG10, VT, Expand);
862     setOperationAction(ISD::FEXP, VT, Expand);
863     setOperationAction(ISD::FEXP2, VT, Expand);
864     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
865     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
866     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
867     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
869     setOperationAction(ISD::TRUNCATE, VT, Expand);
870     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
871     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
872     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
873     setOperationAction(ISD::VSELECT, VT, Expand);
874     setOperationAction(ISD::SELECT_CC, VT, Expand);
875     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
876              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
877       setTruncStoreAction(VT,
878                           (MVT::SimpleValueType)InnerVT, Expand);
879     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
880     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
881     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
882   }
883
884   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
885   // with -msoft-float, disable use of MMX as well.
886   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
887     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
888     // No operations on x86mmx supported, everything uses intrinsics.
889   }
890
891   // MMX-sized vectors (other than x86mmx) are expected to be expanded
892   // into smaller operations.
893   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
894   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
895   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
896   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
897   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
898   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
899   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
900   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
901   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
902   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
903   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
904   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
905   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
906   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
907   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
908   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
909   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
910   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
911   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
912   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
913   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
914   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
915   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
916   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
917   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
918   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
919   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
920   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
921   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
922
923   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
924     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
925
926     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
927     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
928     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
929     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
930     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
931     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
932     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
933     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
934     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
935     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
936     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
937     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
938   }
939
940   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
941     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
942
943     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
944     // registers cannot be used even for integer operations.
945     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
946     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
947     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
948     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
949
950     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
951     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
952     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
953     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
954     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
955     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
956     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
957     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
958     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
959     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
960     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
961     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
962     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
963     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
964     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
965     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
966     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
967     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
968     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
969     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
970     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
971     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
972
973     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
974     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
975     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
976     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
977
978     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
979     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
980     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
983
984     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
985     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
986       MVT VT = (MVT::SimpleValueType)i;
987       // Do not attempt to custom lower non-power-of-2 vectors
988       if (!isPowerOf2_32(VT.getVectorNumElements()))
989         continue;
990       // Do not attempt to custom lower non-128-bit vectors
991       if (!VT.is128BitVector())
992         continue;
993       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
994       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
995       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
996     }
997
998     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
999     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1000     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1001     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1002     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1004
1005     if (Subtarget->is64Bit()) {
1006       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1007       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1008     }
1009
1010     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1011     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1012       MVT VT = (MVT::SimpleValueType)i;
1013
1014       // Do not attempt to promote non-128-bit vectors
1015       if (!VT.is128BitVector())
1016         continue;
1017
1018       setOperationAction(ISD::AND,    VT, Promote);
1019       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1020       setOperationAction(ISD::OR,     VT, Promote);
1021       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1022       setOperationAction(ISD::XOR,    VT, Promote);
1023       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1024       setOperationAction(ISD::LOAD,   VT, Promote);
1025       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1026       setOperationAction(ISD::SELECT, VT, Promote);
1027       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1028     }
1029
1030     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1031
1032     // Custom lower v2i64 and v2f64 selects.
1033     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1034     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1035     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1036     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1037
1038     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1039     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1040
1041     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1042     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1043     // As there is no 64-bit GPR available, we need build a special custom
1044     // sequence to convert from v2i32 to v2f32.
1045     if (!Subtarget->is64Bit())
1046       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1047
1048     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1049     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1050
1051     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1052
1053     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1054     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1055     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1056   }
1057
1058   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1059     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1062     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1064     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1065     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1066     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1067     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1068     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1069
1070     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1071     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1072     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1073     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1074     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1075     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1076     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1077     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1078     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1079     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1080
1081     // FIXME: Do we need to handle scalar-to-vector here?
1082     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1083
1084     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1085     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1086     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1087     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1088     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1089     // There is no BLENDI for byte vectors. We don't need to custom lower
1090     // some vselects for now.
1091     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1092
1093     // i8 and i16 vectors are custom , because the source register and source
1094     // source memory operand types are not the same width.  f32 vectors are
1095     // custom since the immediate controlling the insert encodes additional
1096     // information.
1097     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1098     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1099     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1100     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1101
1102     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1103     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1104     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1105     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1106
1107     // FIXME: these should be Legal but thats only for the case where
1108     // the index is constant.  For now custom expand to deal with that.
1109     if (Subtarget->is64Bit()) {
1110       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1111       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1112     }
1113   }
1114
1115   if (Subtarget->hasSSE2()) {
1116     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1117     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1118
1119     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1120     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1121
1122     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1123     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1124
1125     // In the customized shift lowering, the legal cases in AVX2 will be
1126     // recognized.
1127     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1128     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1129
1130     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1131     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1132
1133     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1134   }
1135
1136   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1137     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1138     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1139     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1140     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1141     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1142     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1143
1144     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1145     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1147
1148     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1149     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1150     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1151     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1152     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1153     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1154     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1155     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1156     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1157     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1158     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1159     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1160
1161     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1162     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1163     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1164     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1165     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1166     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1167     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1168     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1169     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1170     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1171     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1172     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1173
1174     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1175     // even though v8i16 is a legal type.
1176     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1177     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1178     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1179
1180     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1181     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1182     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1183
1184     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1185     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1186
1187     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1188
1189     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1190     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1191
1192     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1193     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1194
1195     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1196     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1197
1198     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1199     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1200     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1201     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1202
1203     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1204     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1205     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1206
1207     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1208     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1209     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1210     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1211
1212     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1213     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1214     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1215     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1216     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1217     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1218     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1219     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1220     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1221     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1222     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1223     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1224
1225     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1226       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1227       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1228       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1229       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1230       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1231       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1232     }
1233
1234     if (Subtarget->hasInt256()) {
1235       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1236       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1237       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1238       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1239
1240       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1241       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1242       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1243       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1244
1245       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1246       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1247       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1248       // Don't lower v32i8 because there is no 128-bit byte mul
1249
1250       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1251       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1252       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1253       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1254
1255       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1256       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1257     } else {
1258       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1259       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1260       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1261       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1262
1263       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1264       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1265       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1266       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1267
1268       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1269       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1270       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1271       // Don't lower v32i8 because there is no 128-bit byte mul
1272     }
1273
1274     // In the customized shift lowering, the legal cases in AVX2 will be
1275     // recognized.
1276     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1277     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1278
1279     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1280     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1281
1282     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1283
1284     // Custom lower several nodes for 256-bit types.
1285     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1286              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1287       MVT VT = (MVT::SimpleValueType)i;
1288
1289       // Extract subvector is special because the value type
1290       // (result) is 128-bit but the source is 256-bit wide.
1291       if (VT.is128BitVector())
1292         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1293
1294       // Do not attempt to custom lower other non-256-bit vectors
1295       if (!VT.is256BitVector())
1296         continue;
1297
1298       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1299       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1300       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1301       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1302       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1303       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1304       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1305     }
1306
1307     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1308     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1309       MVT VT = (MVT::SimpleValueType)i;
1310
1311       // Do not attempt to promote non-256-bit vectors
1312       if (!VT.is256BitVector())
1313         continue;
1314
1315       setOperationAction(ISD::AND,    VT, Promote);
1316       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1317       setOperationAction(ISD::OR,     VT, Promote);
1318       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1319       setOperationAction(ISD::XOR,    VT, Promote);
1320       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1321       setOperationAction(ISD::LOAD,   VT, Promote);
1322       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1323       setOperationAction(ISD::SELECT, VT, Promote);
1324       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1325     }
1326   }
1327
1328   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1329     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1330     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1331     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1332     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1333
1334     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1335     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1336     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1337
1338     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1339     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1340     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1341     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1342     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1343     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1344     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1349
1350     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1356
1357     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1358     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1362     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1363     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1364     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1365
1366     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1367     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1368     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1370     if (Subtarget->is64Bit()) {
1371       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1372       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1373       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1374       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1375     }
1376     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1377     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1379     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1380     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1383     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1384     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1385     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1386
1387     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1388     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1389     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1390     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1391     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1392     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1393     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1394     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1395     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1396     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1397     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1398     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1399     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1400
1401     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1402     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1403     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1404     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1405     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1406     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1407
1408     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1409     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1410
1411     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1412
1413     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1414     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1415     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1416     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1417     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1418     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1419     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1420     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1421     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1422
1423     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1424     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1425
1426     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1427     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1428
1429     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1430
1431     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1432     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1433
1434     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1435     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1436
1437     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1438     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1439
1440     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1441     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1442     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1443     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1444     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1445     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1446
1447     if (Subtarget->hasCDI()) {
1448       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1449       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1450     }
1451
1452     // Custom lower several nodes.
1453     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1454              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1455       MVT VT = (MVT::SimpleValueType)i;
1456
1457       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1458       // Extract subvector is special because the value type
1459       // (result) is 256/128-bit but the source is 512-bit wide.
1460       if (VT.is128BitVector() || VT.is256BitVector())
1461         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1462
1463       if (VT.getVectorElementType() == MVT::i1)
1464         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1465
1466       // Do not attempt to custom lower other non-512-bit vectors
1467       if (!VT.is512BitVector())
1468         continue;
1469
1470       if ( EltSize >= 32) {
1471         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1472         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1473         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1474         setOperationAction(ISD::VSELECT,             VT, Legal);
1475         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1476         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1477         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1478       }
1479     }
1480     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1481       MVT VT = (MVT::SimpleValueType)i;
1482
1483       // Do not attempt to promote non-256-bit vectors
1484       if (!VT.is512BitVector())
1485         continue;
1486
1487       setOperationAction(ISD::SELECT, VT, Promote);
1488       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1489     }
1490   }// has  AVX-512
1491
1492   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1493   // of this type with custom code.
1494   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1495            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1496     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1497                        Custom);
1498   }
1499
1500   // We want to custom lower some of our intrinsics.
1501   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1502   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1503   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1504   if (!Subtarget->is64Bit())
1505     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1506
1507   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1508   // handle type legalization for these operations here.
1509   //
1510   // FIXME: We really should do custom legalization for addition and
1511   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1512   // than generic legalization for 64-bit multiplication-with-overflow, though.
1513   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1514     // Add/Sub/Mul with overflow operations are custom lowered.
1515     MVT VT = IntVTs[i];
1516     setOperationAction(ISD::SADDO, VT, Custom);
1517     setOperationAction(ISD::UADDO, VT, Custom);
1518     setOperationAction(ISD::SSUBO, VT, Custom);
1519     setOperationAction(ISD::USUBO, VT, Custom);
1520     setOperationAction(ISD::SMULO, VT, Custom);
1521     setOperationAction(ISD::UMULO, VT, Custom);
1522   }
1523
1524   // There are no 8-bit 3-address imul/mul instructions
1525   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1526   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1527
1528   if (!Subtarget->is64Bit()) {
1529     // These libcalls are not available in 32-bit.
1530     setLibcallName(RTLIB::SHL_I128, nullptr);
1531     setLibcallName(RTLIB::SRL_I128, nullptr);
1532     setLibcallName(RTLIB::SRA_I128, nullptr);
1533   }
1534
1535   // Combine sin / cos into one node or libcall if possible.
1536   if (Subtarget->hasSinCos()) {
1537     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1538     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1539     if (Subtarget->isTargetDarwin()) {
1540       // For MacOSX, we don't want to the normal expansion of a libcall to
1541       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1542       // traffic.
1543       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1544       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1545     }
1546   }
1547
1548   if (Subtarget->isTargetWin64()) {
1549     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1550     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1551     setOperationAction(ISD::SREM, MVT::i128, Custom);
1552     setOperationAction(ISD::UREM, MVT::i128, Custom);
1553     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1554     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1555   }
1556
1557   // We have target-specific dag combine patterns for the following nodes:
1558   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1559   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1560   setTargetDAGCombine(ISD::VSELECT);
1561   setTargetDAGCombine(ISD::SELECT);
1562   setTargetDAGCombine(ISD::SHL);
1563   setTargetDAGCombine(ISD::SRA);
1564   setTargetDAGCombine(ISD::SRL);
1565   setTargetDAGCombine(ISD::OR);
1566   setTargetDAGCombine(ISD::AND);
1567   setTargetDAGCombine(ISD::ADD);
1568   setTargetDAGCombine(ISD::FADD);
1569   setTargetDAGCombine(ISD::FSUB);
1570   setTargetDAGCombine(ISD::FMA);
1571   setTargetDAGCombine(ISD::SUB);
1572   setTargetDAGCombine(ISD::LOAD);
1573   setTargetDAGCombine(ISD::STORE);
1574   setTargetDAGCombine(ISD::ZERO_EXTEND);
1575   setTargetDAGCombine(ISD::ANY_EXTEND);
1576   setTargetDAGCombine(ISD::SIGN_EXTEND);
1577   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1578   setTargetDAGCombine(ISD::TRUNCATE);
1579   setTargetDAGCombine(ISD::SINT_TO_FP);
1580   setTargetDAGCombine(ISD::SETCC);
1581   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1582   setTargetDAGCombine(ISD::BUILD_VECTOR);
1583   if (Subtarget->is64Bit())
1584     setTargetDAGCombine(ISD::MUL);
1585   setTargetDAGCombine(ISD::XOR);
1586
1587   computeRegisterProperties();
1588
1589   // On Darwin, -Os means optimize for size without hurting performance,
1590   // do not reduce the limit.
1591   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1592   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1593   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1594   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1595   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1596   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1597   setPrefLoopAlignment(4); // 2^4 bytes.
1598
1599   // Predictable cmov don't hurt on atom because it's in-order.
1600   PredictableSelectIsExpensive = !Subtarget->isAtom();
1601
1602   setPrefFunctionAlignment(4); // 2^4 bytes.
1603 }
1604
1605 TargetLoweringBase::LegalizeTypeAction
1606 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1607   if (ExperimentalVectorWideningLegalization &&
1608       VT.getVectorNumElements() != 1 &&
1609       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1610     return TypeWidenVector;
1611
1612   return TargetLoweringBase::getPreferredVectorAction(VT);
1613 }
1614
1615 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1616   if (!VT.isVector())
1617     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1618
1619   if (Subtarget->hasAVX512())
1620     switch(VT.getVectorNumElements()) {
1621     case  8: return MVT::v8i1;
1622     case 16: return MVT::v16i1;
1623   }
1624
1625   return VT.changeVectorElementTypeToInteger();
1626 }
1627
1628 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1629 /// the desired ByVal argument alignment.
1630 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1631   if (MaxAlign == 16)
1632     return;
1633   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1634     if (VTy->getBitWidth() == 128)
1635       MaxAlign = 16;
1636   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1637     unsigned EltAlign = 0;
1638     getMaxByValAlign(ATy->getElementType(), EltAlign);
1639     if (EltAlign > MaxAlign)
1640       MaxAlign = EltAlign;
1641   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1642     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1643       unsigned EltAlign = 0;
1644       getMaxByValAlign(STy->getElementType(i), EltAlign);
1645       if (EltAlign > MaxAlign)
1646         MaxAlign = EltAlign;
1647       if (MaxAlign == 16)
1648         break;
1649     }
1650   }
1651 }
1652
1653 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1654 /// function arguments in the caller parameter area. For X86, aggregates
1655 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1656 /// are at 4-byte boundaries.
1657 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1658   if (Subtarget->is64Bit()) {
1659     // Max of 8 and alignment of type.
1660     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1661     if (TyAlign > 8)
1662       return TyAlign;
1663     return 8;
1664   }
1665
1666   unsigned Align = 4;
1667   if (Subtarget->hasSSE1())
1668     getMaxByValAlign(Ty, Align);
1669   return Align;
1670 }
1671
1672 /// getOptimalMemOpType - Returns the target specific optimal type for load
1673 /// and store operations as a result of memset, memcpy, and memmove
1674 /// lowering. If DstAlign is zero that means it's safe to destination
1675 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1676 /// means there isn't a need to check it against alignment requirement,
1677 /// probably because the source does not need to be loaded. If 'IsMemset' is
1678 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1679 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1680 /// source is constant so it does not need to be loaded.
1681 /// It returns EVT::Other if the type should be determined using generic
1682 /// target-independent logic.
1683 EVT
1684 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1685                                        unsigned DstAlign, unsigned SrcAlign,
1686                                        bool IsMemset, bool ZeroMemset,
1687                                        bool MemcpyStrSrc,
1688                                        MachineFunction &MF) const {
1689   const Function *F = MF.getFunction();
1690   if ((!IsMemset || ZeroMemset) &&
1691       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1692                                        Attribute::NoImplicitFloat)) {
1693     if (Size >= 16 &&
1694         (Subtarget->isUnalignedMemAccessFast() ||
1695          ((DstAlign == 0 || DstAlign >= 16) &&
1696           (SrcAlign == 0 || SrcAlign >= 16)))) {
1697       if (Size >= 32) {
1698         if (Subtarget->hasInt256())
1699           return MVT::v8i32;
1700         if (Subtarget->hasFp256())
1701           return MVT::v8f32;
1702       }
1703       if (Subtarget->hasSSE2())
1704         return MVT::v4i32;
1705       if (Subtarget->hasSSE1())
1706         return MVT::v4f32;
1707     } else if (!MemcpyStrSrc && Size >= 8 &&
1708                !Subtarget->is64Bit() &&
1709                Subtarget->hasSSE2()) {
1710       // Do not use f64 to lower memcpy if source is string constant. It's
1711       // better to use i32 to avoid the loads.
1712       return MVT::f64;
1713     }
1714   }
1715   if (Subtarget->is64Bit() && Size >= 8)
1716     return MVT::i64;
1717   return MVT::i32;
1718 }
1719
1720 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1721   if (VT == MVT::f32)
1722     return X86ScalarSSEf32;
1723   else if (VT == MVT::f64)
1724     return X86ScalarSSEf64;
1725   return true;
1726 }
1727
1728 bool
1729 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1730                                                  unsigned,
1731                                                  bool *Fast) const {
1732   if (Fast)
1733     *Fast = Subtarget->isUnalignedMemAccessFast();
1734   return true;
1735 }
1736
1737 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1738 /// current function.  The returned value is a member of the
1739 /// MachineJumpTableInfo::JTEntryKind enum.
1740 unsigned X86TargetLowering::getJumpTableEncoding() const {
1741   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1742   // symbol.
1743   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1744       Subtarget->isPICStyleGOT())
1745     return MachineJumpTableInfo::EK_Custom32;
1746
1747   // Otherwise, use the normal jump table encoding heuristics.
1748   return TargetLowering::getJumpTableEncoding();
1749 }
1750
1751 const MCExpr *
1752 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1753                                              const MachineBasicBlock *MBB,
1754                                              unsigned uid,MCContext &Ctx) const{
1755   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1756          Subtarget->isPICStyleGOT());
1757   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1758   // entries.
1759   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1760                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1761 }
1762
1763 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1764 /// jumptable.
1765 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1766                                                     SelectionDAG &DAG) const {
1767   if (!Subtarget->is64Bit())
1768     // This doesn't have SDLoc associated with it, but is not really the
1769     // same as a Register.
1770     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1771   return Table;
1772 }
1773
1774 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1775 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1776 /// MCExpr.
1777 const MCExpr *X86TargetLowering::
1778 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1779                              MCContext &Ctx) const {
1780   // X86-64 uses RIP relative addressing based on the jump table label.
1781   if (Subtarget->isPICStyleRIPRel())
1782     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1783
1784   // Otherwise, the reference is relative to the PIC base.
1785   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1786 }
1787
1788 // FIXME: Why this routine is here? Move to RegInfo!
1789 std::pair<const TargetRegisterClass*, uint8_t>
1790 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1791   const TargetRegisterClass *RRC = nullptr;
1792   uint8_t Cost = 1;
1793   switch (VT.SimpleTy) {
1794   default:
1795     return TargetLowering::findRepresentativeClass(VT);
1796   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1797     RRC = Subtarget->is64Bit() ?
1798       (const TargetRegisterClass*)&X86::GR64RegClass :
1799       (const TargetRegisterClass*)&X86::GR32RegClass;
1800     break;
1801   case MVT::x86mmx:
1802     RRC = &X86::VR64RegClass;
1803     break;
1804   case MVT::f32: case MVT::f64:
1805   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1806   case MVT::v4f32: case MVT::v2f64:
1807   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1808   case MVT::v4f64:
1809     RRC = &X86::VR128RegClass;
1810     break;
1811   }
1812   return std::make_pair(RRC, Cost);
1813 }
1814
1815 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1816                                                unsigned &Offset) const {
1817   if (!Subtarget->isTargetLinux())
1818     return false;
1819
1820   if (Subtarget->is64Bit()) {
1821     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1822     Offset = 0x28;
1823     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1824       AddressSpace = 256;
1825     else
1826       AddressSpace = 257;
1827   } else {
1828     // %gs:0x14 on i386
1829     Offset = 0x14;
1830     AddressSpace = 256;
1831   }
1832   return true;
1833 }
1834
1835 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1836                                             unsigned DestAS) const {
1837   assert(SrcAS != DestAS && "Expected different address spaces!");
1838
1839   return SrcAS < 256 && DestAS < 256;
1840 }
1841
1842 //===----------------------------------------------------------------------===//
1843 //               Return Value Calling Convention Implementation
1844 //===----------------------------------------------------------------------===//
1845
1846 #include "X86GenCallingConv.inc"
1847
1848 bool
1849 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1850                                   MachineFunction &MF, bool isVarArg,
1851                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1852                         LLVMContext &Context) const {
1853   SmallVector<CCValAssign, 16> RVLocs;
1854   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1855                  RVLocs, Context);
1856   return CCInfo.CheckReturn(Outs, RetCC_X86);
1857 }
1858
1859 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1860   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1861   return ScratchRegs;
1862 }
1863
1864 SDValue
1865 X86TargetLowering::LowerReturn(SDValue Chain,
1866                                CallingConv::ID CallConv, bool isVarArg,
1867                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1868                                const SmallVectorImpl<SDValue> &OutVals,
1869                                SDLoc dl, SelectionDAG &DAG) const {
1870   MachineFunction &MF = DAG.getMachineFunction();
1871   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1872
1873   SmallVector<CCValAssign, 16> RVLocs;
1874   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1875                  RVLocs, *DAG.getContext());
1876   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1877
1878   SDValue Flag;
1879   SmallVector<SDValue, 6> RetOps;
1880   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1881   // Operand #1 = Bytes To Pop
1882   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1883                    MVT::i16));
1884
1885   // Copy the result values into the output registers.
1886   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1887     CCValAssign &VA = RVLocs[i];
1888     assert(VA.isRegLoc() && "Can only return in registers!");
1889     SDValue ValToCopy = OutVals[i];
1890     EVT ValVT = ValToCopy.getValueType();
1891
1892     // Promote values to the appropriate types
1893     if (VA.getLocInfo() == CCValAssign::SExt)
1894       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1895     else if (VA.getLocInfo() == CCValAssign::ZExt)
1896       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1897     else if (VA.getLocInfo() == CCValAssign::AExt)
1898       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1899     else if (VA.getLocInfo() == CCValAssign::BCvt)
1900       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1901
1902     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1903            "Unexpected FP-extend for return value.");  
1904
1905     // If this is x86-64, and we disabled SSE, we can't return FP values,
1906     // or SSE or MMX vectors.
1907     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1908          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1909           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1910       report_fatal_error("SSE register return with SSE disabled");
1911     }
1912     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1913     // llvm-gcc has never done it right and no one has noticed, so this
1914     // should be OK for now.
1915     if (ValVT == MVT::f64 &&
1916         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1917       report_fatal_error("SSE2 register return with SSE2 disabled");
1918
1919     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1920     // the RET instruction and handled by the FP Stackifier.
1921     if (VA.getLocReg() == X86::ST0 ||
1922         VA.getLocReg() == X86::ST1) {
1923       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1924       // change the value to the FP stack register class.
1925       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1926         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1927       RetOps.push_back(ValToCopy);
1928       // Don't emit a copytoreg.
1929       continue;
1930     }
1931
1932     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1933     // which is returned in RAX / RDX.
1934     if (Subtarget->is64Bit()) {
1935       if (ValVT == MVT::x86mmx) {
1936         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1937           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1938           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1939                                   ValToCopy);
1940           // If we don't have SSE2 available, convert to v4f32 so the generated
1941           // register is legal.
1942           if (!Subtarget->hasSSE2())
1943             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1944         }
1945       }
1946     }
1947
1948     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1949     Flag = Chain.getValue(1);
1950     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1951   }
1952
1953   // The x86-64 ABIs require that for returning structs by value we copy
1954   // the sret argument into %rax/%eax (depending on ABI) for the return.
1955   // Win32 requires us to put the sret argument to %eax as well.
1956   // We saved the argument into a virtual register in the entry block,
1957   // so now we copy the value out and into %rax/%eax.
1958   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1959       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1960     MachineFunction &MF = DAG.getMachineFunction();
1961     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1962     unsigned Reg = FuncInfo->getSRetReturnReg();
1963     assert(Reg &&
1964            "SRetReturnReg should have been set in LowerFormalArguments().");
1965     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1966
1967     unsigned RetValReg
1968         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1969           X86::RAX : X86::EAX;
1970     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1971     Flag = Chain.getValue(1);
1972
1973     // RAX/EAX now acts like a return value.
1974     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1975   }
1976
1977   RetOps[0] = Chain;  // Update chain.
1978
1979   // Add the flag if we have it.
1980   if (Flag.getNode())
1981     RetOps.push_back(Flag);
1982
1983   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1984 }
1985
1986 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1987   if (N->getNumValues() != 1)
1988     return false;
1989   if (!N->hasNUsesOfValue(1, 0))
1990     return false;
1991
1992   SDValue TCChain = Chain;
1993   SDNode *Copy = *N->use_begin();
1994   if (Copy->getOpcode() == ISD::CopyToReg) {
1995     // If the copy has a glue operand, we conservatively assume it isn't safe to
1996     // perform a tail call.
1997     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1998       return false;
1999     TCChain = Copy->getOperand(0);
2000   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2001     return false;
2002
2003   bool HasRet = false;
2004   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2005        UI != UE; ++UI) {
2006     if (UI->getOpcode() != X86ISD::RET_FLAG)
2007       return false;
2008     HasRet = true;
2009   }
2010
2011   if (!HasRet)
2012     return false;
2013
2014   Chain = TCChain;
2015   return true;
2016 }
2017
2018 MVT
2019 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2020                                             ISD::NodeType ExtendKind) const {
2021   MVT ReturnMVT;
2022   // TODO: Is this also valid on 32-bit?
2023   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2024     ReturnMVT = MVT::i8;
2025   else
2026     ReturnMVT = MVT::i32;
2027
2028   MVT MinVT = getRegisterType(ReturnMVT);
2029   return VT.bitsLT(MinVT) ? MinVT : VT;
2030 }
2031
2032 /// LowerCallResult - Lower the result values of a call into the
2033 /// appropriate copies out of appropriate physical registers.
2034 ///
2035 SDValue
2036 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2037                                    CallingConv::ID CallConv, bool isVarArg,
2038                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2039                                    SDLoc dl, SelectionDAG &DAG,
2040                                    SmallVectorImpl<SDValue> &InVals) const {
2041
2042   // Assign locations to each value returned by this call.
2043   SmallVector<CCValAssign, 16> RVLocs;
2044   bool Is64Bit = Subtarget->is64Bit();
2045   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2046                  DAG.getTarget(), RVLocs, *DAG.getContext());
2047   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2048
2049   // Copy all of the result registers out of their specified physreg.
2050   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2051     CCValAssign &VA = RVLocs[i];
2052     EVT CopyVT = VA.getValVT();
2053
2054     // If this is x86-64, and we disabled SSE, we can't return FP values
2055     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2056         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2057       report_fatal_error("SSE register return with SSE disabled");
2058     }
2059
2060     SDValue Val;
2061
2062     // If this is a call to a function that returns an fp value on the floating
2063     // point stack, we must guarantee the value is popped from the stack, so
2064     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2065     // if the return value is not used. We use the FpPOP_RETVAL instruction
2066     // instead.
2067     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2068       // If we prefer to use the value in xmm registers, copy it out as f80 and
2069       // use a truncate to move it from fp stack reg to xmm reg.
2070       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2071       SDValue Ops[] = { Chain, InFlag };
2072       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2073                                          MVT::Other, MVT::Glue, Ops), 1);
2074       Val = Chain.getValue(0);
2075
2076       // Round the f80 to the right size, which also moves it to the appropriate
2077       // xmm register.
2078       if (CopyVT != VA.getValVT())
2079         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2080                           // This truncation won't change the value.
2081                           DAG.getIntPtrConstant(1));
2082     } else {
2083       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2084                                  CopyVT, InFlag).getValue(1);
2085       Val = Chain.getValue(0);
2086     }
2087     InFlag = Chain.getValue(2);
2088     InVals.push_back(Val);
2089   }
2090
2091   return Chain;
2092 }
2093
2094 //===----------------------------------------------------------------------===//
2095 //                C & StdCall & Fast Calling Convention implementation
2096 //===----------------------------------------------------------------------===//
2097 //  StdCall calling convention seems to be standard for many Windows' API
2098 //  routines and around. It differs from C calling convention just a little:
2099 //  callee should clean up the stack, not caller. Symbols should be also
2100 //  decorated in some fancy way :) It doesn't support any vector arguments.
2101 //  For info on fast calling convention see Fast Calling Convention (tail call)
2102 //  implementation LowerX86_32FastCCCallTo.
2103
2104 /// CallIsStructReturn - Determines whether a call uses struct return
2105 /// semantics.
2106 enum StructReturnType {
2107   NotStructReturn,
2108   RegStructReturn,
2109   StackStructReturn
2110 };
2111 static StructReturnType
2112 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2113   if (Outs.empty())
2114     return NotStructReturn;
2115
2116   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2117   if (!Flags.isSRet())
2118     return NotStructReturn;
2119   if (Flags.isInReg())
2120     return RegStructReturn;
2121   return StackStructReturn;
2122 }
2123
2124 /// ArgsAreStructReturn - Determines whether a function uses struct
2125 /// return semantics.
2126 static StructReturnType
2127 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2128   if (Ins.empty())
2129     return NotStructReturn;
2130
2131   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2132   if (!Flags.isSRet())
2133     return NotStructReturn;
2134   if (Flags.isInReg())
2135     return RegStructReturn;
2136   return StackStructReturn;
2137 }
2138
2139 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2140 /// by "Src" to address "Dst" with size and alignment information specified by
2141 /// the specific parameter attribute. The copy will be passed as a byval
2142 /// function parameter.
2143 static SDValue
2144 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2145                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2146                           SDLoc dl) {
2147   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2148
2149   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2150                        /*isVolatile*/false, /*AlwaysInline=*/true,
2151                        MachinePointerInfo(), MachinePointerInfo());
2152 }
2153
2154 /// IsTailCallConvention - Return true if the calling convention is one that
2155 /// supports tail call optimization.
2156 static bool IsTailCallConvention(CallingConv::ID CC) {
2157   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2158           CC == CallingConv::HiPE);
2159 }
2160
2161 /// \brief Return true if the calling convention is a C calling convention.
2162 static bool IsCCallConvention(CallingConv::ID CC) {
2163   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2164           CC == CallingConv::X86_64_SysV);
2165 }
2166
2167 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2168   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2169     return false;
2170
2171   CallSite CS(CI);
2172   CallingConv::ID CalleeCC = CS.getCallingConv();
2173   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2174     return false;
2175
2176   return true;
2177 }
2178
2179 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2180 /// a tailcall target by changing its ABI.
2181 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2182                                    bool GuaranteedTailCallOpt) {
2183   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2184 }
2185
2186 SDValue
2187 X86TargetLowering::LowerMemArgument(SDValue Chain,
2188                                     CallingConv::ID CallConv,
2189                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2190                                     SDLoc dl, SelectionDAG &DAG,
2191                                     const CCValAssign &VA,
2192                                     MachineFrameInfo *MFI,
2193                                     unsigned i) const {
2194   // Create the nodes corresponding to a load from this parameter slot.
2195   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2196   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2197       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2198   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2199   EVT ValVT;
2200
2201   // If value is passed by pointer we have address passed instead of the value
2202   // itself.
2203   if (VA.getLocInfo() == CCValAssign::Indirect)
2204     ValVT = VA.getLocVT();
2205   else
2206     ValVT = VA.getValVT();
2207
2208   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2209   // changed with more analysis.
2210   // In case of tail call optimization mark all arguments mutable. Since they
2211   // could be overwritten by lowering of arguments in case of a tail call.
2212   if (Flags.isByVal()) {
2213     unsigned Bytes = Flags.getByValSize();
2214     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2215     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2216     return DAG.getFrameIndex(FI, getPointerTy());
2217   } else {
2218     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2219                                     VA.getLocMemOffset(), isImmutable);
2220     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2221     return DAG.getLoad(ValVT, dl, Chain, FIN,
2222                        MachinePointerInfo::getFixedStack(FI),
2223                        false, false, false, 0);
2224   }
2225 }
2226
2227 SDValue
2228 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2229                                         CallingConv::ID CallConv,
2230                                         bool isVarArg,
2231                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2232                                         SDLoc dl,
2233                                         SelectionDAG &DAG,
2234                                         SmallVectorImpl<SDValue> &InVals)
2235                                           const {
2236   MachineFunction &MF = DAG.getMachineFunction();
2237   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2238
2239   const Function* Fn = MF.getFunction();
2240   if (Fn->hasExternalLinkage() &&
2241       Subtarget->isTargetCygMing() &&
2242       Fn->getName() == "main")
2243     FuncInfo->setForceFramePointer(true);
2244
2245   MachineFrameInfo *MFI = MF.getFrameInfo();
2246   bool Is64Bit = Subtarget->is64Bit();
2247   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2248
2249   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2250          "Var args not supported with calling convention fastcc, ghc or hipe");
2251
2252   // Assign locations to all of the incoming arguments.
2253   SmallVector<CCValAssign, 16> ArgLocs;
2254   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2255                  ArgLocs, *DAG.getContext());
2256
2257   // Allocate shadow area for Win64
2258   if (IsWin64)
2259     CCInfo.AllocateStack(32, 8);
2260
2261   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2262
2263   unsigned LastVal = ~0U;
2264   SDValue ArgValue;
2265   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2266     CCValAssign &VA = ArgLocs[i];
2267     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2268     // places.
2269     assert(VA.getValNo() != LastVal &&
2270            "Don't support value assigned to multiple locs yet");
2271     (void)LastVal;
2272     LastVal = VA.getValNo();
2273
2274     if (VA.isRegLoc()) {
2275       EVT RegVT = VA.getLocVT();
2276       const TargetRegisterClass *RC;
2277       if (RegVT == MVT::i32)
2278         RC = &X86::GR32RegClass;
2279       else if (Is64Bit && RegVT == MVT::i64)
2280         RC = &X86::GR64RegClass;
2281       else if (RegVT == MVT::f32)
2282         RC = &X86::FR32RegClass;
2283       else if (RegVT == MVT::f64)
2284         RC = &X86::FR64RegClass;
2285       else if (RegVT.is512BitVector())
2286         RC = &X86::VR512RegClass;
2287       else if (RegVT.is256BitVector())
2288         RC = &X86::VR256RegClass;
2289       else if (RegVT.is128BitVector())
2290         RC = &X86::VR128RegClass;
2291       else if (RegVT == MVT::x86mmx)
2292         RC = &X86::VR64RegClass;
2293       else if (RegVT == MVT::i1)
2294         RC = &X86::VK1RegClass;
2295       else if (RegVT == MVT::v8i1)
2296         RC = &X86::VK8RegClass;
2297       else if (RegVT == MVT::v16i1)
2298         RC = &X86::VK16RegClass;
2299       else
2300         llvm_unreachable("Unknown argument type!");
2301
2302       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2303       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2304
2305       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2306       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2307       // right size.
2308       if (VA.getLocInfo() == CCValAssign::SExt)
2309         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2310                                DAG.getValueType(VA.getValVT()));
2311       else if (VA.getLocInfo() == CCValAssign::ZExt)
2312         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2313                                DAG.getValueType(VA.getValVT()));
2314       else if (VA.getLocInfo() == CCValAssign::BCvt)
2315         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2316
2317       if (VA.isExtInLoc()) {
2318         // Handle MMX values passed in XMM regs.
2319         if (RegVT.isVector())
2320           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2321         else
2322           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2323       }
2324     } else {
2325       assert(VA.isMemLoc());
2326       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2327     }
2328
2329     // If value is passed via pointer - do a load.
2330     if (VA.getLocInfo() == CCValAssign::Indirect)
2331       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2332                              MachinePointerInfo(), false, false, false, 0);
2333
2334     InVals.push_back(ArgValue);
2335   }
2336
2337   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2338     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2339       // The x86-64 ABIs require that for returning structs by value we copy
2340       // the sret argument into %rax/%eax (depending on ABI) for the return.
2341       // Win32 requires us to put the sret argument to %eax as well.
2342       // Save the argument into a virtual register so that we can access it
2343       // from the return points.
2344       if (Ins[i].Flags.isSRet()) {
2345         unsigned Reg = FuncInfo->getSRetReturnReg();
2346         if (!Reg) {
2347           MVT PtrTy = getPointerTy();
2348           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2349           FuncInfo->setSRetReturnReg(Reg);
2350         }
2351         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2352         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2353         break;
2354       }
2355     }
2356   }
2357
2358   unsigned StackSize = CCInfo.getNextStackOffset();
2359   // Align stack specially for tail calls.
2360   if (FuncIsMadeTailCallSafe(CallConv,
2361                              MF.getTarget().Options.GuaranteedTailCallOpt))
2362     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2363
2364   // If the function takes variable number of arguments, make a frame index for
2365   // the start of the first vararg value... for expansion of llvm.va_start.
2366   if (isVarArg) {
2367     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2368                     CallConv != CallingConv::X86_ThisCall)) {
2369       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2370     }
2371     if (Is64Bit) {
2372       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2373
2374       // FIXME: We should really autogenerate these arrays
2375       static const MCPhysReg GPR64ArgRegsWin64[] = {
2376         X86::RCX, X86::RDX, X86::R8,  X86::R9
2377       };
2378       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2379         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2380       };
2381       static const MCPhysReg XMMArgRegs64Bit[] = {
2382         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2383         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2384       };
2385       const MCPhysReg *GPR64ArgRegs;
2386       unsigned NumXMMRegs = 0;
2387
2388       if (IsWin64) {
2389         // The XMM registers which might contain var arg parameters are shadowed
2390         // in their paired GPR.  So we only need to save the GPR to their home
2391         // slots.
2392         TotalNumIntRegs = 4;
2393         GPR64ArgRegs = GPR64ArgRegsWin64;
2394       } else {
2395         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2396         GPR64ArgRegs = GPR64ArgRegs64Bit;
2397
2398         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2399                                                 TotalNumXMMRegs);
2400       }
2401       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2402                                                        TotalNumIntRegs);
2403
2404       bool NoImplicitFloatOps = Fn->getAttributes().
2405         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2406       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2407              "SSE register cannot be used when SSE is disabled!");
2408       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2409                NoImplicitFloatOps) &&
2410              "SSE register cannot be used when SSE is disabled!");
2411       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2412           !Subtarget->hasSSE1())
2413         // Kernel mode asks for SSE to be disabled, so don't push them
2414         // on the stack.
2415         TotalNumXMMRegs = 0;
2416
2417       if (IsWin64) {
2418         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2419         // Get to the caller-allocated home save location.  Add 8 to account
2420         // for the return address.
2421         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2422         FuncInfo->setRegSaveFrameIndex(
2423           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2424         // Fixup to set vararg frame on shadow area (4 x i64).
2425         if (NumIntRegs < 4)
2426           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2427       } else {
2428         // For X86-64, if there are vararg parameters that are passed via
2429         // registers, then we must store them to their spots on the stack so
2430         // they may be loaded by deferencing the result of va_next.
2431         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2432         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2433         FuncInfo->setRegSaveFrameIndex(
2434           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2435                                false));
2436       }
2437
2438       // Store the integer parameter registers.
2439       SmallVector<SDValue, 8> MemOps;
2440       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2441                                         getPointerTy());
2442       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2443       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2444         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2445                                   DAG.getIntPtrConstant(Offset));
2446         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2447                                      &X86::GR64RegClass);
2448         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2449         SDValue Store =
2450           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2451                        MachinePointerInfo::getFixedStack(
2452                          FuncInfo->getRegSaveFrameIndex(), Offset),
2453                        false, false, 0);
2454         MemOps.push_back(Store);
2455         Offset += 8;
2456       }
2457
2458       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2459         // Now store the XMM (fp + vector) parameter registers.
2460         SmallVector<SDValue, 11> SaveXMMOps;
2461         SaveXMMOps.push_back(Chain);
2462
2463         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2464         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2465         SaveXMMOps.push_back(ALVal);
2466
2467         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2468                                FuncInfo->getRegSaveFrameIndex()));
2469         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2470                                FuncInfo->getVarArgsFPOffset()));
2471
2472         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2473           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2474                                        &X86::VR128RegClass);
2475           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2476           SaveXMMOps.push_back(Val);
2477         }
2478         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2479                                      MVT::Other, SaveXMMOps));
2480       }
2481
2482       if (!MemOps.empty())
2483         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2484     }
2485   }
2486
2487   // Some CCs need callee pop.
2488   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2489                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2490     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2491   } else {
2492     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2493     // If this is an sret function, the return should pop the hidden pointer.
2494     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2495         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2496         argsAreStructReturn(Ins) == StackStructReturn)
2497       FuncInfo->setBytesToPopOnReturn(4);
2498   }
2499
2500   if (!Is64Bit) {
2501     // RegSaveFrameIndex is X86-64 only.
2502     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2503     if (CallConv == CallingConv::X86_FastCall ||
2504         CallConv == CallingConv::X86_ThisCall)
2505       // fastcc functions can't have varargs.
2506       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2507   }
2508
2509   FuncInfo->setArgumentStackSize(StackSize);
2510
2511   return Chain;
2512 }
2513
2514 SDValue
2515 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2516                                     SDValue StackPtr, SDValue Arg,
2517                                     SDLoc dl, SelectionDAG &DAG,
2518                                     const CCValAssign &VA,
2519                                     ISD::ArgFlagsTy Flags) const {
2520   unsigned LocMemOffset = VA.getLocMemOffset();
2521   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2522   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2523   if (Flags.isByVal())
2524     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2525
2526   return DAG.getStore(Chain, dl, Arg, PtrOff,
2527                       MachinePointerInfo::getStack(LocMemOffset),
2528                       false, false, 0);
2529 }
2530
2531 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2532 /// optimization is performed and it is required.
2533 SDValue
2534 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2535                                            SDValue &OutRetAddr, SDValue Chain,
2536                                            bool IsTailCall, bool Is64Bit,
2537                                            int FPDiff, SDLoc dl) const {
2538   // Adjust the Return address stack slot.
2539   EVT VT = getPointerTy();
2540   OutRetAddr = getReturnAddressFrameIndex(DAG);
2541
2542   // Load the "old" Return address.
2543   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2544                            false, false, false, 0);
2545   return SDValue(OutRetAddr.getNode(), 1);
2546 }
2547
2548 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2549 /// optimization is performed and it is required (FPDiff!=0).
2550 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2551                                         SDValue Chain, SDValue RetAddrFrIdx,
2552                                         EVT PtrVT, unsigned SlotSize,
2553                                         int FPDiff, SDLoc dl) {
2554   // Store the return address to the appropriate stack slot.
2555   if (!FPDiff) return Chain;
2556   // Calculate the new stack slot for the return address.
2557   int NewReturnAddrFI =
2558     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2559                                          false);
2560   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2561   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2562                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2563                        false, false, 0);
2564   return Chain;
2565 }
2566
2567 SDValue
2568 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2569                              SmallVectorImpl<SDValue> &InVals) const {
2570   SelectionDAG &DAG                     = CLI.DAG;
2571   SDLoc &dl                             = CLI.DL;
2572   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2573   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2574   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2575   SDValue Chain                         = CLI.Chain;
2576   SDValue Callee                        = CLI.Callee;
2577   CallingConv::ID CallConv              = CLI.CallConv;
2578   bool &isTailCall                      = CLI.IsTailCall;
2579   bool isVarArg                         = CLI.IsVarArg;
2580
2581   MachineFunction &MF = DAG.getMachineFunction();
2582   bool Is64Bit        = Subtarget->is64Bit();
2583   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2584   StructReturnType SR = callIsStructReturn(Outs);
2585   bool IsSibcall      = false;
2586
2587   if (MF.getTarget().Options.DisableTailCalls)
2588     isTailCall = false;
2589
2590   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2591   if (IsMustTail) {
2592     // Force this to be a tail call.  The verifier rules are enough to ensure
2593     // that we can lower this successfully without moving the return address
2594     // around.
2595     isTailCall = true;
2596   } else if (isTailCall) {
2597     // Check if it's really possible to do a tail call.
2598     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2599                     isVarArg, SR != NotStructReturn,
2600                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2601                     Outs, OutVals, Ins, DAG);
2602
2603     // Sibcalls are automatically detected tailcalls which do not require
2604     // ABI changes.
2605     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2606       IsSibcall = true;
2607
2608     if (isTailCall)
2609       ++NumTailCalls;
2610   }
2611
2612   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2613          "Var args not supported with calling convention fastcc, ghc or hipe");
2614
2615   // Analyze operands of the call, assigning locations to each operand.
2616   SmallVector<CCValAssign, 16> ArgLocs;
2617   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2618                  ArgLocs, *DAG.getContext());
2619
2620   // Allocate shadow area for Win64
2621   if (IsWin64)
2622     CCInfo.AllocateStack(32, 8);
2623
2624   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2625
2626   // Get a count of how many bytes are to be pushed on the stack.
2627   unsigned NumBytes = CCInfo.getNextStackOffset();
2628   if (IsSibcall)
2629     // This is a sibcall. The memory operands are available in caller's
2630     // own caller's stack.
2631     NumBytes = 0;
2632   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2633            IsTailCallConvention(CallConv))
2634     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2635
2636   int FPDiff = 0;
2637   if (isTailCall && !IsSibcall && !IsMustTail) {
2638     // Lower arguments at fp - stackoffset + fpdiff.
2639     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2640     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2641
2642     FPDiff = NumBytesCallerPushed - NumBytes;
2643
2644     // Set the delta of movement of the returnaddr stackslot.
2645     // But only set if delta is greater than previous delta.
2646     if (FPDiff < X86Info->getTCReturnAddrDelta())
2647       X86Info->setTCReturnAddrDelta(FPDiff);
2648   }
2649
2650   unsigned NumBytesToPush = NumBytes;
2651   unsigned NumBytesToPop = NumBytes;
2652
2653   // If we have an inalloca argument, all stack space has already been allocated
2654   // for us and be right at the top of the stack.  We don't support multiple
2655   // arguments passed in memory when using inalloca.
2656   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2657     NumBytesToPush = 0;
2658     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2659            "an inalloca argument must be the only memory argument");
2660   }
2661
2662   if (!IsSibcall)
2663     Chain = DAG.getCALLSEQ_START(
2664         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2665
2666   SDValue RetAddrFrIdx;
2667   // Load return address for tail calls.
2668   if (isTailCall && FPDiff)
2669     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2670                                     Is64Bit, FPDiff, dl);
2671
2672   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2673   SmallVector<SDValue, 8> MemOpChains;
2674   SDValue StackPtr;
2675
2676   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2677   // of tail call optimization arguments are handle later.
2678   const X86RegisterInfo *RegInfo =
2679     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2680   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2681     // Skip inalloca arguments, they have already been written.
2682     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2683     if (Flags.isInAlloca())
2684       continue;
2685
2686     CCValAssign &VA = ArgLocs[i];
2687     EVT RegVT = VA.getLocVT();
2688     SDValue Arg = OutVals[i];
2689     bool isByVal = Flags.isByVal();
2690
2691     // Promote the value if needed.
2692     switch (VA.getLocInfo()) {
2693     default: llvm_unreachable("Unknown loc info!");
2694     case CCValAssign::Full: break;
2695     case CCValAssign::SExt:
2696       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2697       break;
2698     case CCValAssign::ZExt:
2699       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2700       break;
2701     case CCValAssign::AExt:
2702       if (RegVT.is128BitVector()) {
2703         // Special case: passing MMX values in XMM registers.
2704         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2705         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2706         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2707       } else
2708         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2709       break;
2710     case CCValAssign::BCvt:
2711       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2712       break;
2713     case CCValAssign::Indirect: {
2714       // Store the argument.
2715       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2716       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2717       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2718                            MachinePointerInfo::getFixedStack(FI),
2719                            false, false, 0);
2720       Arg = SpillSlot;
2721       break;
2722     }
2723     }
2724
2725     if (VA.isRegLoc()) {
2726       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2727       if (isVarArg && IsWin64) {
2728         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2729         // shadow reg if callee is a varargs function.
2730         unsigned ShadowReg = 0;
2731         switch (VA.getLocReg()) {
2732         case X86::XMM0: ShadowReg = X86::RCX; break;
2733         case X86::XMM1: ShadowReg = X86::RDX; break;
2734         case X86::XMM2: ShadowReg = X86::R8; break;
2735         case X86::XMM3: ShadowReg = X86::R9; break;
2736         }
2737         if (ShadowReg)
2738           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2739       }
2740     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2741       assert(VA.isMemLoc());
2742       if (!StackPtr.getNode())
2743         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2744                                       getPointerTy());
2745       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2746                                              dl, DAG, VA, Flags));
2747     }
2748   }
2749
2750   if (!MemOpChains.empty())
2751     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2752
2753   if (Subtarget->isPICStyleGOT()) {
2754     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2755     // GOT pointer.
2756     if (!isTailCall) {
2757       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2758                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2759     } else {
2760       // If we are tail calling and generating PIC/GOT style code load the
2761       // address of the callee into ECX. The value in ecx is used as target of
2762       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2763       // for tail calls on PIC/GOT architectures. Normally we would just put the
2764       // address of GOT into ebx and then call target@PLT. But for tail calls
2765       // ebx would be restored (since ebx is callee saved) before jumping to the
2766       // target@PLT.
2767
2768       // Note: The actual moving to ECX is done further down.
2769       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2770       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2771           !G->getGlobal()->hasProtectedVisibility())
2772         Callee = LowerGlobalAddress(Callee, DAG);
2773       else if (isa<ExternalSymbolSDNode>(Callee))
2774         Callee = LowerExternalSymbol(Callee, DAG);
2775     }
2776   }
2777
2778   if (Is64Bit && isVarArg && !IsWin64) {
2779     // From AMD64 ABI document:
2780     // For calls that may call functions that use varargs or stdargs
2781     // (prototype-less calls or calls to functions containing ellipsis (...) in
2782     // the declaration) %al is used as hidden argument to specify the number
2783     // of SSE registers used. The contents of %al do not need to match exactly
2784     // the number of registers, but must be an ubound on the number of SSE
2785     // registers used and is in the range 0 - 8 inclusive.
2786
2787     // Count the number of XMM registers allocated.
2788     static const MCPhysReg XMMArgRegs[] = {
2789       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2790       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2791     };
2792     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2793     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2794            && "SSE registers cannot be used when SSE is disabled");
2795
2796     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2797                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2798   }
2799
2800   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2801   // don't need this because the eligibility check rejects calls that require
2802   // shuffling arguments passed in memory.
2803   if (!IsSibcall && isTailCall) {
2804     // Force all the incoming stack arguments to be loaded from the stack
2805     // before any new outgoing arguments are stored to the stack, because the
2806     // outgoing stack slots may alias the incoming argument stack slots, and
2807     // the alias isn't otherwise explicit. This is slightly more conservative
2808     // than necessary, because it means that each store effectively depends
2809     // on every argument instead of just those arguments it would clobber.
2810     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2811
2812     SmallVector<SDValue, 8> MemOpChains2;
2813     SDValue FIN;
2814     int FI = 0;
2815     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2816       CCValAssign &VA = ArgLocs[i];
2817       if (VA.isRegLoc())
2818         continue;
2819       assert(VA.isMemLoc());
2820       SDValue Arg = OutVals[i];
2821       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2822       // Skip inalloca arguments.  They don't require any work.
2823       if (Flags.isInAlloca())
2824         continue;
2825       // Create frame index.
2826       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2827       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2828       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2829       FIN = DAG.getFrameIndex(FI, getPointerTy());
2830
2831       if (Flags.isByVal()) {
2832         // Copy relative to framepointer.
2833         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2834         if (!StackPtr.getNode())
2835           StackPtr = DAG.getCopyFromReg(Chain, dl,
2836                                         RegInfo->getStackRegister(),
2837                                         getPointerTy());
2838         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2839
2840         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2841                                                          ArgChain,
2842                                                          Flags, DAG, dl));
2843       } else {
2844         // Store relative to framepointer.
2845         MemOpChains2.push_back(
2846           DAG.getStore(ArgChain, dl, Arg, FIN,
2847                        MachinePointerInfo::getFixedStack(FI),
2848                        false, false, 0));
2849       }
2850     }
2851
2852     if (!MemOpChains2.empty())
2853       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2854
2855     // Store the return address to the appropriate stack slot.
2856     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2857                                      getPointerTy(), RegInfo->getSlotSize(),
2858                                      FPDiff, dl);
2859   }
2860
2861   // Build a sequence of copy-to-reg nodes chained together with token chain
2862   // and flag operands which copy the outgoing args into registers.
2863   SDValue InFlag;
2864   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2865     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2866                              RegsToPass[i].second, InFlag);
2867     InFlag = Chain.getValue(1);
2868   }
2869
2870   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2871     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2872     // In the 64-bit large code model, we have to make all calls
2873     // through a register, since the call instruction's 32-bit
2874     // pc-relative offset may not be large enough to hold the whole
2875     // address.
2876   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2877     // If the callee is a GlobalAddress node (quite common, every direct call
2878     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2879     // it.
2880
2881     // We should use extra load for direct calls to dllimported functions in
2882     // non-JIT mode.
2883     const GlobalValue *GV = G->getGlobal();
2884     if (!GV->hasDLLImportStorageClass()) {
2885       unsigned char OpFlags = 0;
2886       bool ExtraLoad = false;
2887       unsigned WrapperKind = ISD::DELETED_NODE;
2888
2889       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2890       // external symbols most go through the PLT in PIC mode.  If the symbol
2891       // has hidden or protected visibility, or if it is static or local, then
2892       // we don't need to use the PLT - we can directly call it.
2893       if (Subtarget->isTargetELF() &&
2894           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2895           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2896         OpFlags = X86II::MO_PLT;
2897       } else if (Subtarget->isPICStyleStubAny() &&
2898                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2899                  (!Subtarget->getTargetTriple().isMacOSX() ||
2900                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2901         // PC-relative references to external symbols should go through $stub,
2902         // unless we're building with the leopard linker or later, which
2903         // automatically synthesizes these stubs.
2904         OpFlags = X86II::MO_DARWIN_STUB;
2905       } else if (Subtarget->isPICStyleRIPRel() &&
2906                  isa<Function>(GV) &&
2907                  cast<Function>(GV)->getAttributes().
2908                    hasAttribute(AttributeSet::FunctionIndex,
2909                                 Attribute::NonLazyBind)) {
2910         // If the function is marked as non-lazy, generate an indirect call
2911         // which loads from the GOT directly. This avoids runtime overhead
2912         // at the cost of eager binding (and one extra byte of encoding).
2913         OpFlags = X86II::MO_GOTPCREL;
2914         WrapperKind = X86ISD::WrapperRIP;
2915         ExtraLoad = true;
2916       }
2917
2918       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2919                                           G->getOffset(), OpFlags);
2920
2921       // Add a wrapper if needed.
2922       if (WrapperKind != ISD::DELETED_NODE)
2923         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2924       // Add extra indirection if needed.
2925       if (ExtraLoad)
2926         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2927                              MachinePointerInfo::getGOT(),
2928                              false, false, false, 0);
2929     }
2930   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2931     unsigned char OpFlags = 0;
2932
2933     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2934     // external symbols should go through the PLT.
2935     if (Subtarget->isTargetELF() &&
2936         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2937       OpFlags = X86II::MO_PLT;
2938     } else if (Subtarget->isPICStyleStubAny() &&
2939                (!Subtarget->getTargetTriple().isMacOSX() ||
2940                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2941       // PC-relative references to external symbols should go through $stub,
2942       // unless we're building with the leopard linker or later, which
2943       // automatically synthesizes these stubs.
2944       OpFlags = X86II::MO_DARWIN_STUB;
2945     }
2946
2947     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2948                                          OpFlags);
2949   }
2950
2951   // Returns a chain & a flag for retval copy to use.
2952   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2953   SmallVector<SDValue, 8> Ops;
2954
2955   if (!IsSibcall && isTailCall) {
2956     Chain = DAG.getCALLSEQ_END(Chain,
2957                                DAG.getIntPtrConstant(NumBytesToPop, true),
2958                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2959     InFlag = Chain.getValue(1);
2960   }
2961
2962   Ops.push_back(Chain);
2963   Ops.push_back(Callee);
2964
2965   if (isTailCall)
2966     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2967
2968   // Add argument registers to the end of the list so that they are known live
2969   // into the call.
2970   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2971     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2972                                   RegsToPass[i].second.getValueType()));
2973
2974   // Add a register mask operand representing the call-preserved registers.
2975   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2976   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2977   assert(Mask && "Missing call preserved mask for calling convention");
2978   Ops.push_back(DAG.getRegisterMask(Mask));
2979
2980   if (InFlag.getNode())
2981     Ops.push_back(InFlag);
2982
2983   if (isTailCall) {
2984     // We used to do:
2985     //// If this is the first return lowered for this function, add the regs
2986     //// to the liveout set for the function.
2987     // This isn't right, although it's probably harmless on x86; liveouts
2988     // should be computed from returns not tail calls.  Consider a void
2989     // function making a tail call to a function returning int.
2990     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2991   }
2992
2993   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2994   InFlag = Chain.getValue(1);
2995
2996   // Create the CALLSEQ_END node.
2997   unsigned NumBytesForCalleeToPop;
2998   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2999                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3000     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3001   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3002            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3003            SR == StackStructReturn)
3004     // If this is a call to a struct-return function, the callee
3005     // pops the hidden struct pointer, so we have to push it back.
3006     // This is common for Darwin/X86, Linux & Mingw32 targets.
3007     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3008     NumBytesForCalleeToPop = 4;
3009   else
3010     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3011
3012   // Returns a flag for retval copy to use.
3013   if (!IsSibcall) {
3014     Chain = DAG.getCALLSEQ_END(Chain,
3015                                DAG.getIntPtrConstant(NumBytesToPop, true),
3016                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3017                                                      true),
3018                                InFlag, dl);
3019     InFlag = Chain.getValue(1);
3020   }
3021
3022   // Handle result values, copying them out of physregs into vregs that we
3023   // return.
3024   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3025                          Ins, dl, DAG, InVals);
3026 }
3027
3028 //===----------------------------------------------------------------------===//
3029 //                Fast Calling Convention (tail call) implementation
3030 //===----------------------------------------------------------------------===//
3031
3032 //  Like std call, callee cleans arguments, convention except that ECX is
3033 //  reserved for storing the tail called function address. Only 2 registers are
3034 //  free for argument passing (inreg). Tail call optimization is performed
3035 //  provided:
3036 //                * tailcallopt is enabled
3037 //                * caller/callee are fastcc
3038 //  On X86_64 architecture with GOT-style position independent code only local
3039 //  (within module) calls are supported at the moment.
3040 //  To keep the stack aligned according to platform abi the function
3041 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3042 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3043 //  If a tail called function callee has more arguments than the caller the
3044 //  caller needs to make sure that there is room to move the RETADDR to. This is
3045 //  achieved by reserving an area the size of the argument delta right after the
3046 //  original REtADDR, but before the saved framepointer or the spilled registers
3047 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3048 //  stack layout:
3049 //    arg1
3050 //    arg2
3051 //    RETADDR
3052 //    [ new RETADDR
3053 //      move area ]
3054 //    (possible EBP)
3055 //    ESI
3056 //    EDI
3057 //    local1 ..
3058
3059 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3060 /// for a 16 byte align requirement.
3061 unsigned
3062 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3063                                                SelectionDAG& DAG) const {
3064   MachineFunction &MF = DAG.getMachineFunction();
3065   const TargetMachine &TM = MF.getTarget();
3066   const X86RegisterInfo *RegInfo =
3067     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3068   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3069   unsigned StackAlignment = TFI.getStackAlignment();
3070   uint64_t AlignMask = StackAlignment - 1;
3071   int64_t Offset = StackSize;
3072   unsigned SlotSize = RegInfo->getSlotSize();
3073   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3074     // Number smaller than 12 so just add the difference.
3075     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3076   } else {
3077     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3078     Offset = ((~AlignMask) & Offset) + StackAlignment +
3079       (StackAlignment-SlotSize);
3080   }
3081   return Offset;
3082 }
3083
3084 /// MatchingStackOffset - Return true if the given stack call argument is
3085 /// already available in the same position (relatively) of the caller's
3086 /// incoming argument stack.
3087 static
3088 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3089                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3090                          const X86InstrInfo *TII) {
3091   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3092   int FI = INT_MAX;
3093   if (Arg.getOpcode() == ISD::CopyFromReg) {
3094     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3095     if (!TargetRegisterInfo::isVirtualRegister(VR))
3096       return false;
3097     MachineInstr *Def = MRI->getVRegDef(VR);
3098     if (!Def)
3099       return false;
3100     if (!Flags.isByVal()) {
3101       if (!TII->isLoadFromStackSlot(Def, FI))
3102         return false;
3103     } else {
3104       unsigned Opcode = Def->getOpcode();
3105       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3106           Def->getOperand(1).isFI()) {
3107         FI = Def->getOperand(1).getIndex();
3108         Bytes = Flags.getByValSize();
3109       } else
3110         return false;
3111     }
3112   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3113     if (Flags.isByVal())
3114       // ByVal argument is passed in as a pointer but it's now being
3115       // dereferenced. e.g.
3116       // define @foo(%struct.X* %A) {
3117       //   tail call @bar(%struct.X* byval %A)
3118       // }
3119       return false;
3120     SDValue Ptr = Ld->getBasePtr();
3121     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3122     if (!FINode)
3123       return false;
3124     FI = FINode->getIndex();
3125   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3126     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3127     FI = FINode->getIndex();
3128     Bytes = Flags.getByValSize();
3129   } else
3130     return false;
3131
3132   assert(FI != INT_MAX);
3133   if (!MFI->isFixedObjectIndex(FI))
3134     return false;
3135   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3136 }
3137
3138 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3139 /// for tail call optimization. Targets which want to do tail call
3140 /// optimization should implement this function.
3141 bool
3142 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3143                                                      CallingConv::ID CalleeCC,
3144                                                      bool isVarArg,
3145                                                      bool isCalleeStructRet,
3146                                                      bool isCallerStructRet,
3147                                                      Type *RetTy,
3148                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3149                                     const SmallVectorImpl<SDValue> &OutVals,
3150                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3151                                                      SelectionDAG &DAG) const {
3152   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3153     return false;
3154
3155   // If -tailcallopt is specified, make fastcc functions tail-callable.
3156   const MachineFunction &MF = DAG.getMachineFunction();
3157   const Function *CallerF = MF.getFunction();
3158
3159   // If the function return type is x86_fp80 and the callee return type is not,
3160   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3161   // perform a tailcall optimization here.
3162   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3163     return false;
3164
3165   CallingConv::ID CallerCC = CallerF->getCallingConv();
3166   bool CCMatch = CallerCC == CalleeCC;
3167   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3168   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3169
3170   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3171     if (IsTailCallConvention(CalleeCC) && CCMatch)
3172       return true;
3173     return false;
3174   }
3175
3176   // Look for obvious safe cases to perform tail call optimization that do not
3177   // require ABI changes. This is what gcc calls sibcall.
3178
3179   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3180   // emit a special epilogue.
3181   const X86RegisterInfo *RegInfo =
3182     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3183   if (RegInfo->needsStackRealignment(MF))
3184     return false;
3185
3186   // Also avoid sibcall optimization if either caller or callee uses struct
3187   // return semantics.
3188   if (isCalleeStructRet || isCallerStructRet)
3189     return false;
3190
3191   // An stdcall/thiscall caller is expected to clean up its arguments; the
3192   // callee isn't going to do that.
3193   // FIXME: this is more restrictive than needed. We could produce a tailcall
3194   // when the stack adjustment matches. For example, with a thiscall that takes
3195   // only one argument.
3196   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3197                    CallerCC == CallingConv::X86_ThisCall))
3198     return false;
3199
3200   // Do not sibcall optimize vararg calls unless all arguments are passed via
3201   // registers.
3202   if (isVarArg && !Outs.empty()) {
3203
3204     // Optimizing for varargs on Win64 is unlikely to be safe without
3205     // additional testing.
3206     if (IsCalleeWin64 || IsCallerWin64)
3207       return false;
3208
3209     SmallVector<CCValAssign, 16> ArgLocs;
3210     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3211                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3212
3213     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3214     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3215       if (!ArgLocs[i].isRegLoc())
3216         return false;
3217   }
3218
3219   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3220   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3221   // this into a sibcall.
3222   bool Unused = false;
3223   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3224     if (!Ins[i].Used) {
3225       Unused = true;
3226       break;
3227     }
3228   }
3229   if (Unused) {
3230     SmallVector<CCValAssign, 16> RVLocs;
3231     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3232                    DAG.getTarget(), RVLocs, *DAG.getContext());
3233     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3234     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3235       CCValAssign &VA = RVLocs[i];
3236       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3237         return false;
3238     }
3239   }
3240
3241   // If the calling conventions do not match, then we'd better make sure the
3242   // results are returned in the same way as what the caller expects.
3243   if (!CCMatch) {
3244     SmallVector<CCValAssign, 16> RVLocs1;
3245     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3246                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3247     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3248
3249     SmallVector<CCValAssign, 16> RVLocs2;
3250     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3251                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3252     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3253
3254     if (RVLocs1.size() != RVLocs2.size())
3255       return false;
3256     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3257       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3258         return false;
3259       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3260         return false;
3261       if (RVLocs1[i].isRegLoc()) {
3262         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3263           return false;
3264       } else {
3265         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3266           return false;
3267       }
3268     }
3269   }
3270
3271   // If the callee takes no arguments then go on to check the results of the
3272   // call.
3273   if (!Outs.empty()) {
3274     // Check if stack adjustment is needed. For now, do not do this if any
3275     // argument is passed on the stack.
3276     SmallVector<CCValAssign, 16> ArgLocs;
3277     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3278                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3279
3280     // Allocate shadow area for Win64
3281     if (IsCalleeWin64)
3282       CCInfo.AllocateStack(32, 8);
3283
3284     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3285     if (CCInfo.getNextStackOffset()) {
3286       MachineFunction &MF = DAG.getMachineFunction();
3287       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3288         return false;
3289
3290       // Check if the arguments are already laid out in the right way as
3291       // the caller's fixed stack objects.
3292       MachineFrameInfo *MFI = MF.getFrameInfo();
3293       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3294       const X86InstrInfo *TII =
3295           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3296       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3297         CCValAssign &VA = ArgLocs[i];
3298         SDValue Arg = OutVals[i];
3299         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3300         if (VA.getLocInfo() == CCValAssign::Indirect)
3301           return false;
3302         if (!VA.isRegLoc()) {
3303           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3304                                    MFI, MRI, TII))
3305             return false;
3306         }
3307       }
3308     }
3309
3310     // If the tailcall address may be in a register, then make sure it's
3311     // possible to register allocate for it. In 32-bit, the call address can
3312     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3313     // callee-saved registers are restored. These happen to be the same
3314     // registers used to pass 'inreg' arguments so watch out for those.
3315     if (!Subtarget->is64Bit() &&
3316         ((!isa<GlobalAddressSDNode>(Callee) &&
3317           !isa<ExternalSymbolSDNode>(Callee)) ||
3318          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3319       unsigned NumInRegs = 0;
3320       // In PIC we need an extra register to formulate the address computation
3321       // for the callee.
3322       unsigned MaxInRegs =
3323         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3324
3325       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3326         CCValAssign &VA = ArgLocs[i];
3327         if (!VA.isRegLoc())
3328           continue;
3329         unsigned Reg = VA.getLocReg();
3330         switch (Reg) {
3331         default: break;
3332         case X86::EAX: case X86::EDX: case X86::ECX:
3333           if (++NumInRegs == MaxInRegs)
3334             return false;
3335           break;
3336         }
3337       }
3338     }
3339   }
3340
3341   return true;
3342 }
3343
3344 FastISel *
3345 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3346                                   const TargetLibraryInfo *libInfo) const {
3347   return X86::createFastISel(funcInfo, libInfo);
3348 }
3349
3350 //===----------------------------------------------------------------------===//
3351 //                           Other Lowering Hooks
3352 //===----------------------------------------------------------------------===//
3353
3354 static bool MayFoldLoad(SDValue Op) {
3355   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3356 }
3357
3358 static bool MayFoldIntoStore(SDValue Op) {
3359   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3360 }
3361
3362 static bool isTargetShuffle(unsigned Opcode) {
3363   switch(Opcode) {
3364   default: return false;
3365   case X86ISD::PSHUFD:
3366   case X86ISD::PSHUFHW:
3367   case X86ISD::PSHUFLW:
3368   case X86ISD::SHUFP:
3369   case X86ISD::PALIGNR:
3370   case X86ISD::MOVLHPS:
3371   case X86ISD::MOVLHPD:
3372   case X86ISD::MOVHLPS:
3373   case X86ISD::MOVLPS:
3374   case X86ISD::MOVLPD:
3375   case X86ISD::MOVSHDUP:
3376   case X86ISD::MOVSLDUP:
3377   case X86ISD::MOVDDUP:
3378   case X86ISD::MOVSS:
3379   case X86ISD::MOVSD:
3380   case X86ISD::UNPCKL:
3381   case X86ISD::UNPCKH:
3382   case X86ISD::VPERMILP:
3383   case X86ISD::VPERM2X128:
3384   case X86ISD::VPERMI:
3385     return true;
3386   }
3387 }
3388
3389 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3390                                     SDValue V1, SelectionDAG &DAG) {
3391   switch(Opc) {
3392   default: llvm_unreachable("Unknown x86 shuffle node");
3393   case X86ISD::MOVSHDUP:
3394   case X86ISD::MOVSLDUP:
3395   case X86ISD::MOVDDUP:
3396     return DAG.getNode(Opc, dl, VT, V1);
3397   }
3398 }
3399
3400 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3401                                     SDValue V1, unsigned TargetMask,
3402                                     SelectionDAG &DAG) {
3403   switch(Opc) {
3404   default: llvm_unreachable("Unknown x86 shuffle node");
3405   case X86ISD::PSHUFD:
3406   case X86ISD::PSHUFHW:
3407   case X86ISD::PSHUFLW:
3408   case X86ISD::VPERMILP:
3409   case X86ISD::VPERMI:
3410     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3411   }
3412 }
3413
3414 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3415                                     SDValue V1, SDValue V2, unsigned TargetMask,
3416                                     SelectionDAG &DAG) {
3417   switch(Opc) {
3418   default: llvm_unreachable("Unknown x86 shuffle node");
3419   case X86ISD::PALIGNR:
3420   case X86ISD::SHUFP:
3421   case X86ISD::VPERM2X128:
3422     return DAG.getNode(Opc, dl, VT, V1, V2,
3423                        DAG.getConstant(TargetMask, MVT::i8));
3424   }
3425 }
3426
3427 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3428                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3429   switch(Opc) {
3430   default: llvm_unreachable("Unknown x86 shuffle node");
3431   case X86ISD::MOVLHPS:
3432   case X86ISD::MOVLHPD:
3433   case X86ISD::MOVHLPS:
3434   case X86ISD::MOVLPS:
3435   case X86ISD::MOVLPD:
3436   case X86ISD::MOVSS:
3437   case X86ISD::MOVSD:
3438   case X86ISD::UNPCKL:
3439   case X86ISD::UNPCKH:
3440     return DAG.getNode(Opc, dl, VT, V1, V2);
3441   }
3442 }
3443
3444 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3445   MachineFunction &MF = DAG.getMachineFunction();
3446   const X86RegisterInfo *RegInfo =
3447     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3448   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3449   int ReturnAddrIndex = FuncInfo->getRAIndex();
3450
3451   if (ReturnAddrIndex == 0) {
3452     // Set up a frame object for the return address.
3453     unsigned SlotSize = RegInfo->getSlotSize();
3454     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3455                                                            -(int64_t)SlotSize,
3456                                                            false);
3457     FuncInfo->setRAIndex(ReturnAddrIndex);
3458   }
3459
3460   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3461 }
3462
3463 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3464                                        bool hasSymbolicDisplacement) {
3465   // Offset should fit into 32 bit immediate field.
3466   if (!isInt<32>(Offset))
3467     return false;
3468
3469   // If we don't have a symbolic displacement - we don't have any extra
3470   // restrictions.
3471   if (!hasSymbolicDisplacement)
3472     return true;
3473
3474   // FIXME: Some tweaks might be needed for medium code model.
3475   if (M != CodeModel::Small && M != CodeModel::Kernel)
3476     return false;
3477
3478   // For small code model we assume that latest object is 16MB before end of 31
3479   // bits boundary. We may also accept pretty large negative constants knowing
3480   // that all objects are in the positive half of address space.
3481   if (M == CodeModel::Small && Offset < 16*1024*1024)
3482     return true;
3483
3484   // For kernel code model we know that all object resist in the negative half
3485   // of 32bits address space. We may not accept negative offsets, since they may
3486   // be just off and we may accept pretty large positive ones.
3487   if (M == CodeModel::Kernel && Offset > 0)
3488     return true;
3489
3490   return false;
3491 }
3492
3493 /// isCalleePop - Determines whether the callee is required to pop its
3494 /// own arguments. Callee pop is necessary to support tail calls.
3495 bool X86::isCalleePop(CallingConv::ID CallingConv,
3496                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3497   if (IsVarArg)
3498     return false;
3499
3500   switch (CallingConv) {
3501   default:
3502     return false;
3503   case CallingConv::X86_StdCall:
3504     return !is64Bit;
3505   case CallingConv::X86_FastCall:
3506     return !is64Bit;
3507   case CallingConv::X86_ThisCall:
3508     return !is64Bit;
3509   case CallingConv::Fast:
3510     return TailCallOpt;
3511   case CallingConv::GHC:
3512     return TailCallOpt;
3513   case CallingConv::HiPE:
3514     return TailCallOpt;
3515   }
3516 }
3517
3518 /// \brief Return true if the condition is an unsigned comparison operation.
3519 static bool isX86CCUnsigned(unsigned X86CC) {
3520   switch (X86CC) {
3521   default: llvm_unreachable("Invalid integer condition!");
3522   case X86::COND_E:     return true;
3523   case X86::COND_G:     return false;
3524   case X86::COND_GE:    return false;
3525   case X86::COND_L:     return false;
3526   case X86::COND_LE:    return false;
3527   case X86::COND_NE:    return true;
3528   case X86::COND_B:     return true;
3529   case X86::COND_A:     return true;
3530   case X86::COND_BE:    return true;
3531   case X86::COND_AE:    return true;
3532   }
3533   llvm_unreachable("covered switch fell through?!");
3534 }
3535
3536 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3537 /// specific condition code, returning the condition code and the LHS/RHS of the
3538 /// comparison to make.
3539 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3540                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3541   if (!isFP) {
3542     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3543       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3544         // X > -1   -> X == 0, jump !sign.
3545         RHS = DAG.getConstant(0, RHS.getValueType());
3546         return X86::COND_NS;
3547       }
3548       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3549         // X < 0   -> X == 0, jump on sign.
3550         return X86::COND_S;
3551       }
3552       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3553         // X < 1   -> X <= 0
3554         RHS = DAG.getConstant(0, RHS.getValueType());
3555         return X86::COND_LE;
3556       }
3557     }
3558
3559     switch (SetCCOpcode) {
3560     default: llvm_unreachable("Invalid integer condition!");
3561     case ISD::SETEQ:  return X86::COND_E;
3562     case ISD::SETGT:  return X86::COND_G;
3563     case ISD::SETGE:  return X86::COND_GE;
3564     case ISD::SETLT:  return X86::COND_L;
3565     case ISD::SETLE:  return X86::COND_LE;
3566     case ISD::SETNE:  return X86::COND_NE;
3567     case ISD::SETULT: return X86::COND_B;
3568     case ISD::SETUGT: return X86::COND_A;
3569     case ISD::SETULE: return X86::COND_BE;
3570     case ISD::SETUGE: return X86::COND_AE;
3571     }
3572   }
3573
3574   // First determine if it is required or is profitable to flip the operands.
3575
3576   // If LHS is a foldable load, but RHS is not, flip the condition.
3577   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3578       !ISD::isNON_EXTLoad(RHS.getNode())) {
3579     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3580     std::swap(LHS, RHS);
3581   }
3582
3583   switch (SetCCOpcode) {
3584   default: break;
3585   case ISD::SETOLT:
3586   case ISD::SETOLE:
3587   case ISD::SETUGT:
3588   case ISD::SETUGE:
3589     std::swap(LHS, RHS);
3590     break;
3591   }
3592
3593   // On a floating point condition, the flags are set as follows:
3594   // ZF  PF  CF   op
3595   //  0 | 0 | 0 | X > Y
3596   //  0 | 0 | 1 | X < Y
3597   //  1 | 0 | 0 | X == Y
3598   //  1 | 1 | 1 | unordered
3599   switch (SetCCOpcode) {
3600   default: llvm_unreachable("Condcode should be pre-legalized away");
3601   case ISD::SETUEQ:
3602   case ISD::SETEQ:   return X86::COND_E;
3603   case ISD::SETOLT:              // flipped
3604   case ISD::SETOGT:
3605   case ISD::SETGT:   return X86::COND_A;
3606   case ISD::SETOLE:              // flipped
3607   case ISD::SETOGE:
3608   case ISD::SETGE:   return X86::COND_AE;
3609   case ISD::SETUGT:              // flipped
3610   case ISD::SETULT:
3611   case ISD::SETLT:   return X86::COND_B;
3612   case ISD::SETUGE:              // flipped
3613   case ISD::SETULE:
3614   case ISD::SETLE:   return X86::COND_BE;
3615   case ISD::SETONE:
3616   case ISD::SETNE:   return X86::COND_NE;
3617   case ISD::SETUO:   return X86::COND_P;
3618   case ISD::SETO:    return X86::COND_NP;
3619   case ISD::SETOEQ:
3620   case ISD::SETUNE:  return X86::COND_INVALID;
3621   }
3622 }
3623
3624 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3625 /// code. Current x86 isa includes the following FP cmov instructions:
3626 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3627 static bool hasFPCMov(unsigned X86CC) {
3628   switch (X86CC) {
3629   default:
3630     return false;
3631   case X86::COND_B:
3632   case X86::COND_BE:
3633   case X86::COND_E:
3634   case X86::COND_P:
3635   case X86::COND_A:
3636   case X86::COND_AE:
3637   case X86::COND_NE:
3638   case X86::COND_NP:
3639     return true;
3640   }
3641 }
3642
3643 /// isFPImmLegal - Returns true if the target can instruction select the
3644 /// specified FP immediate natively. If false, the legalizer will
3645 /// materialize the FP immediate as a load from a constant pool.
3646 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3647   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3648     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3649       return true;
3650   }
3651   return false;
3652 }
3653
3654 /// \brief Returns true if it is beneficial to convert a load of a constant
3655 /// to just the constant itself.
3656 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3657                                                           Type *Ty) const {
3658   assert(Ty->isIntegerTy());
3659
3660   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3661   if (BitSize == 0 || BitSize > 64)
3662     return false;
3663   return true;
3664 }
3665
3666 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3667 /// the specified range (L, H].
3668 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3669   return (Val < 0) || (Val >= Low && Val < Hi);
3670 }
3671
3672 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3673 /// specified value.
3674 static bool isUndefOrEqual(int Val, int CmpVal) {
3675   return (Val < 0 || Val == CmpVal);
3676 }
3677
3678 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3679 /// from position Pos and ending in Pos+Size, falls within the specified
3680 /// sequential range (L, L+Pos]. or is undef.
3681 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3682                                        unsigned Pos, unsigned Size, int Low) {
3683   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3684     if (!isUndefOrEqual(Mask[i], Low))
3685       return false;
3686   return true;
3687 }
3688
3689 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3690 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3691 /// the second operand.
3692 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3693   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3694     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3695   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3696     return (Mask[0] < 2 && Mask[1] < 2);
3697   return false;
3698 }
3699
3700 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3701 /// is suitable for input to PSHUFHW.
3702 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3703   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3704     return false;
3705
3706   // Lower quadword copied in order or undef.
3707   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3708     return false;
3709
3710   // Upper quadword shuffled.
3711   for (unsigned i = 4; i != 8; ++i)
3712     if (!isUndefOrInRange(Mask[i], 4, 8))
3713       return false;
3714
3715   if (VT == MVT::v16i16) {
3716     // Lower quadword copied in order or undef.
3717     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3718       return false;
3719
3720     // Upper quadword shuffled.
3721     for (unsigned i = 12; i != 16; ++i)
3722       if (!isUndefOrInRange(Mask[i], 12, 16))
3723         return false;
3724   }
3725
3726   return true;
3727 }
3728
3729 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3730 /// is suitable for input to PSHUFLW.
3731 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3732   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3733     return false;
3734
3735   // Upper quadword copied in order.
3736   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3737     return false;
3738
3739   // Lower quadword shuffled.
3740   for (unsigned i = 0; i != 4; ++i)
3741     if (!isUndefOrInRange(Mask[i], 0, 4))
3742       return false;
3743
3744   if (VT == MVT::v16i16) {
3745     // Upper quadword copied in order.
3746     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3747       return false;
3748
3749     // Lower quadword shuffled.
3750     for (unsigned i = 8; i != 12; ++i)
3751       if (!isUndefOrInRange(Mask[i], 8, 12))
3752         return false;
3753   }
3754
3755   return true;
3756 }
3757
3758 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3759 /// is suitable for input to PALIGNR.
3760 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3761                           const X86Subtarget *Subtarget) {
3762   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3763       (VT.is256BitVector() && !Subtarget->hasInt256()))
3764     return false;
3765
3766   unsigned NumElts = VT.getVectorNumElements();
3767   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3768   unsigned NumLaneElts = NumElts/NumLanes;
3769
3770   // Do not handle 64-bit element shuffles with palignr.
3771   if (NumLaneElts == 2)
3772     return false;
3773
3774   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3775     unsigned i;
3776     for (i = 0; i != NumLaneElts; ++i) {
3777       if (Mask[i+l] >= 0)
3778         break;
3779     }
3780
3781     // Lane is all undef, go to next lane
3782     if (i == NumLaneElts)
3783       continue;
3784
3785     int Start = Mask[i+l];
3786
3787     // Make sure its in this lane in one of the sources
3788     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3789         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3790       return false;
3791
3792     // If not lane 0, then we must match lane 0
3793     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3794       return false;
3795
3796     // Correct second source to be contiguous with first source
3797     if (Start >= (int)NumElts)
3798       Start -= NumElts - NumLaneElts;
3799
3800     // Make sure we're shifting in the right direction.
3801     if (Start <= (int)(i+l))
3802       return false;
3803
3804     Start -= i;
3805
3806     // Check the rest of the elements to see if they are consecutive.
3807     for (++i; i != NumLaneElts; ++i) {
3808       int Idx = Mask[i+l];
3809
3810       // Make sure its in this lane
3811       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3812           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3813         return false;
3814
3815       // If not lane 0, then we must match lane 0
3816       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3817         return false;
3818
3819       if (Idx >= (int)NumElts)
3820         Idx -= NumElts - NumLaneElts;
3821
3822       if (!isUndefOrEqual(Idx, Start+i))
3823         return false;
3824
3825     }
3826   }
3827
3828   return true;
3829 }
3830
3831 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3832 /// the two vector operands have swapped position.
3833 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3834                                      unsigned NumElems) {
3835   for (unsigned i = 0; i != NumElems; ++i) {
3836     int idx = Mask[i];
3837     if (idx < 0)
3838       continue;
3839     else if (idx < (int)NumElems)
3840       Mask[i] = idx + NumElems;
3841     else
3842       Mask[i] = idx - NumElems;
3843   }
3844 }
3845
3846 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3847 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3848 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3849 /// reverse of what x86 shuffles want.
3850 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3851
3852   unsigned NumElems = VT.getVectorNumElements();
3853   unsigned NumLanes = VT.getSizeInBits()/128;
3854   unsigned NumLaneElems = NumElems/NumLanes;
3855
3856   if (NumLaneElems != 2 && NumLaneElems != 4)
3857     return false;
3858
3859   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3860   bool symetricMaskRequired =
3861     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3862
3863   // VSHUFPSY divides the resulting vector into 4 chunks.
3864   // The sources are also splitted into 4 chunks, and each destination
3865   // chunk must come from a different source chunk.
3866   //
3867   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3868   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3869   //
3870   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3871   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3872   //
3873   // VSHUFPDY divides the resulting vector into 4 chunks.
3874   // The sources are also splitted into 4 chunks, and each destination
3875   // chunk must come from a different source chunk.
3876   //
3877   //  SRC1 =>      X3       X2       X1       X0
3878   //  SRC2 =>      Y3       Y2       Y1       Y0
3879   //
3880   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3881   //
3882   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3883   unsigned HalfLaneElems = NumLaneElems/2;
3884   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3885     for (unsigned i = 0; i != NumLaneElems; ++i) {
3886       int Idx = Mask[i+l];
3887       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3888       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3889         return false;
3890       // For VSHUFPSY, the mask of the second half must be the same as the
3891       // first but with the appropriate offsets. This works in the same way as
3892       // VPERMILPS works with masks.
3893       if (!symetricMaskRequired || Idx < 0)
3894         continue;
3895       if (MaskVal[i] < 0) {
3896         MaskVal[i] = Idx - l;
3897         continue;
3898       }
3899       if ((signed)(Idx - l) != MaskVal[i])
3900         return false;
3901     }
3902   }
3903
3904   return true;
3905 }
3906
3907 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3909 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3910   if (!VT.is128BitVector())
3911     return false;
3912
3913   unsigned NumElems = VT.getVectorNumElements();
3914
3915   if (NumElems != 4)
3916     return false;
3917
3918   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3919   return isUndefOrEqual(Mask[0], 6) &&
3920          isUndefOrEqual(Mask[1], 7) &&
3921          isUndefOrEqual(Mask[2], 2) &&
3922          isUndefOrEqual(Mask[3], 3);
3923 }
3924
3925 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3926 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3927 /// <2, 3, 2, 3>
3928 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3929   if (!VT.is128BitVector())
3930     return false;
3931
3932   unsigned NumElems = VT.getVectorNumElements();
3933
3934   if (NumElems != 4)
3935     return false;
3936
3937   return isUndefOrEqual(Mask[0], 2) &&
3938          isUndefOrEqual(Mask[1], 3) &&
3939          isUndefOrEqual(Mask[2], 2) &&
3940          isUndefOrEqual(Mask[3], 3);
3941 }
3942
3943 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3945 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3946   if (!VT.is128BitVector())
3947     return false;
3948
3949   unsigned NumElems = VT.getVectorNumElements();
3950
3951   if (NumElems != 2 && NumElems != 4)
3952     return false;
3953
3954   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3955     if (!isUndefOrEqual(Mask[i], i + NumElems))
3956       return false;
3957
3958   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3959     if (!isUndefOrEqual(Mask[i], i))
3960       return false;
3961
3962   return true;
3963 }
3964
3965 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3967 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3968   if (!VT.is128BitVector())
3969     return false;
3970
3971   unsigned NumElems = VT.getVectorNumElements();
3972
3973   if (NumElems != 2 && NumElems != 4)
3974     return false;
3975
3976   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3977     if (!isUndefOrEqual(Mask[i], i))
3978       return false;
3979
3980   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3981     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3982       return false;
3983
3984   return true;
3985 }
3986
3987 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3988 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3989 /// i. e: If all but one element come from the same vector.
3990 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3991   // TODO: Deal with AVX's VINSERTPS
3992   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3993     return false;
3994
3995   unsigned CorrectPosV1 = 0;
3996   unsigned CorrectPosV2 = 0;
3997   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3998     if (Mask[i] == -1) {
3999       ++CorrectPosV1;
4000       ++CorrectPosV2;
4001       continue;
4002     }
4003
4004     if (Mask[i] == i)
4005       ++CorrectPosV1;
4006     else if (Mask[i] == i + 4)
4007       ++CorrectPosV2;
4008   }
4009
4010   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4011     // We have 3 elements (undefs count as elements from any vector) from one
4012     // vector, and one from another.
4013     return true;
4014
4015   return false;
4016 }
4017
4018 //
4019 // Some special combinations that can be optimized.
4020 //
4021 static
4022 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4023                                SelectionDAG &DAG) {
4024   MVT VT = SVOp->getSimpleValueType(0);
4025   SDLoc dl(SVOp);
4026
4027   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4028     return SDValue();
4029
4030   ArrayRef<int> Mask = SVOp->getMask();
4031
4032   // These are the special masks that may be optimized.
4033   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4034   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4035   bool MatchEvenMask = true;
4036   bool MatchOddMask  = true;
4037   for (int i=0; i<8; ++i) {
4038     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4039       MatchEvenMask = false;
4040     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4041       MatchOddMask = false;
4042   }
4043
4044   if (!MatchEvenMask && !MatchOddMask)
4045     return SDValue();
4046
4047   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4048
4049   SDValue Op0 = SVOp->getOperand(0);
4050   SDValue Op1 = SVOp->getOperand(1);
4051
4052   if (MatchEvenMask) {
4053     // Shift the second operand right to 32 bits.
4054     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4055     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4056   } else {
4057     // Shift the first operand left to 32 bits.
4058     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4059     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4060   }
4061   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4062   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4063 }
4064
4065 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4066 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4067 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4068                          bool HasInt256, bool V2IsSplat = false) {
4069
4070   assert(VT.getSizeInBits() >= 128 &&
4071          "Unsupported vector type for unpckl");
4072
4073   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4074   unsigned NumLanes;
4075   unsigned NumOf256BitLanes;
4076   unsigned NumElts = VT.getVectorNumElements();
4077   if (VT.is256BitVector()) {
4078     if (NumElts != 4 && NumElts != 8 &&
4079         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4080     return false;
4081     NumLanes = 2;
4082     NumOf256BitLanes = 1;
4083   } else if (VT.is512BitVector()) {
4084     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4085            "Unsupported vector type for unpckh");
4086     NumLanes = 2;
4087     NumOf256BitLanes = 2;
4088   } else {
4089     NumLanes = 1;
4090     NumOf256BitLanes = 1;
4091   }
4092
4093   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4094   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4095
4096   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4097     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4098       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4099         int BitI  = Mask[l256*NumEltsInStride+l+i];
4100         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4101         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4102           return false;
4103         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4104           return false;
4105         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4106           return false;
4107       }
4108     }
4109   }
4110   return true;
4111 }
4112
4113 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4114 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4115 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4116                          bool HasInt256, bool V2IsSplat = false) {
4117   assert(VT.getSizeInBits() >= 128 &&
4118          "Unsupported vector type for unpckh");
4119
4120   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4121   unsigned NumLanes;
4122   unsigned NumOf256BitLanes;
4123   unsigned NumElts = VT.getVectorNumElements();
4124   if (VT.is256BitVector()) {
4125     if (NumElts != 4 && NumElts != 8 &&
4126         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4127     return false;
4128     NumLanes = 2;
4129     NumOf256BitLanes = 1;
4130   } else if (VT.is512BitVector()) {
4131     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4132            "Unsupported vector type for unpckh");
4133     NumLanes = 2;
4134     NumOf256BitLanes = 2;
4135   } else {
4136     NumLanes = 1;
4137     NumOf256BitLanes = 1;
4138   }
4139
4140   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4141   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4142
4143   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4144     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4145       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4146         int BitI  = Mask[l256*NumEltsInStride+l+i];
4147         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4148         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4149           return false;
4150         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4151           return false;
4152         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4153           return false;
4154       }
4155     }
4156   }
4157   return true;
4158 }
4159
4160 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4161 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4162 /// <0, 0, 1, 1>
4163 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4164   unsigned NumElts = VT.getVectorNumElements();
4165   bool Is256BitVec = VT.is256BitVector();
4166
4167   if (VT.is512BitVector())
4168     return false;
4169   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4170          "Unsupported vector type for unpckh");
4171
4172   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4173       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4174     return false;
4175
4176   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4177   // FIXME: Need a better way to get rid of this, there's no latency difference
4178   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4179   // the former later. We should also remove the "_undef" special mask.
4180   if (NumElts == 4 && Is256BitVec)
4181     return false;
4182
4183   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4184   // independently on 128-bit lanes.
4185   unsigned NumLanes = VT.getSizeInBits()/128;
4186   unsigned NumLaneElts = NumElts/NumLanes;
4187
4188   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4189     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4190       int BitI  = Mask[l+i];
4191       int BitI1 = Mask[l+i+1];
4192
4193       if (!isUndefOrEqual(BitI, j))
4194         return false;
4195       if (!isUndefOrEqual(BitI1, j))
4196         return false;
4197     }
4198   }
4199
4200   return true;
4201 }
4202
4203 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4204 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4205 /// <2, 2, 3, 3>
4206 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4207   unsigned NumElts = VT.getVectorNumElements();
4208
4209   if (VT.is512BitVector())
4210     return false;
4211
4212   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4213          "Unsupported vector type for unpckh");
4214
4215   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4216       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4217     return false;
4218
4219   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4220   // independently on 128-bit lanes.
4221   unsigned NumLanes = VT.getSizeInBits()/128;
4222   unsigned NumLaneElts = NumElts/NumLanes;
4223
4224   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4225     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4226       int BitI  = Mask[l+i];
4227       int BitI1 = Mask[l+i+1];
4228       if (!isUndefOrEqual(BitI, j))
4229         return false;
4230       if (!isUndefOrEqual(BitI1, j))
4231         return false;
4232     }
4233   }
4234   return true;
4235 }
4236
4237 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4238 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4239 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4240   if (!VT.is512BitVector())
4241     return false;
4242
4243   unsigned NumElts = VT.getVectorNumElements();
4244   unsigned HalfSize = NumElts/2;
4245   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4246     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4247       *Imm = 1;
4248       return true;
4249     }
4250   }
4251   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4252     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4253       *Imm = 0;
4254       return true;
4255     }
4256   }
4257   return false;
4258 }
4259
4260 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4261 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4262 /// MOVSD, and MOVD, i.e. setting the lowest element.
4263 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4264   if (VT.getVectorElementType().getSizeInBits() < 32)
4265     return false;
4266   if (!VT.is128BitVector())
4267     return false;
4268
4269   unsigned NumElts = VT.getVectorNumElements();
4270
4271   if (!isUndefOrEqual(Mask[0], NumElts))
4272     return false;
4273
4274   for (unsigned i = 1; i != NumElts; ++i)
4275     if (!isUndefOrEqual(Mask[i], i))
4276       return false;
4277
4278   return true;
4279 }
4280
4281 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4282 /// as permutations between 128-bit chunks or halves. As an example: this
4283 /// shuffle bellow:
4284 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4285 /// The first half comes from the second half of V1 and the second half from the
4286 /// the second half of V2.
4287 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4288   if (!HasFp256 || !VT.is256BitVector())
4289     return false;
4290
4291   // The shuffle result is divided into half A and half B. In total the two
4292   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4293   // B must come from C, D, E or F.
4294   unsigned HalfSize = VT.getVectorNumElements()/2;
4295   bool MatchA = false, MatchB = false;
4296
4297   // Check if A comes from one of C, D, E, F.
4298   for (unsigned Half = 0; Half != 4; ++Half) {
4299     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4300       MatchA = true;
4301       break;
4302     }
4303   }
4304
4305   // Check if B comes from one of C, D, E, F.
4306   for (unsigned Half = 0; Half != 4; ++Half) {
4307     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4308       MatchB = true;
4309       break;
4310     }
4311   }
4312
4313   return MatchA && MatchB;
4314 }
4315
4316 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4317 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4318 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4319   MVT VT = SVOp->getSimpleValueType(0);
4320
4321   unsigned HalfSize = VT.getVectorNumElements()/2;
4322
4323   unsigned FstHalf = 0, SndHalf = 0;
4324   for (unsigned i = 0; i < HalfSize; ++i) {
4325     if (SVOp->getMaskElt(i) > 0) {
4326       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4327       break;
4328     }
4329   }
4330   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4331     if (SVOp->getMaskElt(i) > 0) {
4332       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4333       break;
4334     }
4335   }
4336
4337   return (FstHalf | (SndHalf << 4));
4338 }
4339
4340 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4341 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4342   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4343   if (EltSize < 32)
4344     return false;
4345
4346   unsigned NumElts = VT.getVectorNumElements();
4347   Imm8 = 0;
4348   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4349     for (unsigned i = 0; i != NumElts; ++i) {
4350       if (Mask[i] < 0)
4351         continue;
4352       Imm8 |= Mask[i] << (i*2);
4353     }
4354     return true;
4355   }
4356
4357   unsigned LaneSize = 4;
4358   SmallVector<int, 4> MaskVal(LaneSize, -1);
4359
4360   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4361     for (unsigned i = 0; i != LaneSize; ++i) {
4362       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4363         return false;
4364       if (Mask[i+l] < 0)
4365         continue;
4366       if (MaskVal[i] < 0) {
4367         MaskVal[i] = Mask[i+l] - l;
4368         Imm8 |= MaskVal[i] << (i*2);
4369         continue;
4370       }
4371       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4372         return false;
4373     }
4374   }
4375   return true;
4376 }
4377
4378 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4379 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4380 /// Note that VPERMIL mask matching is different depending whether theunderlying
4381 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4382 /// to the same elements of the low, but to the higher half of the source.
4383 /// In VPERMILPD the two lanes could be shuffled independently of each other
4384 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4385 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4386   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4387   if (VT.getSizeInBits() < 256 || EltSize < 32)
4388     return false;
4389   bool symetricMaskRequired = (EltSize == 32);
4390   unsigned NumElts = VT.getVectorNumElements();
4391
4392   unsigned NumLanes = VT.getSizeInBits()/128;
4393   unsigned LaneSize = NumElts/NumLanes;
4394   // 2 or 4 elements in one lane
4395
4396   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4397   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4398     for (unsigned i = 0; i != LaneSize; ++i) {
4399       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4400         return false;
4401       if (symetricMaskRequired) {
4402         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4403           ExpectedMaskVal[i] = Mask[i+l] - l;
4404           continue;
4405         }
4406         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4407           return false;
4408       }
4409     }
4410   }
4411   return true;
4412 }
4413
4414 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4415 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4416 /// element of vector 2 and the other elements to come from vector 1 in order.
4417 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4418                                bool V2IsSplat = false, bool V2IsUndef = false) {
4419   if (!VT.is128BitVector())
4420     return false;
4421
4422   unsigned NumOps = VT.getVectorNumElements();
4423   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4424     return false;
4425
4426   if (!isUndefOrEqual(Mask[0], 0))
4427     return false;
4428
4429   for (unsigned i = 1; i != NumOps; ++i)
4430     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4431           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4432           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4433       return false;
4434
4435   return true;
4436 }
4437
4438 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4439 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4440 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4441 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4442                            const X86Subtarget *Subtarget) {
4443   if (!Subtarget->hasSSE3())
4444     return false;
4445
4446   unsigned NumElems = VT.getVectorNumElements();
4447
4448   if ((VT.is128BitVector() && NumElems != 4) ||
4449       (VT.is256BitVector() && NumElems != 8) ||
4450       (VT.is512BitVector() && NumElems != 16))
4451     return false;
4452
4453   // "i+1" is the value the indexed mask element must have
4454   for (unsigned i = 0; i != NumElems; i += 2)
4455     if (!isUndefOrEqual(Mask[i], i+1) ||
4456         !isUndefOrEqual(Mask[i+1], i+1))
4457       return false;
4458
4459   return true;
4460 }
4461
4462 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4463 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4464 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4465 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4466                            const X86Subtarget *Subtarget) {
4467   if (!Subtarget->hasSSE3())
4468     return false;
4469
4470   unsigned NumElems = VT.getVectorNumElements();
4471
4472   if ((VT.is128BitVector() && NumElems != 4) ||
4473       (VT.is256BitVector() && NumElems != 8) ||
4474       (VT.is512BitVector() && NumElems != 16))
4475     return false;
4476
4477   // "i" is the value the indexed mask element must have
4478   for (unsigned i = 0; i != NumElems; i += 2)
4479     if (!isUndefOrEqual(Mask[i], i) ||
4480         !isUndefOrEqual(Mask[i+1], i))
4481       return false;
4482
4483   return true;
4484 }
4485
4486 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4487 /// specifies a shuffle of elements that is suitable for input to 256-bit
4488 /// version of MOVDDUP.
4489 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4490   if (!HasFp256 || !VT.is256BitVector())
4491     return false;
4492
4493   unsigned NumElts = VT.getVectorNumElements();
4494   if (NumElts != 4)
4495     return false;
4496
4497   for (unsigned i = 0; i != NumElts/2; ++i)
4498     if (!isUndefOrEqual(Mask[i], 0))
4499       return false;
4500   for (unsigned i = NumElts/2; i != NumElts; ++i)
4501     if (!isUndefOrEqual(Mask[i], NumElts/2))
4502       return false;
4503   return true;
4504 }
4505
4506 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4507 /// specifies a shuffle of elements that is suitable for input to 128-bit
4508 /// version of MOVDDUP.
4509 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4510   if (!VT.is128BitVector())
4511     return false;
4512
4513   unsigned e = VT.getVectorNumElements() / 2;
4514   for (unsigned i = 0; i != e; ++i)
4515     if (!isUndefOrEqual(Mask[i], i))
4516       return false;
4517   for (unsigned i = 0; i != e; ++i)
4518     if (!isUndefOrEqual(Mask[e+i], i))
4519       return false;
4520   return true;
4521 }
4522
4523 /// isVEXTRACTIndex - Return true if the specified
4524 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4525 /// suitable for instruction that extract 128 or 256 bit vectors
4526 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4527   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4528   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4529     return false;
4530
4531   // The index should be aligned on a vecWidth-bit boundary.
4532   uint64_t Index =
4533     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4534
4535   MVT VT = N->getSimpleValueType(0);
4536   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4537   bool Result = (Index * ElSize) % vecWidth == 0;
4538
4539   return Result;
4540 }
4541
4542 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4543 /// operand specifies a subvector insert that is suitable for input to
4544 /// insertion of 128 or 256-bit subvectors
4545 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4546   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4547   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4548     return false;
4549   // The index should be aligned on a vecWidth-bit boundary.
4550   uint64_t Index =
4551     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4552
4553   MVT VT = N->getSimpleValueType(0);
4554   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4555   bool Result = (Index * ElSize) % vecWidth == 0;
4556
4557   return Result;
4558 }
4559
4560 bool X86::isVINSERT128Index(SDNode *N) {
4561   return isVINSERTIndex(N, 128);
4562 }
4563
4564 bool X86::isVINSERT256Index(SDNode *N) {
4565   return isVINSERTIndex(N, 256);
4566 }
4567
4568 bool X86::isVEXTRACT128Index(SDNode *N) {
4569   return isVEXTRACTIndex(N, 128);
4570 }
4571
4572 bool X86::isVEXTRACT256Index(SDNode *N) {
4573   return isVEXTRACTIndex(N, 256);
4574 }
4575
4576 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4577 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4578 /// Handles 128-bit and 256-bit.
4579 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4580   MVT VT = N->getSimpleValueType(0);
4581
4582   assert((VT.getSizeInBits() >= 128) &&
4583          "Unsupported vector type for PSHUF/SHUFP");
4584
4585   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4586   // independently on 128-bit lanes.
4587   unsigned NumElts = VT.getVectorNumElements();
4588   unsigned NumLanes = VT.getSizeInBits()/128;
4589   unsigned NumLaneElts = NumElts/NumLanes;
4590
4591   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4592          "Only supports 2, 4 or 8 elements per lane");
4593
4594   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4595   unsigned Mask = 0;
4596   for (unsigned i = 0; i != NumElts; ++i) {
4597     int Elt = N->getMaskElt(i);
4598     if (Elt < 0) continue;
4599     Elt &= NumLaneElts - 1;
4600     unsigned ShAmt = (i << Shift) % 8;
4601     Mask |= Elt << ShAmt;
4602   }
4603
4604   return Mask;
4605 }
4606
4607 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4608 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4609 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4610   MVT VT = N->getSimpleValueType(0);
4611
4612   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4613          "Unsupported vector type for PSHUFHW");
4614
4615   unsigned NumElts = VT.getVectorNumElements();
4616
4617   unsigned Mask = 0;
4618   for (unsigned l = 0; l != NumElts; l += 8) {
4619     // 8 nodes per lane, but we only care about the last 4.
4620     for (unsigned i = 0; i < 4; ++i) {
4621       int Elt = N->getMaskElt(l+i+4);
4622       if (Elt < 0) continue;
4623       Elt &= 0x3; // only 2-bits.
4624       Mask |= Elt << (i * 2);
4625     }
4626   }
4627
4628   return Mask;
4629 }
4630
4631 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4632 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4633 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4634   MVT VT = N->getSimpleValueType(0);
4635
4636   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4637          "Unsupported vector type for PSHUFHW");
4638
4639   unsigned NumElts = VT.getVectorNumElements();
4640
4641   unsigned Mask = 0;
4642   for (unsigned l = 0; l != NumElts; l += 8) {
4643     // 8 nodes per lane, but we only care about the first 4.
4644     for (unsigned i = 0; i < 4; ++i) {
4645       int Elt = N->getMaskElt(l+i);
4646       if (Elt < 0) continue;
4647       Elt &= 0x3; // only 2-bits
4648       Mask |= Elt << (i * 2);
4649     }
4650   }
4651
4652   return Mask;
4653 }
4654
4655 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4656 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4657 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4658   MVT VT = SVOp->getSimpleValueType(0);
4659   unsigned EltSize = VT.is512BitVector() ? 1 :
4660     VT.getVectorElementType().getSizeInBits() >> 3;
4661
4662   unsigned NumElts = VT.getVectorNumElements();
4663   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4664   unsigned NumLaneElts = NumElts/NumLanes;
4665
4666   int Val = 0;
4667   unsigned i;
4668   for (i = 0; i != NumElts; ++i) {
4669     Val = SVOp->getMaskElt(i);
4670     if (Val >= 0)
4671       break;
4672   }
4673   if (Val >= (int)NumElts)
4674     Val -= NumElts - NumLaneElts;
4675
4676   assert(Val - i > 0 && "PALIGNR imm should be positive");
4677   return (Val - i) * EltSize;
4678 }
4679
4680 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4681   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4682   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4683     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4684
4685   uint64_t Index =
4686     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4687
4688   MVT VecVT = N->getOperand(0).getSimpleValueType();
4689   MVT ElVT = VecVT.getVectorElementType();
4690
4691   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4692   return Index / NumElemsPerChunk;
4693 }
4694
4695 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4696   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4697   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4698     llvm_unreachable("Illegal insert subvector for VINSERT");
4699
4700   uint64_t Index =
4701     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4702
4703   MVT VecVT = N->getSimpleValueType(0);
4704   MVT ElVT = VecVT.getVectorElementType();
4705
4706   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4707   return Index / NumElemsPerChunk;
4708 }
4709
4710 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4711 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4712 /// and VINSERTI128 instructions.
4713 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4714   return getExtractVEXTRACTImmediate(N, 128);
4715 }
4716
4717 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4718 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4719 /// and VINSERTI64x4 instructions.
4720 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4721   return getExtractVEXTRACTImmediate(N, 256);
4722 }
4723
4724 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4725 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4726 /// and VINSERTI128 instructions.
4727 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4728   return getInsertVINSERTImmediate(N, 128);
4729 }
4730
4731 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4732 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4733 /// and VINSERTI64x4 instructions.
4734 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4735   return getInsertVINSERTImmediate(N, 256);
4736 }
4737
4738 /// isZero - Returns true if Elt is a constant integer zero
4739 static bool isZero(SDValue V) {
4740   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4741   return C && C->isNullValue();
4742 }
4743
4744 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4745 /// constant +0.0.
4746 bool X86::isZeroNode(SDValue Elt) {
4747   if (isZero(Elt))
4748     return true;
4749   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4750     return CFP->getValueAPF().isPosZero();
4751   return false;
4752 }
4753
4754 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4755 /// their permute mask.
4756 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4757                                     SelectionDAG &DAG) {
4758   MVT VT = SVOp->getSimpleValueType(0);
4759   unsigned NumElems = VT.getVectorNumElements();
4760   SmallVector<int, 8> MaskVec;
4761
4762   for (unsigned i = 0; i != NumElems; ++i) {
4763     int Idx = SVOp->getMaskElt(i);
4764     if (Idx >= 0) {
4765       if (Idx < (int)NumElems)
4766         Idx += NumElems;
4767       else
4768         Idx -= NumElems;
4769     }
4770     MaskVec.push_back(Idx);
4771   }
4772   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4773                               SVOp->getOperand(0), &MaskVec[0]);
4774 }
4775
4776 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4777 /// match movhlps. The lower half elements should come from upper half of
4778 /// V1 (and in order), and the upper half elements should come from the upper
4779 /// half of V2 (and in order).
4780 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4781   if (!VT.is128BitVector())
4782     return false;
4783   if (VT.getVectorNumElements() != 4)
4784     return false;
4785   for (unsigned i = 0, e = 2; i != e; ++i)
4786     if (!isUndefOrEqual(Mask[i], i+2))
4787       return false;
4788   for (unsigned i = 2; i != 4; ++i)
4789     if (!isUndefOrEqual(Mask[i], i+4))
4790       return false;
4791   return true;
4792 }
4793
4794 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4795 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4796 /// required.
4797 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4798   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4799     return false;
4800   N = N->getOperand(0).getNode();
4801   if (!ISD::isNON_EXTLoad(N))
4802     return false;
4803   if (LD)
4804     *LD = cast<LoadSDNode>(N);
4805   return true;
4806 }
4807
4808 // Test whether the given value is a vector value which will be legalized
4809 // into a load.
4810 static bool WillBeConstantPoolLoad(SDNode *N) {
4811   if (N->getOpcode() != ISD::BUILD_VECTOR)
4812     return false;
4813
4814   // Check for any non-constant elements.
4815   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4816     switch (N->getOperand(i).getNode()->getOpcode()) {
4817     case ISD::UNDEF:
4818     case ISD::ConstantFP:
4819     case ISD::Constant:
4820       break;
4821     default:
4822       return false;
4823     }
4824
4825   // Vectors of all-zeros and all-ones are materialized with special
4826   // instructions rather than being loaded.
4827   return !ISD::isBuildVectorAllZeros(N) &&
4828          !ISD::isBuildVectorAllOnes(N);
4829 }
4830
4831 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4832 /// match movlp{s|d}. The lower half elements should come from lower half of
4833 /// V1 (and in order), and the upper half elements should come from the upper
4834 /// half of V2 (and in order). And since V1 will become the source of the
4835 /// MOVLP, it must be either a vector load or a scalar load to vector.
4836 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4837                                ArrayRef<int> Mask, MVT VT) {
4838   if (!VT.is128BitVector())
4839     return false;
4840
4841   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4842     return false;
4843   // Is V2 is a vector load, don't do this transformation. We will try to use
4844   // load folding shufps op.
4845   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4846     return false;
4847
4848   unsigned NumElems = VT.getVectorNumElements();
4849
4850   if (NumElems != 2 && NumElems != 4)
4851     return false;
4852   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4853     if (!isUndefOrEqual(Mask[i], i))
4854       return false;
4855   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4856     if (!isUndefOrEqual(Mask[i], i+NumElems))
4857       return false;
4858   return true;
4859 }
4860
4861 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4862 /// to an zero vector.
4863 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4864 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4865   SDValue V1 = N->getOperand(0);
4866   SDValue V2 = N->getOperand(1);
4867   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4868   for (unsigned i = 0; i != NumElems; ++i) {
4869     int Idx = N->getMaskElt(i);
4870     if (Idx >= (int)NumElems) {
4871       unsigned Opc = V2.getOpcode();
4872       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4873         continue;
4874       if (Opc != ISD::BUILD_VECTOR ||
4875           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4876         return false;
4877     } else if (Idx >= 0) {
4878       unsigned Opc = V1.getOpcode();
4879       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4880         continue;
4881       if (Opc != ISD::BUILD_VECTOR ||
4882           !X86::isZeroNode(V1.getOperand(Idx)))
4883         return false;
4884     }
4885   }
4886   return true;
4887 }
4888
4889 /// getZeroVector - Returns a vector of specified type with all zero elements.
4890 ///
4891 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4892                              SelectionDAG &DAG, SDLoc dl) {
4893   assert(VT.isVector() && "Expected a vector type");
4894
4895   // Always build SSE zero vectors as <4 x i32> bitcasted
4896   // to their dest type. This ensures they get CSE'd.
4897   SDValue Vec;
4898   if (VT.is128BitVector()) {  // SSE
4899     if (Subtarget->hasSSE2()) {  // SSE2
4900       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4901       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4902     } else { // SSE1
4903       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4904       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4905     }
4906   } else if (VT.is256BitVector()) { // AVX
4907     if (Subtarget->hasInt256()) { // AVX2
4908       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4909       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4910       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4911     } else {
4912       // 256-bit logic and arithmetic instructions in AVX are all
4913       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4914       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4915       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4916       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4917     }
4918   } else if (VT.is512BitVector()) { // AVX-512
4919       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4920       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4921                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4922       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4923   } else if (VT.getScalarType() == MVT::i1) {
4924     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4925     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4926     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4927     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4928   } else
4929     llvm_unreachable("Unexpected vector type");
4930
4931   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4932 }
4933
4934 /// getOnesVector - Returns a vector of specified type with all bits set.
4935 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4936 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4937 /// Then bitcast to their original type, ensuring they get CSE'd.
4938 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4939                              SDLoc dl) {
4940   assert(VT.isVector() && "Expected a vector type");
4941
4942   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4943   SDValue Vec;
4944   if (VT.is256BitVector()) {
4945     if (HasInt256) { // AVX2
4946       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4947       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4948     } else { // AVX
4949       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4950       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4951     }
4952   } else if (VT.is128BitVector()) {
4953     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4954   } else
4955     llvm_unreachable("Unexpected vector type");
4956
4957   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4958 }
4959
4960 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4961 /// that point to V2 points to its first element.
4962 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4963   for (unsigned i = 0; i != NumElems; ++i) {
4964     if (Mask[i] > (int)NumElems) {
4965       Mask[i] = NumElems;
4966     }
4967   }
4968 }
4969
4970 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4971 /// operation of specified width.
4972 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4973                        SDValue V2) {
4974   unsigned NumElems = VT.getVectorNumElements();
4975   SmallVector<int, 8> Mask;
4976   Mask.push_back(NumElems);
4977   for (unsigned i = 1; i != NumElems; ++i)
4978     Mask.push_back(i);
4979   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4980 }
4981
4982 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4983 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4984                           SDValue V2) {
4985   unsigned NumElems = VT.getVectorNumElements();
4986   SmallVector<int, 8> Mask;
4987   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4988     Mask.push_back(i);
4989     Mask.push_back(i + NumElems);
4990   }
4991   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4992 }
4993
4994 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4995 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4996                           SDValue V2) {
4997   unsigned NumElems = VT.getVectorNumElements();
4998   SmallVector<int, 8> Mask;
4999   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5000     Mask.push_back(i + Half);
5001     Mask.push_back(i + NumElems + Half);
5002   }
5003   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5004 }
5005
5006 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5007 // a generic shuffle instruction because the target has no such instructions.
5008 // Generate shuffles which repeat i16 and i8 several times until they can be
5009 // represented by v4f32 and then be manipulated by target suported shuffles.
5010 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5011   MVT VT = V.getSimpleValueType();
5012   int NumElems = VT.getVectorNumElements();
5013   SDLoc dl(V);
5014
5015   while (NumElems > 4) {
5016     if (EltNo < NumElems/2) {
5017       V = getUnpackl(DAG, dl, VT, V, V);
5018     } else {
5019       V = getUnpackh(DAG, dl, VT, V, V);
5020       EltNo -= NumElems/2;
5021     }
5022     NumElems >>= 1;
5023   }
5024   return V;
5025 }
5026
5027 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5028 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5029   MVT VT = V.getSimpleValueType();
5030   SDLoc dl(V);
5031
5032   if (VT.is128BitVector()) {
5033     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5034     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5035     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5036                              &SplatMask[0]);
5037   } else if (VT.is256BitVector()) {
5038     // To use VPERMILPS to splat scalars, the second half of indicies must
5039     // refer to the higher part, which is a duplication of the lower one,
5040     // because VPERMILPS can only handle in-lane permutations.
5041     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5042                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5043
5044     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5045     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5046                              &SplatMask[0]);
5047   } else
5048     llvm_unreachable("Vector size not supported");
5049
5050   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5051 }
5052
5053 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5054 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5055   MVT SrcVT = SV->getSimpleValueType(0);
5056   SDValue V1 = SV->getOperand(0);
5057   SDLoc dl(SV);
5058
5059   int EltNo = SV->getSplatIndex();
5060   int NumElems = SrcVT.getVectorNumElements();
5061   bool Is256BitVec = SrcVT.is256BitVector();
5062
5063   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5064          "Unknown how to promote splat for type");
5065
5066   // Extract the 128-bit part containing the splat element and update
5067   // the splat element index when it refers to the higher register.
5068   if (Is256BitVec) {
5069     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5070     if (EltNo >= NumElems/2)
5071       EltNo -= NumElems/2;
5072   }
5073
5074   // All i16 and i8 vector types can't be used directly by a generic shuffle
5075   // instruction because the target has no such instruction. Generate shuffles
5076   // which repeat i16 and i8 several times until they fit in i32, and then can
5077   // be manipulated by target suported shuffles.
5078   MVT EltVT = SrcVT.getVectorElementType();
5079   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5080     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5081
5082   // Recreate the 256-bit vector and place the same 128-bit vector
5083   // into the low and high part. This is necessary because we want
5084   // to use VPERM* to shuffle the vectors
5085   if (Is256BitVec) {
5086     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5087   }
5088
5089   return getLegalSplat(DAG, V1, EltNo);
5090 }
5091
5092 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5093 /// vector of zero or undef vector.  This produces a shuffle where the low
5094 /// element of V2 is swizzled into the zero/undef vector, landing at element
5095 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5096 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5097                                            bool IsZero,
5098                                            const X86Subtarget *Subtarget,
5099                                            SelectionDAG &DAG) {
5100   MVT VT = V2.getSimpleValueType();
5101   SDValue V1 = IsZero
5102     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5103   unsigned NumElems = VT.getVectorNumElements();
5104   SmallVector<int, 16> MaskVec;
5105   for (unsigned i = 0; i != NumElems; ++i)
5106     // If this is the insertion idx, put the low elt of V2 here.
5107     MaskVec.push_back(i == Idx ? NumElems : i);
5108   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5109 }
5110
5111 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5112 /// target specific opcode. Returns true if the Mask could be calculated.
5113 /// Sets IsUnary to true if only uses one source.
5114 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5115                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5116   unsigned NumElems = VT.getVectorNumElements();
5117   SDValue ImmN;
5118
5119   IsUnary = false;
5120   switch(N->getOpcode()) {
5121   case X86ISD::SHUFP:
5122     ImmN = N->getOperand(N->getNumOperands()-1);
5123     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5124     break;
5125   case X86ISD::UNPCKH:
5126     DecodeUNPCKHMask(VT, Mask);
5127     break;
5128   case X86ISD::UNPCKL:
5129     DecodeUNPCKLMask(VT, Mask);
5130     break;
5131   case X86ISD::MOVHLPS:
5132     DecodeMOVHLPSMask(NumElems, Mask);
5133     break;
5134   case X86ISD::MOVLHPS:
5135     DecodeMOVLHPSMask(NumElems, Mask);
5136     break;
5137   case X86ISD::PALIGNR:
5138     ImmN = N->getOperand(N->getNumOperands()-1);
5139     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5140     break;
5141   case X86ISD::PSHUFD:
5142   case X86ISD::VPERMILP:
5143     ImmN = N->getOperand(N->getNumOperands()-1);
5144     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5145     IsUnary = true;
5146     break;
5147   case X86ISD::PSHUFHW:
5148     ImmN = N->getOperand(N->getNumOperands()-1);
5149     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5150     IsUnary = true;
5151     break;
5152   case X86ISD::PSHUFLW:
5153     ImmN = N->getOperand(N->getNumOperands()-1);
5154     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5155     IsUnary = true;
5156     break;
5157   case X86ISD::VPERMI:
5158     ImmN = N->getOperand(N->getNumOperands()-1);
5159     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5160     IsUnary = true;
5161     break;
5162   case X86ISD::MOVSS:
5163   case X86ISD::MOVSD: {
5164     // The index 0 always comes from the first element of the second source,
5165     // this is why MOVSS and MOVSD are used in the first place. The other
5166     // elements come from the other positions of the first source vector
5167     Mask.push_back(NumElems);
5168     for (unsigned i = 1; i != NumElems; ++i) {
5169       Mask.push_back(i);
5170     }
5171     break;
5172   }
5173   case X86ISD::VPERM2X128:
5174     ImmN = N->getOperand(N->getNumOperands()-1);
5175     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5176     if (Mask.empty()) return false;
5177     break;
5178   case X86ISD::MOVDDUP:
5179   case X86ISD::MOVLHPD:
5180   case X86ISD::MOVLPD:
5181   case X86ISD::MOVLPS:
5182   case X86ISD::MOVSHDUP:
5183   case X86ISD::MOVSLDUP:
5184     // Not yet implemented
5185     return false;
5186   default: llvm_unreachable("unknown target shuffle node");
5187   }
5188
5189   return true;
5190 }
5191
5192 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5193 /// element of the result of the vector shuffle.
5194 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5195                                    unsigned Depth) {
5196   if (Depth == 6)
5197     return SDValue();  // Limit search depth.
5198
5199   SDValue V = SDValue(N, 0);
5200   EVT VT = V.getValueType();
5201   unsigned Opcode = V.getOpcode();
5202
5203   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5204   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5205     int Elt = SV->getMaskElt(Index);
5206
5207     if (Elt < 0)
5208       return DAG.getUNDEF(VT.getVectorElementType());
5209
5210     unsigned NumElems = VT.getVectorNumElements();
5211     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5212                                          : SV->getOperand(1);
5213     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5214   }
5215
5216   // Recurse into target specific vector shuffles to find scalars.
5217   if (isTargetShuffle(Opcode)) {
5218     MVT ShufVT = V.getSimpleValueType();
5219     unsigned NumElems = ShufVT.getVectorNumElements();
5220     SmallVector<int, 16> ShuffleMask;
5221     bool IsUnary;
5222
5223     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5224       return SDValue();
5225
5226     int Elt = ShuffleMask[Index];
5227     if (Elt < 0)
5228       return DAG.getUNDEF(ShufVT.getVectorElementType());
5229
5230     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5231                                          : N->getOperand(1);
5232     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5233                                Depth+1);
5234   }
5235
5236   // Actual nodes that may contain scalar elements
5237   if (Opcode == ISD::BITCAST) {
5238     V = V.getOperand(0);
5239     EVT SrcVT = V.getValueType();
5240     unsigned NumElems = VT.getVectorNumElements();
5241
5242     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5243       return SDValue();
5244   }
5245
5246   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5247     return (Index == 0) ? V.getOperand(0)
5248                         : DAG.getUNDEF(VT.getVectorElementType());
5249
5250   if (V.getOpcode() == ISD::BUILD_VECTOR)
5251     return V.getOperand(Index);
5252
5253   return SDValue();
5254 }
5255
5256 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5257 /// shuffle operation which come from a consecutively from a zero. The
5258 /// search can start in two different directions, from left or right.
5259 /// We count undefs as zeros until PreferredNum is reached.
5260 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5261                                          unsigned NumElems, bool ZerosFromLeft,
5262                                          SelectionDAG &DAG,
5263                                          unsigned PreferredNum = -1U) {
5264   unsigned NumZeros = 0;
5265   for (unsigned i = 0; i != NumElems; ++i) {
5266     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5267     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5268     if (!Elt.getNode())
5269       break;
5270
5271     if (X86::isZeroNode(Elt))
5272       ++NumZeros;
5273     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5274       NumZeros = std::min(NumZeros + 1, PreferredNum);
5275     else
5276       break;
5277   }
5278
5279   return NumZeros;
5280 }
5281
5282 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5283 /// correspond consecutively to elements from one of the vector operands,
5284 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5285 static
5286 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5287                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5288                               unsigned NumElems, unsigned &OpNum) {
5289   bool SeenV1 = false;
5290   bool SeenV2 = false;
5291
5292   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5293     int Idx = SVOp->getMaskElt(i);
5294     // Ignore undef indicies
5295     if (Idx < 0)
5296       continue;
5297
5298     if (Idx < (int)NumElems)
5299       SeenV1 = true;
5300     else
5301       SeenV2 = true;
5302
5303     // Only accept consecutive elements from the same vector
5304     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5305       return false;
5306   }
5307
5308   OpNum = SeenV1 ? 0 : 1;
5309   return true;
5310 }
5311
5312 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5313 /// logical left shift of a vector.
5314 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5315                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5316   unsigned NumElems =
5317     SVOp->getSimpleValueType(0).getVectorNumElements();
5318   unsigned NumZeros = getNumOfConsecutiveZeros(
5319       SVOp, NumElems, false /* check zeros from right */, DAG,
5320       SVOp->getMaskElt(0));
5321   unsigned OpSrc;
5322
5323   if (!NumZeros)
5324     return false;
5325
5326   // Considering the elements in the mask that are not consecutive zeros,
5327   // check if they consecutively come from only one of the source vectors.
5328   //
5329   //               V1 = {X, A, B, C}     0
5330   //                         \  \  \    /
5331   //   vector_shuffle V1, V2 <1, 2, 3, X>
5332   //
5333   if (!isShuffleMaskConsecutive(SVOp,
5334             0,                   // Mask Start Index
5335             NumElems-NumZeros,   // Mask End Index(exclusive)
5336             NumZeros,            // Where to start looking in the src vector
5337             NumElems,            // Number of elements in vector
5338             OpSrc))              // Which source operand ?
5339     return false;
5340
5341   isLeft = false;
5342   ShAmt = NumZeros;
5343   ShVal = SVOp->getOperand(OpSrc);
5344   return true;
5345 }
5346
5347 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5348 /// logical left shift of a vector.
5349 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5350                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5351   unsigned NumElems =
5352     SVOp->getSimpleValueType(0).getVectorNumElements();
5353   unsigned NumZeros = getNumOfConsecutiveZeros(
5354       SVOp, NumElems, true /* check zeros from left */, DAG,
5355       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5356   unsigned OpSrc;
5357
5358   if (!NumZeros)
5359     return false;
5360
5361   // Considering the elements in the mask that are not consecutive zeros,
5362   // check if they consecutively come from only one of the source vectors.
5363   //
5364   //                           0    { A, B, X, X } = V2
5365   //                          / \    /  /
5366   //   vector_shuffle V1, V2 <X, X, 4, 5>
5367   //
5368   if (!isShuffleMaskConsecutive(SVOp,
5369             NumZeros,     // Mask Start Index
5370             NumElems,     // Mask End Index(exclusive)
5371             0,            // Where to start looking in the src vector
5372             NumElems,     // Number of elements in vector
5373             OpSrc))       // Which source operand ?
5374     return false;
5375
5376   isLeft = true;
5377   ShAmt = NumZeros;
5378   ShVal = SVOp->getOperand(OpSrc);
5379   return true;
5380 }
5381
5382 /// isVectorShift - Returns true if the shuffle can be implemented as a
5383 /// logical left or right shift of a vector.
5384 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5385                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5386   // Although the logic below support any bitwidth size, there are no
5387   // shift instructions which handle more than 128-bit vectors.
5388   if (!SVOp->getSimpleValueType(0).is128BitVector())
5389     return false;
5390
5391   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5392       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5393     return true;
5394
5395   return false;
5396 }
5397
5398 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5399 ///
5400 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5401                                        unsigned NumNonZero, unsigned NumZero,
5402                                        SelectionDAG &DAG,
5403                                        const X86Subtarget* Subtarget,
5404                                        const TargetLowering &TLI) {
5405   if (NumNonZero > 8)
5406     return SDValue();
5407
5408   SDLoc dl(Op);
5409   SDValue V;
5410   bool First = true;
5411   for (unsigned i = 0; i < 16; ++i) {
5412     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5413     if (ThisIsNonZero && First) {
5414       if (NumZero)
5415         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5416       else
5417         V = DAG.getUNDEF(MVT::v8i16);
5418       First = false;
5419     }
5420
5421     if ((i & 1) != 0) {
5422       SDValue ThisElt, LastElt;
5423       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5424       if (LastIsNonZero) {
5425         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5426                               MVT::i16, Op.getOperand(i-1));
5427       }
5428       if (ThisIsNonZero) {
5429         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5430         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5431                               ThisElt, DAG.getConstant(8, MVT::i8));
5432         if (LastIsNonZero)
5433           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5434       } else
5435         ThisElt = LastElt;
5436
5437       if (ThisElt.getNode())
5438         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5439                         DAG.getIntPtrConstant(i/2));
5440     }
5441   }
5442
5443   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5444 }
5445
5446 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5447 ///
5448 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5449                                      unsigned NumNonZero, unsigned NumZero,
5450                                      SelectionDAG &DAG,
5451                                      const X86Subtarget* Subtarget,
5452                                      const TargetLowering &TLI) {
5453   if (NumNonZero > 4)
5454     return SDValue();
5455
5456   SDLoc dl(Op);
5457   SDValue V;
5458   bool First = true;
5459   for (unsigned i = 0; i < 8; ++i) {
5460     bool isNonZero = (NonZeros & (1 << i)) != 0;
5461     if (isNonZero) {
5462       if (First) {
5463         if (NumZero)
5464           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5465         else
5466           V = DAG.getUNDEF(MVT::v8i16);
5467         First = false;
5468       }
5469       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5470                       MVT::v8i16, V, Op.getOperand(i),
5471                       DAG.getIntPtrConstant(i));
5472     }
5473   }
5474
5475   return V;
5476 }
5477
5478 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5479 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5480                                      unsigned NonZeros, unsigned NumNonZero,
5481                                      unsigned NumZero, SelectionDAG &DAG,
5482                                      const X86Subtarget *Subtarget,
5483                                      const TargetLowering &TLI) {
5484   // We know there's at least one non-zero element
5485   unsigned FirstNonZeroIdx = 0;
5486   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5487   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5488          X86::isZeroNode(FirstNonZero)) {
5489     ++FirstNonZeroIdx;
5490     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5491   }
5492
5493   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5494       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5495     return SDValue();
5496
5497   SDValue V = FirstNonZero.getOperand(0);
5498   MVT VVT = V.getSimpleValueType();
5499   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5500     return SDValue();
5501
5502   unsigned FirstNonZeroDst =
5503       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5504   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5505   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5506   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5507
5508   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5509     SDValue Elem = Op.getOperand(Idx);
5510     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5511       continue;
5512
5513     // TODO: What else can be here? Deal with it.
5514     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5515       return SDValue();
5516
5517     // TODO: Some optimizations are still possible here
5518     // ex: Getting one element from a vector, and the rest from another.
5519     if (Elem.getOperand(0) != V)
5520       return SDValue();
5521
5522     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5523     if (Dst == Idx)
5524       ++CorrectIdx;
5525     else if (IncorrectIdx == -1U) {
5526       IncorrectIdx = Idx;
5527       IncorrectDst = Dst;
5528     } else
5529       // There was already one element with an incorrect index.
5530       // We can't optimize this case to an insertps.
5531       return SDValue();
5532   }
5533
5534   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5535     SDLoc dl(Op);
5536     EVT VT = Op.getSimpleValueType();
5537     unsigned ElementMoveMask = 0;
5538     if (IncorrectIdx == -1U)
5539       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5540     else
5541       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5542
5543     SDValue InsertpsMask =
5544         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5545     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5546   }
5547
5548   return SDValue();
5549 }
5550
5551 /// getVShift - Return a vector logical shift node.
5552 ///
5553 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5554                          unsigned NumBits, SelectionDAG &DAG,
5555                          const TargetLowering &TLI, SDLoc dl) {
5556   assert(VT.is128BitVector() && "Unknown type for VShift");
5557   EVT ShVT = MVT::v2i64;
5558   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5559   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5560   return DAG.getNode(ISD::BITCAST, dl, VT,
5561                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5562                              DAG.getConstant(NumBits,
5563                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5564 }
5565
5566 static SDValue
5567 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5568
5569   // Check if the scalar load can be widened into a vector load. And if
5570   // the address is "base + cst" see if the cst can be "absorbed" into
5571   // the shuffle mask.
5572   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5573     SDValue Ptr = LD->getBasePtr();
5574     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5575       return SDValue();
5576     EVT PVT = LD->getValueType(0);
5577     if (PVT != MVT::i32 && PVT != MVT::f32)
5578       return SDValue();
5579
5580     int FI = -1;
5581     int64_t Offset = 0;
5582     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5583       FI = FINode->getIndex();
5584       Offset = 0;
5585     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5586                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5587       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5588       Offset = Ptr.getConstantOperandVal(1);
5589       Ptr = Ptr.getOperand(0);
5590     } else {
5591       return SDValue();
5592     }
5593
5594     // FIXME: 256-bit vector instructions don't require a strict alignment,
5595     // improve this code to support it better.
5596     unsigned RequiredAlign = VT.getSizeInBits()/8;
5597     SDValue Chain = LD->getChain();
5598     // Make sure the stack object alignment is at least 16 or 32.
5599     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5600     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5601       if (MFI->isFixedObjectIndex(FI)) {
5602         // Can't change the alignment. FIXME: It's possible to compute
5603         // the exact stack offset and reference FI + adjust offset instead.
5604         // If someone *really* cares about this. That's the way to implement it.
5605         return SDValue();
5606       } else {
5607         MFI->setObjectAlignment(FI, RequiredAlign);
5608       }
5609     }
5610
5611     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5612     // Ptr + (Offset & ~15).
5613     if (Offset < 0)
5614       return SDValue();
5615     if ((Offset % RequiredAlign) & 3)
5616       return SDValue();
5617     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5618     if (StartOffset)
5619       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5620                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5621
5622     int EltNo = (Offset - StartOffset) >> 2;
5623     unsigned NumElems = VT.getVectorNumElements();
5624
5625     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5626     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5627                              LD->getPointerInfo().getWithOffset(StartOffset),
5628                              false, false, false, 0);
5629
5630     SmallVector<int, 8> Mask;
5631     for (unsigned i = 0; i != NumElems; ++i)
5632       Mask.push_back(EltNo);
5633
5634     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5635   }
5636
5637   return SDValue();
5638 }
5639
5640 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5641 /// vector of type 'VT', see if the elements can be replaced by a single large
5642 /// load which has the same value as a build_vector whose operands are 'elts'.
5643 ///
5644 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5645 ///
5646 /// FIXME: we'd also like to handle the case where the last elements are zero
5647 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5648 /// There's even a handy isZeroNode for that purpose.
5649 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5650                                         SDLoc &DL, SelectionDAG &DAG,
5651                                         bool isAfterLegalize) {
5652   EVT EltVT = VT.getVectorElementType();
5653   unsigned NumElems = Elts.size();
5654
5655   LoadSDNode *LDBase = nullptr;
5656   unsigned LastLoadedElt = -1U;
5657
5658   // For each element in the initializer, see if we've found a load or an undef.
5659   // If we don't find an initial load element, or later load elements are
5660   // non-consecutive, bail out.
5661   for (unsigned i = 0; i < NumElems; ++i) {
5662     SDValue Elt = Elts[i];
5663
5664     if (!Elt.getNode() ||
5665         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5666       return SDValue();
5667     if (!LDBase) {
5668       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5669         return SDValue();
5670       LDBase = cast<LoadSDNode>(Elt.getNode());
5671       LastLoadedElt = i;
5672       continue;
5673     }
5674     if (Elt.getOpcode() == ISD::UNDEF)
5675       continue;
5676
5677     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5678     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5679       return SDValue();
5680     LastLoadedElt = i;
5681   }
5682
5683   // If we have found an entire vector of loads and undefs, then return a large
5684   // load of the entire vector width starting at the base pointer.  If we found
5685   // consecutive loads for the low half, generate a vzext_load node.
5686   if (LastLoadedElt == NumElems - 1) {
5687
5688     if (isAfterLegalize &&
5689         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5690       return SDValue();
5691
5692     SDValue NewLd = SDValue();
5693
5694     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5695       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5696                           LDBase->getPointerInfo(),
5697                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5698                           LDBase->isInvariant(), 0);
5699     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5700                         LDBase->getPointerInfo(),
5701                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5702                         LDBase->isInvariant(), LDBase->getAlignment());
5703
5704     if (LDBase->hasAnyUseOfValue(1)) {
5705       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5706                                      SDValue(LDBase, 1),
5707                                      SDValue(NewLd.getNode(), 1));
5708       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5709       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5710                              SDValue(NewLd.getNode(), 1));
5711     }
5712
5713     return NewLd;
5714   }
5715   if (NumElems == 4 && LastLoadedElt == 1 &&
5716       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5717     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5718     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5719     SDValue ResNode =
5720         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5721                                 LDBase->getPointerInfo(),
5722                                 LDBase->getAlignment(),
5723                                 false/*isVolatile*/, true/*ReadMem*/,
5724                                 false/*WriteMem*/);
5725
5726     // Make sure the newly-created LOAD is in the same position as LDBase in
5727     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5728     // update uses of LDBase's output chain to use the TokenFactor.
5729     if (LDBase->hasAnyUseOfValue(1)) {
5730       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5731                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5732       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5733       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5734                              SDValue(ResNode.getNode(), 1));
5735     }
5736
5737     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5738   }
5739   return SDValue();
5740 }
5741
5742 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5743 /// to generate a splat value for the following cases:
5744 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5745 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5746 /// a scalar load, or a constant.
5747 /// The VBROADCAST node is returned when a pattern is found,
5748 /// or SDValue() otherwise.
5749 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5750                                     SelectionDAG &DAG) {
5751   if (!Subtarget->hasFp256())
5752     return SDValue();
5753
5754   MVT VT = Op.getSimpleValueType();
5755   SDLoc dl(Op);
5756
5757   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5758          "Unsupported vector type for broadcast.");
5759
5760   SDValue Ld;
5761   bool ConstSplatVal;
5762
5763   switch (Op.getOpcode()) {
5764     default:
5765       // Unknown pattern found.
5766       return SDValue();
5767
5768     case ISD::BUILD_VECTOR: {
5769       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5770       BitVector UndefElements;
5771       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5772
5773       // We need a splat of a single value to use broadcast, and it doesn't
5774       // make any sense if the value is only in one element of the vector.
5775       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5776         return SDValue();
5777
5778       Ld = Splat;
5779       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5780                        Ld.getOpcode() == ISD::ConstantFP);
5781
5782       // Make sure that all of the users of a non-constant load are from the
5783       // BUILD_VECTOR node.
5784       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5785         return SDValue();
5786       break;
5787     }
5788
5789     case ISD::VECTOR_SHUFFLE: {
5790       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5791
5792       // Shuffles must have a splat mask where the first element is
5793       // broadcasted.
5794       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5795         return SDValue();
5796
5797       SDValue Sc = Op.getOperand(0);
5798       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5799           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5800
5801         if (!Subtarget->hasInt256())
5802           return SDValue();
5803
5804         // Use the register form of the broadcast instruction available on AVX2.
5805         if (VT.getSizeInBits() >= 256)
5806           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5807         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5808       }
5809
5810       Ld = Sc.getOperand(0);
5811       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5812                        Ld.getOpcode() == ISD::ConstantFP);
5813
5814       // The scalar_to_vector node and the suspected
5815       // load node must have exactly one user.
5816       // Constants may have multiple users.
5817
5818       // AVX-512 has register version of the broadcast
5819       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5820         Ld.getValueType().getSizeInBits() >= 32;
5821       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5822           !hasRegVer))
5823         return SDValue();
5824       break;
5825     }
5826   }
5827
5828   bool IsGE256 = (VT.getSizeInBits() >= 256);
5829
5830   // Handle the broadcasting a single constant scalar from the constant pool
5831   // into a vector. On Sandybridge it is still better to load a constant vector
5832   // from the constant pool and not to broadcast it from a scalar.
5833   if (ConstSplatVal && Subtarget->hasInt256()) {
5834     EVT CVT = Ld.getValueType();
5835     assert(!CVT.isVector() && "Must not broadcast a vector type");
5836     unsigned ScalarSize = CVT.getSizeInBits();
5837
5838     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5839       const Constant *C = nullptr;
5840       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5841         C = CI->getConstantIntValue();
5842       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5843         C = CF->getConstantFPValue();
5844
5845       assert(C && "Invalid constant type");
5846
5847       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5848       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5849       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5850       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5851                        MachinePointerInfo::getConstantPool(),
5852                        false, false, false, Alignment);
5853
5854       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5855     }
5856   }
5857
5858   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5859   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5860
5861   // Handle AVX2 in-register broadcasts.
5862   if (!IsLoad && Subtarget->hasInt256() &&
5863       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5864     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5865
5866   // The scalar source must be a normal load.
5867   if (!IsLoad)
5868     return SDValue();
5869
5870   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5871     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5872
5873   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5874   // double since there is no vbroadcastsd xmm
5875   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5876     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5877       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5878   }
5879
5880   // Unsupported broadcast.
5881   return SDValue();
5882 }
5883
5884 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5885 /// underlying vector and index.
5886 ///
5887 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5888 /// index.
5889 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5890                                          SDValue ExtIdx) {
5891   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5892   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5893     return Idx;
5894
5895   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5896   // lowered this:
5897   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5898   // to:
5899   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5900   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5901   //                           undef)
5902   //                       Constant<0>)
5903   // In this case the vector is the extract_subvector expression and the index
5904   // is 2, as specified by the shuffle.
5905   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5906   SDValue ShuffleVec = SVOp->getOperand(0);
5907   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5908   assert(ShuffleVecVT.getVectorElementType() ==
5909          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5910
5911   int ShuffleIdx = SVOp->getMaskElt(Idx);
5912   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5913     ExtractedFromVec = ShuffleVec;
5914     return ShuffleIdx;
5915   }
5916   return Idx;
5917 }
5918
5919 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5920   MVT VT = Op.getSimpleValueType();
5921
5922   // Skip if insert_vec_elt is not supported.
5923   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5924   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5925     return SDValue();
5926
5927   SDLoc DL(Op);
5928   unsigned NumElems = Op.getNumOperands();
5929
5930   SDValue VecIn1;
5931   SDValue VecIn2;
5932   SmallVector<unsigned, 4> InsertIndices;
5933   SmallVector<int, 8> Mask(NumElems, -1);
5934
5935   for (unsigned i = 0; i != NumElems; ++i) {
5936     unsigned Opc = Op.getOperand(i).getOpcode();
5937
5938     if (Opc == ISD::UNDEF)
5939       continue;
5940
5941     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5942       // Quit if more than 1 elements need inserting.
5943       if (InsertIndices.size() > 1)
5944         return SDValue();
5945
5946       InsertIndices.push_back(i);
5947       continue;
5948     }
5949
5950     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5951     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5952     // Quit if non-constant index.
5953     if (!isa<ConstantSDNode>(ExtIdx))
5954       return SDValue();
5955     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5956
5957     // Quit if extracted from vector of different type.
5958     if (ExtractedFromVec.getValueType() != VT)
5959       return SDValue();
5960
5961     if (!VecIn1.getNode())
5962       VecIn1 = ExtractedFromVec;
5963     else if (VecIn1 != ExtractedFromVec) {
5964       if (!VecIn2.getNode())
5965         VecIn2 = ExtractedFromVec;
5966       else if (VecIn2 != ExtractedFromVec)
5967         // Quit if more than 2 vectors to shuffle
5968         return SDValue();
5969     }
5970
5971     if (ExtractedFromVec == VecIn1)
5972       Mask[i] = Idx;
5973     else if (ExtractedFromVec == VecIn2)
5974       Mask[i] = Idx + NumElems;
5975   }
5976
5977   if (!VecIn1.getNode())
5978     return SDValue();
5979
5980   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5981   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5982   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5983     unsigned Idx = InsertIndices[i];
5984     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5985                      DAG.getIntPtrConstant(Idx));
5986   }
5987
5988   return NV;
5989 }
5990
5991 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5992 SDValue
5993 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5994
5995   MVT VT = Op.getSimpleValueType();
5996   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5997          "Unexpected type in LowerBUILD_VECTORvXi1!");
5998
5999   SDLoc dl(Op);
6000   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6001     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6002     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6004   }
6005
6006   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6007     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6008     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6009     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6010   }
6011
6012   bool AllContants = true;
6013   uint64_t Immediate = 0;
6014   int NonConstIdx = -1;
6015   bool IsSplat = true;
6016   unsigned NumNonConsts = 0;
6017   unsigned NumConsts = 0;
6018   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6019     SDValue In = Op.getOperand(idx);
6020     if (In.getOpcode() == ISD::UNDEF)
6021       continue;
6022     if (!isa<ConstantSDNode>(In)) {
6023       AllContants = false;
6024       NonConstIdx = idx;
6025       NumNonConsts++;
6026     }
6027     else {
6028       NumConsts++;
6029       if (cast<ConstantSDNode>(In)->getZExtValue())
6030       Immediate |= (1ULL << idx);
6031     }
6032     if (In != Op.getOperand(0))
6033       IsSplat = false;
6034   }
6035
6036   if (AllContants) {
6037     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6038       DAG.getConstant(Immediate, MVT::i16));
6039     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6040                        DAG.getIntPtrConstant(0));
6041   }
6042
6043   if (NumNonConsts == 1 && NonConstIdx != 0) {
6044     SDValue DstVec;
6045     if (NumConsts) {
6046       SDValue VecAsImm = DAG.getConstant(Immediate,
6047                                          MVT::getIntegerVT(VT.getSizeInBits()));
6048       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6049     }
6050     else 
6051       DstVec = DAG.getUNDEF(VT);
6052     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6053                        Op.getOperand(NonConstIdx),
6054                        DAG.getIntPtrConstant(NonConstIdx));
6055   }
6056   if (!IsSplat && (NonConstIdx != 0))
6057     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6058   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6059   SDValue Select;
6060   if (IsSplat)
6061     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6062                           DAG.getConstant(-1, SelectVT),
6063                           DAG.getConstant(0, SelectVT));
6064   else
6065     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6066                          DAG.getConstant((Immediate | 1), SelectVT),
6067                          DAG.getConstant(Immediate, SelectVT));
6068   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6069 }
6070
6071 /// \brief Return true if \p N implements a horizontal binop and return the
6072 /// operands for the horizontal binop into V0 and V1.
6073 /// 
6074 /// This is a helper function of PerformBUILD_VECTORCombine.
6075 /// This function checks that the build_vector \p N in input implements a
6076 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6077 /// operation to match.
6078 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6079 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6080 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6081 /// arithmetic sub.
6082 ///
6083 /// This function only analyzes elements of \p N whose indices are
6084 /// in range [BaseIdx, LastIdx).
6085 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6086                               SelectionDAG &DAG,
6087                               unsigned BaseIdx, unsigned LastIdx,
6088                               SDValue &V0, SDValue &V1) {
6089   EVT VT = N->getValueType(0);
6090
6091   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6092   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6093          "Invalid Vector in input!");
6094   
6095   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6096   bool CanFold = true;
6097   unsigned ExpectedVExtractIdx = BaseIdx;
6098   unsigned NumElts = LastIdx - BaseIdx;
6099   V0 = DAG.getUNDEF(VT);
6100   V1 = DAG.getUNDEF(VT);
6101
6102   // Check if N implements a horizontal binop.
6103   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6104     SDValue Op = N->getOperand(i + BaseIdx);
6105
6106     // Skip UNDEFs.
6107     if (Op->getOpcode() == ISD::UNDEF) {
6108       // Update the expected vector extract index.
6109       if (i * 2 == NumElts)
6110         ExpectedVExtractIdx = BaseIdx;
6111       ExpectedVExtractIdx += 2;
6112       continue;
6113     }
6114
6115     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6116
6117     if (!CanFold)
6118       break;
6119
6120     SDValue Op0 = Op.getOperand(0);
6121     SDValue Op1 = Op.getOperand(1);
6122
6123     // Try to match the following pattern:
6124     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6125     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6126         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6127         Op0.getOperand(0) == Op1.getOperand(0) &&
6128         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6129         isa<ConstantSDNode>(Op1.getOperand(1)));
6130     if (!CanFold)
6131       break;
6132
6133     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6134     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6135
6136     if (i * 2 < NumElts) {
6137       if (V0.getOpcode() == ISD::UNDEF)
6138         V0 = Op0.getOperand(0);
6139     } else {
6140       if (V1.getOpcode() == ISD::UNDEF)
6141         V1 = Op0.getOperand(0);
6142       if (i * 2 == NumElts)
6143         ExpectedVExtractIdx = BaseIdx;
6144     }
6145
6146     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6147     if (I0 == ExpectedVExtractIdx)
6148       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6149     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6150       // Try to match the following dag sequence:
6151       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6152       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6153     } else
6154       CanFold = false;
6155
6156     ExpectedVExtractIdx += 2;
6157   }
6158
6159   return CanFold;
6160 }
6161
6162 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6163 /// a concat_vector. 
6164 ///
6165 /// This is a helper function of PerformBUILD_VECTORCombine.
6166 /// This function expects two 256-bit vectors called V0 and V1.
6167 /// At first, each vector is split into two separate 128-bit vectors.
6168 /// Then, the resulting 128-bit vectors are used to implement two
6169 /// horizontal binary operations. 
6170 ///
6171 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6172 ///
6173 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6174 /// the two new horizontal binop.
6175 /// When Mode is set, the first horizontal binop dag node would take as input
6176 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6177 /// horizontal binop dag node would take as input the lower 128-bit of V1
6178 /// and the upper 128-bit of V1.
6179 ///   Example:
6180 ///     HADD V0_LO, V0_HI
6181 ///     HADD V1_LO, V1_HI
6182 ///
6183 /// Otherwise, the first horizontal binop dag node takes as input the lower
6184 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6185 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6186 ///   Example:
6187 ///     HADD V0_LO, V1_LO
6188 ///     HADD V0_HI, V1_HI
6189 ///
6190 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6191 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6192 /// the upper 128-bits of the result.
6193 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6194                                      SDLoc DL, SelectionDAG &DAG,
6195                                      unsigned X86Opcode, bool Mode,
6196                                      bool isUndefLO, bool isUndefHI) {
6197   EVT VT = V0.getValueType();
6198   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6199          "Invalid nodes in input!");
6200
6201   unsigned NumElts = VT.getVectorNumElements();
6202   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6203   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6204   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6205   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6206   EVT NewVT = V0_LO.getValueType();
6207
6208   SDValue LO = DAG.getUNDEF(NewVT);
6209   SDValue HI = DAG.getUNDEF(NewVT);
6210
6211   if (Mode) {
6212     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6214       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6215     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6216       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6217   } else {
6218     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6219     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6220                        V1_LO->getOpcode() != ISD::UNDEF))
6221       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6222
6223     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6224                        V1_HI->getOpcode() != ISD::UNDEF))
6225       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6226   }
6227
6228   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6229 }
6230
6231 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6232 /// sequence of 'vadd + vsub + blendi'.
6233 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6234                            const X86Subtarget *Subtarget) {
6235   SDLoc DL(BV);
6236   EVT VT = BV->getValueType(0);
6237   unsigned NumElts = VT.getVectorNumElements();
6238   SDValue InVec0 = DAG.getUNDEF(VT);
6239   SDValue InVec1 = DAG.getUNDEF(VT);
6240
6241   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6242           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6243
6244   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6245   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6246   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6247     return SDValue();
6248
6249   // Odd-numbered elements in the input build vector are obtained from
6250   // adding two integer/float elements.
6251   // Even-numbered elements in the input build vector are obtained from
6252   // subtracting two integer/float elements.
6253   unsigned ExpectedOpcode = ISD::FSUB;
6254   unsigned NextExpectedOpcode = ISD::FADD;
6255   bool AddFound = false;
6256   bool SubFound = false;
6257
6258   for (unsigned i = 0, e = NumElts; i != e; i++) {
6259     SDValue Op = BV->getOperand(i);
6260       
6261     // Skip 'undef' values.
6262     unsigned Opcode = Op.getOpcode();
6263     if (Opcode == ISD::UNDEF) {
6264       std::swap(ExpectedOpcode, NextExpectedOpcode);
6265       continue;
6266     }
6267       
6268     // Early exit if we found an unexpected opcode.
6269     if (Opcode != ExpectedOpcode)
6270       return SDValue();
6271
6272     SDValue Op0 = Op.getOperand(0);
6273     SDValue Op1 = Op.getOperand(1);
6274
6275     // Try to match the following pattern:
6276     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6277     // Early exit if we cannot match that sequence.
6278     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6279         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6280         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6281         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6282         Op0.getOperand(1) != Op1.getOperand(1))
6283       return SDValue();
6284
6285     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6286     if (I0 != i)
6287       return SDValue();
6288
6289     // We found a valid add/sub node. Update the information accordingly.
6290     if (i & 1)
6291       AddFound = true;
6292     else
6293       SubFound = true;
6294
6295     // Update InVec0 and InVec1.
6296     if (InVec0.getOpcode() == ISD::UNDEF)
6297       InVec0 = Op0.getOperand(0);
6298     if (InVec1.getOpcode() == ISD::UNDEF)
6299       InVec1 = Op1.getOperand(0);
6300
6301     // Make sure that operands in input to each add/sub node always
6302     // come from a same pair of vectors.
6303     if (InVec0 != Op0.getOperand(0)) {
6304       if (ExpectedOpcode == ISD::FSUB)
6305         return SDValue();
6306
6307       // FADD is commutable. Try to commute the operands
6308       // and then test again.
6309       std::swap(Op0, Op1);
6310       if (InVec0 != Op0.getOperand(0))
6311         return SDValue();
6312     }
6313
6314     if (InVec1 != Op1.getOperand(0))
6315       return SDValue();
6316
6317     // Update the pair of expected opcodes.
6318     std::swap(ExpectedOpcode, NextExpectedOpcode);
6319   }
6320
6321   // Don't try to fold this build_vector into a VSELECT if it has
6322   // too many UNDEF operands.
6323   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6324       InVec1.getOpcode() != ISD::UNDEF) {
6325     // Emit a sequence of vector add and sub followed by a VSELECT.
6326     // The new VSELECT will be lowered into a BLENDI.
6327     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6328     // and emit a single ADDSUB instruction.
6329     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6330     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6331
6332     // Construct the VSELECT mask.
6333     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6334     EVT SVT = MaskVT.getVectorElementType();
6335     unsigned SVTBits = SVT.getSizeInBits();
6336     SmallVector<SDValue, 8> Ops;
6337
6338     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6339       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6340                             APInt::getAllOnesValue(SVTBits);
6341       SDValue Constant = DAG.getConstant(Value, SVT);
6342       Ops.push_back(Constant);
6343     }
6344
6345     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6346     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6347   }
6348   
6349   return SDValue();
6350 }
6351
6352 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6353                                           const X86Subtarget *Subtarget) {
6354   SDLoc DL(N);
6355   EVT VT = N->getValueType(0);
6356   unsigned NumElts = VT.getVectorNumElements();
6357   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6358   SDValue InVec0, InVec1;
6359
6360   // Try to match an ADDSUB.
6361   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6362       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6363     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6364     if (Value.getNode())
6365       return Value;
6366   }
6367
6368   // Try to match horizontal ADD/SUB.
6369   unsigned NumUndefsLO = 0;
6370   unsigned NumUndefsHI = 0;
6371   unsigned Half = NumElts/2;
6372
6373   // Count the number of UNDEF operands in the build_vector in input.
6374   for (unsigned i = 0, e = Half; i != e; ++i)
6375     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6376       NumUndefsLO++;
6377
6378   for (unsigned i = Half, e = NumElts; i != e; ++i)
6379     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6380       NumUndefsHI++;
6381
6382   // Early exit if this is either a build_vector of all UNDEFs or all the
6383   // operands but one are UNDEF.
6384   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6385     return SDValue();
6386
6387   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6388     // Try to match an SSE3 float HADD/HSUB.
6389     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6390       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6391     
6392     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6393       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6394   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6395     // Try to match an SSSE3 integer HADD/HSUB.
6396     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6397       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6398     
6399     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6400       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6401   }
6402   
6403   if (!Subtarget->hasAVX())
6404     return SDValue();
6405
6406   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6407     // Try to match an AVX horizontal add/sub of packed single/double
6408     // precision floating point values from 256-bit vectors.
6409     SDValue InVec2, InVec3;
6410     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6411         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6412         ((InVec0.getOpcode() == ISD::UNDEF ||
6413           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6414         ((InVec1.getOpcode() == ISD::UNDEF ||
6415           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6416       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6417
6418     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6419         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6420         ((InVec0.getOpcode() == ISD::UNDEF ||
6421           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6422         ((InVec1.getOpcode() == ISD::UNDEF ||
6423           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6424       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6425   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6426     // Try to match an AVX2 horizontal add/sub of signed integers.
6427     SDValue InVec2, InVec3;
6428     unsigned X86Opcode;
6429     bool CanFold = true;
6430
6431     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6432         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6433         ((InVec0.getOpcode() == ISD::UNDEF ||
6434           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6435         ((InVec1.getOpcode() == ISD::UNDEF ||
6436           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6437       X86Opcode = X86ISD::HADD;
6438     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6439         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6440         ((InVec0.getOpcode() == ISD::UNDEF ||
6441           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6442         ((InVec1.getOpcode() == ISD::UNDEF ||
6443           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6444       X86Opcode = X86ISD::HSUB;
6445     else
6446       CanFold = false;
6447
6448     if (CanFold) {
6449       // Fold this build_vector into a single horizontal add/sub.
6450       // Do this only if the target has AVX2.
6451       if (Subtarget->hasAVX2())
6452         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6453  
6454       // Do not try to expand this build_vector into a pair of horizontal
6455       // add/sub if we can emit a pair of scalar add/sub.
6456       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6457         return SDValue();
6458
6459       // Convert this build_vector into a pair of horizontal binop followed by
6460       // a concat vector.
6461       bool isUndefLO = NumUndefsLO == Half;
6462       bool isUndefHI = NumUndefsHI == Half;
6463       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6464                                    isUndefLO, isUndefHI);
6465     }
6466   }
6467
6468   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6469        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6470     unsigned X86Opcode;
6471     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6472       X86Opcode = X86ISD::HADD;
6473     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6474       X86Opcode = X86ISD::HSUB;
6475     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6476       X86Opcode = X86ISD::FHADD;
6477     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6478       X86Opcode = X86ISD::FHSUB;
6479     else
6480       return SDValue();
6481
6482     // Don't try to expand this build_vector into a pair of horizontal add/sub
6483     // if we can simply emit a pair of scalar add/sub.
6484     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6485       return SDValue();
6486
6487     // Convert this build_vector into two horizontal add/sub followed by
6488     // a concat vector.
6489     bool isUndefLO = NumUndefsLO == Half;
6490     bool isUndefHI = NumUndefsHI == Half;
6491     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6492                                  isUndefLO, isUndefHI);
6493   }
6494
6495   return SDValue();
6496 }
6497
6498 SDValue
6499 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6500   SDLoc dl(Op);
6501
6502   MVT VT = Op.getSimpleValueType();
6503   MVT ExtVT = VT.getVectorElementType();
6504   unsigned NumElems = Op.getNumOperands();
6505
6506   // Generate vectors for predicate vectors.
6507   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6508     return LowerBUILD_VECTORvXi1(Op, DAG);
6509
6510   // Vectors containing all zeros can be matched by pxor and xorps later
6511   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6512     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6513     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6514     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6515       return Op;
6516
6517     return getZeroVector(VT, Subtarget, DAG, dl);
6518   }
6519
6520   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6521   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6522   // vpcmpeqd on 256-bit vectors.
6523   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6524     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6525       return Op;
6526
6527     if (!VT.is512BitVector())
6528       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6529   }
6530
6531   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6532   if (Broadcast.getNode())
6533     return Broadcast;
6534
6535   unsigned EVTBits = ExtVT.getSizeInBits();
6536
6537   unsigned NumZero  = 0;
6538   unsigned NumNonZero = 0;
6539   unsigned NonZeros = 0;
6540   bool IsAllConstants = true;
6541   SmallSet<SDValue, 8> Values;
6542   for (unsigned i = 0; i < NumElems; ++i) {
6543     SDValue Elt = Op.getOperand(i);
6544     if (Elt.getOpcode() == ISD::UNDEF)
6545       continue;
6546     Values.insert(Elt);
6547     if (Elt.getOpcode() != ISD::Constant &&
6548         Elt.getOpcode() != ISD::ConstantFP)
6549       IsAllConstants = false;
6550     if (X86::isZeroNode(Elt))
6551       NumZero++;
6552     else {
6553       NonZeros |= (1 << i);
6554       NumNonZero++;
6555     }
6556   }
6557
6558   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6559   if (NumNonZero == 0)
6560     return DAG.getUNDEF(VT);
6561
6562   // Special case for single non-zero, non-undef, element.
6563   if (NumNonZero == 1) {
6564     unsigned Idx = countTrailingZeros(NonZeros);
6565     SDValue Item = Op.getOperand(Idx);
6566
6567     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6568     // the value are obviously zero, truncate the value to i32 and do the
6569     // insertion that way.  Only do this if the value is non-constant or if the
6570     // value is a constant being inserted into element 0.  It is cheaper to do
6571     // a constant pool load than it is to do a movd + shuffle.
6572     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6573         (!IsAllConstants || Idx == 0)) {
6574       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6575         // Handle SSE only.
6576         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6577         EVT VecVT = MVT::v4i32;
6578         unsigned VecElts = 4;
6579
6580         // Truncate the value (which may itself be a constant) to i32, and
6581         // convert it to a vector with movd (S2V+shuffle to zero extend).
6582         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6583         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6584         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6585
6586         // Now we have our 32-bit value zero extended in the low element of
6587         // a vector.  If Idx != 0, swizzle it into place.
6588         if (Idx != 0) {
6589           SmallVector<int, 4> Mask;
6590           Mask.push_back(Idx);
6591           for (unsigned i = 1; i != VecElts; ++i)
6592             Mask.push_back(i);
6593           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6594                                       &Mask[0]);
6595         }
6596         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6597       }
6598     }
6599
6600     // If we have a constant or non-constant insertion into the low element of
6601     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6602     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6603     // depending on what the source datatype is.
6604     if (Idx == 0) {
6605       if (NumZero == 0)
6606         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6607
6608       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6609           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6610         if (VT.is256BitVector() || VT.is512BitVector()) {
6611           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6612           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6613                              Item, DAG.getIntPtrConstant(0));
6614         }
6615         assert(VT.is128BitVector() && "Expected an SSE value type!");
6616         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6617         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6618         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6619       }
6620
6621       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6622         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6623         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6624         if (VT.is256BitVector()) {
6625           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6626           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6627         } else {
6628           assert(VT.is128BitVector() && "Expected an SSE value type!");
6629           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6630         }
6631         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6632       }
6633     }
6634
6635     // Is it a vector logical left shift?
6636     if (NumElems == 2 && Idx == 1 &&
6637         X86::isZeroNode(Op.getOperand(0)) &&
6638         !X86::isZeroNode(Op.getOperand(1))) {
6639       unsigned NumBits = VT.getSizeInBits();
6640       return getVShift(true, VT,
6641                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6642                                    VT, Op.getOperand(1)),
6643                        NumBits/2, DAG, *this, dl);
6644     }
6645
6646     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6647       return SDValue();
6648
6649     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6650     // is a non-constant being inserted into an element other than the low one,
6651     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6652     // movd/movss) to move this into the low element, then shuffle it into
6653     // place.
6654     if (EVTBits == 32) {
6655       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6656
6657       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6658       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6659       SmallVector<int, 8> MaskVec;
6660       for (unsigned i = 0; i != NumElems; ++i)
6661         MaskVec.push_back(i == Idx ? 0 : 1);
6662       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6663     }
6664   }
6665
6666   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6667   if (Values.size() == 1) {
6668     if (EVTBits == 32) {
6669       // Instead of a shuffle like this:
6670       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6671       // Check if it's possible to issue this instead.
6672       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6673       unsigned Idx = countTrailingZeros(NonZeros);
6674       SDValue Item = Op.getOperand(Idx);
6675       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6676         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6677     }
6678     return SDValue();
6679   }
6680
6681   // A vector full of immediates; various special cases are already
6682   // handled, so this is best done with a single constant-pool load.
6683   if (IsAllConstants)
6684     return SDValue();
6685
6686   // For AVX-length vectors, build the individual 128-bit pieces and use
6687   // shuffles to put them in place.
6688   if (VT.is256BitVector() || VT.is512BitVector()) {
6689     SmallVector<SDValue, 64> V;
6690     for (unsigned i = 0; i != NumElems; ++i)
6691       V.push_back(Op.getOperand(i));
6692
6693     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6694
6695     // Build both the lower and upper subvector.
6696     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6697                                 makeArrayRef(&V[0], NumElems/2));
6698     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6699                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6700
6701     // Recreate the wider vector with the lower and upper part.
6702     if (VT.is256BitVector())
6703       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6704     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6705   }
6706
6707   // Let legalizer expand 2-wide build_vectors.
6708   if (EVTBits == 64) {
6709     if (NumNonZero == 1) {
6710       // One half is zero or undef.
6711       unsigned Idx = countTrailingZeros(NonZeros);
6712       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6713                                  Op.getOperand(Idx));
6714       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6715     }
6716     return SDValue();
6717   }
6718
6719   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6720   if (EVTBits == 8 && NumElems == 16) {
6721     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6722                                         Subtarget, *this);
6723     if (V.getNode()) return V;
6724   }
6725
6726   if (EVTBits == 16 && NumElems == 8) {
6727     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6728                                       Subtarget, *this);
6729     if (V.getNode()) return V;
6730   }
6731
6732   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6733   if (EVTBits == 32 && NumElems == 4) {
6734     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6735                                       NumZero, DAG, Subtarget, *this);
6736     if (V.getNode())
6737       return V;
6738   }
6739
6740   // If element VT is == 32 bits, turn it into a number of shuffles.
6741   SmallVector<SDValue, 8> V(NumElems);
6742   if (NumElems == 4 && NumZero > 0) {
6743     for (unsigned i = 0; i < 4; ++i) {
6744       bool isZero = !(NonZeros & (1 << i));
6745       if (isZero)
6746         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6747       else
6748         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6749     }
6750
6751     for (unsigned i = 0; i < 2; ++i) {
6752       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6753         default: break;
6754         case 0:
6755           V[i] = V[i*2];  // Must be a zero vector.
6756           break;
6757         case 1:
6758           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6759           break;
6760         case 2:
6761           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6762           break;
6763         case 3:
6764           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6765           break;
6766       }
6767     }
6768
6769     bool Reverse1 = (NonZeros & 0x3) == 2;
6770     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6771     int MaskVec[] = {
6772       Reverse1 ? 1 : 0,
6773       Reverse1 ? 0 : 1,
6774       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6775       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6776     };
6777     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6778   }
6779
6780   if (Values.size() > 1 && VT.is128BitVector()) {
6781     // Check for a build vector of consecutive loads.
6782     for (unsigned i = 0; i < NumElems; ++i)
6783       V[i] = Op.getOperand(i);
6784
6785     // Check for elements which are consecutive loads.
6786     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6787     if (LD.getNode())
6788       return LD;
6789
6790     // Check for a build vector from mostly shuffle plus few inserting.
6791     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6792     if (Sh.getNode())
6793       return Sh;
6794
6795     // For SSE 4.1, use insertps to put the high elements into the low element.
6796     if (getSubtarget()->hasSSE41()) {
6797       SDValue Result;
6798       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6799         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6800       else
6801         Result = DAG.getUNDEF(VT);
6802
6803       for (unsigned i = 1; i < NumElems; ++i) {
6804         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6805         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6806                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6807       }
6808       return Result;
6809     }
6810
6811     // Otherwise, expand into a number of unpckl*, start by extending each of
6812     // our (non-undef) elements to the full vector width with the element in the
6813     // bottom slot of the vector (which generates no code for SSE).
6814     for (unsigned i = 0; i < NumElems; ++i) {
6815       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6816         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6817       else
6818         V[i] = DAG.getUNDEF(VT);
6819     }
6820
6821     // Next, we iteratively mix elements, e.g. for v4f32:
6822     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6823     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6824     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6825     unsigned EltStride = NumElems >> 1;
6826     while (EltStride != 0) {
6827       for (unsigned i = 0; i < EltStride; ++i) {
6828         // If V[i+EltStride] is undef and this is the first round of mixing,
6829         // then it is safe to just drop this shuffle: V[i] is already in the
6830         // right place, the one element (since it's the first round) being
6831         // inserted as undef can be dropped.  This isn't safe for successive
6832         // rounds because they will permute elements within both vectors.
6833         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6834             EltStride == NumElems/2)
6835           continue;
6836
6837         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6838       }
6839       EltStride >>= 1;
6840     }
6841     return V[0];
6842   }
6843   return SDValue();
6844 }
6845
6846 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6847 // to create 256-bit vectors from two other 128-bit ones.
6848 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6849   SDLoc dl(Op);
6850   MVT ResVT = Op.getSimpleValueType();
6851
6852   assert((ResVT.is256BitVector() ||
6853           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6854
6855   SDValue V1 = Op.getOperand(0);
6856   SDValue V2 = Op.getOperand(1);
6857   unsigned NumElems = ResVT.getVectorNumElements();
6858   if(ResVT.is256BitVector())
6859     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6860
6861   if (Op.getNumOperands() == 4) {
6862     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6863                                 ResVT.getVectorNumElements()/2);
6864     SDValue V3 = Op.getOperand(2);
6865     SDValue V4 = Op.getOperand(3);
6866     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6867       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6868   }
6869   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6870 }
6871
6872 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6873   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6874   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6875          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6876           Op.getNumOperands() == 4)));
6877
6878   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6879   // from two other 128-bit ones.
6880
6881   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6882   return LowerAVXCONCAT_VECTORS(Op, DAG);
6883 }
6884
6885
6886 //===----------------------------------------------------------------------===//
6887 // Vector shuffle lowering
6888 //
6889 // This is an experimental code path for lowering vector shuffles on x86. It is
6890 // designed to handle arbitrary vector shuffles and blends, gracefully
6891 // degrading performance as necessary. It works hard to recognize idiomatic
6892 // shuffles and lower them to optimal instruction patterns without leaving
6893 // a framework that allows reasonably efficient handling of all vector shuffle
6894 // patterns.
6895 //===----------------------------------------------------------------------===//
6896
6897 /// \brief Tiny helper function to identify a no-op mask.
6898 ///
6899 /// This is a somewhat boring predicate function. It checks whether the mask
6900 /// array input, which is assumed to be a single-input shuffle mask of the kind
6901 /// used by the X86 shuffle instructions (not a fully general
6902 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6903 /// in-place shuffle are 'no-op's.
6904 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6905   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6906     if (Mask[i] != -1 && Mask[i] != i)
6907       return false;
6908   return true;
6909 }
6910
6911 /// \brief Helper function to classify a mask as a single-input mask.
6912 ///
6913 /// This isn't a generic single-input test because in the vector shuffle
6914 /// lowering we canonicalize single inputs to be the first input operand. This
6915 /// means we can more quickly test for a single input by only checking whether
6916 /// an input from the second operand exists. We also assume that the size of
6917 /// mask corresponds to the size of the input vectors which isn't true in the
6918 /// fully general case.
6919 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6920   for (int M : Mask)
6921     if (M >= (int)Mask.size())
6922       return false;
6923   return true;
6924 }
6925
6926 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6927 ///
6928 /// This helper function produces an 8-bit shuffle immediate corresponding to
6929 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6930 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6931 /// example.
6932 ///
6933 /// NB: We rely heavily on "undef" masks preserving the input lane.
6934 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6935                                           SelectionDAG &DAG) {
6936   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6937   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6938   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6939   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6940   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6941
6942   unsigned Imm = 0;
6943   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6944   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6945   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6946   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6947   return DAG.getConstant(Imm, MVT::i8);
6948 }
6949
6950 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6951 ///
6952 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6953 /// support for floating point shuffles but not integer shuffles. These
6954 /// instructions will incur a domain crossing penalty on some chips though so
6955 /// it is better to avoid lowering through this for integer vectors where
6956 /// possible.
6957 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6958                                        const X86Subtarget *Subtarget,
6959                                        SelectionDAG &DAG) {
6960   SDLoc DL(Op);
6961   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6962   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6963   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6964   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6965   ArrayRef<int> Mask = SVOp->getMask();
6966   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6967
6968   if (isSingleInputShuffleMask(Mask)) {
6969     // Straight shuffle of a single input vector. Simulate this by using the
6970     // single input as both of the "inputs" to this instruction..
6971     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6972     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6973                        DAG.getConstant(SHUFPDMask, MVT::i8));
6974   }
6975   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6976   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6977
6978   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6979   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6980                      DAG.getConstant(SHUFPDMask, MVT::i8));
6981 }
6982
6983 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6984 ///
6985 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6986 /// the integer unit to minimize domain crossing penalties. However, for blends
6987 /// it falls back to the floating point shuffle operation with appropriate bit
6988 /// casting.
6989 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6990                                        const X86Subtarget *Subtarget,
6991                                        SelectionDAG &DAG) {
6992   SDLoc DL(Op);
6993   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6994   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6995   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6996   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6997   ArrayRef<int> Mask = SVOp->getMask();
6998   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6999
7000   if (isSingleInputShuffleMask(Mask)) {
7001     // Straight shuffle of a single input vector. For everything from SSE2
7002     // onward this has a single fast instruction with no scary immediates.
7003     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7004     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7005     int WidenedMask[4] = {
7006         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7007         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7008     return DAG.getNode(
7009         ISD::BITCAST, DL, MVT::v2i64,
7010         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7011                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7012   }
7013
7014   // We implement this with SHUFPD which is pretty lame because it will likely
7015   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7016   // However, all the alternatives are still more cycles and newer chips don't
7017   // have this problem. It would be really nice if x86 had better shuffles here.
7018   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7019   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7020   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7021                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7022 }
7023
7024 /// \brief Lower 4-lane 32-bit floating point shuffles.
7025 ///
7026 /// Uses instructions exclusively from the floating point unit to minimize
7027 /// domain crossing penalties, as these are sufficient to implement all v4f32
7028 /// shuffles.
7029 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7030                                        const X86Subtarget *Subtarget,
7031                                        SelectionDAG &DAG) {
7032   SDLoc DL(Op);
7033   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7034   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7035   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7036   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7037   ArrayRef<int> Mask = SVOp->getMask();
7038   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7039
7040   SDValue LowV = V1, HighV = V2;
7041   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7042
7043   int NumV2Elements =
7044       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7045
7046   if (NumV2Elements == 0)
7047     // Straight shuffle of a single input vector. We pass the input vector to
7048     // both operands to simulate this with a SHUFPS.
7049     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7050                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7051
7052   if (NumV2Elements == 1) {
7053     int V2Index =
7054         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7055         Mask.begin();
7056     // Compute the index adjacent to V2Index and in the same half by toggling
7057     // the low bit.
7058     int V2AdjIndex = V2Index ^ 1;
7059
7060     if (Mask[V2AdjIndex] == -1) {
7061       // Handles all the cases where we have a single V2 element and an undef.
7062       // This will only ever happen in the high lanes because we commute the
7063       // vector otherwise.
7064       if (V2Index < 2)
7065         std::swap(LowV, HighV);
7066       NewMask[V2Index] -= 4;
7067     } else {
7068       // Handle the case where the V2 element ends up adjacent to a V1 element.
7069       // To make this work, blend them together as the first step.
7070       int V1Index = V2AdjIndex;
7071       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7072       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7073                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7074
7075       // Now proceed to reconstruct the final blend as we have the necessary
7076       // high or low half formed.
7077       if (V2Index < 2) {
7078         LowV = V2;
7079         HighV = V1;
7080       } else {
7081         HighV = V2;
7082       }
7083       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7084       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7085     }
7086   } else if (NumV2Elements == 2) {
7087     if (Mask[0] < 4 && Mask[1] < 4) {
7088       // Handle the easy case where we have V1 in the low lanes and V2 in the
7089       // high lanes. We never see this reversed because we sort the shuffle.
7090       NewMask[2] -= 4;
7091       NewMask[3] -= 4;
7092     } else {
7093       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7094       // trying to place elements directly, just blend them and set up the final
7095       // shuffle to place them.
7096
7097       // The first two blend mask elements are for V1, the second two are for
7098       // V2.
7099       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7100                           Mask[2] < 4 ? Mask[2] : Mask[3],
7101                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7102                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7103       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7104                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7105
7106       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7107       // a blend.
7108       LowV = HighV = V1;
7109       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7110       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7111       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7112       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7113     }
7114   }
7115   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7116                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7117 }
7118
7119 /// \brief Lower 4-lane i32 vector shuffles.
7120 ///
7121 /// We try to handle these with integer-domain shuffles where we can, but for
7122 /// blends we use the floating point domain blend instructions.
7123 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7124                                        const X86Subtarget *Subtarget,
7125                                        SelectionDAG &DAG) {
7126   SDLoc DL(Op);
7127   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7128   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7129   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7130   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7131   ArrayRef<int> Mask = SVOp->getMask();
7132   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7133
7134   if (isSingleInputShuffleMask(Mask))
7135     // Straight shuffle of a single input vector. For everything from SSE2
7136     // onward this has a single fast instruction with no scary immediates.
7137     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7138                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7139
7140   // We implement this with SHUFPS because it can blend from two vectors.
7141   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7142   // up the inputs, bypassing domain shift penalties that we would encur if we
7143   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7144   // relevant.
7145   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7146                      DAG.getVectorShuffle(
7147                          MVT::v4f32, DL,
7148                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7149                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7150 }
7151
7152 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7153 /// shuffle lowering, and the most complex part.
7154 ///
7155 /// The lowering strategy is to try to form pairs of input lanes which are
7156 /// targeted at the same half of the final vector, and then use a dword shuffle
7157 /// to place them onto the right half, and finally unpack the paired lanes into
7158 /// their final position.
7159 ///
7160 /// The exact breakdown of how to form these dword pairs and align them on the
7161 /// correct sides is really tricky. See the comments within the function for
7162 /// more of the details.
7163 static SDValue lowerV8I16SingleInputVectorShuffle(
7164     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7165     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7166   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7167   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7168   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7169
7170   SmallVector<int, 4> LoInputs;
7171   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7172                [](int M) { return M >= 0; });
7173   std::sort(LoInputs.begin(), LoInputs.end());
7174   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7175   SmallVector<int, 4> HiInputs;
7176   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7177                [](int M) { return M >= 0; });
7178   std::sort(HiInputs.begin(), HiInputs.end());
7179   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7180   int NumLToL =
7181       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7182   int NumHToL = LoInputs.size() - NumLToL;
7183   int NumLToH =
7184       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7185   int NumHToH = HiInputs.size() - NumLToH;
7186   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7187   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7188   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7189   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7190
7191   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7192   // such inputs we can swap two of the dwords across the half mark and end up
7193   // with <=2 inputs to each half in each half. Once there, we can fall through
7194   // to the generic code below. For example:
7195   //
7196   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7197   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7198   //
7199   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7200   // and 2-2.
7201   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7202                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7203     // Compute the index of dword with only one word among the three inputs in
7204     // a half by taking the sum of the half with three inputs and subtracting
7205     // the sum of the actual three inputs. The difference is the remaining
7206     // slot.
7207     int DWordA = (ThreeInputHalfSum -
7208                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7209                  2;
7210     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7211
7212     int PSHUFDMask[] = {0, 1, 2, 3};
7213     PSHUFDMask[DWordA] = DWordB;
7214     PSHUFDMask[DWordB] = DWordA;
7215     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7216                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7217                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7218                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7219
7220     // Adjust the mask to match the new locations of A and B.
7221     for (int &M : Mask)
7222       if (M != -1 && M/2 == DWordA)
7223         M = 2 * DWordB + M % 2;
7224       else if (M != -1 && M/2 == DWordB)
7225         M = 2 * DWordA + M % 2;
7226
7227     // Recurse back into this routine to re-compute state now that this isn't
7228     // a 3 and 1 problem.
7229     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7230                                 Mask);
7231   };
7232   if (NumLToL == 3 && NumHToL == 1)
7233     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7234   else if (NumLToL == 1 && NumHToL == 3)
7235     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7236   else if (NumLToH == 1 && NumHToH == 3)
7237     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7238   else if (NumLToH == 3 && NumHToH == 1)
7239     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7240
7241   // At this point there are at most two inputs to the low and high halves from
7242   // each half. That means the inputs can always be grouped into dwords and
7243   // those dwords can then be moved to the correct half with a dword shuffle.
7244   // We use at most one low and one high word shuffle to collect these paired
7245   // inputs into dwords, and finally a dword shuffle to place them.
7246   int PSHUFLMask[4] = {-1, -1, -1, -1};
7247   int PSHUFHMask[4] = {-1, -1, -1, -1};
7248   int PSHUFDMask[4] = {-1, -1, -1, -1};
7249
7250   // First fix the masks for all the inputs that are staying in their
7251   // original halves. This will then dictate the targets of the cross-half
7252   // shuffles.
7253   auto fixInPlaceInputs = [&PSHUFDMask](
7254       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7255       MutableArrayRef<int> HalfMask, int HalfOffset) {
7256     if (InPlaceInputs.empty())
7257       return;
7258     if (InPlaceInputs.size() == 1) {
7259       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7260           InPlaceInputs[0] - HalfOffset;
7261       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7262       return;
7263     }
7264
7265     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7266     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7267         InPlaceInputs[0] - HalfOffset;
7268     // Put the second input next to the first so that they are packed into
7269     // a dword. We find the adjacent index by toggling the low bit.
7270     int AdjIndex = InPlaceInputs[0] ^ 1;
7271     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7272     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7273     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7274   };
7275   if (!HToLInputs.empty())
7276     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7277   if (!LToHInputs.empty())
7278     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7279
7280   // Now gather the cross-half inputs and place them into a free dword of
7281   // their target half.
7282   // FIXME: This operation could almost certainly be simplified dramatically to
7283   // look more like the 3-1 fixing operation.
7284   auto moveInputsToRightHalf = [&PSHUFDMask](
7285       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7286       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7287       int SourceOffset, int DestOffset) {
7288     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7289       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7290     };
7291     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7292                                                int Word) {
7293       int LowWord = Word & ~1;
7294       int HighWord = Word | 1;
7295       return isWordClobbered(SourceHalfMask, LowWord) ||
7296              isWordClobbered(SourceHalfMask, HighWord);
7297     };
7298
7299     if (IncomingInputs.empty())
7300       return;
7301
7302     if (ExistingInputs.empty()) {
7303       // Map any dwords with inputs from them into the right half.
7304       for (int Input : IncomingInputs) {
7305         // If the source half mask maps over the inputs, turn those into
7306         // swaps and use the swapped lane.
7307         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7308           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7309             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7310                 Input - SourceOffset;
7311             // We have to swap the uses in our half mask in one sweep.
7312             for (int &M : HalfMask)
7313               if (M == SourceHalfMask[Input - SourceOffset])
7314                 M = Input;
7315               else if (M == Input)
7316                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7317           } else {
7318             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7319                        Input - SourceOffset &&
7320                    "Previous placement doesn't match!");
7321           }
7322           // Note that this correctly re-maps both when we do a swap and when
7323           // we observe the other side of the swap above. We rely on that to
7324           // avoid swapping the members of the input list directly.
7325           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7326         }
7327
7328         // Map the input's dword into the correct half.
7329         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7330           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7331         else
7332           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7333                      Input / 2 &&
7334                  "Previous placement doesn't match!");
7335       }
7336
7337       // And just directly shift any other-half mask elements to be same-half
7338       // as we will have mirrored the dword containing the element into the
7339       // same position within that half.
7340       for (int &M : HalfMask)
7341         if (M >= SourceOffset && M < SourceOffset + 4) {
7342           M = M - SourceOffset + DestOffset;
7343           assert(M >= 0 && "This should never wrap below zero!");
7344         }
7345       return;
7346     }
7347
7348     // Ensure we have the input in a viable dword of its current half. This
7349     // is particularly tricky because the original position may be clobbered
7350     // by inputs being moved and *staying* in that half.
7351     if (IncomingInputs.size() == 1) {
7352       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7353         int InputFixed = std::find(std::begin(SourceHalfMask),
7354                                    std::end(SourceHalfMask), -1) -
7355                          std::begin(SourceHalfMask) + SourceOffset;
7356         SourceHalfMask[InputFixed - SourceOffset] =
7357             IncomingInputs[0] - SourceOffset;
7358         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7359                      InputFixed);
7360         IncomingInputs[0] = InputFixed;
7361       }
7362     } else if (IncomingInputs.size() == 2) {
7363       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7364           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7365         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7366         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7367                "Not all dwords can be clobbered!");
7368         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7369         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7370         for (int &M : HalfMask)
7371           if (M == IncomingInputs[0])
7372             M = SourceDWordBase + SourceOffset;
7373           else if (M == IncomingInputs[1])
7374             M = SourceDWordBase + 1 + SourceOffset;
7375         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7376         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7377       }
7378     } else {
7379       llvm_unreachable("Unhandled input size!");
7380     }
7381
7382     // Now hoist the DWord down to the right half.
7383     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7384     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7385     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7386     for (int Input : IncomingInputs)
7387       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7388                    FreeDWord * 2 + Input % 2);
7389   };
7390   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7391                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7392   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7393                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7394
7395   // Now enact all the shuffles we've computed to move the inputs into their
7396   // target half.
7397   if (!isNoopShuffleMask(PSHUFLMask))
7398     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7399                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7400   if (!isNoopShuffleMask(PSHUFHMask))
7401     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7402                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7403   if (!isNoopShuffleMask(PSHUFDMask))
7404     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7405                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7406                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7407                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7408
7409   // At this point, each half should contain all its inputs, and we can then
7410   // just shuffle them into their final position.
7411   assert(std::count_if(LoMask.begin(), LoMask.end(),
7412                        [](int M) { return M >= 4; }) == 0 &&
7413          "Failed to lift all the high half inputs to the low mask!");
7414   assert(std::count_if(HiMask.begin(), HiMask.end(),
7415                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7416          "Failed to lift all the low half inputs to the high mask!");
7417
7418   // Do a half shuffle for the low mask.
7419   if (!isNoopShuffleMask(LoMask))
7420     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7421                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7422
7423   // Do a half shuffle with the high mask after shifting its values down.
7424   for (int &M : HiMask)
7425     if (M >= 0)
7426       M -= 4;
7427   if (!isNoopShuffleMask(HiMask))
7428     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7429                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7430
7431   return V;
7432 }
7433
7434 /// \brief Detect whether the mask pattern should be lowered through
7435 /// interleaving.
7436 ///
7437 /// This essentially tests whether viewing the mask as an interleaving of two
7438 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7439 /// lowering it through interleaving is a significantly better strategy.
7440 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7441   int NumEvenInputs[2] = {0, 0};
7442   int NumOddInputs[2] = {0, 0};
7443   int NumLoInputs[2] = {0, 0};
7444   int NumHiInputs[2] = {0, 0};
7445   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7446     if (Mask[i] < 0)
7447       continue;
7448
7449     int InputIdx = Mask[i] >= Size;
7450
7451     if (i < Size / 2)
7452       ++NumLoInputs[InputIdx];
7453     else
7454       ++NumHiInputs[InputIdx];
7455
7456     if ((i % 2) == 0)
7457       ++NumEvenInputs[InputIdx];
7458     else
7459       ++NumOddInputs[InputIdx];
7460   }
7461
7462   // The minimum number of cross-input results for both the interleaved and
7463   // split cases. If interleaving results in fewer cross-input results, return
7464   // true.
7465   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7466                                     NumEvenInputs[0] + NumOddInputs[1]);
7467   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7468                               NumLoInputs[0] + NumHiInputs[1]);
7469   return InterleavedCrosses < SplitCrosses;
7470 }
7471
7472 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7473 ///
7474 /// This strategy only works when the inputs from each vector fit into a single
7475 /// half of that vector, and generally there are not so many inputs as to leave
7476 /// the in-place shuffles required highly constrained (and thus expensive). It
7477 /// shifts all the inputs into a single side of both input vectors and then
7478 /// uses an unpack to interleave these inputs in a single vector. At that
7479 /// point, we will fall back on the generic single input shuffle lowering.
7480 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7481                                                  SDValue V2,
7482                                                  MutableArrayRef<int> Mask,
7483                                                  const X86Subtarget *Subtarget,
7484                                                  SelectionDAG &DAG) {
7485   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7486   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7487   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7488   for (int i = 0; i < 8; ++i)
7489     if (Mask[i] >= 0 && Mask[i] < 4)
7490       LoV1Inputs.push_back(i);
7491     else if (Mask[i] >= 4 && Mask[i] < 8)
7492       HiV1Inputs.push_back(i);
7493     else if (Mask[i] >= 8 && Mask[i] < 12)
7494       LoV2Inputs.push_back(i);
7495     else if (Mask[i] >= 12)
7496       HiV2Inputs.push_back(i);
7497
7498   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7499   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7500   (void)NumV1Inputs;
7501   (void)NumV2Inputs;
7502   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7503   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7504   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7505
7506   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7507                      HiV1Inputs.size() + HiV2Inputs.size();
7508
7509   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7510                               ArrayRef<int> HiInputs, bool MoveToLo,
7511                               int MaskOffset) {
7512     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7513     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7514     if (BadInputs.empty())
7515       return V;
7516
7517     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7518     int MoveOffset = MoveToLo ? 0 : 4;
7519
7520     if (GoodInputs.empty()) {
7521       for (int BadInput : BadInputs) {
7522         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7523         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7524       }
7525     } else {
7526       if (GoodInputs.size() == 2) {
7527         // If the low inputs are spread across two dwords, pack them into
7528         // a single dword.
7529         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7530             Mask[GoodInputs[0]] - MaskOffset;
7531         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7532             Mask[GoodInputs[1]] - MaskOffset;
7533         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7534         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7535       } else {
7536         // Otherwise pin the low inputs.
7537         for (int GoodInput : GoodInputs)
7538           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7539       }
7540
7541       int MoveMaskIdx =
7542           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7543           std::begin(MoveMask);
7544       assert(MoveMaskIdx >= MoveOffset && "Established above");
7545
7546       if (BadInputs.size() == 2) {
7547         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7548         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7549         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7550             Mask[BadInputs[0]] - MaskOffset;
7551         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7552             Mask[BadInputs[1]] - MaskOffset;
7553         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7554         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7555       } else {
7556         assert(BadInputs.size() == 1 && "All sizes handled");
7557         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7558         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7559       }
7560     }
7561
7562     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7563                                 MoveMask);
7564   };
7565   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7566                         /*MaskOffset*/ 0);
7567   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7568                         /*MaskOffset*/ 8);
7569
7570   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7571   // cross-half traffic in the final shuffle.
7572
7573   // Munge the mask to be a single-input mask after the unpack merges the
7574   // results.
7575   for (int &M : Mask)
7576     if (M != -1)
7577       M = 2 * (M % 4) + (M / 8);
7578
7579   return DAG.getVectorShuffle(
7580       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7581                                   DL, MVT::v8i16, V1, V2),
7582       DAG.getUNDEF(MVT::v8i16), Mask);
7583 }
7584
7585 /// \brief Generic lowering of 8-lane i16 shuffles.
7586 ///
7587 /// This handles both single-input shuffles and combined shuffle/blends with
7588 /// two inputs. The single input shuffles are immediately delegated to
7589 /// a dedicated lowering routine.
7590 ///
7591 /// The blends are lowered in one of three fundamental ways. If there are few
7592 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7593 /// of the input is significantly cheaper when lowered as an interleaving of
7594 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7595 /// halves of the inputs separately (making them have relatively few inputs)
7596 /// and then concatenate them.
7597 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7598                                        const X86Subtarget *Subtarget,
7599                                        SelectionDAG &DAG) {
7600   SDLoc DL(Op);
7601   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7602   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7603   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7604   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7605   ArrayRef<int> OrigMask = SVOp->getMask();
7606   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7607                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7608   MutableArrayRef<int> Mask(MaskStorage);
7609
7610   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7611
7612   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7613   auto isV2 = [](int M) { return M >= 8; };
7614
7615   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7616   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7617
7618   if (NumV2Inputs == 0)
7619     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7620
7621   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7622                             "to be V1-input shuffles.");
7623
7624   if (NumV1Inputs + NumV2Inputs <= 4)
7625     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7626
7627   // Check whether an interleaving lowering is likely to be more efficient.
7628   // This isn't perfect but it is a strong heuristic that tends to work well on
7629   // the kinds of shuffles that show up in practice.
7630   //
7631   // FIXME: Handle 1x, 2x, and 4x interleaving.
7632   if (shouldLowerAsInterleaving(Mask)) {
7633     // FIXME: Figure out whether we should pack these into the low or high
7634     // halves.
7635
7636     int EMask[8], OMask[8];
7637     for (int i = 0; i < 4; ++i) {
7638       EMask[i] = Mask[2*i];
7639       OMask[i] = Mask[2*i + 1];
7640       EMask[i + 4] = -1;
7641       OMask[i + 4] = -1;
7642     }
7643
7644     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7645     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7646
7647     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7648   }
7649
7650   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7651   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7652
7653   for (int i = 0; i < 4; ++i) {
7654     LoBlendMask[i] = Mask[i];
7655     HiBlendMask[i] = Mask[i + 4];
7656   }
7657
7658   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7659   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7660   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7661   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7662
7663   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7664                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7665 }
7666
7667 /// \brief Generic lowering of v16i8 shuffles.
7668 ///
7669 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7670 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7671 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7672 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7673 /// back together.
7674 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7675                                        const X86Subtarget *Subtarget,
7676                                        SelectionDAG &DAG) {
7677   SDLoc DL(Op);
7678   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7679   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7680   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7681   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7682   ArrayRef<int> OrigMask = SVOp->getMask();
7683   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7684   int MaskStorage[16] = {
7685       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7686       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7687       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7688       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7689   MutableArrayRef<int> Mask(MaskStorage);
7690   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7691   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7692
7693   // For single-input shuffles, there are some nicer lowering tricks we can use.
7694   if (isSingleInputShuffleMask(Mask)) {
7695     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7696     // Notably, this handles splat and partial-splat shuffles more efficiently.
7697     //
7698     // FIXME: We should check for other patterns which can be widened into an
7699     // i16 shuffle as well.
7700     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7701       for (int i = 0; i < 16; i += 2) {
7702         if (Mask[i] != Mask[i + 1])
7703           return false;
7704       }
7705       return true;
7706     };
7707     if (canWidenViaDuplication(Mask)) {
7708       SmallVector<int, 4> LoInputs;
7709       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7710                    [](int M) { return M >= 0 && M < 8; });
7711       std::sort(LoInputs.begin(), LoInputs.end());
7712       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7713                      LoInputs.end());
7714       SmallVector<int, 4> HiInputs;
7715       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7716                    [](int M) { return M >= 8; });
7717       std::sort(HiInputs.begin(), HiInputs.end());
7718       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7719                      HiInputs.end());
7720
7721       bool TargetLo = LoInputs.size() >= HiInputs.size();
7722       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7723       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7724
7725       int ByteMask[16];
7726       SmallDenseMap<int, int, 8> LaneMap;
7727       for (int i = 0; i < 16; ++i)
7728         ByteMask[i] = -1;
7729       for (int I : InPlaceInputs) {
7730         ByteMask[I] = I;
7731         LaneMap[I] = I;
7732       }
7733       int FreeByteIdx = 0;
7734       int TargetOffset = TargetLo ? 0 : 8;
7735       for (int I : MovingInputs) {
7736         // Walk the free index into the byte mask until we find an unoccupied
7737         // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7738         // principle indicates that there *must* be a spot as we can only have
7739         // 8 duplicated inputs. We have to walk the index using modular
7740         // arithmetic to wrap around as necessary.
7741         // FIXME: We could do a much better job of picking an inexpensive slot
7742         // so this doesn't go through the worst case for the byte shuffle.
7743         for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7744              ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7745           ;
7746         assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7747                "Failed to find a free byte!");
7748         ByteMask[FreeByteIdx + TargetOffset] = I;
7749         LaneMap[I] = FreeByteIdx + TargetOffset;
7750       }
7751       V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7752                                 ByteMask);
7753       for (int &M : Mask)
7754         if (M != -1)
7755           M = LaneMap[M];
7756
7757       // Unpack the bytes to form the i16s that will be shuffled into place.
7758       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7759                        MVT::v16i8, V1, V1);
7760
7761       int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7762       for (int i = 0; i < 16; i += 2) {
7763         if (Mask[i] != -1)
7764           I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7765         assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7766       }
7767       return DAG.getVectorShuffle(MVT::v8i16, DL,
7768                                   DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7769                                   DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7770     }
7771   }
7772
7773   // Check whether an interleaving lowering is likely to be more efficient.
7774   // This isn't perfect but it is a strong heuristic that tends to work well on
7775   // the kinds of shuffles that show up in practice.
7776   //
7777   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7778   if (shouldLowerAsInterleaving(Mask)) {
7779     // FIXME: Figure out whether we should pack these into the low or high
7780     // halves.
7781
7782     int EMask[16], OMask[16];
7783     for (int i = 0; i < 8; ++i) {
7784       EMask[i] = Mask[2*i];
7785       OMask[i] = Mask[2*i + 1];
7786       EMask[i + 8] = -1;
7787       OMask[i + 8] = -1;
7788     }
7789
7790     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7791     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7792
7793     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7794   }
7795
7796   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7797   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7798   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7799   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7800
7801   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7802                             MutableArrayRef<int> V1HalfBlendMask,
7803                             MutableArrayRef<int> V2HalfBlendMask) {
7804     for (int i = 0; i < 8; ++i)
7805       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7806         V1HalfBlendMask[i] = HalfMask[i];
7807         HalfMask[i] = i;
7808       } else if (HalfMask[i] >= 16) {
7809         V2HalfBlendMask[i] = HalfMask[i] - 16;
7810         HalfMask[i] = i + 8;
7811       }
7812   };
7813   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7814   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7815
7816   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7817
7818   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7819                              MutableArrayRef<int> HiBlendMask) {
7820     SDValue V1, V2;
7821     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7822     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7823     // i16s.
7824     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7825                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7826         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7827                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7828       // Use a mask to drop the high bytes.
7829       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7830       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7831                        DAG.getConstant(0x00FF, MVT::v8i16));
7832
7833       // This will be a single vector shuffle instead of a blend so nuke V2.
7834       V2 = DAG.getUNDEF(MVT::v8i16);
7835
7836       // Squash the masks to point directly into V1.
7837       for (int &M : LoBlendMask)
7838         if (M >= 0)
7839           M /= 2;
7840       for (int &M : HiBlendMask)
7841         if (M >= 0)
7842           M /= 2;
7843     } else {
7844       // Otherwise just unpack the low half of V into V1 and the high half into
7845       // V2 so that we can blend them as i16s.
7846       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7847                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7848       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7849                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7850     }
7851
7852     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7853     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7854     return std::make_pair(BlendedLo, BlendedHi);
7855   };
7856   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7857   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7858   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7859
7860   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7861   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7862
7863   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7864 }
7865
7866 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7867 ///
7868 /// This routine breaks down the specific type of 128-bit shuffle and
7869 /// dispatches to the lowering routines accordingly.
7870 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7871                                         MVT VT, const X86Subtarget *Subtarget,
7872                                         SelectionDAG &DAG) {
7873   switch (VT.SimpleTy) {
7874   case MVT::v2i64:
7875     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7876   case MVT::v2f64:
7877     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7878   case MVT::v4i32:
7879     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7880   case MVT::v4f32:
7881     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7882   case MVT::v8i16:
7883     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7884   case MVT::v16i8:
7885     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7886
7887   default:
7888     llvm_unreachable("Unimplemented!");
7889   }
7890 }
7891
7892 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7893 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7894   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7895     if (Mask[i] + 1 != Mask[i+1])
7896       return false;
7897
7898   return true;
7899 }
7900
7901 /// \brief Top-level lowering for x86 vector shuffles.
7902 ///
7903 /// This handles decomposition, canonicalization, and lowering of all x86
7904 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7905 /// above in helper routines. The canonicalization attempts to widen shuffles
7906 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7907 /// s.t. only one of the two inputs needs to be tested, etc.
7908 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7909                                   SelectionDAG &DAG) {
7910   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7911   ArrayRef<int> Mask = SVOp->getMask();
7912   SDValue V1 = Op.getOperand(0);
7913   SDValue V2 = Op.getOperand(1);
7914   MVT VT = Op.getSimpleValueType();
7915   int NumElements = VT.getVectorNumElements();
7916   SDLoc dl(Op);
7917
7918   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7919
7920   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7921   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7922   if (V1IsUndef && V2IsUndef)
7923     return DAG.getUNDEF(VT);
7924
7925   // When we create a shuffle node we put the UNDEF node to second operand,
7926   // but in some cases the first operand may be transformed to UNDEF.
7927   // In this case we should just commute the node.
7928   if (V1IsUndef)
7929     return CommuteVectorShuffle(SVOp, DAG);
7930
7931   // Check for non-undef masks pointing at an undef vector and make the masks
7932   // undef as well. This makes it easier to match the shuffle based solely on
7933   // the mask.
7934   if (V2IsUndef)
7935     for (int M : Mask)
7936       if (M >= NumElements) {
7937         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7938         for (int &M : NewMask)
7939           if (M >= NumElements)
7940             M = -1;
7941         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7942       }
7943
7944   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7945   // lanes but wider integers. We cap this to not form integers larger than i64
7946   // but it might be interesting to form i128 integers to handle flipping the
7947   // low and high halves of AVX 256-bit vectors.
7948   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7949       areAdjacentMasksSequential(Mask)) {
7950     SmallVector<int, 8> NewMask;
7951     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7952       NewMask.push_back(Mask[i] / 2);
7953     MVT NewVT =
7954         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7955                          VT.getVectorNumElements() / 2);
7956     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7957     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7958     return DAG.getNode(ISD::BITCAST, dl, VT,
7959                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7960   }
7961
7962   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7963   for (int M : SVOp->getMask())
7964     if (M < 0)
7965       ++NumUndefElements;
7966     else if (M < NumElements)
7967       ++NumV1Elements;
7968     else
7969       ++NumV2Elements;
7970
7971   // Commute the shuffle as needed such that more elements come from V1 than
7972   // V2. This allows us to match the shuffle pattern strictly on how many
7973   // elements come from V1 without handling the symmetric cases.
7974   if (NumV2Elements > NumV1Elements)
7975     return CommuteVectorShuffle(SVOp, DAG);
7976
7977   // When the number of V1 and V2 elements are the same, try to minimize the
7978   // number of uses of V2 in the low half of the vector.
7979   if (NumV1Elements == NumV2Elements) {
7980     int LowV1Elements = 0, LowV2Elements = 0;
7981     for (int M : SVOp->getMask().slice(0, NumElements / 2))
7982       if (M >= NumElements)
7983         ++LowV2Elements;
7984       else if (M >= 0)
7985         ++LowV1Elements;
7986     if (LowV2Elements > LowV1Elements)
7987       return CommuteVectorShuffle(SVOp, DAG);
7988   }
7989
7990   // For each vector width, delegate to a specialized lowering routine.
7991   if (VT.getSizeInBits() == 128)
7992     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7993
7994   llvm_unreachable("Unimplemented!");
7995 }
7996
7997
7998 //===----------------------------------------------------------------------===//
7999 // Legacy vector shuffle lowering
8000 //
8001 // This code is the legacy code handling vector shuffles until the above
8002 // replaces its functionality and performance.
8003 //===----------------------------------------------------------------------===//
8004
8005 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8006                         bool hasInt256, unsigned *MaskOut = nullptr) {
8007   MVT EltVT = VT.getVectorElementType();
8008
8009   // There is no blend with immediate in AVX-512.
8010   if (VT.is512BitVector())
8011     return false;
8012
8013   if (!hasSSE41 || EltVT == MVT::i8)
8014     return false;
8015   if (!hasInt256 && VT == MVT::v16i16)
8016     return false;
8017
8018   unsigned MaskValue = 0;
8019   unsigned NumElems = VT.getVectorNumElements();
8020   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8021   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8022   unsigned NumElemsInLane = NumElems / NumLanes;
8023
8024   // Blend for v16i16 should be symetric for the both lanes.
8025   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8026
8027     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8028     int EltIdx = MaskVals[i];
8029
8030     if ((EltIdx < 0 || EltIdx == (int)i) &&
8031         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8032       continue;
8033
8034     if (((unsigned)EltIdx == (i + NumElems)) &&
8035         (SndLaneEltIdx < 0 ||
8036          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8037       MaskValue |= (1 << i);
8038     else
8039       return false;
8040   }
8041
8042   if (MaskOut)
8043     *MaskOut = MaskValue;
8044   return true;
8045 }
8046
8047 // Try to lower a shuffle node into a simple blend instruction.
8048 // This function assumes isBlendMask returns true for this
8049 // SuffleVectorSDNode
8050 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8051                                           unsigned MaskValue,
8052                                           const X86Subtarget *Subtarget,
8053                                           SelectionDAG &DAG) {
8054   MVT VT = SVOp->getSimpleValueType(0);
8055   MVT EltVT = VT.getVectorElementType();
8056   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8057                      Subtarget->hasInt256() && "Trying to lower a "
8058                                                "VECTOR_SHUFFLE to a Blend but "
8059                                                "with the wrong mask"));
8060   SDValue V1 = SVOp->getOperand(0);
8061   SDValue V2 = SVOp->getOperand(1);
8062   SDLoc dl(SVOp);
8063   unsigned NumElems = VT.getVectorNumElements();
8064
8065   // Convert i32 vectors to floating point if it is not AVX2.
8066   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8067   MVT BlendVT = VT;
8068   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8069     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8070                                NumElems);
8071     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8072     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8073   }
8074
8075   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8076                             DAG.getConstant(MaskValue, MVT::i32));
8077   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8078 }
8079
8080 /// In vector type \p VT, return true if the element at index \p InputIdx
8081 /// falls on a different 128-bit lane than \p OutputIdx.
8082 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8083                                      unsigned OutputIdx) {
8084   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8085   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8086 }
8087
8088 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8089 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8090 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8091 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8092 /// zero.
8093 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8094                          SelectionDAG &DAG) {
8095   MVT VT = V1.getSimpleValueType();
8096   assert(VT.is128BitVector() || VT.is256BitVector());
8097
8098   MVT EltVT = VT.getVectorElementType();
8099   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8100   unsigned NumElts = VT.getVectorNumElements();
8101
8102   SmallVector<SDValue, 32> PshufbMask;
8103   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8104     int InputIdx = MaskVals[OutputIdx];
8105     unsigned InputByteIdx;
8106
8107     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8108       InputByteIdx = 0x80;
8109     else {
8110       // Cross lane is not allowed.
8111       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8112         return SDValue();
8113       InputByteIdx = InputIdx * EltSizeInBytes;
8114       // Index is an byte offset within the 128-bit lane.
8115       InputByteIdx &= 0xf;
8116     }
8117
8118     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8119       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8120       if (InputByteIdx != 0x80)
8121         ++InputByteIdx;
8122     }
8123   }
8124
8125   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8126   if (ShufVT != VT)
8127     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8128   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8129                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8130 }
8131
8132 // v8i16 shuffles - Prefer shuffles in the following order:
8133 // 1. [all]   pshuflw, pshufhw, optional move
8134 // 2. [ssse3] 1 x pshufb
8135 // 3. [ssse3] 2 x pshufb + 1 x por
8136 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8137 static SDValue
8138 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8139                          SelectionDAG &DAG) {
8140   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8141   SDValue V1 = SVOp->getOperand(0);
8142   SDValue V2 = SVOp->getOperand(1);
8143   SDLoc dl(SVOp);
8144   SmallVector<int, 8> MaskVals;
8145
8146   // Determine if more than 1 of the words in each of the low and high quadwords
8147   // of the result come from the same quadword of one of the two inputs.  Undef
8148   // mask values count as coming from any quadword, for better codegen.
8149   //
8150   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8151   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8152   unsigned LoQuad[] = { 0, 0, 0, 0 };
8153   unsigned HiQuad[] = { 0, 0, 0, 0 };
8154   // Indices of quads used.
8155   std::bitset<4> InputQuads;
8156   for (unsigned i = 0; i < 8; ++i) {
8157     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8158     int EltIdx = SVOp->getMaskElt(i);
8159     MaskVals.push_back(EltIdx);
8160     if (EltIdx < 0) {
8161       ++Quad[0];
8162       ++Quad[1];
8163       ++Quad[2];
8164       ++Quad[3];
8165       continue;
8166     }
8167     ++Quad[EltIdx / 4];
8168     InputQuads.set(EltIdx / 4);
8169   }
8170
8171   int BestLoQuad = -1;
8172   unsigned MaxQuad = 1;
8173   for (unsigned i = 0; i < 4; ++i) {
8174     if (LoQuad[i] > MaxQuad) {
8175       BestLoQuad = i;
8176       MaxQuad = LoQuad[i];
8177     }
8178   }
8179
8180   int BestHiQuad = -1;
8181   MaxQuad = 1;
8182   for (unsigned i = 0; i < 4; ++i) {
8183     if (HiQuad[i] > MaxQuad) {
8184       BestHiQuad = i;
8185       MaxQuad = HiQuad[i];
8186     }
8187   }
8188
8189   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8190   // of the two input vectors, shuffle them into one input vector so only a
8191   // single pshufb instruction is necessary. If there are more than 2 input
8192   // quads, disable the next transformation since it does not help SSSE3.
8193   bool V1Used = InputQuads[0] || InputQuads[1];
8194   bool V2Used = InputQuads[2] || InputQuads[3];
8195   if (Subtarget->hasSSSE3()) {
8196     if (InputQuads.count() == 2 && V1Used && V2Used) {
8197       BestLoQuad = InputQuads[0] ? 0 : 1;
8198       BestHiQuad = InputQuads[2] ? 2 : 3;
8199     }
8200     if (InputQuads.count() > 2) {
8201       BestLoQuad = -1;
8202       BestHiQuad = -1;
8203     }
8204   }
8205
8206   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8207   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8208   // words from all 4 input quadwords.
8209   SDValue NewV;
8210   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8211     int MaskV[] = {
8212       BestLoQuad < 0 ? 0 : BestLoQuad,
8213       BestHiQuad < 0 ? 1 : BestHiQuad
8214     };
8215     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8216                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8217                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8218     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8219
8220     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8221     // source words for the shuffle, to aid later transformations.
8222     bool AllWordsInNewV = true;
8223     bool InOrder[2] = { true, true };
8224     for (unsigned i = 0; i != 8; ++i) {
8225       int idx = MaskVals[i];
8226       if (idx != (int)i)
8227         InOrder[i/4] = false;
8228       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8229         continue;
8230       AllWordsInNewV = false;
8231       break;
8232     }
8233
8234     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8235     if (AllWordsInNewV) {
8236       for (int i = 0; i != 8; ++i) {
8237         int idx = MaskVals[i];
8238         if (idx < 0)
8239           continue;
8240         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8241         if ((idx != i) && idx < 4)
8242           pshufhw = false;
8243         if ((idx != i) && idx > 3)
8244           pshuflw = false;
8245       }
8246       V1 = NewV;
8247       V2Used = false;
8248       BestLoQuad = 0;
8249       BestHiQuad = 1;
8250     }
8251
8252     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8253     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8254     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8255       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8256       unsigned TargetMask = 0;
8257       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8258                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8259       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8260       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8261                              getShufflePSHUFLWImmediate(SVOp);
8262       V1 = NewV.getOperand(0);
8263       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8264     }
8265   }
8266
8267   // Promote splats to a larger type which usually leads to more efficient code.
8268   // FIXME: Is this true if pshufb is available?
8269   if (SVOp->isSplat())
8270     return PromoteSplat(SVOp, DAG);
8271
8272   // If we have SSSE3, and all words of the result are from 1 input vector,
8273   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8274   // is present, fall back to case 4.
8275   if (Subtarget->hasSSSE3()) {
8276     SmallVector<SDValue,16> pshufbMask;
8277
8278     // If we have elements from both input vectors, set the high bit of the
8279     // shuffle mask element to zero out elements that come from V2 in the V1
8280     // mask, and elements that come from V1 in the V2 mask, so that the two
8281     // results can be OR'd together.
8282     bool TwoInputs = V1Used && V2Used;
8283     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8284     if (!TwoInputs)
8285       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8286
8287     // Calculate the shuffle mask for the second input, shuffle it, and
8288     // OR it with the first shuffled input.
8289     CommuteVectorShuffleMask(MaskVals, 8);
8290     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8291     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8292     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8293   }
8294
8295   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8296   // and update MaskVals with new element order.
8297   std::bitset<8> InOrder;
8298   if (BestLoQuad >= 0) {
8299     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8300     for (int i = 0; i != 4; ++i) {
8301       int idx = MaskVals[i];
8302       if (idx < 0) {
8303         InOrder.set(i);
8304       } else if ((idx / 4) == BestLoQuad) {
8305         MaskV[i] = idx & 3;
8306         InOrder.set(i);
8307       }
8308     }
8309     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8310                                 &MaskV[0]);
8311
8312     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8313       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8314       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8315                                   NewV.getOperand(0),
8316                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8317     }
8318   }
8319
8320   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8321   // and update MaskVals with the new element order.
8322   if (BestHiQuad >= 0) {
8323     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8324     for (unsigned i = 4; i != 8; ++i) {
8325       int idx = MaskVals[i];
8326       if (idx < 0) {
8327         InOrder.set(i);
8328       } else if ((idx / 4) == BestHiQuad) {
8329         MaskV[i] = (idx & 3) + 4;
8330         InOrder.set(i);
8331       }
8332     }
8333     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8334                                 &MaskV[0]);
8335
8336     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8337       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8338       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8339                                   NewV.getOperand(0),
8340                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8341     }
8342   }
8343
8344   // In case BestHi & BestLo were both -1, which means each quadword has a word
8345   // from each of the four input quadwords, calculate the InOrder bitvector now
8346   // before falling through to the insert/extract cleanup.
8347   if (BestLoQuad == -1 && BestHiQuad == -1) {
8348     NewV = V1;
8349     for (int i = 0; i != 8; ++i)
8350       if (MaskVals[i] < 0 || MaskVals[i] == i)
8351         InOrder.set(i);
8352   }
8353
8354   // The other elements are put in the right place using pextrw and pinsrw.
8355   for (unsigned i = 0; i != 8; ++i) {
8356     if (InOrder[i])
8357       continue;
8358     int EltIdx = MaskVals[i];
8359     if (EltIdx < 0)
8360       continue;
8361     SDValue ExtOp = (EltIdx < 8) ?
8362       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8363                   DAG.getIntPtrConstant(EltIdx)) :
8364       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8365                   DAG.getIntPtrConstant(EltIdx - 8));
8366     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8367                        DAG.getIntPtrConstant(i));
8368   }
8369   return NewV;
8370 }
8371
8372 /// \brief v16i16 shuffles
8373 ///
8374 /// FIXME: We only support generation of a single pshufb currently.  We can
8375 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8376 /// well (e.g 2 x pshufb + 1 x por).
8377 static SDValue
8378 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8379   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8380   SDValue V1 = SVOp->getOperand(0);
8381   SDValue V2 = SVOp->getOperand(1);
8382   SDLoc dl(SVOp);
8383
8384   if (V2.getOpcode() != ISD::UNDEF)
8385     return SDValue();
8386
8387   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8388   return getPSHUFB(MaskVals, V1, dl, DAG);
8389 }
8390
8391 // v16i8 shuffles - Prefer shuffles in the following order:
8392 // 1. [ssse3] 1 x pshufb
8393 // 2. [ssse3] 2 x pshufb + 1 x por
8394 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8395 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8396                                         const X86Subtarget* Subtarget,
8397                                         SelectionDAG &DAG) {
8398   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8399   SDValue V1 = SVOp->getOperand(0);
8400   SDValue V2 = SVOp->getOperand(1);
8401   SDLoc dl(SVOp);
8402   ArrayRef<int> MaskVals = SVOp->getMask();
8403
8404   // Promote splats to a larger type which usually leads to more efficient code.
8405   // FIXME: Is this true if pshufb is available?
8406   if (SVOp->isSplat())
8407     return PromoteSplat(SVOp, DAG);
8408
8409   // If we have SSSE3, case 1 is generated when all result bytes come from
8410   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8411   // present, fall back to case 3.
8412
8413   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8414   if (Subtarget->hasSSSE3()) {
8415     SmallVector<SDValue,16> pshufbMask;
8416
8417     // If all result elements are from one input vector, then only translate
8418     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8419     //
8420     // Otherwise, we have elements from both input vectors, and must zero out
8421     // elements that come from V2 in the first mask, and V1 in the second mask
8422     // so that we can OR them together.
8423     for (unsigned i = 0; i != 16; ++i) {
8424       int EltIdx = MaskVals[i];
8425       if (EltIdx < 0 || EltIdx >= 16)
8426         EltIdx = 0x80;
8427       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8428     }
8429     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8430                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8431                                  MVT::v16i8, pshufbMask));
8432
8433     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8434     // the 2nd operand if it's undefined or zero.
8435     if (V2.getOpcode() == ISD::UNDEF ||
8436         ISD::isBuildVectorAllZeros(V2.getNode()))
8437       return V1;
8438
8439     // Calculate the shuffle mask for the second input, shuffle it, and
8440     // OR it with the first shuffled input.
8441     pshufbMask.clear();
8442     for (unsigned i = 0; i != 16; ++i) {
8443       int EltIdx = MaskVals[i];
8444       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8445       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8446     }
8447     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8448                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8449                                  MVT::v16i8, pshufbMask));
8450     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8451   }
8452
8453   // No SSSE3 - Calculate in place words and then fix all out of place words
8454   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8455   // the 16 different words that comprise the two doublequadword input vectors.
8456   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8457   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8458   SDValue NewV = V1;
8459   for (int i = 0; i != 8; ++i) {
8460     int Elt0 = MaskVals[i*2];
8461     int Elt1 = MaskVals[i*2+1];
8462
8463     // This word of the result is all undef, skip it.
8464     if (Elt0 < 0 && Elt1 < 0)
8465       continue;
8466
8467     // This word of the result is already in the correct place, skip it.
8468     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8469       continue;
8470
8471     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8472     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8473     SDValue InsElt;
8474
8475     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8476     // using a single extract together, load it and store it.
8477     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8478       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8479                            DAG.getIntPtrConstant(Elt1 / 2));
8480       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8481                         DAG.getIntPtrConstant(i));
8482       continue;
8483     }
8484
8485     // If Elt1 is defined, extract it from the appropriate source.  If the
8486     // source byte is not also odd, shift the extracted word left 8 bits
8487     // otherwise clear the bottom 8 bits if we need to do an or.
8488     if (Elt1 >= 0) {
8489       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8490                            DAG.getIntPtrConstant(Elt1 / 2));
8491       if ((Elt1 & 1) == 0)
8492         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8493                              DAG.getConstant(8,
8494                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8495       else if (Elt0 >= 0)
8496         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8497                              DAG.getConstant(0xFF00, MVT::i16));
8498     }
8499     // If Elt0 is defined, extract it from the appropriate source.  If the
8500     // source byte is not also even, shift the extracted word right 8 bits. If
8501     // Elt1 was also defined, OR the extracted values together before
8502     // inserting them in the result.
8503     if (Elt0 >= 0) {
8504       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8505                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8506       if ((Elt0 & 1) != 0)
8507         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8508                               DAG.getConstant(8,
8509                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8510       else if (Elt1 >= 0)
8511         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8512                              DAG.getConstant(0x00FF, MVT::i16));
8513       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8514                          : InsElt0;
8515     }
8516     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8517                        DAG.getIntPtrConstant(i));
8518   }
8519   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8520 }
8521
8522 // v32i8 shuffles - Translate to VPSHUFB if possible.
8523 static
8524 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8525                                  const X86Subtarget *Subtarget,
8526                                  SelectionDAG &DAG) {
8527   MVT VT = SVOp->getSimpleValueType(0);
8528   SDValue V1 = SVOp->getOperand(0);
8529   SDValue V2 = SVOp->getOperand(1);
8530   SDLoc dl(SVOp);
8531   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8532
8533   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8534   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8535   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8536
8537   // VPSHUFB may be generated if
8538   // (1) one of input vector is undefined or zeroinitializer.
8539   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8540   // And (2) the mask indexes don't cross the 128-bit lane.
8541   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8542       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8543     return SDValue();
8544
8545   if (V1IsAllZero && !V2IsAllZero) {
8546     CommuteVectorShuffleMask(MaskVals, 32);
8547     V1 = V2;
8548   }
8549   return getPSHUFB(MaskVals, V1, dl, DAG);
8550 }
8551
8552 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8553 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8554 /// done when every pair / quad of shuffle mask elements point to elements in
8555 /// the right sequence. e.g.
8556 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8557 static
8558 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8559                                  SelectionDAG &DAG) {
8560   MVT VT = SVOp->getSimpleValueType(0);
8561   SDLoc dl(SVOp);
8562   unsigned NumElems = VT.getVectorNumElements();
8563   MVT NewVT;
8564   unsigned Scale;
8565   switch (VT.SimpleTy) {
8566   default: llvm_unreachable("Unexpected!");
8567   case MVT::v2i64:
8568   case MVT::v2f64:
8569            return SDValue(SVOp, 0);
8570   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8571   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8572   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8573   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8574   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8575   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8576   }
8577
8578   SmallVector<int, 8> MaskVec;
8579   for (unsigned i = 0; i != NumElems; i += Scale) {
8580     int StartIdx = -1;
8581     for (unsigned j = 0; j != Scale; ++j) {
8582       int EltIdx = SVOp->getMaskElt(i+j);
8583       if (EltIdx < 0)
8584         continue;
8585       if (StartIdx < 0)
8586         StartIdx = (EltIdx / Scale);
8587       if (EltIdx != (int)(StartIdx*Scale + j))
8588         return SDValue();
8589     }
8590     MaskVec.push_back(StartIdx);
8591   }
8592
8593   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8594   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8595   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8596 }
8597
8598 /// getVZextMovL - Return a zero-extending vector move low node.
8599 ///
8600 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8601                             SDValue SrcOp, SelectionDAG &DAG,
8602                             const X86Subtarget *Subtarget, SDLoc dl) {
8603   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8604     LoadSDNode *LD = nullptr;
8605     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8606       LD = dyn_cast<LoadSDNode>(SrcOp);
8607     if (!LD) {
8608       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8609       // instead.
8610       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8611       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8612           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8613           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8614           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8615         // PR2108
8616         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8617         return DAG.getNode(ISD::BITCAST, dl, VT,
8618                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8619                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8620                                                    OpVT,
8621                                                    SrcOp.getOperand(0)
8622                                                           .getOperand(0))));
8623       }
8624     }
8625   }
8626
8627   return DAG.getNode(ISD::BITCAST, dl, VT,
8628                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8629                                  DAG.getNode(ISD::BITCAST, dl,
8630                                              OpVT, SrcOp)));
8631 }
8632
8633 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8634 /// which could not be matched by any known target speficic shuffle
8635 static SDValue
8636 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8637
8638   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8639   if (NewOp.getNode())
8640     return NewOp;
8641
8642   MVT VT = SVOp->getSimpleValueType(0);
8643
8644   unsigned NumElems = VT.getVectorNumElements();
8645   unsigned NumLaneElems = NumElems / 2;
8646
8647   SDLoc dl(SVOp);
8648   MVT EltVT = VT.getVectorElementType();
8649   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8650   SDValue Output[2];
8651
8652   SmallVector<int, 16> Mask;
8653   for (unsigned l = 0; l < 2; ++l) {
8654     // Build a shuffle mask for the output, discovering on the fly which
8655     // input vectors to use as shuffle operands (recorded in InputUsed).
8656     // If building a suitable shuffle vector proves too hard, then bail
8657     // out with UseBuildVector set.
8658     bool UseBuildVector = false;
8659     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8660     unsigned LaneStart = l * NumLaneElems;
8661     for (unsigned i = 0; i != NumLaneElems; ++i) {
8662       // The mask element.  This indexes into the input.
8663       int Idx = SVOp->getMaskElt(i+LaneStart);
8664       if (Idx < 0) {
8665         // the mask element does not index into any input vector.
8666         Mask.push_back(-1);
8667         continue;
8668       }
8669
8670       // The input vector this mask element indexes into.
8671       int Input = Idx / NumLaneElems;
8672
8673       // Turn the index into an offset from the start of the input vector.
8674       Idx -= Input * NumLaneElems;
8675
8676       // Find or create a shuffle vector operand to hold this input.
8677       unsigned OpNo;
8678       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8679         if (InputUsed[OpNo] == Input)
8680           // This input vector is already an operand.
8681           break;
8682         if (InputUsed[OpNo] < 0) {
8683           // Create a new operand for this input vector.
8684           InputUsed[OpNo] = Input;
8685           break;
8686         }
8687       }
8688
8689       if (OpNo >= array_lengthof(InputUsed)) {
8690         // More than two input vectors used!  Give up on trying to create a
8691         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8692         UseBuildVector = true;
8693         break;
8694       }
8695
8696       // Add the mask index for the new shuffle vector.
8697       Mask.push_back(Idx + OpNo * NumLaneElems);
8698     }
8699
8700     if (UseBuildVector) {
8701       SmallVector<SDValue, 16> SVOps;
8702       for (unsigned i = 0; i != NumLaneElems; ++i) {
8703         // The mask element.  This indexes into the input.
8704         int Idx = SVOp->getMaskElt(i+LaneStart);
8705         if (Idx < 0) {
8706           SVOps.push_back(DAG.getUNDEF(EltVT));
8707           continue;
8708         }
8709
8710         // The input vector this mask element indexes into.
8711         int Input = Idx / NumElems;
8712
8713         // Turn the index into an offset from the start of the input vector.
8714         Idx -= Input * NumElems;
8715
8716         // Extract the vector element by hand.
8717         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8718                                     SVOp->getOperand(Input),
8719                                     DAG.getIntPtrConstant(Idx)));
8720       }
8721
8722       // Construct the output using a BUILD_VECTOR.
8723       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8724     } else if (InputUsed[0] < 0) {
8725       // No input vectors were used! The result is undefined.
8726       Output[l] = DAG.getUNDEF(NVT);
8727     } else {
8728       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8729                                         (InputUsed[0] % 2) * NumLaneElems,
8730                                         DAG, dl);
8731       // If only one input was used, use an undefined vector for the other.
8732       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8733         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8734                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8735       // At least one input vector was used. Create a new shuffle vector.
8736       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8737     }
8738
8739     Mask.clear();
8740   }
8741
8742   // Concatenate the result back
8743   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8744 }
8745
8746 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8747 /// 4 elements, and match them with several different shuffle types.
8748 static SDValue
8749 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8750   SDValue V1 = SVOp->getOperand(0);
8751   SDValue V2 = SVOp->getOperand(1);
8752   SDLoc dl(SVOp);
8753   MVT VT = SVOp->getSimpleValueType(0);
8754
8755   assert(VT.is128BitVector() && "Unsupported vector size");
8756
8757   std::pair<int, int> Locs[4];
8758   int Mask1[] = { -1, -1, -1, -1 };
8759   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8760
8761   unsigned NumHi = 0;
8762   unsigned NumLo = 0;
8763   for (unsigned i = 0; i != 4; ++i) {
8764     int Idx = PermMask[i];
8765     if (Idx < 0) {
8766       Locs[i] = std::make_pair(-1, -1);
8767     } else {
8768       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8769       if (Idx < 4) {
8770         Locs[i] = std::make_pair(0, NumLo);
8771         Mask1[NumLo] = Idx;
8772         NumLo++;
8773       } else {
8774         Locs[i] = std::make_pair(1, NumHi);
8775         if (2+NumHi < 4)
8776           Mask1[2+NumHi] = Idx;
8777         NumHi++;
8778       }
8779     }
8780   }
8781
8782   if (NumLo <= 2 && NumHi <= 2) {
8783     // If no more than two elements come from either vector. This can be
8784     // implemented with two shuffles. First shuffle gather the elements.
8785     // The second shuffle, which takes the first shuffle as both of its
8786     // vector operands, put the elements into the right order.
8787     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8788
8789     int Mask2[] = { -1, -1, -1, -1 };
8790
8791     for (unsigned i = 0; i != 4; ++i)
8792       if (Locs[i].first != -1) {
8793         unsigned Idx = (i < 2) ? 0 : 4;
8794         Idx += Locs[i].first * 2 + Locs[i].second;
8795         Mask2[i] = Idx;
8796       }
8797
8798     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8799   }
8800
8801   if (NumLo == 3 || NumHi == 3) {
8802     // Otherwise, we must have three elements from one vector, call it X, and
8803     // one element from the other, call it Y.  First, use a shufps to build an
8804     // intermediate vector with the one element from Y and the element from X
8805     // that will be in the same half in the final destination (the indexes don't
8806     // matter). Then, use a shufps to build the final vector, taking the half
8807     // containing the element from Y from the intermediate, and the other half
8808     // from X.
8809     if (NumHi == 3) {
8810       // Normalize it so the 3 elements come from V1.
8811       CommuteVectorShuffleMask(PermMask, 4);
8812       std::swap(V1, V2);
8813     }
8814
8815     // Find the element from V2.
8816     unsigned HiIndex;
8817     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8818       int Val = PermMask[HiIndex];
8819       if (Val < 0)
8820         continue;
8821       if (Val >= 4)
8822         break;
8823     }
8824
8825     Mask1[0] = PermMask[HiIndex];
8826     Mask1[1] = -1;
8827     Mask1[2] = PermMask[HiIndex^1];
8828     Mask1[3] = -1;
8829     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8830
8831     if (HiIndex >= 2) {
8832       Mask1[0] = PermMask[0];
8833       Mask1[1] = PermMask[1];
8834       Mask1[2] = HiIndex & 1 ? 6 : 4;
8835       Mask1[3] = HiIndex & 1 ? 4 : 6;
8836       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8837     }
8838
8839     Mask1[0] = HiIndex & 1 ? 2 : 0;
8840     Mask1[1] = HiIndex & 1 ? 0 : 2;
8841     Mask1[2] = PermMask[2];
8842     Mask1[3] = PermMask[3];
8843     if (Mask1[2] >= 0)
8844       Mask1[2] += 4;
8845     if (Mask1[3] >= 0)
8846       Mask1[3] += 4;
8847     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8848   }
8849
8850   // Break it into (shuffle shuffle_hi, shuffle_lo).
8851   int LoMask[] = { -1, -1, -1, -1 };
8852   int HiMask[] = { -1, -1, -1, -1 };
8853
8854   int *MaskPtr = LoMask;
8855   unsigned MaskIdx = 0;
8856   unsigned LoIdx = 0;
8857   unsigned HiIdx = 2;
8858   for (unsigned i = 0; i != 4; ++i) {
8859     if (i == 2) {
8860       MaskPtr = HiMask;
8861       MaskIdx = 1;
8862       LoIdx = 0;
8863       HiIdx = 2;
8864     }
8865     int Idx = PermMask[i];
8866     if (Idx < 0) {
8867       Locs[i] = std::make_pair(-1, -1);
8868     } else if (Idx < 4) {
8869       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8870       MaskPtr[LoIdx] = Idx;
8871       LoIdx++;
8872     } else {
8873       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8874       MaskPtr[HiIdx] = Idx;
8875       HiIdx++;
8876     }
8877   }
8878
8879   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8880   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8881   int MaskOps[] = { -1, -1, -1, -1 };
8882   for (unsigned i = 0; i != 4; ++i)
8883     if (Locs[i].first != -1)
8884       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8885   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8886 }
8887
8888 static bool MayFoldVectorLoad(SDValue V) {
8889   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8890     V = V.getOperand(0);
8891
8892   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8893     V = V.getOperand(0);
8894   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8895       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8896     // BUILD_VECTOR (load), undef
8897     V = V.getOperand(0);
8898
8899   return MayFoldLoad(V);
8900 }
8901
8902 static
8903 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8904   MVT VT = Op.getSimpleValueType();
8905
8906   // Canonizalize to v2f64.
8907   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8908   return DAG.getNode(ISD::BITCAST, dl, VT,
8909                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8910                                           V1, DAG));
8911 }
8912
8913 static
8914 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8915                         bool HasSSE2) {
8916   SDValue V1 = Op.getOperand(0);
8917   SDValue V2 = Op.getOperand(1);
8918   MVT VT = Op.getSimpleValueType();
8919
8920   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8921
8922   if (HasSSE2 && VT == MVT::v2f64)
8923     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8924
8925   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8926   return DAG.getNode(ISD::BITCAST, dl, VT,
8927                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8928                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8929                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8930 }
8931
8932 static
8933 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8934   SDValue V1 = Op.getOperand(0);
8935   SDValue V2 = Op.getOperand(1);
8936   MVT VT = Op.getSimpleValueType();
8937
8938   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8939          "unsupported shuffle type");
8940
8941   if (V2.getOpcode() == ISD::UNDEF)
8942     V2 = V1;
8943
8944   // v4i32 or v4f32
8945   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8946 }
8947
8948 static
8949 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8950   SDValue V1 = Op.getOperand(0);
8951   SDValue V2 = Op.getOperand(1);
8952   MVT VT = Op.getSimpleValueType();
8953   unsigned NumElems = VT.getVectorNumElements();
8954
8955   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8956   // operand of these instructions is only memory, so check if there's a
8957   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8958   // same masks.
8959   bool CanFoldLoad = false;
8960
8961   // Trivial case, when V2 comes from a load.
8962   if (MayFoldVectorLoad(V2))
8963     CanFoldLoad = true;
8964
8965   // When V1 is a load, it can be folded later into a store in isel, example:
8966   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8967   //    turns into:
8968   //  (MOVLPSmr addr:$src1, VR128:$src2)
8969   // So, recognize this potential and also use MOVLPS or MOVLPD
8970   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8971     CanFoldLoad = true;
8972
8973   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8974   if (CanFoldLoad) {
8975     if (HasSSE2 && NumElems == 2)
8976       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8977
8978     if (NumElems == 4)
8979       // If we don't care about the second element, proceed to use movss.
8980       if (SVOp->getMaskElt(1) != -1)
8981         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8982   }
8983
8984   // movl and movlp will both match v2i64, but v2i64 is never matched by
8985   // movl earlier because we make it strict to avoid messing with the movlp load
8986   // folding logic (see the code above getMOVLP call). Match it here then,
8987   // this is horrible, but will stay like this until we move all shuffle
8988   // matching to x86 specific nodes. Note that for the 1st condition all
8989   // types are matched with movsd.
8990   if (HasSSE2) {
8991     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8992     // as to remove this logic from here, as much as possible
8993     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8994       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8995     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8996   }
8997
8998   assert(VT != MVT::v4i32 && "unsupported shuffle type");
8999
9000   // Invert the operand order and use SHUFPS to match it.
9001   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9002                               getShuffleSHUFImmediate(SVOp), DAG);
9003 }
9004
9005 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9006                                          SelectionDAG &DAG) {
9007   SDLoc dl(Load);
9008   MVT VT = Load->getSimpleValueType(0);
9009   MVT EVT = VT.getVectorElementType();
9010   SDValue Addr = Load->getOperand(1);
9011   SDValue NewAddr = DAG.getNode(
9012       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9013       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9014
9015   SDValue NewLoad =
9016       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9017                   DAG.getMachineFunction().getMachineMemOperand(
9018                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9019   return NewLoad;
9020 }
9021
9022 // It is only safe to call this function if isINSERTPSMask is true for
9023 // this shufflevector mask.
9024 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9025                            SelectionDAG &DAG) {
9026   // Generate an insertps instruction when inserting an f32 from memory onto a
9027   // v4f32 or when copying a member from one v4f32 to another.
9028   // We also use it for transferring i32 from one register to another,
9029   // since it simply copies the same bits.
9030   // If we're transferring an i32 from memory to a specific element in a
9031   // register, we output a generic DAG that will match the PINSRD
9032   // instruction.
9033   MVT VT = SVOp->getSimpleValueType(0);
9034   MVT EVT = VT.getVectorElementType();
9035   SDValue V1 = SVOp->getOperand(0);
9036   SDValue V2 = SVOp->getOperand(1);
9037   auto Mask = SVOp->getMask();
9038   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9039          "unsupported vector type for insertps/pinsrd");
9040
9041   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9042   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9043   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9044
9045   SDValue From;
9046   SDValue To;
9047   unsigned DestIndex;
9048   if (FromV1 == 1) {
9049     From = V1;
9050     To = V2;
9051     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9052                 Mask.begin();
9053   } else {
9054     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9055            "More than one element from V1 and from V2, or no elements from one "
9056            "of the vectors. This case should not have returned true from "
9057            "isINSERTPSMask");
9058     From = V2;
9059     To = V1;
9060     DestIndex =
9061         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9062   }
9063
9064   unsigned SrcIndex = Mask[DestIndex] % 4;
9065   if (MayFoldLoad(From)) {
9066     // Trivial case, when From comes from a load and is only used by the
9067     // shuffle. Make it use insertps from the vector that we need from that
9068     // load.
9069     SDValue NewLoad =
9070         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9071     if (!NewLoad.getNode())
9072       return SDValue();
9073
9074     if (EVT == MVT::f32) {
9075       // Create this as a scalar to vector to match the instruction pattern.
9076       SDValue LoadScalarToVector =
9077           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9078       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9079       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9080                          InsertpsMask);
9081     } else { // EVT == MVT::i32
9082       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9083       // instruction, to match the PINSRD instruction, which loads an i32 to a
9084       // certain vector element.
9085       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9086                          DAG.getConstant(DestIndex, MVT::i32));
9087     }
9088   }
9089
9090   // Vector-element-to-vector
9091   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9092   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9093 }
9094
9095 // Reduce a vector shuffle to zext.
9096 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9097                                     SelectionDAG &DAG) {
9098   // PMOVZX is only available from SSE41.
9099   if (!Subtarget->hasSSE41())
9100     return SDValue();
9101
9102   MVT VT = Op.getSimpleValueType();
9103
9104   // Only AVX2 support 256-bit vector integer extending.
9105   if (!Subtarget->hasInt256() && VT.is256BitVector())
9106     return SDValue();
9107
9108   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9109   SDLoc DL(Op);
9110   SDValue V1 = Op.getOperand(0);
9111   SDValue V2 = Op.getOperand(1);
9112   unsigned NumElems = VT.getVectorNumElements();
9113
9114   // Extending is an unary operation and the element type of the source vector
9115   // won't be equal to or larger than i64.
9116   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9117       VT.getVectorElementType() == MVT::i64)
9118     return SDValue();
9119
9120   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9121   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9122   while ((1U << Shift) < NumElems) {
9123     if (SVOp->getMaskElt(1U << Shift) == 1)
9124       break;
9125     Shift += 1;
9126     // The maximal ratio is 8, i.e. from i8 to i64.
9127     if (Shift > 3)
9128       return SDValue();
9129   }
9130
9131   // Check the shuffle mask.
9132   unsigned Mask = (1U << Shift) - 1;
9133   for (unsigned i = 0; i != NumElems; ++i) {
9134     int EltIdx = SVOp->getMaskElt(i);
9135     if ((i & Mask) != 0 && EltIdx != -1)
9136       return SDValue();
9137     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9138       return SDValue();
9139   }
9140
9141   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9142   MVT NeVT = MVT::getIntegerVT(NBits);
9143   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9144
9145   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9146     return SDValue();
9147
9148   // Simplify the operand as it's prepared to be fed into shuffle.
9149   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9150   if (V1.getOpcode() == ISD::BITCAST &&
9151       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9152       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9153       V1.getOperand(0).getOperand(0)
9154         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9155     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9156     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9157     ConstantSDNode *CIdx =
9158       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9159     // If it's foldable, i.e. normal load with single use, we will let code
9160     // selection to fold it. Otherwise, we will short the conversion sequence.
9161     if (CIdx && CIdx->getZExtValue() == 0 &&
9162         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9163       MVT FullVT = V.getSimpleValueType();
9164       MVT V1VT = V1.getSimpleValueType();
9165       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9166         // The "ext_vec_elt" node is wider than the result node.
9167         // In this case we should extract subvector from V.
9168         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9169         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9170         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9171                                         FullVT.getVectorNumElements()/Ratio);
9172         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9173                         DAG.getIntPtrConstant(0));
9174       }
9175       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9176     }
9177   }
9178
9179   return DAG.getNode(ISD::BITCAST, DL, VT,
9180                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9181 }
9182
9183 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9184                                       SelectionDAG &DAG) {
9185   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9186   MVT VT = Op.getSimpleValueType();
9187   SDLoc dl(Op);
9188   SDValue V1 = Op.getOperand(0);
9189   SDValue V2 = Op.getOperand(1);
9190
9191   if (isZeroShuffle(SVOp))
9192     return getZeroVector(VT, Subtarget, DAG, dl);
9193
9194   // Handle splat operations
9195   if (SVOp->isSplat()) {
9196     // Use vbroadcast whenever the splat comes from a foldable load
9197     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9198     if (Broadcast.getNode())
9199       return Broadcast;
9200   }
9201
9202   // Check integer expanding shuffles.
9203   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9204   if (NewOp.getNode())
9205     return NewOp;
9206
9207   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9208   // do it!
9209   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9210       VT == MVT::v32i8) {
9211     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9212     if (NewOp.getNode())
9213       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9214   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9215     // FIXME: Figure out a cleaner way to do this.
9216     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9217       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9218       if (NewOp.getNode()) {
9219         MVT NewVT = NewOp.getSimpleValueType();
9220         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9221                                NewVT, true, false))
9222           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9223                               dl);
9224       }
9225     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9226       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9227       if (NewOp.getNode()) {
9228         MVT NewVT = NewOp.getSimpleValueType();
9229         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9230           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9231                               dl);
9232       }
9233     }
9234   }
9235   return SDValue();
9236 }
9237
9238 SDValue
9239 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9240   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9241   SDValue V1 = Op.getOperand(0);
9242   SDValue V2 = Op.getOperand(1);
9243   MVT VT = Op.getSimpleValueType();
9244   SDLoc dl(Op);
9245   unsigned NumElems = VT.getVectorNumElements();
9246   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9247   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9248   bool V1IsSplat = false;
9249   bool V2IsSplat = false;
9250   bool HasSSE2 = Subtarget->hasSSE2();
9251   bool HasFp256    = Subtarget->hasFp256();
9252   bool HasInt256   = Subtarget->hasInt256();
9253   MachineFunction &MF = DAG.getMachineFunction();
9254   bool OptForSize = MF.getFunction()->getAttributes().
9255     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9256
9257   // Check if we should use the experimental vector shuffle lowering. If so,
9258   // delegate completely to that code path.
9259   if (ExperimentalVectorShuffleLowering)
9260     return lowerVectorShuffle(Op, Subtarget, DAG);
9261
9262   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9263
9264   if (V1IsUndef && V2IsUndef)
9265     return DAG.getUNDEF(VT);
9266
9267   // When we create a shuffle node we put the UNDEF node to second operand,
9268   // but in some cases the first operand may be transformed to UNDEF.
9269   // In this case we should just commute the node.
9270   if (V1IsUndef)
9271     return CommuteVectorShuffle(SVOp, DAG);
9272
9273   // Vector shuffle lowering takes 3 steps:
9274   //
9275   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9276   //    narrowing and commutation of operands should be handled.
9277   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9278   //    shuffle nodes.
9279   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9280   //    so the shuffle can be broken into other shuffles and the legalizer can
9281   //    try the lowering again.
9282   //
9283   // The general idea is that no vector_shuffle operation should be left to
9284   // be matched during isel, all of them must be converted to a target specific
9285   // node here.
9286
9287   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9288   // narrowing and commutation of operands should be handled. The actual code
9289   // doesn't include all of those, work in progress...
9290   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9291   if (NewOp.getNode())
9292     return NewOp;
9293
9294   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9295
9296   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9297   // unpckh_undef). Only use pshufd if speed is more important than size.
9298   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9299     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9300   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9301     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9302
9303   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9304       V2IsUndef && MayFoldVectorLoad(V1))
9305     return getMOVDDup(Op, dl, V1, DAG);
9306
9307   if (isMOVHLPS_v_undef_Mask(M, VT))
9308     return getMOVHighToLow(Op, dl, DAG);
9309
9310   // Use to match splats
9311   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9312       (VT == MVT::v2f64 || VT == MVT::v2i64))
9313     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9314
9315   if (isPSHUFDMask(M, VT)) {
9316     // The actual implementation will match the mask in the if above and then
9317     // during isel it can match several different instructions, not only pshufd
9318     // as its name says, sad but true, emulate the behavior for now...
9319     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9320       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9321
9322     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9323
9324     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9325       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9326
9327     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9328       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9329                                   DAG);
9330
9331     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9332                                 TargetMask, DAG);
9333   }
9334
9335   if (isPALIGNRMask(M, VT, Subtarget))
9336     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9337                                 getShufflePALIGNRImmediate(SVOp),
9338                                 DAG);
9339
9340   // Check if this can be converted into a logical shift.
9341   bool isLeft = false;
9342   unsigned ShAmt = 0;
9343   SDValue ShVal;
9344   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9345   if (isShift && ShVal.hasOneUse()) {
9346     // If the shifted value has multiple uses, it may be cheaper to use
9347     // v_set0 + movlhps or movhlps, etc.
9348     MVT EltVT = VT.getVectorElementType();
9349     ShAmt *= EltVT.getSizeInBits();
9350     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9351   }
9352
9353   if (isMOVLMask(M, VT)) {
9354     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9355       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9356     if (!isMOVLPMask(M, VT)) {
9357       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9358         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9359
9360       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9361         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9362     }
9363   }
9364
9365   // FIXME: fold these into legal mask.
9366   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9367     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9368
9369   if (isMOVHLPSMask(M, VT))
9370     return getMOVHighToLow(Op, dl, DAG);
9371
9372   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9373     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9374
9375   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9376     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9377
9378   if (isMOVLPMask(M, VT))
9379     return getMOVLP(Op, dl, DAG, HasSSE2);
9380
9381   if (ShouldXformToMOVHLPS(M, VT) ||
9382       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9383     return CommuteVectorShuffle(SVOp, DAG);
9384
9385   if (isShift) {
9386     // No better options. Use a vshldq / vsrldq.
9387     MVT EltVT = VT.getVectorElementType();
9388     ShAmt *= EltVT.getSizeInBits();
9389     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9390   }
9391
9392   bool Commuted = false;
9393   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9394   // 1,1,1,1 -> v8i16 though.
9395   BitVector UndefElements;
9396   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9397     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9398       V1IsSplat = true;
9399   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9400     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9401       V2IsSplat = true;
9402
9403   // Canonicalize the splat or undef, if present, to be on the RHS.
9404   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9405     CommuteVectorShuffleMask(M, NumElems);
9406     std::swap(V1, V2);
9407     std::swap(V1IsSplat, V2IsSplat);
9408     Commuted = true;
9409   }
9410
9411   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9412     // Shuffling low element of v1 into undef, just return v1.
9413     if (V2IsUndef)
9414       return V1;
9415     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9416     // the instruction selector will not match, so get a canonical MOVL with
9417     // swapped operands to undo the commute.
9418     return getMOVL(DAG, dl, VT, V2, V1);
9419   }
9420
9421   if (isUNPCKLMask(M, VT, HasInt256))
9422     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9423
9424   if (isUNPCKHMask(M, VT, HasInt256))
9425     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9426
9427   if (V2IsSplat) {
9428     // Normalize mask so all entries that point to V2 points to its first
9429     // element then try to match unpck{h|l} again. If match, return a
9430     // new vector_shuffle with the corrected mask.p
9431     SmallVector<int, 8> NewMask(M.begin(), M.end());
9432     NormalizeMask(NewMask, NumElems);
9433     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9434       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9435     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9436       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9437   }
9438
9439   if (Commuted) {
9440     // Commute is back and try unpck* again.
9441     // FIXME: this seems wrong.
9442     CommuteVectorShuffleMask(M, NumElems);
9443     std::swap(V1, V2);
9444     std::swap(V1IsSplat, V2IsSplat);
9445
9446     if (isUNPCKLMask(M, VT, HasInt256))
9447       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9448
9449     if (isUNPCKHMask(M, VT, HasInt256))
9450       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9451   }
9452
9453   // Normalize the node to match x86 shuffle ops if needed
9454   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9455     return CommuteVectorShuffle(SVOp, DAG);
9456
9457   // The checks below are all present in isShuffleMaskLegal, but they are
9458   // inlined here right now to enable us to directly emit target specific
9459   // nodes, and remove one by one until they don't return Op anymore.
9460
9461   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9462       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9463     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9464       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9465   }
9466
9467   if (isPSHUFHWMask(M, VT, HasInt256))
9468     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9469                                 getShufflePSHUFHWImmediate(SVOp),
9470                                 DAG);
9471
9472   if (isPSHUFLWMask(M, VT, HasInt256))
9473     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9474                                 getShufflePSHUFLWImmediate(SVOp),
9475                                 DAG);
9476
9477   unsigned MaskValue;
9478   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9479                   &MaskValue))
9480     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9481
9482   if (isSHUFPMask(M, VT))
9483     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9484                                 getShuffleSHUFImmediate(SVOp), DAG);
9485
9486   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9487     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9488   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9489     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9490
9491   //===--------------------------------------------------------------------===//
9492   // Generate target specific nodes for 128 or 256-bit shuffles only
9493   // supported in the AVX instruction set.
9494   //
9495
9496   // Handle VMOVDDUPY permutations
9497   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9498     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9499
9500   // Handle VPERMILPS/D* permutations
9501   if (isVPERMILPMask(M, VT)) {
9502     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9503       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9504                                   getShuffleSHUFImmediate(SVOp), DAG);
9505     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9506                                 getShuffleSHUFImmediate(SVOp), DAG);
9507   }
9508
9509   unsigned Idx;
9510   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9511     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9512                               Idx*(NumElems/2), DAG, dl);
9513
9514   // Handle VPERM2F128/VPERM2I128 permutations
9515   if (isVPERM2X128Mask(M, VT, HasFp256))
9516     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9517                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9518
9519   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9520     return getINSERTPS(SVOp, dl, DAG);
9521
9522   unsigned Imm8;
9523   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9524     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9525
9526   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9527       VT.is512BitVector()) {
9528     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9529     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9530     SmallVector<SDValue, 16> permclMask;
9531     for (unsigned i = 0; i != NumElems; ++i) {
9532       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9533     }
9534
9535     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9536     if (V2IsUndef)
9537       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9538       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9539                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9540     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9541                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9542   }
9543
9544   //===--------------------------------------------------------------------===//
9545   // Since no target specific shuffle was selected for this generic one,
9546   // lower it into other known shuffles. FIXME: this isn't true yet, but
9547   // this is the plan.
9548   //
9549
9550   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9551   if (VT == MVT::v8i16) {
9552     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9553     if (NewOp.getNode())
9554       return NewOp;
9555   }
9556
9557   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9558     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9559     if (NewOp.getNode())
9560       return NewOp;
9561   }
9562
9563   if (VT == MVT::v16i8) {
9564     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9565     if (NewOp.getNode())
9566       return NewOp;
9567   }
9568
9569   if (VT == MVT::v32i8) {
9570     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9571     if (NewOp.getNode())
9572       return NewOp;
9573   }
9574
9575   // Handle all 128-bit wide vectors with 4 elements, and match them with
9576   // several different shuffle types.
9577   if (NumElems == 4 && VT.is128BitVector())
9578     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9579
9580   // Handle general 256-bit shuffles
9581   if (VT.is256BitVector())
9582     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9583
9584   return SDValue();
9585 }
9586
9587 // This function assumes its argument is a BUILD_VECTOR of constants or
9588 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9589 // true.
9590 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9591                                     unsigned &MaskValue) {
9592   MaskValue = 0;
9593   unsigned NumElems = BuildVector->getNumOperands();
9594   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9595   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9596   unsigned NumElemsInLane = NumElems / NumLanes;
9597
9598   // Blend for v16i16 should be symetric for the both lanes.
9599   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9600     SDValue EltCond = BuildVector->getOperand(i);
9601     SDValue SndLaneEltCond =
9602         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9603
9604     int Lane1Cond = -1, Lane2Cond = -1;
9605     if (isa<ConstantSDNode>(EltCond))
9606       Lane1Cond = !isZero(EltCond);
9607     if (isa<ConstantSDNode>(SndLaneEltCond))
9608       Lane2Cond = !isZero(SndLaneEltCond);
9609
9610     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9611       // Lane1Cond != 0, means we want the first argument.
9612       // Lane1Cond == 0, means we want the second argument.
9613       // The encoding of this argument is 0 for the first argument, 1
9614       // for the second. Therefore, invert the condition.
9615       MaskValue |= !Lane1Cond << i;
9616     else if (Lane1Cond < 0)
9617       MaskValue |= !Lane2Cond << i;
9618     else
9619       return false;
9620   }
9621   return true;
9622 }
9623
9624 // Try to lower a vselect node into a simple blend instruction.
9625 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9626                                    SelectionDAG &DAG) {
9627   SDValue Cond = Op.getOperand(0);
9628   SDValue LHS = Op.getOperand(1);
9629   SDValue RHS = Op.getOperand(2);
9630   SDLoc dl(Op);
9631   MVT VT = Op.getSimpleValueType();
9632   MVT EltVT = VT.getVectorElementType();
9633   unsigned NumElems = VT.getVectorNumElements();
9634
9635   // There is no blend with immediate in AVX-512.
9636   if (VT.is512BitVector())
9637     return SDValue();
9638
9639   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9640     return SDValue();
9641   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9642     return SDValue();
9643
9644   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9645     return SDValue();
9646
9647   // Check the mask for BLEND and build the value.
9648   unsigned MaskValue = 0;
9649   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9650     return SDValue();
9651
9652   // Convert i32 vectors to floating point if it is not AVX2.
9653   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9654   MVT BlendVT = VT;
9655   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9656     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9657                                NumElems);
9658     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9659     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9660   }
9661
9662   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9663                             DAG.getConstant(MaskValue, MVT::i32));
9664   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9665 }
9666
9667 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9668   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9669   if (BlendOp.getNode())
9670     return BlendOp;
9671
9672   // Some types for vselect were previously set to Expand, not Legal or
9673   // Custom. Return an empty SDValue so we fall-through to Expand, after
9674   // the Custom lowering phase.
9675   MVT VT = Op.getSimpleValueType();
9676   switch (VT.SimpleTy) {
9677   default:
9678     break;
9679   case MVT::v8i16:
9680   case MVT::v16i16:
9681     return SDValue();
9682   }
9683
9684   // We couldn't create a "Blend with immediate" node.
9685   // This node should still be legal, but we'll have to emit a blendv*
9686   // instruction.
9687   return Op;
9688 }
9689
9690 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9691   MVT VT = Op.getSimpleValueType();
9692   SDLoc dl(Op);
9693
9694   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9695     return SDValue();
9696
9697   if (VT.getSizeInBits() == 8) {
9698     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9699                                   Op.getOperand(0), Op.getOperand(1));
9700     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9701                                   DAG.getValueType(VT));
9702     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9703   }
9704
9705   if (VT.getSizeInBits() == 16) {
9706     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9707     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9708     if (Idx == 0)
9709       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9710                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9711                                      DAG.getNode(ISD::BITCAST, dl,
9712                                                  MVT::v4i32,
9713                                                  Op.getOperand(0)),
9714                                      Op.getOperand(1)));
9715     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9716                                   Op.getOperand(0), Op.getOperand(1));
9717     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9718                                   DAG.getValueType(VT));
9719     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9720   }
9721
9722   if (VT == MVT::f32) {
9723     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9724     // the result back to FR32 register. It's only worth matching if the
9725     // result has a single use which is a store or a bitcast to i32.  And in
9726     // the case of a store, it's not worth it if the index is a constant 0,
9727     // because a MOVSSmr can be used instead, which is smaller and faster.
9728     if (!Op.hasOneUse())
9729       return SDValue();
9730     SDNode *User = *Op.getNode()->use_begin();
9731     if ((User->getOpcode() != ISD::STORE ||
9732          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9733           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9734         (User->getOpcode() != ISD::BITCAST ||
9735          User->getValueType(0) != MVT::i32))
9736       return SDValue();
9737     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9738                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9739                                               Op.getOperand(0)),
9740                                               Op.getOperand(1));
9741     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9742   }
9743
9744   if (VT == MVT::i32 || VT == MVT::i64) {
9745     // ExtractPS/pextrq works with constant index.
9746     if (isa<ConstantSDNode>(Op.getOperand(1)))
9747       return Op;
9748   }
9749   return SDValue();
9750 }
9751
9752 /// Extract one bit from mask vector, like v16i1 or v8i1.
9753 /// AVX-512 feature.
9754 SDValue
9755 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9756   SDValue Vec = Op.getOperand(0);
9757   SDLoc dl(Vec);
9758   MVT VecVT = Vec.getSimpleValueType();
9759   SDValue Idx = Op.getOperand(1);
9760   MVT EltVT = Op.getSimpleValueType();
9761
9762   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9763
9764   // variable index can't be handled in mask registers,
9765   // extend vector to VR512
9766   if (!isa<ConstantSDNode>(Idx)) {
9767     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9768     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9769     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9770                               ExtVT.getVectorElementType(), Ext, Idx);
9771     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9772   }
9773
9774   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9775   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9776   unsigned MaxSift = rc->getSize()*8 - 1;
9777   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9778                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9779   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9780                     DAG.getConstant(MaxSift, MVT::i8));
9781   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9782                        DAG.getIntPtrConstant(0));
9783 }
9784
9785 SDValue
9786 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9787                                            SelectionDAG &DAG) const {
9788   SDLoc dl(Op);
9789   SDValue Vec = Op.getOperand(0);
9790   MVT VecVT = Vec.getSimpleValueType();
9791   SDValue Idx = Op.getOperand(1);
9792
9793   if (Op.getSimpleValueType() == MVT::i1)
9794     return ExtractBitFromMaskVector(Op, DAG);
9795
9796   if (!isa<ConstantSDNode>(Idx)) {
9797     if (VecVT.is512BitVector() ||
9798         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9799          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9800
9801       MVT MaskEltVT =
9802         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9803       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9804                                     MaskEltVT.getSizeInBits());
9805
9806       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9807       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9808                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9809                                 Idx, DAG.getConstant(0, getPointerTy()));
9810       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9811       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9812                         Perm, DAG.getConstant(0, getPointerTy()));
9813     }
9814     return SDValue();
9815   }
9816
9817   // If this is a 256-bit vector result, first extract the 128-bit vector and
9818   // then extract the element from the 128-bit vector.
9819   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9820
9821     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9822     // Get the 128-bit vector.
9823     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9824     MVT EltVT = VecVT.getVectorElementType();
9825
9826     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9827
9828     //if (IdxVal >= NumElems/2)
9829     //  IdxVal -= NumElems/2;
9830     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9831     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9832                        DAG.getConstant(IdxVal, MVT::i32));
9833   }
9834
9835   assert(VecVT.is128BitVector() && "Unexpected vector length");
9836
9837   if (Subtarget->hasSSE41()) {
9838     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9839     if (Res.getNode())
9840       return Res;
9841   }
9842
9843   MVT VT = Op.getSimpleValueType();
9844   // TODO: handle v16i8.
9845   if (VT.getSizeInBits() == 16) {
9846     SDValue Vec = Op.getOperand(0);
9847     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9848     if (Idx == 0)
9849       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9850                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9851                                      DAG.getNode(ISD::BITCAST, dl,
9852                                                  MVT::v4i32, Vec),
9853                                      Op.getOperand(1)));
9854     // Transform it so it match pextrw which produces a 32-bit result.
9855     MVT EltVT = MVT::i32;
9856     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9857                                   Op.getOperand(0), Op.getOperand(1));
9858     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9859                                   DAG.getValueType(VT));
9860     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9861   }
9862
9863   if (VT.getSizeInBits() == 32) {
9864     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9865     if (Idx == 0)
9866       return Op;
9867
9868     // SHUFPS the element to the lowest double word, then movss.
9869     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9870     MVT VVT = Op.getOperand(0).getSimpleValueType();
9871     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9872                                        DAG.getUNDEF(VVT), Mask);
9873     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9874                        DAG.getIntPtrConstant(0));
9875   }
9876
9877   if (VT.getSizeInBits() == 64) {
9878     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9879     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9880     //        to match extract_elt for f64.
9881     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9882     if (Idx == 0)
9883       return Op;
9884
9885     // UNPCKHPD the element to the lowest double word, then movsd.
9886     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9887     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9888     int Mask[2] = { 1, -1 };
9889     MVT VVT = Op.getOperand(0).getSimpleValueType();
9890     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9891                                        DAG.getUNDEF(VVT), Mask);
9892     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9893                        DAG.getIntPtrConstant(0));
9894   }
9895
9896   return SDValue();
9897 }
9898
9899 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9900   MVT VT = Op.getSimpleValueType();
9901   MVT EltVT = VT.getVectorElementType();
9902   SDLoc dl(Op);
9903
9904   SDValue N0 = Op.getOperand(0);
9905   SDValue N1 = Op.getOperand(1);
9906   SDValue N2 = Op.getOperand(2);
9907
9908   if (!VT.is128BitVector())
9909     return SDValue();
9910
9911   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9912       isa<ConstantSDNode>(N2)) {
9913     unsigned Opc;
9914     if (VT == MVT::v8i16)
9915       Opc = X86ISD::PINSRW;
9916     else if (VT == MVT::v16i8)
9917       Opc = X86ISD::PINSRB;
9918     else
9919       Opc = X86ISD::PINSRB;
9920
9921     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9922     // argument.
9923     if (N1.getValueType() != MVT::i32)
9924       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9925     if (N2.getValueType() != MVT::i32)
9926       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9927     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9928   }
9929
9930   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9931     // Bits [7:6] of the constant are the source select.  This will always be
9932     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9933     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9934     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9935     // Bits [5:4] of the constant are the destination select.  This is the
9936     //  value of the incoming immediate.
9937     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9938     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9939     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9940     // Create this as a scalar to vector..
9941     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9942     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9943   }
9944
9945   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9946     // PINSR* works with constant index.
9947     return Op;
9948   }
9949   return SDValue();
9950 }
9951
9952 /// Insert one bit to mask vector, like v16i1 or v8i1.
9953 /// AVX-512 feature.
9954 SDValue 
9955 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9956   SDLoc dl(Op);
9957   SDValue Vec = Op.getOperand(0);
9958   SDValue Elt = Op.getOperand(1);
9959   SDValue Idx = Op.getOperand(2);
9960   MVT VecVT = Vec.getSimpleValueType();
9961
9962   if (!isa<ConstantSDNode>(Idx)) {
9963     // Non constant index. Extend source and destination,
9964     // insert element and then truncate the result.
9965     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9966     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9967     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9968       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9969       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9970     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9971   }
9972
9973   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9974   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9975   if (Vec.getOpcode() == ISD::UNDEF)
9976     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9977                        DAG.getConstant(IdxVal, MVT::i8));
9978   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9979   unsigned MaxSift = rc->getSize()*8 - 1;
9980   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9981                     DAG.getConstant(MaxSift, MVT::i8));
9982   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9983                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9984   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9985 }
9986 SDValue
9987 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9988   MVT VT = Op.getSimpleValueType();
9989   MVT EltVT = VT.getVectorElementType();
9990   
9991   if (EltVT == MVT::i1)
9992     return InsertBitToMaskVector(Op, DAG);
9993
9994   SDLoc dl(Op);
9995   SDValue N0 = Op.getOperand(0);
9996   SDValue N1 = Op.getOperand(1);
9997   SDValue N2 = Op.getOperand(2);
9998
9999   // If this is a 256-bit vector result, first extract the 128-bit vector,
10000   // insert the element into the extracted half and then place it back.
10001   if (VT.is256BitVector() || VT.is512BitVector()) {
10002     if (!isa<ConstantSDNode>(N2))
10003       return SDValue();
10004
10005     // Get the desired 128-bit vector half.
10006     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10007     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10008
10009     // Insert the element into the desired half.
10010     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10011     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10012
10013     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10014                     DAG.getConstant(IdxIn128, MVT::i32));
10015
10016     // Insert the changed part back to the 256-bit vector
10017     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10018   }
10019
10020   if (Subtarget->hasSSE41())
10021     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10022
10023   if (EltVT == MVT::i8)
10024     return SDValue();
10025
10026   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10027     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10028     // as its second argument.
10029     if (N1.getValueType() != MVT::i32)
10030       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10031     if (N2.getValueType() != MVT::i32)
10032       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10033     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10034   }
10035   return SDValue();
10036 }
10037
10038 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10039   SDLoc dl(Op);
10040   MVT OpVT = Op.getSimpleValueType();
10041
10042   // If this is a 256-bit vector result, first insert into a 128-bit
10043   // vector and then insert into the 256-bit vector.
10044   if (!OpVT.is128BitVector()) {
10045     // Insert into a 128-bit vector.
10046     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10047     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10048                                  OpVT.getVectorNumElements() / SizeFactor);
10049
10050     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10051
10052     // Insert the 128-bit vector.
10053     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10054   }
10055
10056   if (OpVT == MVT::v1i64 &&
10057       Op.getOperand(0).getValueType() == MVT::i64)
10058     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10059
10060   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10061   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10062   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10063                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10064 }
10065
10066 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10067 // a simple subregister reference or explicit instructions to grab
10068 // upper bits of a vector.
10069 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10070                                       SelectionDAG &DAG) {
10071   SDLoc dl(Op);
10072   SDValue In =  Op.getOperand(0);
10073   SDValue Idx = Op.getOperand(1);
10074   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10075   MVT ResVT   = Op.getSimpleValueType();
10076   MVT InVT    = In.getSimpleValueType();
10077
10078   if (Subtarget->hasFp256()) {
10079     if (ResVT.is128BitVector() &&
10080         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10081         isa<ConstantSDNode>(Idx)) {
10082       return Extract128BitVector(In, IdxVal, DAG, dl);
10083     }
10084     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10085         isa<ConstantSDNode>(Idx)) {
10086       return Extract256BitVector(In, IdxVal, DAG, dl);
10087     }
10088   }
10089   return SDValue();
10090 }
10091
10092 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10093 // simple superregister reference or explicit instructions to insert
10094 // the upper bits of a vector.
10095 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10096                                      SelectionDAG &DAG) {
10097   if (Subtarget->hasFp256()) {
10098     SDLoc dl(Op.getNode());
10099     SDValue Vec = Op.getNode()->getOperand(0);
10100     SDValue SubVec = Op.getNode()->getOperand(1);
10101     SDValue Idx = Op.getNode()->getOperand(2);
10102
10103     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10104          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10105         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10106         isa<ConstantSDNode>(Idx)) {
10107       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10108       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10109     }
10110
10111     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10112         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10113         isa<ConstantSDNode>(Idx)) {
10114       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10115       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10116     }
10117   }
10118   return SDValue();
10119 }
10120
10121 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10122 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10123 // one of the above mentioned nodes. It has to be wrapped because otherwise
10124 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10125 // be used to form addressing mode. These wrapped nodes will be selected
10126 // into MOV32ri.
10127 SDValue
10128 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10129   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10130
10131   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10132   // global base reg.
10133   unsigned char OpFlag = 0;
10134   unsigned WrapperKind = X86ISD::Wrapper;
10135   CodeModel::Model M = DAG.getTarget().getCodeModel();
10136
10137   if (Subtarget->isPICStyleRIPRel() &&
10138       (M == CodeModel::Small || M == CodeModel::Kernel))
10139     WrapperKind = X86ISD::WrapperRIP;
10140   else if (Subtarget->isPICStyleGOT())
10141     OpFlag = X86II::MO_GOTOFF;
10142   else if (Subtarget->isPICStyleStubPIC())
10143     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10144
10145   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10146                                              CP->getAlignment(),
10147                                              CP->getOffset(), OpFlag);
10148   SDLoc DL(CP);
10149   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10150   // With PIC, the address is actually $g + Offset.
10151   if (OpFlag) {
10152     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10153                          DAG.getNode(X86ISD::GlobalBaseReg,
10154                                      SDLoc(), getPointerTy()),
10155                          Result);
10156   }
10157
10158   return Result;
10159 }
10160
10161 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10162   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10163
10164   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10165   // global base reg.
10166   unsigned char OpFlag = 0;
10167   unsigned WrapperKind = X86ISD::Wrapper;
10168   CodeModel::Model M = DAG.getTarget().getCodeModel();
10169
10170   if (Subtarget->isPICStyleRIPRel() &&
10171       (M == CodeModel::Small || M == CodeModel::Kernel))
10172     WrapperKind = X86ISD::WrapperRIP;
10173   else if (Subtarget->isPICStyleGOT())
10174     OpFlag = X86II::MO_GOTOFF;
10175   else if (Subtarget->isPICStyleStubPIC())
10176     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10177
10178   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10179                                           OpFlag);
10180   SDLoc DL(JT);
10181   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10182
10183   // With PIC, the address is actually $g + Offset.
10184   if (OpFlag)
10185     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10186                          DAG.getNode(X86ISD::GlobalBaseReg,
10187                                      SDLoc(), getPointerTy()),
10188                          Result);
10189
10190   return Result;
10191 }
10192
10193 SDValue
10194 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10195   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10196
10197   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10198   // global base reg.
10199   unsigned char OpFlag = 0;
10200   unsigned WrapperKind = X86ISD::Wrapper;
10201   CodeModel::Model M = DAG.getTarget().getCodeModel();
10202
10203   if (Subtarget->isPICStyleRIPRel() &&
10204       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10205     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10206       OpFlag = X86II::MO_GOTPCREL;
10207     WrapperKind = X86ISD::WrapperRIP;
10208   } else if (Subtarget->isPICStyleGOT()) {
10209     OpFlag = X86II::MO_GOT;
10210   } else if (Subtarget->isPICStyleStubPIC()) {
10211     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10212   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10213     OpFlag = X86II::MO_DARWIN_NONLAZY;
10214   }
10215
10216   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10217
10218   SDLoc DL(Op);
10219   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10220
10221   // With PIC, the address is actually $g + Offset.
10222   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10223       !Subtarget->is64Bit()) {
10224     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10225                          DAG.getNode(X86ISD::GlobalBaseReg,
10226                                      SDLoc(), getPointerTy()),
10227                          Result);
10228   }
10229
10230   // For symbols that require a load from a stub to get the address, emit the
10231   // load.
10232   if (isGlobalStubReference(OpFlag))
10233     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10234                          MachinePointerInfo::getGOT(), false, false, false, 0);
10235
10236   return Result;
10237 }
10238
10239 SDValue
10240 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10241   // Create the TargetBlockAddressAddress node.
10242   unsigned char OpFlags =
10243     Subtarget->ClassifyBlockAddressReference();
10244   CodeModel::Model M = DAG.getTarget().getCodeModel();
10245   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10246   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10247   SDLoc dl(Op);
10248   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10249                                              OpFlags);
10250
10251   if (Subtarget->isPICStyleRIPRel() &&
10252       (M == CodeModel::Small || M == CodeModel::Kernel))
10253     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10254   else
10255     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10256
10257   // With PIC, the address is actually $g + Offset.
10258   if (isGlobalRelativeToPICBase(OpFlags)) {
10259     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10260                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10261                          Result);
10262   }
10263
10264   return Result;
10265 }
10266
10267 SDValue
10268 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10269                                       int64_t Offset, SelectionDAG &DAG) const {
10270   // Create the TargetGlobalAddress node, folding in the constant
10271   // offset if it is legal.
10272   unsigned char OpFlags =
10273       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10274   CodeModel::Model M = DAG.getTarget().getCodeModel();
10275   SDValue Result;
10276   if (OpFlags == X86II::MO_NO_FLAG &&
10277       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10278     // A direct static reference to a global.
10279     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10280     Offset = 0;
10281   } else {
10282     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10283   }
10284
10285   if (Subtarget->isPICStyleRIPRel() &&
10286       (M == CodeModel::Small || M == CodeModel::Kernel))
10287     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10288   else
10289     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10290
10291   // With PIC, the address is actually $g + Offset.
10292   if (isGlobalRelativeToPICBase(OpFlags)) {
10293     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10294                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10295                          Result);
10296   }
10297
10298   // For globals that require a load from a stub to get the address, emit the
10299   // load.
10300   if (isGlobalStubReference(OpFlags))
10301     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10302                          MachinePointerInfo::getGOT(), false, false, false, 0);
10303
10304   // If there was a non-zero offset that we didn't fold, create an explicit
10305   // addition for it.
10306   if (Offset != 0)
10307     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10308                          DAG.getConstant(Offset, getPointerTy()));
10309
10310   return Result;
10311 }
10312
10313 SDValue
10314 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10315   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10316   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10317   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10318 }
10319
10320 static SDValue
10321 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10322            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10323            unsigned char OperandFlags, bool LocalDynamic = false) {
10324   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10325   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10326   SDLoc dl(GA);
10327   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10328                                            GA->getValueType(0),
10329                                            GA->getOffset(),
10330                                            OperandFlags);
10331
10332   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10333                                            : X86ISD::TLSADDR;
10334
10335   if (InFlag) {
10336     SDValue Ops[] = { Chain,  TGA, *InFlag };
10337     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10338   } else {
10339     SDValue Ops[]  = { Chain, TGA };
10340     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10341   }
10342
10343   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10344   MFI->setAdjustsStack(true);
10345
10346   SDValue Flag = Chain.getValue(1);
10347   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10348 }
10349
10350 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10351 static SDValue
10352 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10353                                 const EVT PtrVT) {
10354   SDValue InFlag;
10355   SDLoc dl(GA);  // ? function entry point might be better
10356   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10357                                    DAG.getNode(X86ISD::GlobalBaseReg,
10358                                                SDLoc(), PtrVT), InFlag);
10359   InFlag = Chain.getValue(1);
10360
10361   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10362 }
10363
10364 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10365 static SDValue
10366 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10367                                 const EVT PtrVT) {
10368   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10369                     X86::RAX, X86II::MO_TLSGD);
10370 }
10371
10372 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10373                                            SelectionDAG &DAG,
10374                                            const EVT PtrVT,
10375                                            bool is64Bit) {
10376   SDLoc dl(GA);
10377
10378   // Get the start address of the TLS block for this module.
10379   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10380       .getInfo<X86MachineFunctionInfo>();
10381   MFI->incNumLocalDynamicTLSAccesses();
10382
10383   SDValue Base;
10384   if (is64Bit) {
10385     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10386                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10387   } else {
10388     SDValue InFlag;
10389     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10390         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10391     InFlag = Chain.getValue(1);
10392     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10393                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10394   }
10395
10396   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10397   // of Base.
10398
10399   // Build x@dtpoff.
10400   unsigned char OperandFlags = X86II::MO_DTPOFF;
10401   unsigned WrapperKind = X86ISD::Wrapper;
10402   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10403                                            GA->getValueType(0),
10404                                            GA->getOffset(), OperandFlags);
10405   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10406
10407   // Add x@dtpoff with the base.
10408   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10409 }
10410
10411 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10412 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10413                                    const EVT PtrVT, TLSModel::Model model,
10414                                    bool is64Bit, bool isPIC) {
10415   SDLoc dl(GA);
10416
10417   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10418   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10419                                                          is64Bit ? 257 : 256));
10420
10421   SDValue ThreadPointer =
10422       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10423                   MachinePointerInfo(Ptr), false, false, false, 0);
10424
10425   unsigned char OperandFlags = 0;
10426   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10427   // initialexec.
10428   unsigned WrapperKind = X86ISD::Wrapper;
10429   if (model == TLSModel::LocalExec) {
10430     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10431   } else if (model == TLSModel::InitialExec) {
10432     if (is64Bit) {
10433       OperandFlags = X86II::MO_GOTTPOFF;
10434       WrapperKind = X86ISD::WrapperRIP;
10435     } else {
10436       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10437     }
10438   } else {
10439     llvm_unreachable("Unexpected model");
10440   }
10441
10442   // emit "addl x@ntpoff,%eax" (local exec)
10443   // or "addl x@indntpoff,%eax" (initial exec)
10444   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10445   SDValue TGA =
10446       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10447                                  GA->getOffset(), OperandFlags);
10448   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10449
10450   if (model == TLSModel::InitialExec) {
10451     if (isPIC && !is64Bit) {
10452       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10453                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10454                            Offset);
10455     }
10456
10457     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10458                          MachinePointerInfo::getGOT(), false, false, false, 0);
10459   }
10460
10461   // The address of the thread local variable is the add of the thread
10462   // pointer with the offset of the variable.
10463   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10464 }
10465
10466 SDValue
10467 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10468
10469   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10470   const GlobalValue *GV = GA->getGlobal();
10471
10472   if (Subtarget->isTargetELF()) {
10473     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10474
10475     switch (model) {
10476       case TLSModel::GeneralDynamic:
10477         if (Subtarget->is64Bit())
10478           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10479         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10480       case TLSModel::LocalDynamic:
10481         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10482                                            Subtarget->is64Bit());
10483       case TLSModel::InitialExec:
10484       case TLSModel::LocalExec:
10485         return LowerToTLSExecModel(
10486             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10487             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10488     }
10489     llvm_unreachable("Unknown TLS model.");
10490   }
10491
10492   if (Subtarget->isTargetDarwin()) {
10493     // Darwin only has one model of TLS.  Lower to that.
10494     unsigned char OpFlag = 0;
10495     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10496                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10497
10498     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10499     // global base reg.
10500     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10501                  !Subtarget->is64Bit();
10502     if (PIC32)
10503       OpFlag = X86II::MO_TLVP_PIC_BASE;
10504     else
10505       OpFlag = X86II::MO_TLVP;
10506     SDLoc DL(Op);
10507     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10508                                                 GA->getValueType(0),
10509                                                 GA->getOffset(), OpFlag);
10510     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10511
10512     // With PIC32, the address is actually $g + Offset.
10513     if (PIC32)
10514       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10515                            DAG.getNode(X86ISD::GlobalBaseReg,
10516                                        SDLoc(), getPointerTy()),
10517                            Offset);
10518
10519     // Lowering the machine isd will make sure everything is in the right
10520     // location.
10521     SDValue Chain = DAG.getEntryNode();
10522     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10523     SDValue Args[] = { Chain, Offset };
10524     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10525
10526     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10527     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10528     MFI->setAdjustsStack(true);
10529
10530     // And our return value (tls address) is in the standard call return value
10531     // location.
10532     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10533     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10534                               Chain.getValue(1));
10535   }
10536
10537   if (Subtarget->isTargetKnownWindowsMSVC() ||
10538       Subtarget->isTargetWindowsGNU()) {
10539     // Just use the implicit TLS architecture
10540     // Need to generate someting similar to:
10541     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10542     //                                  ; from TEB
10543     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10544     //   mov     rcx, qword [rdx+rcx*8]
10545     //   mov     eax, .tls$:tlsvar
10546     //   [rax+rcx] contains the address
10547     // Windows 64bit: gs:0x58
10548     // Windows 32bit: fs:__tls_array
10549
10550     SDLoc dl(GA);
10551     SDValue Chain = DAG.getEntryNode();
10552
10553     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10554     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10555     // use its literal value of 0x2C.
10556     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10557                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10558                                                              256)
10559                                         : Type::getInt32PtrTy(*DAG.getContext(),
10560                                                               257));
10561
10562     SDValue TlsArray =
10563         Subtarget->is64Bit()
10564             ? DAG.getIntPtrConstant(0x58)
10565             : (Subtarget->isTargetWindowsGNU()
10566                    ? DAG.getIntPtrConstant(0x2C)
10567                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10568
10569     SDValue ThreadPointer =
10570         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10571                     MachinePointerInfo(Ptr), false, false, false, 0);
10572
10573     // Load the _tls_index variable
10574     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10575     if (Subtarget->is64Bit())
10576       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10577                            IDX, MachinePointerInfo(), MVT::i32,
10578                            false, false, 0);
10579     else
10580       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10581                         false, false, false, 0);
10582
10583     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10584                                     getPointerTy());
10585     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10586
10587     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10588     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10589                       false, false, false, 0);
10590
10591     // Get the offset of start of .tls section
10592     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10593                                              GA->getValueType(0),
10594                                              GA->getOffset(), X86II::MO_SECREL);
10595     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10596
10597     // The address of the thread local variable is the add of the thread
10598     // pointer with the offset of the variable.
10599     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10600   }
10601
10602   llvm_unreachable("TLS not implemented for this target.");
10603 }
10604
10605 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10606 /// and take a 2 x i32 value to shift plus a shift amount.
10607 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10608   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10609   MVT VT = Op.getSimpleValueType();
10610   unsigned VTBits = VT.getSizeInBits();
10611   SDLoc dl(Op);
10612   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10613   SDValue ShOpLo = Op.getOperand(0);
10614   SDValue ShOpHi = Op.getOperand(1);
10615   SDValue ShAmt  = Op.getOperand(2);
10616   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10617   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10618   // during isel.
10619   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10620                                   DAG.getConstant(VTBits - 1, MVT::i8));
10621   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10622                                      DAG.getConstant(VTBits - 1, MVT::i8))
10623                        : DAG.getConstant(0, VT);
10624
10625   SDValue Tmp2, Tmp3;
10626   if (Op.getOpcode() == ISD::SHL_PARTS) {
10627     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10628     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10629   } else {
10630     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10631     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10632   }
10633
10634   // If the shift amount is larger or equal than the width of a part we can't
10635   // rely on the results of shld/shrd. Insert a test and select the appropriate
10636   // values for large shift amounts.
10637   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10638                                 DAG.getConstant(VTBits, MVT::i8));
10639   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10640                              AndNode, DAG.getConstant(0, MVT::i8));
10641
10642   SDValue Hi, Lo;
10643   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10644   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10645   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10646
10647   if (Op.getOpcode() == ISD::SHL_PARTS) {
10648     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10649     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10650   } else {
10651     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10652     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10653   }
10654
10655   SDValue Ops[2] = { Lo, Hi };
10656   return DAG.getMergeValues(Ops, dl);
10657 }
10658
10659 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10660                                            SelectionDAG &DAG) const {
10661   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10662
10663   if (SrcVT.isVector())
10664     return SDValue();
10665
10666   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10667          "Unknown SINT_TO_FP to lower!");
10668
10669   // These are really Legal; return the operand so the caller accepts it as
10670   // Legal.
10671   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10672     return Op;
10673   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10674       Subtarget->is64Bit()) {
10675     return Op;
10676   }
10677
10678   SDLoc dl(Op);
10679   unsigned Size = SrcVT.getSizeInBits()/8;
10680   MachineFunction &MF = DAG.getMachineFunction();
10681   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10682   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10683   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10684                                StackSlot,
10685                                MachinePointerInfo::getFixedStack(SSFI),
10686                                false, false, 0);
10687   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10688 }
10689
10690 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10691                                      SDValue StackSlot,
10692                                      SelectionDAG &DAG) const {
10693   // Build the FILD
10694   SDLoc DL(Op);
10695   SDVTList Tys;
10696   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10697   if (useSSE)
10698     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10699   else
10700     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10701
10702   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10703
10704   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10705   MachineMemOperand *MMO;
10706   if (FI) {
10707     int SSFI = FI->getIndex();
10708     MMO =
10709       DAG.getMachineFunction()
10710       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10711                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10712   } else {
10713     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10714     StackSlot = StackSlot.getOperand(1);
10715   }
10716   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10717   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10718                                            X86ISD::FILD, DL,
10719                                            Tys, Ops, SrcVT, MMO);
10720
10721   if (useSSE) {
10722     Chain = Result.getValue(1);
10723     SDValue InFlag = Result.getValue(2);
10724
10725     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10726     // shouldn't be necessary except that RFP cannot be live across
10727     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10728     MachineFunction &MF = DAG.getMachineFunction();
10729     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10730     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10731     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10732     Tys = DAG.getVTList(MVT::Other);
10733     SDValue Ops[] = {
10734       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10735     };
10736     MachineMemOperand *MMO =
10737       DAG.getMachineFunction()
10738       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10739                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10740
10741     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10742                                     Ops, Op.getValueType(), MMO);
10743     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10744                          MachinePointerInfo::getFixedStack(SSFI),
10745                          false, false, false, 0);
10746   }
10747
10748   return Result;
10749 }
10750
10751 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10752 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10753                                                SelectionDAG &DAG) const {
10754   // This algorithm is not obvious. Here it is what we're trying to output:
10755   /*
10756      movq       %rax,  %xmm0
10757      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10758      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10759      #ifdef __SSE3__
10760        haddpd   %xmm0, %xmm0
10761      #else
10762        pshufd   $0x4e, %xmm0, %xmm1
10763        addpd    %xmm1, %xmm0
10764      #endif
10765   */
10766
10767   SDLoc dl(Op);
10768   LLVMContext *Context = DAG.getContext();
10769
10770   // Build some magic constants.
10771   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10772   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10773   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10774
10775   SmallVector<Constant*,2> CV1;
10776   CV1.push_back(
10777     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10778                                       APInt(64, 0x4330000000000000ULL))));
10779   CV1.push_back(
10780     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10781                                       APInt(64, 0x4530000000000000ULL))));
10782   Constant *C1 = ConstantVector::get(CV1);
10783   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10784
10785   // Load the 64-bit value into an XMM register.
10786   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10787                             Op.getOperand(0));
10788   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10789                               MachinePointerInfo::getConstantPool(),
10790                               false, false, false, 16);
10791   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10792                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10793                               CLod0);
10794
10795   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10796                               MachinePointerInfo::getConstantPool(),
10797                               false, false, false, 16);
10798   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10799   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10800   SDValue Result;
10801
10802   if (Subtarget->hasSSE3()) {
10803     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10804     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10805   } else {
10806     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10807     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10808                                            S2F, 0x4E, DAG);
10809     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10810                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10811                          Sub);
10812   }
10813
10814   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10815                      DAG.getIntPtrConstant(0));
10816 }
10817
10818 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10819 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10820                                                SelectionDAG &DAG) const {
10821   SDLoc dl(Op);
10822   // FP constant to bias correct the final result.
10823   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10824                                    MVT::f64);
10825
10826   // Load the 32-bit value into an XMM register.
10827   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10828                              Op.getOperand(0));
10829
10830   // Zero out the upper parts of the register.
10831   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10832
10833   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10834                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10835                      DAG.getIntPtrConstant(0));
10836
10837   // Or the load with the bias.
10838   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10839                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10840                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10841                                                    MVT::v2f64, Load)),
10842                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10843                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10844                                                    MVT::v2f64, Bias)));
10845   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10846                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10847                    DAG.getIntPtrConstant(0));
10848
10849   // Subtract the bias.
10850   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10851
10852   // Handle final rounding.
10853   EVT DestVT = Op.getValueType();
10854
10855   if (DestVT.bitsLT(MVT::f64))
10856     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10857                        DAG.getIntPtrConstant(0));
10858   if (DestVT.bitsGT(MVT::f64))
10859     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10860
10861   // Handle final rounding.
10862   return Sub;
10863 }
10864
10865 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10866                                                SelectionDAG &DAG) const {
10867   SDValue N0 = Op.getOperand(0);
10868   MVT SVT = N0.getSimpleValueType();
10869   SDLoc dl(Op);
10870
10871   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10872           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10873          "Custom UINT_TO_FP is not supported!");
10874
10875   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10876   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10877                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10878 }
10879
10880 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10881                                            SelectionDAG &DAG) const {
10882   SDValue N0 = Op.getOperand(0);
10883   SDLoc dl(Op);
10884
10885   if (Op.getValueType().isVector())
10886     return lowerUINT_TO_FP_vec(Op, DAG);
10887
10888   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10889   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10890   // the optimization here.
10891   if (DAG.SignBitIsZero(N0))
10892     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10893
10894   MVT SrcVT = N0.getSimpleValueType();
10895   MVT DstVT = Op.getSimpleValueType();
10896   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10897     return LowerUINT_TO_FP_i64(Op, DAG);
10898   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10899     return LowerUINT_TO_FP_i32(Op, DAG);
10900   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10901     return SDValue();
10902
10903   // Make a 64-bit buffer, and use it to build an FILD.
10904   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10905   if (SrcVT == MVT::i32) {
10906     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10907     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10908                                      getPointerTy(), StackSlot, WordOff);
10909     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10910                                   StackSlot, MachinePointerInfo(),
10911                                   false, false, 0);
10912     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10913                                   OffsetSlot, MachinePointerInfo(),
10914                                   false, false, 0);
10915     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10916     return Fild;
10917   }
10918
10919   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10920   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10921                                StackSlot, MachinePointerInfo(),
10922                                false, false, 0);
10923   // For i64 source, we need to add the appropriate power of 2 if the input
10924   // was negative.  This is the same as the optimization in
10925   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10926   // we must be careful to do the computation in x87 extended precision, not
10927   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10928   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10929   MachineMemOperand *MMO =
10930     DAG.getMachineFunction()
10931     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10932                           MachineMemOperand::MOLoad, 8, 8);
10933
10934   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10935   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10936   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10937                                          MVT::i64, MMO);
10938
10939   APInt FF(32, 0x5F800000ULL);
10940
10941   // Check whether the sign bit is set.
10942   SDValue SignSet = DAG.getSetCC(dl,
10943                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10944                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10945                                  ISD::SETLT);
10946
10947   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10948   SDValue FudgePtr = DAG.getConstantPool(
10949                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10950                                          getPointerTy());
10951
10952   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10953   SDValue Zero = DAG.getIntPtrConstant(0);
10954   SDValue Four = DAG.getIntPtrConstant(4);
10955   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10956                                Zero, Four);
10957   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10958
10959   // Load the value out, extending it from f32 to f80.
10960   // FIXME: Avoid the extend by constructing the right constant pool?
10961   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10962                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10963                                  MVT::f32, false, false, 4);
10964   // Extend everything to 80 bits to force it to be done on x87.
10965   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10966   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10967 }
10968
10969 std::pair<SDValue,SDValue>
10970 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10971                                     bool IsSigned, bool IsReplace) const {
10972   SDLoc DL(Op);
10973
10974   EVT DstTy = Op.getValueType();
10975
10976   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10977     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10978     DstTy = MVT::i64;
10979   }
10980
10981   assert(DstTy.getSimpleVT() <= MVT::i64 &&
10982          DstTy.getSimpleVT() >= MVT::i16 &&
10983          "Unknown FP_TO_INT to lower!");
10984
10985   // These are really Legal.
10986   if (DstTy == MVT::i32 &&
10987       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10988     return std::make_pair(SDValue(), SDValue());
10989   if (Subtarget->is64Bit() &&
10990       DstTy == MVT::i64 &&
10991       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10992     return std::make_pair(SDValue(), SDValue());
10993
10994   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10995   // stack slot, or into the FTOL runtime function.
10996   MachineFunction &MF = DAG.getMachineFunction();
10997   unsigned MemSize = DstTy.getSizeInBits()/8;
10998   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
10999   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11000
11001   unsigned Opc;
11002   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11003     Opc = X86ISD::WIN_FTOL;
11004   else
11005     switch (DstTy.getSimpleVT().SimpleTy) {
11006     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11007     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11008     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11009     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11010     }
11011
11012   SDValue Chain = DAG.getEntryNode();
11013   SDValue Value = Op.getOperand(0);
11014   EVT TheVT = Op.getOperand(0).getValueType();
11015   // FIXME This causes a redundant load/store if the SSE-class value is already
11016   // in memory, such as if it is on the callstack.
11017   if (isScalarFPTypeInSSEReg(TheVT)) {
11018     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11019     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11020                          MachinePointerInfo::getFixedStack(SSFI),
11021                          false, false, 0);
11022     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11023     SDValue Ops[] = {
11024       Chain, StackSlot, DAG.getValueType(TheVT)
11025     };
11026
11027     MachineMemOperand *MMO =
11028       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11029                               MachineMemOperand::MOLoad, MemSize, MemSize);
11030     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11031     Chain = Value.getValue(1);
11032     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11033     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11034   }
11035
11036   MachineMemOperand *MMO =
11037     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11038                             MachineMemOperand::MOStore, MemSize, MemSize);
11039
11040   if (Opc != X86ISD::WIN_FTOL) {
11041     // Build the FP_TO_INT*_IN_MEM
11042     SDValue Ops[] = { Chain, Value, StackSlot };
11043     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11044                                            Ops, DstTy, MMO);
11045     return std::make_pair(FIST, StackSlot);
11046   } else {
11047     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11048       DAG.getVTList(MVT::Other, MVT::Glue),
11049       Chain, Value);
11050     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11051       MVT::i32, ftol.getValue(1));
11052     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11053       MVT::i32, eax.getValue(2));
11054     SDValue Ops[] = { eax, edx };
11055     SDValue pair = IsReplace
11056       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11057       : DAG.getMergeValues(Ops, DL);
11058     return std::make_pair(pair, SDValue());
11059   }
11060 }
11061
11062 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11063                               const X86Subtarget *Subtarget) {
11064   MVT VT = Op->getSimpleValueType(0);
11065   SDValue In = Op->getOperand(0);
11066   MVT InVT = In.getSimpleValueType();
11067   SDLoc dl(Op);
11068
11069   // Optimize vectors in AVX mode:
11070   //
11071   //   v8i16 -> v8i32
11072   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11073   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11074   //   Concat upper and lower parts.
11075   //
11076   //   v4i32 -> v4i64
11077   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11078   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11079   //   Concat upper and lower parts.
11080   //
11081
11082   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11083       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11084       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11085     return SDValue();
11086
11087   if (Subtarget->hasInt256())
11088     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11089
11090   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11091   SDValue Undef = DAG.getUNDEF(InVT);
11092   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11093   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11094   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11095
11096   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11097                              VT.getVectorNumElements()/2);
11098
11099   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11100   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11101
11102   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11103 }
11104
11105 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11106                                         SelectionDAG &DAG) {
11107   MVT VT = Op->getSimpleValueType(0);
11108   SDValue In = Op->getOperand(0);
11109   MVT InVT = In.getSimpleValueType();
11110   SDLoc DL(Op);
11111   unsigned int NumElts = VT.getVectorNumElements();
11112   if (NumElts != 8 && NumElts != 16)
11113     return SDValue();
11114
11115   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11116     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11117
11118   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11119   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11120   // Now we have only mask extension
11121   assert(InVT.getVectorElementType() == MVT::i1);
11122   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11123   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11124   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11125   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11126   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11127                            MachinePointerInfo::getConstantPool(),
11128                            false, false, false, Alignment);
11129
11130   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11131   if (VT.is512BitVector())
11132     return Brcst;
11133   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11134 }
11135
11136 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11137                                SelectionDAG &DAG) {
11138   if (Subtarget->hasFp256()) {
11139     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11140     if (Res.getNode())
11141       return Res;
11142   }
11143
11144   return SDValue();
11145 }
11146
11147 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11148                                 SelectionDAG &DAG) {
11149   SDLoc DL(Op);
11150   MVT VT = Op.getSimpleValueType();
11151   SDValue In = Op.getOperand(0);
11152   MVT SVT = In.getSimpleValueType();
11153
11154   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11155     return LowerZERO_EXTEND_AVX512(Op, DAG);
11156
11157   if (Subtarget->hasFp256()) {
11158     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11159     if (Res.getNode())
11160       return Res;
11161   }
11162
11163   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11164          VT.getVectorNumElements() != SVT.getVectorNumElements());
11165   return SDValue();
11166 }
11167
11168 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11169   SDLoc DL(Op);
11170   MVT VT = Op.getSimpleValueType();
11171   SDValue In = Op.getOperand(0);
11172   MVT InVT = In.getSimpleValueType();
11173
11174   if (VT == MVT::i1) {
11175     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11176            "Invalid scalar TRUNCATE operation");
11177     if (InVT == MVT::i32)
11178       return SDValue();
11179     if (InVT.getSizeInBits() == 64)
11180       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11181     else if (InVT.getSizeInBits() < 32)
11182       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11183     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11184   }
11185   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11186          "Invalid TRUNCATE operation");
11187
11188   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11189     if (VT.getVectorElementType().getSizeInBits() >=8)
11190       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11191
11192     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11193     unsigned NumElts = InVT.getVectorNumElements();
11194     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11195     if (InVT.getSizeInBits() < 512) {
11196       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11197       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11198       InVT = ExtVT;
11199     }
11200     
11201     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11202     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11203     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11204     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11205     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11206                            MachinePointerInfo::getConstantPool(),
11207                            false, false, false, Alignment);
11208     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11209     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11210     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11211   }
11212
11213   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11214     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11215     if (Subtarget->hasInt256()) {
11216       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11217       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11218       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11219                                 ShufMask);
11220       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11221                          DAG.getIntPtrConstant(0));
11222     }
11223
11224     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11225                                DAG.getIntPtrConstant(0));
11226     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11227                                DAG.getIntPtrConstant(2));
11228     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11229     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11230     static const int ShufMask[] = {0, 2, 4, 6};
11231     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11232   }
11233
11234   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11235     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11236     if (Subtarget->hasInt256()) {
11237       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11238
11239       SmallVector<SDValue,32> pshufbMask;
11240       for (unsigned i = 0; i < 2; ++i) {
11241         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11242         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11243         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11244         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11245         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11246         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11247         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11248         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11249         for (unsigned j = 0; j < 8; ++j)
11250           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11251       }
11252       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11253       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11254       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11255
11256       static const int ShufMask[] = {0,  2,  -1,  -1};
11257       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11258                                 &ShufMask[0]);
11259       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11260                        DAG.getIntPtrConstant(0));
11261       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11262     }
11263
11264     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11265                                DAG.getIntPtrConstant(0));
11266
11267     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11268                                DAG.getIntPtrConstant(4));
11269
11270     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11271     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11272
11273     // The PSHUFB mask:
11274     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11275                                    -1, -1, -1, -1, -1, -1, -1, -1};
11276
11277     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11278     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11279     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11280
11281     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11282     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11283
11284     // The MOVLHPS Mask:
11285     static const int ShufMask2[] = {0, 1, 4, 5};
11286     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11287     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11288   }
11289
11290   // Handle truncation of V256 to V128 using shuffles.
11291   if (!VT.is128BitVector() || !InVT.is256BitVector())
11292     return SDValue();
11293
11294   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11295
11296   unsigned NumElems = VT.getVectorNumElements();
11297   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11298
11299   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11300   // Prepare truncation shuffle mask
11301   for (unsigned i = 0; i != NumElems; ++i)
11302     MaskVec[i] = i * 2;
11303   SDValue V = DAG.getVectorShuffle(NVT, DL,
11304                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11305                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11306   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11307                      DAG.getIntPtrConstant(0));
11308 }
11309
11310 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11311                                            SelectionDAG &DAG) const {
11312   assert(!Op.getSimpleValueType().isVector());
11313
11314   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11315     /*IsSigned=*/ true, /*IsReplace=*/ false);
11316   SDValue FIST = Vals.first, StackSlot = Vals.second;
11317   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11318   if (!FIST.getNode()) return Op;
11319
11320   if (StackSlot.getNode())
11321     // Load the result.
11322     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11323                        FIST, StackSlot, MachinePointerInfo(),
11324                        false, false, false, 0);
11325
11326   // The node is the result.
11327   return FIST;
11328 }
11329
11330 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11331                                            SelectionDAG &DAG) const {
11332   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11333     /*IsSigned=*/ false, /*IsReplace=*/ false);
11334   SDValue FIST = Vals.first, StackSlot = Vals.second;
11335   assert(FIST.getNode() && "Unexpected failure");
11336
11337   if (StackSlot.getNode())
11338     // Load the result.
11339     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11340                        FIST, StackSlot, MachinePointerInfo(),
11341                        false, false, false, 0);
11342
11343   // The node is the result.
11344   return FIST;
11345 }
11346
11347 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11348   SDLoc DL(Op);
11349   MVT VT = Op.getSimpleValueType();
11350   SDValue In = Op.getOperand(0);
11351   MVT SVT = In.getSimpleValueType();
11352
11353   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11354
11355   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11356                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11357                                  In, DAG.getUNDEF(SVT)));
11358 }
11359
11360 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11361   LLVMContext *Context = DAG.getContext();
11362   SDLoc dl(Op);
11363   MVT VT = Op.getSimpleValueType();
11364   MVT EltVT = VT;
11365   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11366   if (VT.isVector()) {
11367     EltVT = VT.getVectorElementType();
11368     NumElts = VT.getVectorNumElements();
11369   }
11370   Constant *C;
11371   if (EltVT == MVT::f64)
11372     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11373                                           APInt(64, ~(1ULL << 63))));
11374   else
11375     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11376                                           APInt(32, ~(1U << 31))));
11377   C = ConstantVector::getSplat(NumElts, C);
11378   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11379   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11380   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11381   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11382                              MachinePointerInfo::getConstantPool(),
11383                              false, false, false, Alignment);
11384   if (VT.isVector()) {
11385     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11386     return DAG.getNode(ISD::BITCAST, dl, VT,
11387                        DAG.getNode(ISD::AND, dl, ANDVT,
11388                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11389                                                Op.getOperand(0)),
11390                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11391   }
11392   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11393 }
11394
11395 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11396   LLVMContext *Context = DAG.getContext();
11397   SDLoc dl(Op);
11398   MVT VT = Op.getSimpleValueType();
11399   MVT EltVT = VT;
11400   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11401   if (VT.isVector()) {
11402     EltVT = VT.getVectorElementType();
11403     NumElts = VT.getVectorNumElements();
11404   }
11405   Constant *C;
11406   if (EltVT == MVT::f64)
11407     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11408                                           APInt(64, 1ULL << 63)));
11409   else
11410     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11411                                           APInt(32, 1U << 31)));
11412   C = ConstantVector::getSplat(NumElts, C);
11413   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11414   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11415   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11416   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11417                              MachinePointerInfo::getConstantPool(),
11418                              false, false, false, Alignment);
11419   if (VT.isVector()) {
11420     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11421     return DAG.getNode(ISD::BITCAST, dl, VT,
11422                        DAG.getNode(ISD::XOR, dl, XORVT,
11423                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11424                                                Op.getOperand(0)),
11425                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11426   }
11427
11428   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11429 }
11430
11431 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11433   LLVMContext *Context = DAG.getContext();
11434   SDValue Op0 = Op.getOperand(0);
11435   SDValue Op1 = Op.getOperand(1);
11436   SDLoc dl(Op);
11437   MVT VT = Op.getSimpleValueType();
11438   MVT SrcVT = Op1.getSimpleValueType();
11439
11440   // If second operand is smaller, extend it first.
11441   if (SrcVT.bitsLT(VT)) {
11442     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11443     SrcVT = VT;
11444   }
11445   // And if it is bigger, shrink it first.
11446   if (SrcVT.bitsGT(VT)) {
11447     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11448     SrcVT = VT;
11449   }
11450
11451   // At this point the operands and the result should have the same
11452   // type, and that won't be f80 since that is not custom lowered.
11453
11454   // First get the sign bit of second operand.
11455   SmallVector<Constant*,4> CV;
11456   if (SrcVT == MVT::f64) {
11457     const fltSemantics &Sem = APFloat::IEEEdouble;
11458     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11459     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11460   } else {
11461     const fltSemantics &Sem = APFloat::IEEEsingle;
11462     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11463     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11464     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11465     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11466   }
11467   Constant *C = ConstantVector::get(CV);
11468   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11469   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11470                               MachinePointerInfo::getConstantPool(),
11471                               false, false, false, 16);
11472   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11473
11474   // Shift sign bit right or left if the two operands have different types.
11475   if (SrcVT.bitsGT(VT)) {
11476     // Op0 is MVT::f32, Op1 is MVT::f64.
11477     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11478     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11479                           DAG.getConstant(32, MVT::i32));
11480     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11481     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11482                           DAG.getIntPtrConstant(0));
11483   }
11484
11485   // Clear first operand sign bit.
11486   CV.clear();
11487   if (VT == MVT::f64) {
11488     const fltSemantics &Sem = APFloat::IEEEdouble;
11489     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11490                                                    APInt(64, ~(1ULL << 63)))));
11491     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11492   } else {
11493     const fltSemantics &Sem = APFloat::IEEEsingle;
11494     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11495                                                    APInt(32, ~(1U << 31)))));
11496     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11497     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11498     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11499   }
11500   C = ConstantVector::get(CV);
11501   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11502   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11503                               MachinePointerInfo::getConstantPool(),
11504                               false, false, false, 16);
11505   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11506
11507   // Or the value with the sign bit.
11508   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11509 }
11510
11511 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11512   SDValue N0 = Op.getOperand(0);
11513   SDLoc dl(Op);
11514   MVT VT = Op.getSimpleValueType();
11515
11516   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11517   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11518                                   DAG.getConstant(1, VT));
11519   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11520 }
11521
11522 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11523 //
11524 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11525                                       SelectionDAG &DAG) {
11526   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11527
11528   if (!Subtarget->hasSSE41())
11529     return SDValue();
11530
11531   if (!Op->hasOneUse())
11532     return SDValue();
11533
11534   SDNode *N = Op.getNode();
11535   SDLoc DL(N);
11536
11537   SmallVector<SDValue, 8> Opnds;
11538   DenseMap<SDValue, unsigned> VecInMap;
11539   SmallVector<SDValue, 8> VecIns;
11540   EVT VT = MVT::Other;
11541
11542   // Recognize a special case where a vector is casted into wide integer to
11543   // test all 0s.
11544   Opnds.push_back(N->getOperand(0));
11545   Opnds.push_back(N->getOperand(1));
11546
11547   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11548     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11549     // BFS traverse all OR'd operands.
11550     if (I->getOpcode() == ISD::OR) {
11551       Opnds.push_back(I->getOperand(0));
11552       Opnds.push_back(I->getOperand(1));
11553       // Re-evaluate the number of nodes to be traversed.
11554       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11555       continue;
11556     }
11557
11558     // Quit if a non-EXTRACT_VECTOR_ELT
11559     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11560       return SDValue();
11561
11562     // Quit if without a constant index.
11563     SDValue Idx = I->getOperand(1);
11564     if (!isa<ConstantSDNode>(Idx))
11565       return SDValue();
11566
11567     SDValue ExtractedFromVec = I->getOperand(0);
11568     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11569     if (M == VecInMap.end()) {
11570       VT = ExtractedFromVec.getValueType();
11571       // Quit if not 128/256-bit vector.
11572       if (!VT.is128BitVector() && !VT.is256BitVector())
11573         return SDValue();
11574       // Quit if not the same type.
11575       if (VecInMap.begin() != VecInMap.end() &&
11576           VT != VecInMap.begin()->first.getValueType())
11577         return SDValue();
11578       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11579       VecIns.push_back(ExtractedFromVec);
11580     }
11581     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11582   }
11583
11584   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11585          "Not extracted from 128-/256-bit vector.");
11586
11587   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11588
11589   for (DenseMap<SDValue, unsigned>::const_iterator
11590         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11591     // Quit if not all elements are used.
11592     if (I->second != FullMask)
11593       return SDValue();
11594   }
11595
11596   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11597
11598   // Cast all vectors into TestVT for PTEST.
11599   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11600     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11601
11602   // If more than one full vectors are evaluated, OR them first before PTEST.
11603   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11604     // Each iteration will OR 2 nodes and append the result until there is only
11605     // 1 node left, i.e. the final OR'd value of all vectors.
11606     SDValue LHS = VecIns[Slot];
11607     SDValue RHS = VecIns[Slot + 1];
11608     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11609   }
11610
11611   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11612                      VecIns.back(), VecIns.back());
11613 }
11614
11615 /// \brief return true if \c Op has a use that doesn't just read flags.
11616 static bool hasNonFlagsUse(SDValue Op) {
11617   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11618        ++UI) {
11619     SDNode *User = *UI;
11620     unsigned UOpNo = UI.getOperandNo();
11621     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11622       // Look pass truncate.
11623       UOpNo = User->use_begin().getOperandNo();
11624       User = *User->use_begin();
11625     }
11626
11627     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11628         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11629       return true;
11630   }
11631   return false;
11632 }
11633
11634 /// Emit nodes that will be selected as "test Op0,Op0", or something
11635 /// equivalent.
11636 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11637                                     SelectionDAG &DAG) const {
11638   if (Op.getValueType() == MVT::i1)
11639     // KORTEST instruction should be selected
11640     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11641                        DAG.getConstant(0, Op.getValueType()));
11642
11643   // CF and OF aren't always set the way we want. Determine which
11644   // of these we need.
11645   bool NeedCF = false;
11646   bool NeedOF = false;
11647   switch (X86CC) {
11648   default: break;
11649   case X86::COND_A: case X86::COND_AE:
11650   case X86::COND_B: case X86::COND_BE:
11651     NeedCF = true;
11652     break;
11653   case X86::COND_G: case X86::COND_GE:
11654   case X86::COND_L: case X86::COND_LE:
11655   case X86::COND_O: case X86::COND_NO: {
11656     // Check if we really need to set the
11657     // Overflow flag. If NoSignedWrap is present
11658     // that is not actually needed.
11659     switch (Op->getOpcode()) {
11660     case ISD::ADD:
11661     case ISD::SUB:
11662     case ISD::MUL:
11663     case ISD::SHL: {
11664       const BinaryWithFlagsSDNode *BinNode =
11665           cast<BinaryWithFlagsSDNode>(Op.getNode());
11666       if (BinNode->hasNoSignedWrap())
11667         break;
11668     }
11669     default:
11670       NeedOF = true;
11671       break;
11672     }
11673     break;
11674   }
11675   }
11676   // See if we can use the EFLAGS value from the operand instead of
11677   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11678   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11679   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11680     // Emit a CMP with 0, which is the TEST pattern.
11681     //if (Op.getValueType() == MVT::i1)
11682     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11683     //                     DAG.getConstant(0, MVT::i1));
11684     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11685                        DAG.getConstant(0, Op.getValueType()));
11686   }
11687   unsigned Opcode = 0;
11688   unsigned NumOperands = 0;
11689
11690   // Truncate operations may prevent the merge of the SETCC instruction
11691   // and the arithmetic instruction before it. Attempt to truncate the operands
11692   // of the arithmetic instruction and use a reduced bit-width instruction.
11693   bool NeedTruncation = false;
11694   SDValue ArithOp = Op;
11695   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11696     SDValue Arith = Op->getOperand(0);
11697     // Both the trunc and the arithmetic op need to have one user each.
11698     if (Arith->hasOneUse())
11699       switch (Arith.getOpcode()) {
11700         default: break;
11701         case ISD::ADD:
11702         case ISD::SUB:
11703         case ISD::AND:
11704         case ISD::OR:
11705         case ISD::XOR: {
11706           NeedTruncation = true;
11707           ArithOp = Arith;
11708         }
11709       }
11710   }
11711
11712   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11713   // which may be the result of a CAST.  We use the variable 'Op', which is the
11714   // non-casted variable when we check for possible users.
11715   switch (ArithOp.getOpcode()) {
11716   case ISD::ADD:
11717     // Due to an isel shortcoming, be conservative if this add is likely to be
11718     // selected as part of a load-modify-store instruction. When the root node
11719     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11720     // uses of other nodes in the match, such as the ADD in this case. This
11721     // leads to the ADD being left around and reselected, with the result being
11722     // two adds in the output.  Alas, even if none our users are stores, that
11723     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11724     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11725     // climbing the DAG back to the root, and it doesn't seem to be worth the
11726     // effort.
11727     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11728          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11729       if (UI->getOpcode() != ISD::CopyToReg &&
11730           UI->getOpcode() != ISD::SETCC &&
11731           UI->getOpcode() != ISD::STORE)
11732         goto default_case;
11733
11734     if (ConstantSDNode *C =
11735         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11736       // An add of one will be selected as an INC.
11737       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11738         Opcode = X86ISD::INC;
11739         NumOperands = 1;
11740         break;
11741       }
11742
11743       // An add of negative one (subtract of one) will be selected as a DEC.
11744       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11745         Opcode = X86ISD::DEC;
11746         NumOperands = 1;
11747         break;
11748       }
11749     }
11750
11751     // Otherwise use a regular EFLAGS-setting add.
11752     Opcode = X86ISD::ADD;
11753     NumOperands = 2;
11754     break;
11755   case ISD::SHL:
11756   case ISD::SRL:
11757     // If we have a constant logical shift that's only used in a comparison
11758     // against zero turn it into an equivalent AND. This allows turning it into
11759     // a TEST instruction later.
11760     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11761         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11762       EVT VT = Op.getValueType();
11763       unsigned BitWidth = VT.getSizeInBits();
11764       unsigned ShAmt = Op->getConstantOperandVal(1);
11765       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11766         break;
11767       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11768                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11769                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11770       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11771         break;
11772       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11773                                 DAG.getConstant(Mask, VT));
11774       DAG.ReplaceAllUsesWith(Op, New);
11775       Op = New;
11776     }
11777     break;
11778
11779   case ISD::AND:
11780     // If the primary and result isn't used, don't bother using X86ISD::AND,
11781     // because a TEST instruction will be better.
11782     if (!hasNonFlagsUse(Op))
11783       break;
11784     // FALL THROUGH
11785   case ISD::SUB:
11786   case ISD::OR:
11787   case ISD::XOR:
11788     // Due to the ISEL shortcoming noted above, be conservative if this op is
11789     // likely to be selected as part of a load-modify-store instruction.
11790     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11791            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11792       if (UI->getOpcode() == ISD::STORE)
11793         goto default_case;
11794
11795     // Otherwise use a regular EFLAGS-setting instruction.
11796     switch (ArithOp.getOpcode()) {
11797     default: llvm_unreachable("unexpected operator!");
11798     case ISD::SUB: Opcode = X86ISD::SUB; break;
11799     case ISD::XOR: Opcode = X86ISD::XOR; break;
11800     case ISD::AND: Opcode = X86ISD::AND; break;
11801     case ISD::OR: {
11802       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11803         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11804         if (EFLAGS.getNode())
11805           return EFLAGS;
11806       }
11807       Opcode = X86ISD::OR;
11808       break;
11809     }
11810     }
11811
11812     NumOperands = 2;
11813     break;
11814   case X86ISD::ADD:
11815   case X86ISD::SUB:
11816   case X86ISD::INC:
11817   case X86ISD::DEC:
11818   case X86ISD::OR:
11819   case X86ISD::XOR:
11820   case X86ISD::AND:
11821     return SDValue(Op.getNode(), 1);
11822   default:
11823   default_case:
11824     break;
11825   }
11826
11827   // If we found that truncation is beneficial, perform the truncation and
11828   // update 'Op'.
11829   if (NeedTruncation) {
11830     EVT VT = Op.getValueType();
11831     SDValue WideVal = Op->getOperand(0);
11832     EVT WideVT = WideVal.getValueType();
11833     unsigned ConvertedOp = 0;
11834     // Use a target machine opcode to prevent further DAGCombine
11835     // optimizations that may separate the arithmetic operations
11836     // from the setcc node.
11837     switch (WideVal.getOpcode()) {
11838       default: break;
11839       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11840       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11841       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11842       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11843       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11844     }
11845
11846     if (ConvertedOp) {
11847       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11848       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11849         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11850         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11851         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11852       }
11853     }
11854   }
11855
11856   if (Opcode == 0)
11857     // Emit a CMP with 0, which is the TEST pattern.
11858     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11859                        DAG.getConstant(0, Op.getValueType()));
11860
11861   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11862   SmallVector<SDValue, 4> Ops;
11863   for (unsigned i = 0; i != NumOperands; ++i)
11864     Ops.push_back(Op.getOperand(i));
11865
11866   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11867   DAG.ReplaceAllUsesWith(Op, New);
11868   return SDValue(New.getNode(), 1);
11869 }
11870
11871 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11872 /// equivalent.
11873 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11874                                    SDLoc dl, SelectionDAG &DAG) const {
11875   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11876     if (C->getAPIntValue() == 0)
11877       return EmitTest(Op0, X86CC, dl, DAG);
11878
11879      if (Op0.getValueType() == MVT::i1)
11880        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11881   }
11882  
11883   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11884        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11885     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11886     // This avoids subregister aliasing issues. Keep the smaller reference 
11887     // if we're optimizing for size, however, as that'll allow better folding 
11888     // of memory operations.
11889     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11890         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11891              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11892         !Subtarget->isAtom()) {
11893       unsigned ExtendOp =
11894           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11895       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11896       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11897     }
11898     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11899     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11900     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11901                               Op0, Op1);
11902     return SDValue(Sub.getNode(), 1);
11903   }
11904   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11905 }
11906
11907 /// Convert a comparison if required by the subtarget.
11908 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11909                                                  SelectionDAG &DAG) const {
11910   // If the subtarget does not support the FUCOMI instruction, floating-point
11911   // comparisons have to be converted.
11912   if (Subtarget->hasCMov() ||
11913       Cmp.getOpcode() != X86ISD::CMP ||
11914       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11915       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11916     return Cmp;
11917
11918   // The instruction selector will select an FUCOM instruction instead of
11919   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11920   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11921   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11922   SDLoc dl(Cmp);
11923   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11924   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11925   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11926                             DAG.getConstant(8, MVT::i8));
11927   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11928   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11929 }
11930
11931 static bool isAllOnes(SDValue V) {
11932   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11933   return C && C->isAllOnesValue();
11934 }
11935
11936 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11937 /// if it's possible.
11938 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11939                                      SDLoc dl, SelectionDAG &DAG) const {
11940   SDValue Op0 = And.getOperand(0);
11941   SDValue Op1 = And.getOperand(1);
11942   if (Op0.getOpcode() == ISD::TRUNCATE)
11943     Op0 = Op0.getOperand(0);
11944   if (Op1.getOpcode() == ISD::TRUNCATE)
11945     Op1 = Op1.getOperand(0);
11946
11947   SDValue LHS, RHS;
11948   if (Op1.getOpcode() == ISD::SHL)
11949     std::swap(Op0, Op1);
11950   if (Op0.getOpcode() == ISD::SHL) {
11951     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11952       if (And00C->getZExtValue() == 1) {
11953         // If we looked past a truncate, check that it's only truncating away
11954         // known zeros.
11955         unsigned BitWidth = Op0.getValueSizeInBits();
11956         unsigned AndBitWidth = And.getValueSizeInBits();
11957         if (BitWidth > AndBitWidth) {
11958           APInt Zeros, Ones;
11959           DAG.computeKnownBits(Op0, Zeros, Ones);
11960           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11961             return SDValue();
11962         }
11963         LHS = Op1;
11964         RHS = Op0.getOperand(1);
11965       }
11966   } else if (Op1.getOpcode() == ISD::Constant) {
11967     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11968     uint64_t AndRHSVal = AndRHS->getZExtValue();
11969     SDValue AndLHS = Op0;
11970
11971     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11972       LHS = AndLHS.getOperand(0);
11973       RHS = AndLHS.getOperand(1);
11974     }
11975
11976     // Use BT if the immediate can't be encoded in a TEST instruction.
11977     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11978       LHS = AndLHS;
11979       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11980     }
11981   }
11982
11983   if (LHS.getNode()) {
11984     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
11985     // instruction.  Since the shift amount is in-range-or-undefined, we know
11986     // that doing a bittest on the i32 value is ok.  We extend to i32 because
11987     // the encoding for the i16 version is larger than the i32 version.
11988     // Also promote i16 to i32 for performance / code size reason.
11989     if (LHS.getValueType() == MVT::i8 ||
11990         LHS.getValueType() == MVT::i16)
11991       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11992
11993     // If the operand types disagree, extend the shift amount to match.  Since
11994     // BT ignores high bits (like shifts) we can use anyextend.
11995     if (LHS.getValueType() != RHS.getValueType())
11996       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
11997
11998     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
11999     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12000     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12001                        DAG.getConstant(Cond, MVT::i8), BT);
12002   }
12003
12004   return SDValue();
12005 }
12006
12007 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12008 /// mask CMPs.
12009 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12010                               SDValue &Op1) {
12011   unsigned SSECC;
12012   bool Swap = false;
12013
12014   // SSE Condition code mapping:
12015   //  0 - EQ
12016   //  1 - LT
12017   //  2 - LE
12018   //  3 - UNORD
12019   //  4 - NEQ
12020   //  5 - NLT
12021   //  6 - NLE
12022   //  7 - ORD
12023   switch (SetCCOpcode) {
12024   default: llvm_unreachable("Unexpected SETCC condition");
12025   case ISD::SETOEQ:
12026   case ISD::SETEQ:  SSECC = 0; break;
12027   case ISD::SETOGT:
12028   case ISD::SETGT:  Swap = true; // Fallthrough
12029   case ISD::SETLT:
12030   case ISD::SETOLT: SSECC = 1; break;
12031   case ISD::SETOGE:
12032   case ISD::SETGE:  Swap = true; // Fallthrough
12033   case ISD::SETLE:
12034   case ISD::SETOLE: SSECC = 2; break;
12035   case ISD::SETUO:  SSECC = 3; break;
12036   case ISD::SETUNE:
12037   case ISD::SETNE:  SSECC = 4; break;
12038   case ISD::SETULE: Swap = true; // Fallthrough
12039   case ISD::SETUGE: SSECC = 5; break;
12040   case ISD::SETULT: Swap = true; // Fallthrough
12041   case ISD::SETUGT: SSECC = 6; break;
12042   case ISD::SETO:   SSECC = 7; break;
12043   case ISD::SETUEQ:
12044   case ISD::SETONE: SSECC = 8; break;
12045   }
12046   if (Swap)
12047     std::swap(Op0, Op1);
12048
12049   return SSECC;
12050 }
12051
12052 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12053 // ones, and then concatenate the result back.
12054 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12055   MVT VT = Op.getSimpleValueType();
12056
12057   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12058          "Unsupported value type for operation");
12059
12060   unsigned NumElems = VT.getVectorNumElements();
12061   SDLoc dl(Op);
12062   SDValue CC = Op.getOperand(2);
12063
12064   // Extract the LHS vectors
12065   SDValue LHS = Op.getOperand(0);
12066   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12067   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12068
12069   // Extract the RHS vectors
12070   SDValue RHS = Op.getOperand(1);
12071   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12072   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12073
12074   // Issue the operation on the smaller types and concatenate the result back
12075   MVT EltVT = VT.getVectorElementType();
12076   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12077   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12078                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12079                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12080 }
12081
12082 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12083                                      const X86Subtarget *Subtarget) {
12084   SDValue Op0 = Op.getOperand(0);
12085   SDValue Op1 = Op.getOperand(1);
12086   SDValue CC = Op.getOperand(2);
12087   MVT VT = Op.getSimpleValueType();
12088   SDLoc dl(Op);
12089
12090   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12091          Op.getValueType().getScalarType() == MVT::i1 &&
12092          "Cannot set masked compare for this operation");
12093
12094   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12095   unsigned  Opc = 0;
12096   bool Unsigned = false;
12097   bool Swap = false;
12098   unsigned SSECC;
12099   switch (SetCCOpcode) {
12100   default: llvm_unreachable("Unexpected SETCC condition");
12101   case ISD::SETNE:  SSECC = 4; break;
12102   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12103   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12104   case ISD::SETLT:  Swap = true; //fall-through
12105   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12106   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12107   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12108   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12109   case ISD::SETULE: Unsigned = true; //fall-through
12110   case ISD::SETLE:  SSECC = 2; break;
12111   }
12112
12113   if (Swap)
12114     std::swap(Op0, Op1);
12115   if (Opc)
12116     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12117   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12118   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12119                      DAG.getConstant(SSECC, MVT::i8));
12120 }
12121
12122 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12123 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12124 /// return an empty value.
12125 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12126 {
12127   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12128   if (!BV)
12129     return SDValue();
12130
12131   MVT VT = Op1.getSimpleValueType();
12132   MVT EVT = VT.getVectorElementType();
12133   unsigned n = VT.getVectorNumElements();
12134   SmallVector<SDValue, 8> ULTOp1;
12135
12136   for (unsigned i = 0; i < n; ++i) {
12137     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12138     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12139       return SDValue();
12140
12141     // Avoid underflow.
12142     APInt Val = Elt->getAPIntValue();
12143     if (Val == 0)
12144       return SDValue();
12145
12146     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12147   }
12148
12149   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12150 }
12151
12152 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12153                            SelectionDAG &DAG) {
12154   SDValue Op0 = Op.getOperand(0);
12155   SDValue Op1 = Op.getOperand(1);
12156   SDValue CC = Op.getOperand(2);
12157   MVT VT = Op.getSimpleValueType();
12158   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12159   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12160   SDLoc dl(Op);
12161
12162   if (isFP) {
12163 #ifndef NDEBUG
12164     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12165     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12166 #endif
12167
12168     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12169     unsigned Opc = X86ISD::CMPP;
12170     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12171       assert(VT.getVectorNumElements() <= 16);
12172       Opc = X86ISD::CMPM;
12173     }
12174     // In the two special cases we can't handle, emit two comparisons.
12175     if (SSECC == 8) {
12176       unsigned CC0, CC1;
12177       unsigned CombineOpc;
12178       if (SetCCOpcode == ISD::SETUEQ) {
12179         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12180       } else {
12181         assert(SetCCOpcode == ISD::SETONE);
12182         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12183       }
12184
12185       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12186                                  DAG.getConstant(CC0, MVT::i8));
12187       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12188                                  DAG.getConstant(CC1, MVT::i8));
12189       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12190     }
12191     // Handle all other FP comparisons here.
12192     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12193                        DAG.getConstant(SSECC, MVT::i8));
12194   }
12195
12196   // Break 256-bit integer vector compare into smaller ones.
12197   if (VT.is256BitVector() && !Subtarget->hasInt256())
12198     return Lower256IntVSETCC(Op, DAG);
12199
12200   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12201   EVT OpVT = Op1.getValueType();
12202   if (Subtarget->hasAVX512()) {
12203     if (Op1.getValueType().is512BitVector() ||
12204         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12205       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12206
12207     // In AVX-512 architecture setcc returns mask with i1 elements,
12208     // But there is no compare instruction for i8 and i16 elements.
12209     // We are not talking about 512-bit operands in this case, these
12210     // types are illegal.
12211     if (MaskResult &&
12212         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12213          OpVT.getVectorElementType().getSizeInBits() >= 8))
12214       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12215                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12216   }
12217
12218   // We are handling one of the integer comparisons here.  Since SSE only has
12219   // GT and EQ comparisons for integer, swapping operands and multiple
12220   // operations may be required for some comparisons.
12221   unsigned Opc;
12222   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12223   bool Subus = false;
12224
12225   switch (SetCCOpcode) {
12226   default: llvm_unreachable("Unexpected SETCC condition");
12227   case ISD::SETNE:  Invert = true;
12228   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12229   case ISD::SETLT:  Swap = true;
12230   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12231   case ISD::SETGE:  Swap = true;
12232   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12233                     Invert = true; break;
12234   case ISD::SETULT: Swap = true;
12235   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12236                     FlipSigns = true; break;
12237   case ISD::SETUGE: Swap = true;
12238   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12239                     FlipSigns = true; Invert = true; break;
12240   }
12241
12242   // Special case: Use min/max operations for SETULE/SETUGE
12243   MVT VET = VT.getVectorElementType();
12244   bool hasMinMax =
12245        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12246     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12247
12248   if (hasMinMax) {
12249     switch (SetCCOpcode) {
12250     default: break;
12251     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12252     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12253     }
12254
12255     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12256   }
12257
12258   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12259   if (!MinMax && hasSubus) {
12260     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12261     // Op0 u<= Op1:
12262     //   t = psubus Op0, Op1
12263     //   pcmpeq t, <0..0>
12264     switch (SetCCOpcode) {
12265     default: break;
12266     case ISD::SETULT: {
12267       // If the comparison is against a constant we can turn this into a
12268       // setule.  With psubus, setule does not require a swap.  This is
12269       // beneficial because the constant in the register is no longer
12270       // destructed as the destination so it can be hoisted out of a loop.
12271       // Only do this pre-AVX since vpcmp* is no longer destructive.
12272       if (Subtarget->hasAVX())
12273         break;
12274       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12275       if (ULEOp1.getNode()) {
12276         Op1 = ULEOp1;
12277         Subus = true; Invert = false; Swap = false;
12278       }
12279       break;
12280     }
12281     // Psubus is better than flip-sign because it requires no inversion.
12282     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12283     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12284     }
12285
12286     if (Subus) {
12287       Opc = X86ISD::SUBUS;
12288       FlipSigns = false;
12289     }
12290   }
12291
12292   if (Swap)
12293     std::swap(Op0, Op1);
12294
12295   // Check that the operation in question is available (most are plain SSE2,
12296   // but PCMPGTQ and PCMPEQQ have different requirements).
12297   if (VT == MVT::v2i64) {
12298     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12299       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12300
12301       // First cast everything to the right type.
12302       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12303       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12304
12305       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12306       // bits of the inputs before performing those operations. The lower
12307       // compare is always unsigned.
12308       SDValue SB;
12309       if (FlipSigns) {
12310         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12311       } else {
12312         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12313         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12314         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12315                          Sign, Zero, Sign, Zero);
12316       }
12317       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12318       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12319
12320       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12321       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12322       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12323
12324       // Create masks for only the low parts/high parts of the 64 bit integers.
12325       static const int MaskHi[] = { 1, 1, 3, 3 };
12326       static const int MaskLo[] = { 0, 0, 2, 2 };
12327       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12328       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12329       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12330
12331       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12332       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12333
12334       if (Invert)
12335         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12336
12337       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12338     }
12339
12340     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12341       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12342       // pcmpeqd + pshufd + pand.
12343       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12344
12345       // First cast everything to the right type.
12346       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12347       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12348
12349       // Do the compare.
12350       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12351
12352       // Make sure the lower and upper halves are both all-ones.
12353       static const int Mask[] = { 1, 0, 3, 2 };
12354       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12355       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12356
12357       if (Invert)
12358         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12359
12360       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12361     }
12362   }
12363
12364   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12365   // bits of the inputs before performing those operations.
12366   if (FlipSigns) {
12367     EVT EltVT = VT.getVectorElementType();
12368     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12369     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12370     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12371   }
12372
12373   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12374
12375   // If the logical-not of the result is required, perform that now.
12376   if (Invert)
12377     Result = DAG.getNOT(dl, Result, VT);
12378
12379   if (MinMax)
12380     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12381
12382   if (Subus)
12383     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12384                          getZeroVector(VT, Subtarget, DAG, dl));
12385
12386   return Result;
12387 }
12388
12389 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12390
12391   MVT VT = Op.getSimpleValueType();
12392
12393   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12394
12395   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12396          && "SetCC type must be 8-bit or 1-bit integer");
12397   SDValue Op0 = Op.getOperand(0);
12398   SDValue Op1 = Op.getOperand(1);
12399   SDLoc dl(Op);
12400   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12401
12402   // Optimize to BT if possible.
12403   // Lower (X & (1 << N)) == 0 to BT(X, N).
12404   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12405   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12406   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12407       Op1.getOpcode() == ISD::Constant &&
12408       cast<ConstantSDNode>(Op1)->isNullValue() &&
12409       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12410     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12411     if (NewSetCC.getNode())
12412       return NewSetCC;
12413   }
12414
12415   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12416   // these.
12417   if (Op1.getOpcode() == ISD::Constant &&
12418       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12419        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12420       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12421
12422     // If the input is a setcc, then reuse the input setcc or use a new one with
12423     // the inverted condition.
12424     if (Op0.getOpcode() == X86ISD::SETCC) {
12425       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12426       bool Invert = (CC == ISD::SETNE) ^
12427         cast<ConstantSDNode>(Op1)->isNullValue();
12428       if (!Invert)
12429         return Op0;
12430
12431       CCode = X86::GetOppositeBranchCondition(CCode);
12432       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12433                                   DAG.getConstant(CCode, MVT::i8),
12434                                   Op0.getOperand(1));
12435       if (VT == MVT::i1)
12436         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12437       return SetCC;
12438     }
12439   }
12440   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12441       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12442       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12443
12444     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12445     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12446   }
12447
12448   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12449   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12450   if (X86CC == X86::COND_INVALID)
12451     return SDValue();
12452
12453   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12454   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12455   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12456                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12457   if (VT == MVT::i1)
12458     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12459   return SetCC;
12460 }
12461
12462 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12463 static bool isX86LogicalCmp(SDValue Op) {
12464   unsigned Opc = Op.getNode()->getOpcode();
12465   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12466       Opc == X86ISD::SAHF)
12467     return true;
12468   if (Op.getResNo() == 1 &&
12469       (Opc == X86ISD::ADD ||
12470        Opc == X86ISD::SUB ||
12471        Opc == X86ISD::ADC ||
12472        Opc == X86ISD::SBB ||
12473        Opc == X86ISD::SMUL ||
12474        Opc == X86ISD::UMUL ||
12475        Opc == X86ISD::INC ||
12476        Opc == X86ISD::DEC ||
12477        Opc == X86ISD::OR ||
12478        Opc == X86ISD::XOR ||
12479        Opc == X86ISD::AND))
12480     return true;
12481
12482   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12483     return true;
12484
12485   return false;
12486 }
12487
12488 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12489   if (V.getOpcode() != ISD::TRUNCATE)
12490     return false;
12491
12492   SDValue VOp0 = V.getOperand(0);
12493   unsigned InBits = VOp0.getValueSizeInBits();
12494   unsigned Bits = V.getValueSizeInBits();
12495   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12496 }
12497
12498 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12499   bool addTest = true;
12500   SDValue Cond  = Op.getOperand(0);
12501   SDValue Op1 = Op.getOperand(1);
12502   SDValue Op2 = Op.getOperand(2);
12503   SDLoc DL(Op);
12504   EVT VT = Op1.getValueType();
12505   SDValue CC;
12506
12507   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12508   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12509   // sequence later on.
12510   if (Cond.getOpcode() == ISD::SETCC &&
12511       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12512        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12513       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12514     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12515     int SSECC = translateX86FSETCC(
12516         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12517
12518     if (SSECC != 8) {
12519       if (Subtarget->hasAVX512()) {
12520         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12521                                   DAG.getConstant(SSECC, MVT::i8));
12522         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12523       }
12524       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12525                                 DAG.getConstant(SSECC, MVT::i8));
12526       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12527       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12528       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12529     }
12530   }
12531
12532   if (Cond.getOpcode() == ISD::SETCC) {
12533     SDValue NewCond = LowerSETCC(Cond, DAG);
12534     if (NewCond.getNode())
12535       Cond = NewCond;
12536   }
12537
12538   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12539   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12540   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12541   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12542   if (Cond.getOpcode() == X86ISD::SETCC &&
12543       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12544       isZero(Cond.getOperand(1).getOperand(1))) {
12545     SDValue Cmp = Cond.getOperand(1);
12546
12547     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12548
12549     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12550         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12551       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12552
12553       SDValue CmpOp0 = Cmp.getOperand(0);
12554       // Apply further optimizations for special cases
12555       // (select (x != 0), -1, 0) -> neg & sbb
12556       // (select (x == 0), 0, -1) -> neg & sbb
12557       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12558         if (YC->isNullValue() &&
12559             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12560           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12561           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12562                                     DAG.getConstant(0, CmpOp0.getValueType()),
12563                                     CmpOp0);
12564           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12565                                     DAG.getConstant(X86::COND_B, MVT::i8),
12566                                     SDValue(Neg.getNode(), 1));
12567           return Res;
12568         }
12569
12570       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12571                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12572       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12573
12574       SDValue Res =   // Res = 0 or -1.
12575         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12576                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12577
12578       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12579         Res = DAG.getNOT(DL, Res, Res.getValueType());
12580
12581       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12582       if (!N2C || !N2C->isNullValue())
12583         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12584       return Res;
12585     }
12586   }
12587
12588   // Look past (and (setcc_carry (cmp ...)), 1).
12589   if (Cond.getOpcode() == ISD::AND &&
12590       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12591     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12592     if (C && C->getAPIntValue() == 1)
12593       Cond = Cond.getOperand(0);
12594   }
12595
12596   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12597   // setting operand in place of the X86ISD::SETCC.
12598   unsigned CondOpcode = Cond.getOpcode();
12599   if (CondOpcode == X86ISD::SETCC ||
12600       CondOpcode == X86ISD::SETCC_CARRY) {
12601     CC = Cond.getOperand(0);
12602
12603     SDValue Cmp = Cond.getOperand(1);
12604     unsigned Opc = Cmp.getOpcode();
12605     MVT VT = Op.getSimpleValueType();
12606
12607     bool IllegalFPCMov = false;
12608     if (VT.isFloatingPoint() && !VT.isVector() &&
12609         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12610       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12611
12612     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12613         Opc == X86ISD::BT) { // FIXME
12614       Cond = Cmp;
12615       addTest = false;
12616     }
12617   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12618              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12619              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12620               Cond.getOperand(0).getValueType() != MVT::i8)) {
12621     SDValue LHS = Cond.getOperand(0);
12622     SDValue RHS = Cond.getOperand(1);
12623     unsigned X86Opcode;
12624     unsigned X86Cond;
12625     SDVTList VTs;
12626     switch (CondOpcode) {
12627     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12628     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12629     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12630     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12631     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12632     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12633     default: llvm_unreachable("unexpected overflowing operator");
12634     }
12635     if (CondOpcode == ISD::UMULO)
12636       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12637                           MVT::i32);
12638     else
12639       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12640
12641     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12642
12643     if (CondOpcode == ISD::UMULO)
12644       Cond = X86Op.getValue(2);
12645     else
12646       Cond = X86Op.getValue(1);
12647
12648     CC = DAG.getConstant(X86Cond, MVT::i8);
12649     addTest = false;
12650   }
12651
12652   if (addTest) {
12653     // Look pass the truncate if the high bits are known zero.
12654     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12655         Cond = Cond.getOperand(0);
12656
12657     // We know the result of AND is compared against zero. Try to match
12658     // it to BT.
12659     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12660       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12661       if (NewSetCC.getNode()) {
12662         CC = NewSetCC.getOperand(0);
12663         Cond = NewSetCC.getOperand(1);
12664         addTest = false;
12665       }
12666     }
12667   }
12668
12669   if (addTest) {
12670     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12671     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12672   }
12673
12674   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12675   // a <  b ?  0 : -1 -> RES = setcc_carry
12676   // a >= b ? -1 :  0 -> RES = setcc_carry
12677   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12678   if (Cond.getOpcode() == X86ISD::SUB) {
12679     Cond = ConvertCmpIfNecessary(Cond, DAG);
12680     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12681
12682     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12683         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12684       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12685                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12686       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12687         return DAG.getNOT(DL, Res, Res.getValueType());
12688       return Res;
12689     }
12690   }
12691
12692   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12693   // widen the cmov and push the truncate through. This avoids introducing a new
12694   // branch during isel and doesn't add any extensions.
12695   if (Op.getValueType() == MVT::i8 &&
12696       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12697     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12698     if (T1.getValueType() == T2.getValueType() &&
12699         // Blacklist CopyFromReg to avoid partial register stalls.
12700         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12701       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12702       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12703       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12704     }
12705   }
12706
12707   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12708   // condition is true.
12709   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12710   SDValue Ops[] = { Op2, Op1, CC, Cond };
12711   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12712 }
12713
12714 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12715   MVT VT = Op->getSimpleValueType(0);
12716   SDValue In = Op->getOperand(0);
12717   MVT InVT = In.getSimpleValueType();
12718   SDLoc dl(Op);
12719
12720   unsigned int NumElts = VT.getVectorNumElements();
12721   if (NumElts != 8 && NumElts != 16)
12722     return SDValue();
12723
12724   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12725     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12726
12727   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12728   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12729
12730   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12731   Constant *C = ConstantInt::get(*DAG.getContext(),
12732     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12733
12734   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12735   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12736   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12737                           MachinePointerInfo::getConstantPool(),
12738                           false, false, false, Alignment);
12739   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12740   if (VT.is512BitVector())
12741     return Brcst;
12742   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12743 }
12744
12745 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12746                                 SelectionDAG &DAG) {
12747   MVT VT = Op->getSimpleValueType(0);
12748   SDValue In = Op->getOperand(0);
12749   MVT InVT = In.getSimpleValueType();
12750   SDLoc dl(Op);
12751
12752   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12753     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12754
12755   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12756       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12757       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12758     return SDValue();
12759
12760   if (Subtarget->hasInt256())
12761     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12762
12763   // Optimize vectors in AVX mode
12764   // Sign extend  v8i16 to v8i32 and
12765   //              v4i32 to v4i64
12766   //
12767   // Divide input vector into two parts
12768   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12769   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12770   // concat the vectors to original VT
12771
12772   unsigned NumElems = InVT.getVectorNumElements();
12773   SDValue Undef = DAG.getUNDEF(InVT);
12774
12775   SmallVector<int,8> ShufMask1(NumElems, -1);
12776   for (unsigned i = 0; i != NumElems/2; ++i)
12777     ShufMask1[i] = i;
12778
12779   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12780
12781   SmallVector<int,8> ShufMask2(NumElems, -1);
12782   for (unsigned i = 0; i != NumElems/2; ++i)
12783     ShufMask2[i] = i + NumElems/2;
12784
12785   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12786
12787   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12788                                 VT.getVectorNumElements()/2);
12789
12790   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12791   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12792
12793   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12794 }
12795
12796 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12797 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12798 // from the AND / OR.
12799 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12800   Opc = Op.getOpcode();
12801   if (Opc != ISD::OR && Opc != ISD::AND)
12802     return false;
12803   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12804           Op.getOperand(0).hasOneUse() &&
12805           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12806           Op.getOperand(1).hasOneUse());
12807 }
12808
12809 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12810 // 1 and that the SETCC node has a single use.
12811 static bool isXor1OfSetCC(SDValue Op) {
12812   if (Op.getOpcode() != ISD::XOR)
12813     return false;
12814   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12815   if (N1C && N1C->getAPIntValue() == 1) {
12816     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12817       Op.getOperand(0).hasOneUse();
12818   }
12819   return false;
12820 }
12821
12822 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12823   bool addTest = true;
12824   SDValue Chain = Op.getOperand(0);
12825   SDValue Cond  = Op.getOperand(1);
12826   SDValue Dest  = Op.getOperand(2);
12827   SDLoc dl(Op);
12828   SDValue CC;
12829   bool Inverted = false;
12830
12831   if (Cond.getOpcode() == ISD::SETCC) {
12832     // Check for setcc([su]{add,sub,mul}o == 0).
12833     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12834         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12835         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12836         Cond.getOperand(0).getResNo() == 1 &&
12837         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12838          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12839          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12840          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12841          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12842          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12843       Inverted = true;
12844       Cond = Cond.getOperand(0);
12845     } else {
12846       SDValue NewCond = LowerSETCC(Cond, DAG);
12847       if (NewCond.getNode())
12848         Cond = NewCond;
12849     }
12850   }
12851 #if 0
12852   // FIXME: LowerXALUO doesn't handle these!!
12853   else if (Cond.getOpcode() == X86ISD::ADD  ||
12854            Cond.getOpcode() == X86ISD::SUB  ||
12855            Cond.getOpcode() == X86ISD::SMUL ||
12856            Cond.getOpcode() == X86ISD::UMUL)
12857     Cond = LowerXALUO(Cond, DAG);
12858 #endif
12859
12860   // Look pass (and (setcc_carry (cmp ...)), 1).
12861   if (Cond.getOpcode() == ISD::AND &&
12862       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12863     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12864     if (C && C->getAPIntValue() == 1)
12865       Cond = Cond.getOperand(0);
12866   }
12867
12868   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12869   // setting operand in place of the X86ISD::SETCC.
12870   unsigned CondOpcode = Cond.getOpcode();
12871   if (CondOpcode == X86ISD::SETCC ||
12872       CondOpcode == X86ISD::SETCC_CARRY) {
12873     CC = Cond.getOperand(0);
12874
12875     SDValue Cmp = Cond.getOperand(1);
12876     unsigned Opc = Cmp.getOpcode();
12877     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12878     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12879       Cond = Cmp;
12880       addTest = false;
12881     } else {
12882       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12883       default: break;
12884       case X86::COND_O:
12885       case X86::COND_B:
12886         // These can only come from an arithmetic instruction with overflow,
12887         // e.g. SADDO, UADDO.
12888         Cond = Cond.getNode()->getOperand(1);
12889         addTest = false;
12890         break;
12891       }
12892     }
12893   }
12894   CondOpcode = Cond.getOpcode();
12895   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12896       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12897       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12898        Cond.getOperand(0).getValueType() != MVT::i8)) {
12899     SDValue LHS = Cond.getOperand(0);
12900     SDValue RHS = Cond.getOperand(1);
12901     unsigned X86Opcode;
12902     unsigned X86Cond;
12903     SDVTList VTs;
12904     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12905     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12906     // X86ISD::INC).
12907     switch (CondOpcode) {
12908     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12909     case ISD::SADDO:
12910       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12911         if (C->isOne()) {
12912           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12913           break;
12914         }
12915       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12916     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12917     case ISD::SSUBO:
12918       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12919         if (C->isOne()) {
12920           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12921           break;
12922         }
12923       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12924     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12925     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12926     default: llvm_unreachable("unexpected overflowing operator");
12927     }
12928     if (Inverted)
12929       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12930     if (CondOpcode == ISD::UMULO)
12931       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12932                           MVT::i32);
12933     else
12934       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12935
12936     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12937
12938     if (CondOpcode == ISD::UMULO)
12939       Cond = X86Op.getValue(2);
12940     else
12941       Cond = X86Op.getValue(1);
12942
12943     CC = DAG.getConstant(X86Cond, MVT::i8);
12944     addTest = false;
12945   } else {
12946     unsigned CondOpc;
12947     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12948       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12949       if (CondOpc == ISD::OR) {
12950         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12951         // two branches instead of an explicit OR instruction with a
12952         // separate test.
12953         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12954             isX86LogicalCmp(Cmp)) {
12955           CC = Cond.getOperand(0).getOperand(0);
12956           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12957                               Chain, Dest, CC, Cmp);
12958           CC = Cond.getOperand(1).getOperand(0);
12959           Cond = Cmp;
12960           addTest = false;
12961         }
12962       } else { // ISD::AND
12963         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12964         // two branches instead of an explicit AND instruction with a
12965         // separate test. However, we only do this if this block doesn't
12966         // have a fall-through edge, because this requires an explicit
12967         // jmp when the condition is false.
12968         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12969             isX86LogicalCmp(Cmp) &&
12970             Op.getNode()->hasOneUse()) {
12971           X86::CondCode CCode =
12972             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12973           CCode = X86::GetOppositeBranchCondition(CCode);
12974           CC = DAG.getConstant(CCode, MVT::i8);
12975           SDNode *User = *Op.getNode()->use_begin();
12976           // Look for an unconditional branch following this conditional branch.
12977           // We need this because we need to reverse the successors in order
12978           // to implement FCMP_OEQ.
12979           if (User->getOpcode() == ISD::BR) {
12980             SDValue FalseBB = User->getOperand(1);
12981             SDNode *NewBR =
12982               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12983             assert(NewBR == User);
12984             (void)NewBR;
12985             Dest = FalseBB;
12986
12987             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12988                                 Chain, Dest, CC, Cmp);
12989             X86::CondCode CCode =
12990               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12991             CCode = X86::GetOppositeBranchCondition(CCode);
12992             CC = DAG.getConstant(CCode, MVT::i8);
12993             Cond = Cmp;
12994             addTest = false;
12995           }
12996         }
12997       }
12998     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
12999       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13000       // It should be transformed during dag combiner except when the condition
13001       // is set by a arithmetics with overflow node.
13002       X86::CondCode CCode =
13003         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13004       CCode = X86::GetOppositeBranchCondition(CCode);
13005       CC = DAG.getConstant(CCode, MVT::i8);
13006       Cond = Cond.getOperand(0).getOperand(1);
13007       addTest = false;
13008     } else if (Cond.getOpcode() == ISD::SETCC &&
13009                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13010       // For FCMP_OEQ, we can emit
13011       // two branches instead of an explicit AND instruction with a
13012       // separate test. However, we only do this if this block doesn't
13013       // have a fall-through edge, because this requires an explicit
13014       // jmp when the condition is false.
13015       if (Op.getNode()->hasOneUse()) {
13016         SDNode *User = *Op.getNode()->use_begin();
13017         // Look for an unconditional branch following this conditional branch.
13018         // We need this because we need to reverse the successors in order
13019         // to implement FCMP_OEQ.
13020         if (User->getOpcode() == ISD::BR) {
13021           SDValue FalseBB = User->getOperand(1);
13022           SDNode *NewBR =
13023             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13024           assert(NewBR == User);
13025           (void)NewBR;
13026           Dest = FalseBB;
13027
13028           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13029                                     Cond.getOperand(0), Cond.getOperand(1));
13030           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13031           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13032           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13033                               Chain, Dest, CC, Cmp);
13034           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13035           Cond = Cmp;
13036           addTest = false;
13037         }
13038       }
13039     } else if (Cond.getOpcode() == ISD::SETCC &&
13040                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13041       // For FCMP_UNE, we can emit
13042       // two branches instead of an explicit AND instruction with a
13043       // separate test. However, we only do this if this block doesn't
13044       // have a fall-through edge, because this requires an explicit
13045       // jmp when the condition is false.
13046       if (Op.getNode()->hasOneUse()) {
13047         SDNode *User = *Op.getNode()->use_begin();
13048         // Look for an unconditional branch following this conditional branch.
13049         // We need this because we need to reverse the successors in order
13050         // to implement FCMP_UNE.
13051         if (User->getOpcode() == ISD::BR) {
13052           SDValue FalseBB = User->getOperand(1);
13053           SDNode *NewBR =
13054             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13055           assert(NewBR == User);
13056           (void)NewBR;
13057
13058           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13059                                     Cond.getOperand(0), Cond.getOperand(1));
13060           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13061           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13062           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13063                               Chain, Dest, CC, Cmp);
13064           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13065           Cond = Cmp;
13066           addTest = false;
13067           Dest = FalseBB;
13068         }
13069       }
13070     }
13071   }
13072
13073   if (addTest) {
13074     // Look pass the truncate if the high bits are known zero.
13075     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13076         Cond = Cond.getOperand(0);
13077
13078     // We know the result of AND is compared against zero. Try to match
13079     // it to BT.
13080     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13081       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13082       if (NewSetCC.getNode()) {
13083         CC = NewSetCC.getOperand(0);
13084         Cond = NewSetCC.getOperand(1);
13085         addTest = false;
13086       }
13087     }
13088   }
13089
13090   if (addTest) {
13091     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13092     CC = DAG.getConstant(X86Cond, MVT::i8);
13093     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13094   }
13095   Cond = ConvertCmpIfNecessary(Cond, DAG);
13096   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13097                      Chain, Dest, CC, Cond);
13098 }
13099
13100 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13101 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13102 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13103 // that the guard pages used by the OS virtual memory manager are allocated in
13104 // correct sequence.
13105 SDValue
13106 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13107                                            SelectionDAG &DAG) const {
13108   MachineFunction &MF = DAG.getMachineFunction();
13109   bool SplitStack = MF.shouldSplitStack();
13110   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13111                SplitStack;
13112   SDLoc dl(Op);
13113
13114   if (!Lower) {
13115     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13116     SDNode* Node = Op.getNode();
13117
13118     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13119     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13120         " not tell us which reg is the stack pointer!");
13121     EVT VT = Node->getValueType(0);
13122     SDValue Tmp1 = SDValue(Node, 0);
13123     SDValue Tmp2 = SDValue(Node, 1);
13124     SDValue Tmp3 = Node->getOperand(2);
13125     SDValue Chain = Tmp1.getOperand(0);
13126
13127     // Chain the dynamic stack allocation so that it doesn't modify the stack
13128     // pointer when other instructions are using the stack.
13129     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13130         SDLoc(Node));
13131
13132     SDValue Size = Tmp2.getOperand(1);
13133     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13134     Chain = SP.getValue(1);
13135     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13136     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13137     unsigned StackAlign = TFI.getStackAlignment();
13138     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13139     if (Align > StackAlign)
13140       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13141           DAG.getConstant(-(uint64_t)Align, VT));
13142     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13143
13144     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13145         DAG.getIntPtrConstant(0, true), SDValue(),
13146         SDLoc(Node));
13147
13148     SDValue Ops[2] = { Tmp1, Tmp2 };
13149     return DAG.getMergeValues(Ops, dl);
13150   }
13151
13152   // Get the inputs.
13153   SDValue Chain = Op.getOperand(0);
13154   SDValue Size  = Op.getOperand(1);
13155   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13156   EVT VT = Op.getNode()->getValueType(0);
13157
13158   bool Is64Bit = Subtarget->is64Bit();
13159   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13160
13161   if (SplitStack) {
13162     MachineRegisterInfo &MRI = MF.getRegInfo();
13163
13164     if (Is64Bit) {
13165       // The 64 bit implementation of segmented stacks needs to clobber both r10
13166       // r11. This makes it impossible to use it along with nested parameters.
13167       const Function *F = MF.getFunction();
13168
13169       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13170            I != E; ++I)
13171         if (I->hasNestAttr())
13172           report_fatal_error("Cannot use segmented stacks with functions that "
13173                              "have nested arguments.");
13174     }
13175
13176     const TargetRegisterClass *AddrRegClass =
13177       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13178     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13179     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13180     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13181                                 DAG.getRegister(Vreg, SPTy));
13182     SDValue Ops1[2] = { Value, Chain };
13183     return DAG.getMergeValues(Ops1, dl);
13184   } else {
13185     SDValue Flag;
13186     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13187
13188     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13189     Flag = Chain.getValue(1);
13190     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13191
13192     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13193
13194     const X86RegisterInfo *RegInfo =
13195       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13196     unsigned SPReg = RegInfo->getStackRegister();
13197     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13198     Chain = SP.getValue(1);
13199
13200     if (Align) {
13201       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13202                        DAG.getConstant(-(uint64_t)Align, VT));
13203       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13204     }
13205
13206     SDValue Ops1[2] = { SP, Chain };
13207     return DAG.getMergeValues(Ops1, dl);
13208   }
13209 }
13210
13211 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13212   MachineFunction &MF = DAG.getMachineFunction();
13213   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13214
13215   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13216   SDLoc DL(Op);
13217
13218   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13219     // vastart just stores the address of the VarArgsFrameIndex slot into the
13220     // memory location argument.
13221     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13222                                    getPointerTy());
13223     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13224                         MachinePointerInfo(SV), false, false, 0);
13225   }
13226
13227   // __va_list_tag:
13228   //   gp_offset         (0 - 6 * 8)
13229   //   fp_offset         (48 - 48 + 8 * 16)
13230   //   overflow_arg_area (point to parameters coming in memory).
13231   //   reg_save_area
13232   SmallVector<SDValue, 8> MemOps;
13233   SDValue FIN = Op.getOperand(1);
13234   // Store gp_offset
13235   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13236                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13237                                                MVT::i32),
13238                                FIN, MachinePointerInfo(SV), false, false, 0);
13239   MemOps.push_back(Store);
13240
13241   // Store fp_offset
13242   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13243                     FIN, DAG.getIntPtrConstant(4));
13244   Store = DAG.getStore(Op.getOperand(0), DL,
13245                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13246                                        MVT::i32),
13247                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13248   MemOps.push_back(Store);
13249
13250   // Store ptr to overflow_arg_area
13251   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13252                     FIN, DAG.getIntPtrConstant(4));
13253   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13254                                     getPointerTy());
13255   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13256                        MachinePointerInfo(SV, 8),
13257                        false, false, 0);
13258   MemOps.push_back(Store);
13259
13260   // Store ptr to reg_save_area.
13261   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13262                     FIN, DAG.getIntPtrConstant(8));
13263   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13264                                     getPointerTy());
13265   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13266                        MachinePointerInfo(SV, 16), false, false, 0);
13267   MemOps.push_back(Store);
13268   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13269 }
13270
13271 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13272   assert(Subtarget->is64Bit() &&
13273          "LowerVAARG only handles 64-bit va_arg!");
13274   assert((Subtarget->isTargetLinux() ||
13275           Subtarget->isTargetDarwin()) &&
13276           "Unhandled target in LowerVAARG");
13277   assert(Op.getNode()->getNumOperands() == 4);
13278   SDValue Chain = Op.getOperand(0);
13279   SDValue SrcPtr = Op.getOperand(1);
13280   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13281   unsigned Align = Op.getConstantOperandVal(3);
13282   SDLoc dl(Op);
13283
13284   EVT ArgVT = Op.getNode()->getValueType(0);
13285   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13286   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13287   uint8_t ArgMode;
13288
13289   // Decide which area this value should be read from.
13290   // TODO: Implement the AMD64 ABI in its entirety. This simple
13291   // selection mechanism works only for the basic types.
13292   if (ArgVT == MVT::f80) {
13293     llvm_unreachable("va_arg for f80 not yet implemented");
13294   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13295     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13296   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13297     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13298   } else {
13299     llvm_unreachable("Unhandled argument type in LowerVAARG");
13300   }
13301
13302   if (ArgMode == 2) {
13303     // Sanity Check: Make sure using fp_offset makes sense.
13304     assert(!DAG.getTarget().Options.UseSoftFloat &&
13305            !(DAG.getMachineFunction()
13306                 .getFunction()->getAttributes()
13307                 .hasAttribute(AttributeSet::FunctionIndex,
13308                               Attribute::NoImplicitFloat)) &&
13309            Subtarget->hasSSE1());
13310   }
13311
13312   // Insert VAARG_64 node into the DAG
13313   // VAARG_64 returns two values: Variable Argument Address, Chain
13314   SmallVector<SDValue, 11> InstOps;
13315   InstOps.push_back(Chain);
13316   InstOps.push_back(SrcPtr);
13317   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13318   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13319   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13320   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13321   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13322                                           VTs, InstOps, MVT::i64,
13323                                           MachinePointerInfo(SV),
13324                                           /*Align=*/0,
13325                                           /*Volatile=*/false,
13326                                           /*ReadMem=*/true,
13327                                           /*WriteMem=*/true);
13328   Chain = VAARG.getValue(1);
13329
13330   // Load the next argument and return it
13331   return DAG.getLoad(ArgVT, dl,
13332                      Chain,
13333                      VAARG,
13334                      MachinePointerInfo(),
13335                      false, false, false, 0);
13336 }
13337
13338 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13339                            SelectionDAG &DAG) {
13340   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13341   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13342   SDValue Chain = Op.getOperand(0);
13343   SDValue DstPtr = Op.getOperand(1);
13344   SDValue SrcPtr = Op.getOperand(2);
13345   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13346   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13347   SDLoc DL(Op);
13348
13349   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13350                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13351                        false,
13352                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13353 }
13354
13355 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13356 // amount is a constant. Takes immediate version of shift as input.
13357 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13358                                           SDValue SrcOp, uint64_t ShiftAmt,
13359                                           SelectionDAG &DAG) {
13360   MVT ElementType = VT.getVectorElementType();
13361
13362   // Fold this packed shift into its first operand if ShiftAmt is 0.
13363   if (ShiftAmt == 0)
13364     return SrcOp;
13365
13366   // Check for ShiftAmt >= element width
13367   if (ShiftAmt >= ElementType.getSizeInBits()) {
13368     if (Opc == X86ISD::VSRAI)
13369       ShiftAmt = ElementType.getSizeInBits() - 1;
13370     else
13371       return DAG.getConstant(0, VT);
13372   }
13373
13374   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13375          && "Unknown target vector shift-by-constant node");
13376
13377   // Fold this packed vector shift into a build vector if SrcOp is a
13378   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13379   if (VT == SrcOp.getSimpleValueType() &&
13380       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13381     SmallVector<SDValue, 8> Elts;
13382     unsigned NumElts = SrcOp->getNumOperands();
13383     ConstantSDNode *ND;
13384
13385     switch(Opc) {
13386     default: llvm_unreachable(nullptr);
13387     case X86ISD::VSHLI:
13388       for (unsigned i=0; i!=NumElts; ++i) {
13389         SDValue CurrentOp = SrcOp->getOperand(i);
13390         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13391           Elts.push_back(CurrentOp);
13392           continue;
13393         }
13394         ND = cast<ConstantSDNode>(CurrentOp);
13395         const APInt &C = ND->getAPIntValue();
13396         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13397       }
13398       break;
13399     case X86ISD::VSRLI:
13400       for (unsigned i=0; i!=NumElts; ++i) {
13401         SDValue CurrentOp = SrcOp->getOperand(i);
13402         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13403           Elts.push_back(CurrentOp);
13404           continue;
13405         }
13406         ND = cast<ConstantSDNode>(CurrentOp);
13407         const APInt &C = ND->getAPIntValue();
13408         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13409       }
13410       break;
13411     case X86ISD::VSRAI:
13412       for (unsigned i=0; i!=NumElts; ++i) {
13413         SDValue CurrentOp = SrcOp->getOperand(i);
13414         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13415           Elts.push_back(CurrentOp);
13416           continue;
13417         }
13418         ND = cast<ConstantSDNode>(CurrentOp);
13419         const APInt &C = ND->getAPIntValue();
13420         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13421       }
13422       break;
13423     }
13424
13425     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13426   }
13427
13428   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13429 }
13430
13431 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13432 // may or may not be a constant. Takes immediate version of shift as input.
13433 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13434                                    SDValue SrcOp, SDValue ShAmt,
13435                                    SelectionDAG &DAG) {
13436   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13437
13438   // Catch shift-by-constant.
13439   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13440     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13441                                       CShAmt->getZExtValue(), DAG);
13442
13443   // Change opcode to non-immediate version
13444   switch (Opc) {
13445     default: llvm_unreachable("Unknown target vector shift node");
13446     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13447     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13448     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13449   }
13450
13451   // Need to build a vector containing shift amount
13452   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13453   SDValue ShOps[4];
13454   ShOps[0] = ShAmt;
13455   ShOps[1] = DAG.getConstant(0, MVT::i32);
13456   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13457   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13458
13459   // The return type has to be a 128-bit type with the same element
13460   // type as the input type.
13461   MVT EltVT = VT.getVectorElementType();
13462   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13463
13464   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13465   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13466 }
13467
13468 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13469   SDLoc dl(Op);
13470   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13471   switch (IntNo) {
13472   default: return SDValue();    // Don't custom lower most intrinsics.
13473   // Comparison intrinsics.
13474   case Intrinsic::x86_sse_comieq_ss:
13475   case Intrinsic::x86_sse_comilt_ss:
13476   case Intrinsic::x86_sse_comile_ss:
13477   case Intrinsic::x86_sse_comigt_ss:
13478   case Intrinsic::x86_sse_comige_ss:
13479   case Intrinsic::x86_sse_comineq_ss:
13480   case Intrinsic::x86_sse_ucomieq_ss:
13481   case Intrinsic::x86_sse_ucomilt_ss:
13482   case Intrinsic::x86_sse_ucomile_ss:
13483   case Intrinsic::x86_sse_ucomigt_ss:
13484   case Intrinsic::x86_sse_ucomige_ss:
13485   case Intrinsic::x86_sse_ucomineq_ss:
13486   case Intrinsic::x86_sse2_comieq_sd:
13487   case Intrinsic::x86_sse2_comilt_sd:
13488   case Intrinsic::x86_sse2_comile_sd:
13489   case Intrinsic::x86_sse2_comigt_sd:
13490   case Intrinsic::x86_sse2_comige_sd:
13491   case Intrinsic::x86_sse2_comineq_sd:
13492   case Intrinsic::x86_sse2_ucomieq_sd:
13493   case Intrinsic::x86_sse2_ucomilt_sd:
13494   case Intrinsic::x86_sse2_ucomile_sd:
13495   case Intrinsic::x86_sse2_ucomigt_sd:
13496   case Intrinsic::x86_sse2_ucomige_sd:
13497   case Intrinsic::x86_sse2_ucomineq_sd: {
13498     unsigned Opc;
13499     ISD::CondCode CC;
13500     switch (IntNo) {
13501     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13502     case Intrinsic::x86_sse_comieq_ss:
13503     case Intrinsic::x86_sse2_comieq_sd:
13504       Opc = X86ISD::COMI;
13505       CC = ISD::SETEQ;
13506       break;
13507     case Intrinsic::x86_sse_comilt_ss:
13508     case Intrinsic::x86_sse2_comilt_sd:
13509       Opc = X86ISD::COMI;
13510       CC = ISD::SETLT;
13511       break;
13512     case Intrinsic::x86_sse_comile_ss:
13513     case Intrinsic::x86_sse2_comile_sd:
13514       Opc = X86ISD::COMI;
13515       CC = ISD::SETLE;
13516       break;
13517     case Intrinsic::x86_sse_comigt_ss:
13518     case Intrinsic::x86_sse2_comigt_sd:
13519       Opc = X86ISD::COMI;
13520       CC = ISD::SETGT;
13521       break;
13522     case Intrinsic::x86_sse_comige_ss:
13523     case Intrinsic::x86_sse2_comige_sd:
13524       Opc = X86ISD::COMI;
13525       CC = ISD::SETGE;
13526       break;
13527     case Intrinsic::x86_sse_comineq_ss:
13528     case Intrinsic::x86_sse2_comineq_sd:
13529       Opc = X86ISD::COMI;
13530       CC = ISD::SETNE;
13531       break;
13532     case Intrinsic::x86_sse_ucomieq_ss:
13533     case Intrinsic::x86_sse2_ucomieq_sd:
13534       Opc = X86ISD::UCOMI;
13535       CC = ISD::SETEQ;
13536       break;
13537     case Intrinsic::x86_sse_ucomilt_ss:
13538     case Intrinsic::x86_sse2_ucomilt_sd:
13539       Opc = X86ISD::UCOMI;
13540       CC = ISD::SETLT;
13541       break;
13542     case Intrinsic::x86_sse_ucomile_ss:
13543     case Intrinsic::x86_sse2_ucomile_sd:
13544       Opc = X86ISD::UCOMI;
13545       CC = ISD::SETLE;
13546       break;
13547     case Intrinsic::x86_sse_ucomigt_ss:
13548     case Intrinsic::x86_sse2_ucomigt_sd:
13549       Opc = X86ISD::UCOMI;
13550       CC = ISD::SETGT;
13551       break;
13552     case Intrinsic::x86_sse_ucomige_ss:
13553     case Intrinsic::x86_sse2_ucomige_sd:
13554       Opc = X86ISD::UCOMI;
13555       CC = ISD::SETGE;
13556       break;
13557     case Intrinsic::x86_sse_ucomineq_ss:
13558     case Intrinsic::x86_sse2_ucomineq_sd:
13559       Opc = X86ISD::UCOMI;
13560       CC = ISD::SETNE;
13561       break;
13562     }
13563
13564     SDValue LHS = Op.getOperand(1);
13565     SDValue RHS = Op.getOperand(2);
13566     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13567     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13568     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13569     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13570                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13571     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13572   }
13573
13574   // Arithmetic intrinsics.
13575   case Intrinsic::x86_sse2_pmulu_dq:
13576   case Intrinsic::x86_avx2_pmulu_dq:
13577     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13578                        Op.getOperand(1), Op.getOperand(2));
13579
13580   case Intrinsic::x86_sse41_pmuldq:
13581   case Intrinsic::x86_avx2_pmul_dq:
13582     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13583                        Op.getOperand(1), Op.getOperand(2));
13584
13585   case Intrinsic::x86_sse2_pmulhu_w:
13586   case Intrinsic::x86_avx2_pmulhu_w:
13587     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13588                        Op.getOperand(1), Op.getOperand(2));
13589
13590   case Intrinsic::x86_sse2_pmulh_w:
13591   case Intrinsic::x86_avx2_pmulh_w:
13592     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13593                        Op.getOperand(1), Op.getOperand(2));
13594
13595   // SSE2/AVX2 sub with unsigned saturation intrinsics
13596   case Intrinsic::x86_sse2_psubus_b:
13597   case Intrinsic::x86_sse2_psubus_w:
13598   case Intrinsic::x86_avx2_psubus_b:
13599   case Intrinsic::x86_avx2_psubus_w:
13600     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13601                        Op.getOperand(1), Op.getOperand(2));
13602
13603   // SSE3/AVX horizontal add/sub intrinsics
13604   case Intrinsic::x86_sse3_hadd_ps:
13605   case Intrinsic::x86_sse3_hadd_pd:
13606   case Intrinsic::x86_avx_hadd_ps_256:
13607   case Intrinsic::x86_avx_hadd_pd_256:
13608   case Intrinsic::x86_sse3_hsub_ps:
13609   case Intrinsic::x86_sse3_hsub_pd:
13610   case Intrinsic::x86_avx_hsub_ps_256:
13611   case Intrinsic::x86_avx_hsub_pd_256:
13612   case Intrinsic::x86_ssse3_phadd_w_128:
13613   case Intrinsic::x86_ssse3_phadd_d_128:
13614   case Intrinsic::x86_avx2_phadd_w:
13615   case Intrinsic::x86_avx2_phadd_d:
13616   case Intrinsic::x86_ssse3_phsub_w_128:
13617   case Intrinsic::x86_ssse3_phsub_d_128:
13618   case Intrinsic::x86_avx2_phsub_w:
13619   case Intrinsic::x86_avx2_phsub_d: {
13620     unsigned Opcode;
13621     switch (IntNo) {
13622     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13623     case Intrinsic::x86_sse3_hadd_ps:
13624     case Intrinsic::x86_sse3_hadd_pd:
13625     case Intrinsic::x86_avx_hadd_ps_256:
13626     case Intrinsic::x86_avx_hadd_pd_256:
13627       Opcode = X86ISD::FHADD;
13628       break;
13629     case Intrinsic::x86_sse3_hsub_ps:
13630     case Intrinsic::x86_sse3_hsub_pd:
13631     case Intrinsic::x86_avx_hsub_ps_256:
13632     case Intrinsic::x86_avx_hsub_pd_256:
13633       Opcode = X86ISD::FHSUB;
13634       break;
13635     case Intrinsic::x86_ssse3_phadd_w_128:
13636     case Intrinsic::x86_ssse3_phadd_d_128:
13637     case Intrinsic::x86_avx2_phadd_w:
13638     case Intrinsic::x86_avx2_phadd_d:
13639       Opcode = X86ISD::HADD;
13640       break;
13641     case Intrinsic::x86_ssse3_phsub_w_128:
13642     case Intrinsic::x86_ssse3_phsub_d_128:
13643     case Intrinsic::x86_avx2_phsub_w:
13644     case Intrinsic::x86_avx2_phsub_d:
13645       Opcode = X86ISD::HSUB;
13646       break;
13647     }
13648     return DAG.getNode(Opcode, dl, Op.getValueType(),
13649                        Op.getOperand(1), Op.getOperand(2));
13650   }
13651
13652   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13653   case Intrinsic::x86_sse2_pmaxu_b:
13654   case Intrinsic::x86_sse41_pmaxuw:
13655   case Intrinsic::x86_sse41_pmaxud:
13656   case Intrinsic::x86_avx2_pmaxu_b:
13657   case Intrinsic::x86_avx2_pmaxu_w:
13658   case Intrinsic::x86_avx2_pmaxu_d:
13659   case Intrinsic::x86_sse2_pminu_b:
13660   case Intrinsic::x86_sse41_pminuw:
13661   case Intrinsic::x86_sse41_pminud:
13662   case Intrinsic::x86_avx2_pminu_b:
13663   case Intrinsic::x86_avx2_pminu_w:
13664   case Intrinsic::x86_avx2_pminu_d:
13665   case Intrinsic::x86_sse41_pmaxsb:
13666   case Intrinsic::x86_sse2_pmaxs_w:
13667   case Intrinsic::x86_sse41_pmaxsd:
13668   case Intrinsic::x86_avx2_pmaxs_b:
13669   case Intrinsic::x86_avx2_pmaxs_w:
13670   case Intrinsic::x86_avx2_pmaxs_d:
13671   case Intrinsic::x86_sse41_pminsb:
13672   case Intrinsic::x86_sse2_pmins_w:
13673   case Intrinsic::x86_sse41_pminsd:
13674   case Intrinsic::x86_avx2_pmins_b:
13675   case Intrinsic::x86_avx2_pmins_w:
13676   case Intrinsic::x86_avx2_pmins_d: {
13677     unsigned Opcode;
13678     switch (IntNo) {
13679     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13680     case Intrinsic::x86_sse2_pmaxu_b:
13681     case Intrinsic::x86_sse41_pmaxuw:
13682     case Intrinsic::x86_sse41_pmaxud:
13683     case Intrinsic::x86_avx2_pmaxu_b:
13684     case Intrinsic::x86_avx2_pmaxu_w:
13685     case Intrinsic::x86_avx2_pmaxu_d:
13686       Opcode = X86ISD::UMAX;
13687       break;
13688     case Intrinsic::x86_sse2_pminu_b:
13689     case Intrinsic::x86_sse41_pminuw:
13690     case Intrinsic::x86_sse41_pminud:
13691     case Intrinsic::x86_avx2_pminu_b:
13692     case Intrinsic::x86_avx2_pminu_w:
13693     case Intrinsic::x86_avx2_pminu_d:
13694       Opcode = X86ISD::UMIN;
13695       break;
13696     case Intrinsic::x86_sse41_pmaxsb:
13697     case Intrinsic::x86_sse2_pmaxs_w:
13698     case Intrinsic::x86_sse41_pmaxsd:
13699     case Intrinsic::x86_avx2_pmaxs_b:
13700     case Intrinsic::x86_avx2_pmaxs_w:
13701     case Intrinsic::x86_avx2_pmaxs_d:
13702       Opcode = X86ISD::SMAX;
13703       break;
13704     case Intrinsic::x86_sse41_pminsb:
13705     case Intrinsic::x86_sse2_pmins_w:
13706     case Intrinsic::x86_sse41_pminsd:
13707     case Intrinsic::x86_avx2_pmins_b:
13708     case Intrinsic::x86_avx2_pmins_w:
13709     case Intrinsic::x86_avx2_pmins_d:
13710       Opcode = X86ISD::SMIN;
13711       break;
13712     }
13713     return DAG.getNode(Opcode, dl, Op.getValueType(),
13714                        Op.getOperand(1), Op.getOperand(2));
13715   }
13716
13717   // SSE/SSE2/AVX floating point max/min intrinsics.
13718   case Intrinsic::x86_sse_max_ps:
13719   case Intrinsic::x86_sse2_max_pd:
13720   case Intrinsic::x86_avx_max_ps_256:
13721   case Intrinsic::x86_avx_max_pd_256:
13722   case Intrinsic::x86_sse_min_ps:
13723   case Intrinsic::x86_sse2_min_pd:
13724   case Intrinsic::x86_avx_min_ps_256:
13725   case Intrinsic::x86_avx_min_pd_256: {
13726     unsigned Opcode;
13727     switch (IntNo) {
13728     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13729     case Intrinsic::x86_sse_max_ps:
13730     case Intrinsic::x86_sse2_max_pd:
13731     case Intrinsic::x86_avx_max_ps_256:
13732     case Intrinsic::x86_avx_max_pd_256:
13733       Opcode = X86ISD::FMAX;
13734       break;
13735     case Intrinsic::x86_sse_min_ps:
13736     case Intrinsic::x86_sse2_min_pd:
13737     case Intrinsic::x86_avx_min_ps_256:
13738     case Intrinsic::x86_avx_min_pd_256:
13739       Opcode = X86ISD::FMIN;
13740       break;
13741     }
13742     return DAG.getNode(Opcode, dl, Op.getValueType(),
13743                        Op.getOperand(1), Op.getOperand(2));
13744   }
13745
13746   // AVX2 variable shift intrinsics
13747   case Intrinsic::x86_avx2_psllv_d:
13748   case Intrinsic::x86_avx2_psllv_q:
13749   case Intrinsic::x86_avx2_psllv_d_256:
13750   case Intrinsic::x86_avx2_psllv_q_256:
13751   case Intrinsic::x86_avx2_psrlv_d:
13752   case Intrinsic::x86_avx2_psrlv_q:
13753   case Intrinsic::x86_avx2_psrlv_d_256:
13754   case Intrinsic::x86_avx2_psrlv_q_256:
13755   case Intrinsic::x86_avx2_psrav_d:
13756   case Intrinsic::x86_avx2_psrav_d_256: {
13757     unsigned Opcode;
13758     switch (IntNo) {
13759     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13760     case Intrinsic::x86_avx2_psllv_d:
13761     case Intrinsic::x86_avx2_psllv_q:
13762     case Intrinsic::x86_avx2_psllv_d_256:
13763     case Intrinsic::x86_avx2_psllv_q_256:
13764       Opcode = ISD::SHL;
13765       break;
13766     case Intrinsic::x86_avx2_psrlv_d:
13767     case Intrinsic::x86_avx2_psrlv_q:
13768     case Intrinsic::x86_avx2_psrlv_d_256:
13769     case Intrinsic::x86_avx2_psrlv_q_256:
13770       Opcode = ISD::SRL;
13771       break;
13772     case Intrinsic::x86_avx2_psrav_d:
13773     case Intrinsic::x86_avx2_psrav_d_256:
13774       Opcode = ISD::SRA;
13775       break;
13776     }
13777     return DAG.getNode(Opcode, dl, Op.getValueType(),
13778                        Op.getOperand(1), Op.getOperand(2));
13779   }
13780
13781   case Intrinsic::x86_sse2_packssdw_128:
13782   case Intrinsic::x86_sse2_packsswb_128:
13783   case Intrinsic::x86_avx2_packssdw:
13784   case Intrinsic::x86_avx2_packsswb:
13785     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13786                        Op.getOperand(1), Op.getOperand(2));
13787
13788   case Intrinsic::x86_sse2_packuswb_128:
13789   case Intrinsic::x86_sse41_packusdw:
13790   case Intrinsic::x86_avx2_packuswb:
13791   case Intrinsic::x86_avx2_packusdw:
13792     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13793                        Op.getOperand(1), Op.getOperand(2));
13794
13795   case Intrinsic::x86_ssse3_pshuf_b_128:
13796   case Intrinsic::x86_avx2_pshuf_b:
13797     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13798                        Op.getOperand(1), Op.getOperand(2));
13799
13800   case Intrinsic::x86_sse2_pshuf_d:
13801     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13802                        Op.getOperand(1), Op.getOperand(2));
13803
13804   case Intrinsic::x86_sse2_pshufl_w:
13805     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13806                        Op.getOperand(1), Op.getOperand(2));
13807
13808   case Intrinsic::x86_sse2_pshufh_w:
13809     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13810                        Op.getOperand(1), Op.getOperand(2));
13811
13812   case Intrinsic::x86_ssse3_psign_b_128:
13813   case Intrinsic::x86_ssse3_psign_w_128:
13814   case Intrinsic::x86_ssse3_psign_d_128:
13815   case Intrinsic::x86_avx2_psign_b:
13816   case Intrinsic::x86_avx2_psign_w:
13817   case Intrinsic::x86_avx2_psign_d:
13818     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13819                        Op.getOperand(1), Op.getOperand(2));
13820
13821   case Intrinsic::x86_sse41_insertps:
13822     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13823                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13824
13825   case Intrinsic::x86_avx_vperm2f128_ps_256:
13826   case Intrinsic::x86_avx_vperm2f128_pd_256:
13827   case Intrinsic::x86_avx_vperm2f128_si_256:
13828   case Intrinsic::x86_avx2_vperm2i128:
13829     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13830                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13831
13832   case Intrinsic::x86_avx2_permd:
13833   case Intrinsic::x86_avx2_permps:
13834     // Operands intentionally swapped. Mask is last operand to intrinsic,
13835     // but second operand for node/instruction.
13836     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13837                        Op.getOperand(2), Op.getOperand(1));
13838
13839   case Intrinsic::x86_sse_sqrt_ps:
13840   case Intrinsic::x86_sse2_sqrt_pd:
13841   case Intrinsic::x86_avx_sqrt_ps_256:
13842   case Intrinsic::x86_avx_sqrt_pd_256:
13843     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13844
13845   // ptest and testp intrinsics. The intrinsic these come from are designed to
13846   // return an integer value, not just an instruction so lower it to the ptest
13847   // or testp pattern and a setcc for the result.
13848   case Intrinsic::x86_sse41_ptestz:
13849   case Intrinsic::x86_sse41_ptestc:
13850   case Intrinsic::x86_sse41_ptestnzc:
13851   case Intrinsic::x86_avx_ptestz_256:
13852   case Intrinsic::x86_avx_ptestc_256:
13853   case Intrinsic::x86_avx_ptestnzc_256:
13854   case Intrinsic::x86_avx_vtestz_ps:
13855   case Intrinsic::x86_avx_vtestc_ps:
13856   case Intrinsic::x86_avx_vtestnzc_ps:
13857   case Intrinsic::x86_avx_vtestz_pd:
13858   case Intrinsic::x86_avx_vtestc_pd:
13859   case Intrinsic::x86_avx_vtestnzc_pd:
13860   case Intrinsic::x86_avx_vtestz_ps_256:
13861   case Intrinsic::x86_avx_vtestc_ps_256:
13862   case Intrinsic::x86_avx_vtestnzc_ps_256:
13863   case Intrinsic::x86_avx_vtestz_pd_256:
13864   case Intrinsic::x86_avx_vtestc_pd_256:
13865   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13866     bool IsTestPacked = false;
13867     unsigned X86CC;
13868     switch (IntNo) {
13869     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13870     case Intrinsic::x86_avx_vtestz_ps:
13871     case Intrinsic::x86_avx_vtestz_pd:
13872     case Intrinsic::x86_avx_vtestz_ps_256:
13873     case Intrinsic::x86_avx_vtestz_pd_256:
13874       IsTestPacked = true; // Fallthrough
13875     case Intrinsic::x86_sse41_ptestz:
13876     case Intrinsic::x86_avx_ptestz_256:
13877       // ZF = 1
13878       X86CC = X86::COND_E;
13879       break;
13880     case Intrinsic::x86_avx_vtestc_ps:
13881     case Intrinsic::x86_avx_vtestc_pd:
13882     case Intrinsic::x86_avx_vtestc_ps_256:
13883     case Intrinsic::x86_avx_vtestc_pd_256:
13884       IsTestPacked = true; // Fallthrough
13885     case Intrinsic::x86_sse41_ptestc:
13886     case Intrinsic::x86_avx_ptestc_256:
13887       // CF = 1
13888       X86CC = X86::COND_B;
13889       break;
13890     case Intrinsic::x86_avx_vtestnzc_ps:
13891     case Intrinsic::x86_avx_vtestnzc_pd:
13892     case Intrinsic::x86_avx_vtestnzc_ps_256:
13893     case Intrinsic::x86_avx_vtestnzc_pd_256:
13894       IsTestPacked = true; // Fallthrough
13895     case Intrinsic::x86_sse41_ptestnzc:
13896     case Intrinsic::x86_avx_ptestnzc_256:
13897       // ZF and CF = 0
13898       X86CC = X86::COND_A;
13899       break;
13900     }
13901
13902     SDValue LHS = Op.getOperand(1);
13903     SDValue RHS = Op.getOperand(2);
13904     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13905     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13906     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13907     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13908     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13909   }
13910   case Intrinsic::x86_avx512_kortestz_w:
13911   case Intrinsic::x86_avx512_kortestc_w: {
13912     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13913     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13914     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13915     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13916     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13917     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13918     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13919   }
13920
13921   // SSE/AVX shift intrinsics
13922   case Intrinsic::x86_sse2_psll_w:
13923   case Intrinsic::x86_sse2_psll_d:
13924   case Intrinsic::x86_sse2_psll_q:
13925   case Intrinsic::x86_avx2_psll_w:
13926   case Intrinsic::x86_avx2_psll_d:
13927   case Intrinsic::x86_avx2_psll_q:
13928   case Intrinsic::x86_sse2_psrl_w:
13929   case Intrinsic::x86_sse2_psrl_d:
13930   case Intrinsic::x86_sse2_psrl_q:
13931   case Intrinsic::x86_avx2_psrl_w:
13932   case Intrinsic::x86_avx2_psrl_d:
13933   case Intrinsic::x86_avx2_psrl_q:
13934   case Intrinsic::x86_sse2_psra_w:
13935   case Intrinsic::x86_sse2_psra_d:
13936   case Intrinsic::x86_avx2_psra_w:
13937   case Intrinsic::x86_avx2_psra_d: {
13938     unsigned Opcode;
13939     switch (IntNo) {
13940     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13941     case Intrinsic::x86_sse2_psll_w:
13942     case Intrinsic::x86_sse2_psll_d:
13943     case Intrinsic::x86_sse2_psll_q:
13944     case Intrinsic::x86_avx2_psll_w:
13945     case Intrinsic::x86_avx2_psll_d:
13946     case Intrinsic::x86_avx2_psll_q:
13947       Opcode = X86ISD::VSHL;
13948       break;
13949     case Intrinsic::x86_sse2_psrl_w:
13950     case Intrinsic::x86_sse2_psrl_d:
13951     case Intrinsic::x86_sse2_psrl_q:
13952     case Intrinsic::x86_avx2_psrl_w:
13953     case Intrinsic::x86_avx2_psrl_d:
13954     case Intrinsic::x86_avx2_psrl_q:
13955       Opcode = X86ISD::VSRL;
13956       break;
13957     case Intrinsic::x86_sse2_psra_w:
13958     case Intrinsic::x86_sse2_psra_d:
13959     case Intrinsic::x86_avx2_psra_w:
13960     case Intrinsic::x86_avx2_psra_d:
13961       Opcode = X86ISD::VSRA;
13962       break;
13963     }
13964     return DAG.getNode(Opcode, dl, Op.getValueType(),
13965                        Op.getOperand(1), Op.getOperand(2));
13966   }
13967
13968   // SSE/AVX immediate shift intrinsics
13969   case Intrinsic::x86_sse2_pslli_w:
13970   case Intrinsic::x86_sse2_pslli_d:
13971   case Intrinsic::x86_sse2_pslli_q:
13972   case Intrinsic::x86_avx2_pslli_w:
13973   case Intrinsic::x86_avx2_pslli_d:
13974   case Intrinsic::x86_avx2_pslli_q:
13975   case Intrinsic::x86_sse2_psrli_w:
13976   case Intrinsic::x86_sse2_psrli_d:
13977   case Intrinsic::x86_sse2_psrli_q:
13978   case Intrinsic::x86_avx2_psrli_w:
13979   case Intrinsic::x86_avx2_psrli_d:
13980   case Intrinsic::x86_avx2_psrli_q:
13981   case Intrinsic::x86_sse2_psrai_w:
13982   case Intrinsic::x86_sse2_psrai_d:
13983   case Intrinsic::x86_avx2_psrai_w:
13984   case Intrinsic::x86_avx2_psrai_d: {
13985     unsigned Opcode;
13986     switch (IntNo) {
13987     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13988     case Intrinsic::x86_sse2_pslli_w:
13989     case Intrinsic::x86_sse2_pslli_d:
13990     case Intrinsic::x86_sse2_pslli_q:
13991     case Intrinsic::x86_avx2_pslli_w:
13992     case Intrinsic::x86_avx2_pslli_d:
13993     case Intrinsic::x86_avx2_pslli_q:
13994       Opcode = X86ISD::VSHLI;
13995       break;
13996     case Intrinsic::x86_sse2_psrli_w:
13997     case Intrinsic::x86_sse2_psrli_d:
13998     case Intrinsic::x86_sse2_psrli_q:
13999     case Intrinsic::x86_avx2_psrli_w:
14000     case Intrinsic::x86_avx2_psrli_d:
14001     case Intrinsic::x86_avx2_psrli_q:
14002       Opcode = X86ISD::VSRLI;
14003       break;
14004     case Intrinsic::x86_sse2_psrai_w:
14005     case Intrinsic::x86_sse2_psrai_d:
14006     case Intrinsic::x86_avx2_psrai_w:
14007     case Intrinsic::x86_avx2_psrai_d:
14008       Opcode = X86ISD::VSRAI;
14009       break;
14010     }
14011     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14012                                Op.getOperand(1), Op.getOperand(2), DAG);
14013   }
14014
14015   case Intrinsic::x86_sse42_pcmpistria128:
14016   case Intrinsic::x86_sse42_pcmpestria128:
14017   case Intrinsic::x86_sse42_pcmpistric128:
14018   case Intrinsic::x86_sse42_pcmpestric128:
14019   case Intrinsic::x86_sse42_pcmpistrio128:
14020   case Intrinsic::x86_sse42_pcmpestrio128:
14021   case Intrinsic::x86_sse42_pcmpistris128:
14022   case Intrinsic::x86_sse42_pcmpestris128:
14023   case Intrinsic::x86_sse42_pcmpistriz128:
14024   case Intrinsic::x86_sse42_pcmpestriz128: {
14025     unsigned Opcode;
14026     unsigned X86CC;
14027     switch (IntNo) {
14028     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14029     case Intrinsic::x86_sse42_pcmpistria128:
14030       Opcode = X86ISD::PCMPISTRI;
14031       X86CC = X86::COND_A;
14032       break;
14033     case Intrinsic::x86_sse42_pcmpestria128:
14034       Opcode = X86ISD::PCMPESTRI;
14035       X86CC = X86::COND_A;
14036       break;
14037     case Intrinsic::x86_sse42_pcmpistric128:
14038       Opcode = X86ISD::PCMPISTRI;
14039       X86CC = X86::COND_B;
14040       break;
14041     case Intrinsic::x86_sse42_pcmpestric128:
14042       Opcode = X86ISD::PCMPESTRI;
14043       X86CC = X86::COND_B;
14044       break;
14045     case Intrinsic::x86_sse42_pcmpistrio128:
14046       Opcode = X86ISD::PCMPISTRI;
14047       X86CC = X86::COND_O;
14048       break;
14049     case Intrinsic::x86_sse42_pcmpestrio128:
14050       Opcode = X86ISD::PCMPESTRI;
14051       X86CC = X86::COND_O;
14052       break;
14053     case Intrinsic::x86_sse42_pcmpistris128:
14054       Opcode = X86ISD::PCMPISTRI;
14055       X86CC = X86::COND_S;
14056       break;
14057     case Intrinsic::x86_sse42_pcmpestris128:
14058       Opcode = X86ISD::PCMPESTRI;
14059       X86CC = X86::COND_S;
14060       break;
14061     case Intrinsic::x86_sse42_pcmpistriz128:
14062       Opcode = X86ISD::PCMPISTRI;
14063       X86CC = X86::COND_E;
14064       break;
14065     case Intrinsic::x86_sse42_pcmpestriz128:
14066       Opcode = X86ISD::PCMPESTRI;
14067       X86CC = X86::COND_E;
14068       break;
14069     }
14070     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14071     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14072     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14073     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14074                                 DAG.getConstant(X86CC, MVT::i8),
14075                                 SDValue(PCMP.getNode(), 1));
14076     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14077   }
14078
14079   case Intrinsic::x86_sse42_pcmpistri128:
14080   case Intrinsic::x86_sse42_pcmpestri128: {
14081     unsigned Opcode;
14082     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14083       Opcode = X86ISD::PCMPISTRI;
14084     else
14085       Opcode = X86ISD::PCMPESTRI;
14086
14087     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14088     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14089     return DAG.getNode(Opcode, dl, VTs, NewOps);
14090   }
14091   case Intrinsic::x86_fma_vfmadd_ps:
14092   case Intrinsic::x86_fma_vfmadd_pd:
14093   case Intrinsic::x86_fma_vfmsub_ps:
14094   case Intrinsic::x86_fma_vfmsub_pd:
14095   case Intrinsic::x86_fma_vfnmadd_ps:
14096   case Intrinsic::x86_fma_vfnmadd_pd:
14097   case Intrinsic::x86_fma_vfnmsub_ps:
14098   case Intrinsic::x86_fma_vfnmsub_pd:
14099   case Intrinsic::x86_fma_vfmaddsub_ps:
14100   case Intrinsic::x86_fma_vfmaddsub_pd:
14101   case Intrinsic::x86_fma_vfmsubadd_ps:
14102   case Intrinsic::x86_fma_vfmsubadd_pd:
14103   case Intrinsic::x86_fma_vfmadd_ps_256:
14104   case Intrinsic::x86_fma_vfmadd_pd_256:
14105   case Intrinsic::x86_fma_vfmsub_ps_256:
14106   case Intrinsic::x86_fma_vfmsub_pd_256:
14107   case Intrinsic::x86_fma_vfnmadd_ps_256:
14108   case Intrinsic::x86_fma_vfnmadd_pd_256:
14109   case Intrinsic::x86_fma_vfnmsub_ps_256:
14110   case Intrinsic::x86_fma_vfnmsub_pd_256:
14111   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14112   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14113   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14114   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14115   case Intrinsic::x86_fma_vfmadd_ps_512:
14116   case Intrinsic::x86_fma_vfmadd_pd_512:
14117   case Intrinsic::x86_fma_vfmsub_ps_512:
14118   case Intrinsic::x86_fma_vfmsub_pd_512:
14119   case Intrinsic::x86_fma_vfnmadd_ps_512:
14120   case Intrinsic::x86_fma_vfnmadd_pd_512:
14121   case Intrinsic::x86_fma_vfnmsub_ps_512:
14122   case Intrinsic::x86_fma_vfnmsub_pd_512:
14123   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14124   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14125   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14126   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14127     unsigned Opc;
14128     switch (IntNo) {
14129     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14130     case Intrinsic::x86_fma_vfmadd_ps:
14131     case Intrinsic::x86_fma_vfmadd_pd:
14132     case Intrinsic::x86_fma_vfmadd_ps_256:
14133     case Intrinsic::x86_fma_vfmadd_pd_256:
14134     case Intrinsic::x86_fma_vfmadd_ps_512:
14135     case Intrinsic::x86_fma_vfmadd_pd_512:
14136       Opc = X86ISD::FMADD;
14137       break;
14138     case Intrinsic::x86_fma_vfmsub_ps:
14139     case Intrinsic::x86_fma_vfmsub_pd:
14140     case Intrinsic::x86_fma_vfmsub_ps_256:
14141     case Intrinsic::x86_fma_vfmsub_pd_256:
14142     case Intrinsic::x86_fma_vfmsub_ps_512:
14143     case Intrinsic::x86_fma_vfmsub_pd_512:
14144       Opc = X86ISD::FMSUB;
14145       break;
14146     case Intrinsic::x86_fma_vfnmadd_ps:
14147     case Intrinsic::x86_fma_vfnmadd_pd:
14148     case Intrinsic::x86_fma_vfnmadd_ps_256:
14149     case Intrinsic::x86_fma_vfnmadd_pd_256:
14150     case Intrinsic::x86_fma_vfnmadd_ps_512:
14151     case Intrinsic::x86_fma_vfnmadd_pd_512:
14152       Opc = X86ISD::FNMADD;
14153       break;
14154     case Intrinsic::x86_fma_vfnmsub_ps:
14155     case Intrinsic::x86_fma_vfnmsub_pd:
14156     case Intrinsic::x86_fma_vfnmsub_ps_256:
14157     case Intrinsic::x86_fma_vfnmsub_pd_256:
14158     case Intrinsic::x86_fma_vfnmsub_ps_512:
14159     case Intrinsic::x86_fma_vfnmsub_pd_512:
14160       Opc = X86ISD::FNMSUB;
14161       break;
14162     case Intrinsic::x86_fma_vfmaddsub_ps:
14163     case Intrinsic::x86_fma_vfmaddsub_pd:
14164     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14165     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14166     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14167     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14168       Opc = X86ISD::FMADDSUB;
14169       break;
14170     case Intrinsic::x86_fma_vfmsubadd_ps:
14171     case Intrinsic::x86_fma_vfmsubadd_pd:
14172     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14173     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14174     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14175     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14176       Opc = X86ISD::FMSUBADD;
14177       break;
14178     }
14179
14180     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14181                        Op.getOperand(2), Op.getOperand(3));
14182   }
14183   }
14184 }
14185
14186 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14187                               SDValue Src, SDValue Mask, SDValue Base,
14188                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14189                               const X86Subtarget * Subtarget) {
14190   SDLoc dl(Op);
14191   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14192   assert(C && "Invalid scale type");
14193   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14194   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14195                              Index.getSimpleValueType().getVectorNumElements());
14196   SDValue MaskInReg;
14197   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14198   if (MaskC)
14199     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14200   else
14201     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14202   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14203   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14204   SDValue Segment = DAG.getRegister(0, MVT::i32);
14205   if (Src.getOpcode() == ISD::UNDEF)
14206     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14207   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14208   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14209   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14210   return DAG.getMergeValues(RetOps, dl);
14211 }
14212
14213 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14214                                SDValue Src, SDValue Mask, SDValue Base,
14215                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14216   SDLoc dl(Op);
14217   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14218   assert(C && "Invalid scale type");
14219   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14220   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14221   SDValue Segment = DAG.getRegister(0, MVT::i32);
14222   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14223                              Index.getSimpleValueType().getVectorNumElements());
14224   SDValue MaskInReg;
14225   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14226   if (MaskC)
14227     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14228   else
14229     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14230   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14231   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14232   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14233   return SDValue(Res, 1);
14234 }
14235
14236 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14237                                SDValue Mask, SDValue Base, SDValue Index,
14238                                SDValue ScaleOp, SDValue Chain) {
14239   SDLoc dl(Op);
14240   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14241   assert(C && "Invalid scale type");
14242   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14243   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14244   SDValue Segment = DAG.getRegister(0, MVT::i32);
14245   EVT MaskVT =
14246     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14247   SDValue MaskInReg;
14248   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14249   if (MaskC)
14250     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14251   else
14252     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14253   //SDVTList VTs = DAG.getVTList(MVT::Other);
14254   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14255   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14256   return SDValue(Res, 0);
14257 }
14258
14259 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14260 // read performance monitor counters (x86_rdpmc).
14261 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14262                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14263                               SmallVectorImpl<SDValue> &Results) {
14264   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14265   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14266   SDValue LO, HI;
14267
14268   // The ECX register is used to select the index of the performance counter
14269   // to read.
14270   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14271                                    N->getOperand(2));
14272   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14273
14274   // Reads the content of a 64-bit performance counter and returns it in the
14275   // registers EDX:EAX.
14276   if (Subtarget->is64Bit()) {
14277     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14278     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14279                             LO.getValue(2));
14280   } else {
14281     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14282     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14283                             LO.getValue(2));
14284   }
14285   Chain = HI.getValue(1);
14286
14287   if (Subtarget->is64Bit()) {
14288     // The EAX register is loaded with the low-order 32 bits. The EDX register
14289     // is loaded with the supported high-order bits of the counter.
14290     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14291                               DAG.getConstant(32, MVT::i8));
14292     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14293     Results.push_back(Chain);
14294     return;
14295   }
14296
14297   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14298   SDValue Ops[] = { LO, HI };
14299   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14300   Results.push_back(Pair);
14301   Results.push_back(Chain);
14302 }
14303
14304 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14305 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14306 // also used to custom lower READCYCLECOUNTER nodes.
14307 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14308                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14309                               SmallVectorImpl<SDValue> &Results) {
14310   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14311   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14312   SDValue LO, HI;
14313
14314   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14315   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14316   // and the EAX register is loaded with the low-order 32 bits.
14317   if (Subtarget->is64Bit()) {
14318     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14319     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14320                             LO.getValue(2));
14321   } else {
14322     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14323     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14324                             LO.getValue(2));
14325   }
14326   SDValue Chain = HI.getValue(1);
14327
14328   if (Opcode == X86ISD::RDTSCP_DAG) {
14329     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14330
14331     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14332     // the ECX register. Add 'ecx' explicitly to the chain.
14333     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14334                                      HI.getValue(2));
14335     // Explicitly store the content of ECX at the location passed in input
14336     // to the 'rdtscp' intrinsic.
14337     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14338                          MachinePointerInfo(), false, false, 0);
14339   }
14340
14341   if (Subtarget->is64Bit()) {
14342     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14343     // the EAX register is loaded with the low-order 32 bits.
14344     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14345                               DAG.getConstant(32, MVT::i8));
14346     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14347     Results.push_back(Chain);
14348     return;
14349   }
14350
14351   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14352   SDValue Ops[] = { LO, HI };
14353   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14354   Results.push_back(Pair);
14355   Results.push_back(Chain);
14356 }
14357
14358 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14359                                      SelectionDAG &DAG) {
14360   SmallVector<SDValue, 2> Results;
14361   SDLoc DL(Op);
14362   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14363                           Results);
14364   return DAG.getMergeValues(Results, DL);
14365 }
14366
14367 enum IntrinsicType {
14368   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14369 };
14370
14371 struct IntrinsicData {
14372   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14373     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14374   IntrinsicType Type;
14375   unsigned      Opc0;
14376   unsigned      Opc1;
14377 };
14378
14379 std::map < unsigned, IntrinsicData> IntrMap;
14380 static void InitIntinsicsMap() {
14381   static bool Initialized = false;
14382   if (Initialized) 
14383     return;
14384   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14385                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14386   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14387                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14388   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14389                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14390   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14391                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14392   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14393                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14394   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14395                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14396   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14397                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14398   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14399                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14400   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14401                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14402
14403   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14404                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14405   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14406                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14407   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14408                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14409   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14410                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14411   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14412                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14413   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14414                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14415   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14416                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14417   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14418                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14419    
14420   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14421                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14422                                                         X86::VGATHERPF1QPSm)));
14423   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14424                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14425                                                         X86::VGATHERPF1QPDm)));
14426   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14427                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14428                                                         X86::VGATHERPF1DPDm)));
14429   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14430                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14431                                                         X86::VGATHERPF1DPSm)));
14432   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14433                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14434                                                         X86::VSCATTERPF1QPSm)));
14435   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14436                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14437                                                         X86::VSCATTERPF1QPDm)));
14438   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14439                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14440                                                         X86::VSCATTERPF1DPDm)));
14441   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14442                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14443                                                         X86::VSCATTERPF1DPSm)));
14444   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14445                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14446   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14447                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14448   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14449                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14450   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14451                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14452   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14453                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14454   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14455                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14456   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14457                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14458   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14459                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14460   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14461                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14462   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14463                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14464   Initialized = true;
14465 }
14466
14467 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14468                                       SelectionDAG &DAG) {
14469   InitIntinsicsMap();
14470   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14471   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14472   if (itr == IntrMap.end())
14473     return SDValue();
14474
14475   SDLoc dl(Op);
14476   IntrinsicData Intr = itr->second;
14477   switch(Intr.Type) {
14478   case RDSEED:
14479   case RDRAND: {
14480     // Emit the node with the right value type.
14481     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14482     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14483
14484     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14485     // Otherwise return the value from Rand, which is always 0, casted to i32.
14486     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14487                       DAG.getConstant(1, Op->getValueType(1)),
14488                       DAG.getConstant(X86::COND_B, MVT::i32),
14489                       SDValue(Result.getNode(), 1) };
14490     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14491                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14492                                   Ops);
14493
14494     // Return { result, isValid, chain }.
14495     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14496                        SDValue(Result.getNode(), 2));
14497   }
14498   case GATHER: {
14499   //gather(v1, mask, index, base, scale);
14500     SDValue Chain = Op.getOperand(0);
14501     SDValue Src   = Op.getOperand(2);
14502     SDValue Base  = Op.getOperand(3);
14503     SDValue Index = Op.getOperand(4);
14504     SDValue Mask  = Op.getOperand(5);
14505     SDValue Scale = Op.getOperand(6);
14506     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14507                           Subtarget);
14508   }
14509   case SCATTER: {
14510   //scatter(base, mask, index, v1, scale);
14511     SDValue Chain = Op.getOperand(0);
14512     SDValue Base  = Op.getOperand(2);
14513     SDValue Mask  = Op.getOperand(3);
14514     SDValue Index = Op.getOperand(4);
14515     SDValue Src   = Op.getOperand(5);
14516     SDValue Scale = Op.getOperand(6);
14517     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14518   }
14519   case PREFETCH: {
14520     SDValue Hint = Op.getOperand(6);
14521     unsigned HintVal;
14522     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14523         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14524       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14525     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14526     SDValue Chain = Op.getOperand(0);
14527     SDValue Mask  = Op.getOperand(2);
14528     SDValue Index = Op.getOperand(3);
14529     SDValue Base  = Op.getOperand(4);
14530     SDValue Scale = Op.getOperand(5);
14531     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14532   }
14533   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14534   case RDTSC: {
14535     SmallVector<SDValue, 2> Results;
14536     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14537     return DAG.getMergeValues(Results, dl);
14538   }
14539   // Read Performance Monitoring Counters.
14540   case RDPMC: {
14541     SmallVector<SDValue, 2> Results;
14542     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14543     return DAG.getMergeValues(Results, dl);
14544   }
14545   // XTEST intrinsics.
14546   case XTEST: {
14547     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14548     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14549     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14550                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14551                                 InTrans);
14552     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14553     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14554                        Ret, SDValue(InTrans.getNode(), 1));
14555   }
14556   }
14557   llvm_unreachable("Unknown Intrinsic Type");
14558 }
14559
14560 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14561                                            SelectionDAG &DAG) const {
14562   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14563   MFI->setReturnAddressIsTaken(true);
14564
14565   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14566     return SDValue();
14567
14568   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14569   SDLoc dl(Op);
14570   EVT PtrVT = getPointerTy();
14571
14572   if (Depth > 0) {
14573     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14574     const X86RegisterInfo *RegInfo =
14575       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14576     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14577     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14578                        DAG.getNode(ISD::ADD, dl, PtrVT,
14579                                    FrameAddr, Offset),
14580                        MachinePointerInfo(), false, false, false, 0);
14581   }
14582
14583   // Just load the return address.
14584   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14585   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14586                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14587 }
14588
14589 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14590   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14591   MFI->setFrameAddressIsTaken(true);
14592
14593   EVT VT = Op.getValueType();
14594   SDLoc dl(Op);  // FIXME probably not meaningful
14595   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14596   const X86RegisterInfo *RegInfo =
14597     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14598   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14599   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14600           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14601          "Invalid Frame Register!");
14602   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14603   while (Depth--)
14604     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14605                             MachinePointerInfo(),
14606                             false, false, false, 0);
14607   return FrameAddr;
14608 }
14609
14610 // FIXME? Maybe this could be a TableGen attribute on some registers and
14611 // this table could be generated automatically from RegInfo.
14612 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14613                                               EVT VT) const {
14614   unsigned Reg = StringSwitch<unsigned>(RegName)
14615                        .Case("esp", X86::ESP)
14616                        .Case("rsp", X86::RSP)
14617                        .Default(0);
14618   if (Reg)
14619     return Reg;
14620   report_fatal_error("Invalid register name global variable");
14621 }
14622
14623 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14624                                                      SelectionDAG &DAG) const {
14625   const X86RegisterInfo *RegInfo =
14626     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14627   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14628 }
14629
14630 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14631   SDValue Chain     = Op.getOperand(0);
14632   SDValue Offset    = Op.getOperand(1);
14633   SDValue Handler   = Op.getOperand(2);
14634   SDLoc dl      (Op);
14635
14636   EVT PtrVT = getPointerTy();
14637   const X86RegisterInfo *RegInfo =
14638     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14639   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14640   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14641           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14642          "Invalid Frame Register!");
14643   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14644   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14645
14646   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14647                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14648   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14649   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14650                        false, false, 0);
14651   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14652
14653   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14654                      DAG.getRegister(StoreAddrReg, PtrVT));
14655 }
14656
14657 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14658                                                SelectionDAG &DAG) const {
14659   SDLoc DL(Op);
14660   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14661                      DAG.getVTList(MVT::i32, MVT::Other),
14662                      Op.getOperand(0), Op.getOperand(1));
14663 }
14664
14665 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14666                                                 SelectionDAG &DAG) const {
14667   SDLoc DL(Op);
14668   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14669                      Op.getOperand(0), Op.getOperand(1));
14670 }
14671
14672 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14673   return Op.getOperand(0);
14674 }
14675
14676 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14677                                                 SelectionDAG &DAG) const {
14678   SDValue Root = Op.getOperand(0);
14679   SDValue Trmp = Op.getOperand(1); // trampoline
14680   SDValue FPtr = Op.getOperand(2); // nested function
14681   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14682   SDLoc dl (Op);
14683
14684   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14685   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14686
14687   if (Subtarget->is64Bit()) {
14688     SDValue OutChains[6];
14689
14690     // Large code-model.
14691     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14692     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14693
14694     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14695     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14696
14697     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14698
14699     // Load the pointer to the nested function into R11.
14700     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14701     SDValue Addr = Trmp;
14702     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14703                                 Addr, MachinePointerInfo(TrmpAddr),
14704                                 false, false, 0);
14705
14706     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14707                        DAG.getConstant(2, MVT::i64));
14708     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14709                                 MachinePointerInfo(TrmpAddr, 2),
14710                                 false, false, 2);
14711
14712     // Load the 'nest' parameter value into R10.
14713     // R10 is specified in X86CallingConv.td
14714     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14715     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14716                        DAG.getConstant(10, MVT::i64));
14717     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14718                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14719                                 false, false, 0);
14720
14721     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14722                        DAG.getConstant(12, MVT::i64));
14723     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14724                                 MachinePointerInfo(TrmpAddr, 12),
14725                                 false, false, 2);
14726
14727     // Jump to the nested function.
14728     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14729     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14730                        DAG.getConstant(20, MVT::i64));
14731     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14732                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14733                                 false, false, 0);
14734
14735     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14736     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14737                        DAG.getConstant(22, MVT::i64));
14738     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14739                                 MachinePointerInfo(TrmpAddr, 22),
14740                                 false, false, 0);
14741
14742     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14743   } else {
14744     const Function *Func =
14745       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14746     CallingConv::ID CC = Func->getCallingConv();
14747     unsigned NestReg;
14748
14749     switch (CC) {
14750     default:
14751       llvm_unreachable("Unsupported calling convention");
14752     case CallingConv::C:
14753     case CallingConv::X86_StdCall: {
14754       // Pass 'nest' parameter in ECX.
14755       // Must be kept in sync with X86CallingConv.td
14756       NestReg = X86::ECX;
14757
14758       // Check that ECX wasn't needed by an 'inreg' parameter.
14759       FunctionType *FTy = Func->getFunctionType();
14760       const AttributeSet &Attrs = Func->getAttributes();
14761
14762       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14763         unsigned InRegCount = 0;
14764         unsigned Idx = 1;
14765
14766         for (FunctionType::param_iterator I = FTy->param_begin(),
14767              E = FTy->param_end(); I != E; ++I, ++Idx)
14768           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14769             // FIXME: should only count parameters that are lowered to integers.
14770             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14771
14772         if (InRegCount > 2) {
14773           report_fatal_error("Nest register in use - reduce number of inreg"
14774                              " parameters!");
14775         }
14776       }
14777       break;
14778     }
14779     case CallingConv::X86_FastCall:
14780     case CallingConv::X86_ThisCall:
14781     case CallingConv::Fast:
14782       // Pass 'nest' parameter in EAX.
14783       // Must be kept in sync with X86CallingConv.td
14784       NestReg = X86::EAX;
14785       break;
14786     }
14787
14788     SDValue OutChains[4];
14789     SDValue Addr, Disp;
14790
14791     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14792                        DAG.getConstant(10, MVT::i32));
14793     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14794
14795     // This is storing the opcode for MOV32ri.
14796     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14797     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14798     OutChains[0] = DAG.getStore(Root, dl,
14799                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14800                                 Trmp, MachinePointerInfo(TrmpAddr),
14801                                 false, false, 0);
14802
14803     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14804                        DAG.getConstant(1, MVT::i32));
14805     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14806                                 MachinePointerInfo(TrmpAddr, 1),
14807                                 false, false, 1);
14808
14809     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14810     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14811                        DAG.getConstant(5, MVT::i32));
14812     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14813                                 MachinePointerInfo(TrmpAddr, 5),
14814                                 false, false, 1);
14815
14816     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14817                        DAG.getConstant(6, MVT::i32));
14818     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14819                                 MachinePointerInfo(TrmpAddr, 6),
14820                                 false, false, 1);
14821
14822     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14823   }
14824 }
14825
14826 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14827                                             SelectionDAG &DAG) const {
14828   /*
14829    The rounding mode is in bits 11:10 of FPSR, and has the following
14830    settings:
14831      00 Round to nearest
14832      01 Round to -inf
14833      10 Round to +inf
14834      11 Round to 0
14835
14836   FLT_ROUNDS, on the other hand, expects the following:
14837     -1 Undefined
14838      0 Round to 0
14839      1 Round to nearest
14840      2 Round to +inf
14841      3 Round to -inf
14842
14843   To perform the conversion, we do:
14844     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14845   */
14846
14847   MachineFunction &MF = DAG.getMachineFunction();
14848   const TargetMachine &TM = MF.getTarget();
14849   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14850   unsigned StackAlignment = TFI.getStackAlignment();
14851   MVT VT = Op.getSimpleValueType();
14852   SDLoc DL(Op);
14853
14854   // Save FP Control Word to stack slot
14855   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14856   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14857
14858   MachineMemOperand *MMO =
14859    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14860                            MachineMemOperand::MOStore, 2, 2);
14861
14862   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14863   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14864                                           DAG.getVTList(MVT::Other),
14865                                           Ops, MVT::i16, MMO);
14866
14867   // Load FP Control Word from stack slot
14868   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14869                             MachinePointerInfo(), false, false, false, 0);
14870
14871   // Transform as necessary
14872   SDValue CWD1 =
14873     DAG.getNode(ISD::SRL, DL, MVT::i16,
14874                 DAG.getNode(ISD::AND, DL, MVT::i16,
14875                             CWD, DAG.getConstant(0x800, MVT::i16)),
14876                 DAG.getConstant(11, MVT::i8));
14877   SDValue CWD2 =
14878     DAG.getNode(ISD::SRL, DL, MVT::i16,
14879                 DAG.getNode(ISD::AND, DL, MVT::i16,
14880                             CWD, DAG.getConstant(0x400, MVT::i16)),
14881                 DAG.getConstant(9, MVT::i8));
14882
14883   SDValue RetVal =
14884     DAG.getNode(ISD::AND, DL, MVT::i16,
14885                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14886                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14887                             DAG.getConstant(1, MVT::i16)),
14888                 DAG.getConstant(3, MVT::i16));
14889
14890   return DAG.getNode((VT.getSizeInBits() < 16 ?
14891                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14892 }
14893
14894 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14895   MVT VT = Op.getSimpleValueType();
14896   EVT OpVT = VT;
14897   unsigned NumBits = VT.getSizeInBits();
14898   SDLoc dl(Op);
14899
14900   Op = Op.getOperand(0);
14901   if (VT == MVT::i8) {
14902     // Zero extend to i32 since there is not an i8 bsr.
14903     OpVT = MVT::i32;
14904     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14905   }
14906
14907   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14908   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14909   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14910
14911   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14912   SDValue Ops[] = {
14913     Op,
14914     DAG.getConstant(NumBits+NumBits-1, OpVT),
14915     DAG.getConstant(X86::COND_E, MVT::i8),
14916     Op.getValue(1)
14917   };
14918   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14919
14920   // Finally xor with NumBits-1.
14921   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14922
14923   if (VT == MVT::i8)
14924     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14925   return Op;
14926 }
14927
14928 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14929   MVT VT = Op.getSimpleValueType();
14930   EVT OpVT = VT;
14931   unsigned NumBits = VT.getSizeInBits();
14932   SDLoc dl(Op);
14933
14934   Op = Op.getOperand(0);
14935   if (VT == MVT::i8) {
14936     // Zero extend to i32 since there is not an i8 bsr.
14937     OpVT = MVT::i32;
14938     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14939   }
14940
14941   // Issue a bsr (scan bits in reverse).
14942   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14943   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14944
14945   // And xor with NumBits-1.
14946   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14947
14948   if (VT == MVT::i8)
14949     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14950   return Op;
14951 }
14952
14953 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14954   MVT VT = Op.getSimpleValueType();
14955   unsigned NumBits = VT.getSizeInBits();
14956   SDLoc dl(Op);
14957   Op = Op.getOperand(0);
14958
14959   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14960   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14961   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14962
14963   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14964   SDValue Ops[] = {
14965     Op,
14966     DAG.getConstant(NumBits, VT),
14967     DAG.getConstant(X86::COND_E, MVT::i8),
14968     Op.getValue(1)
14969   };
14970   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14971 }
14972
14973 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14974 // ones, and then concatenate the result back.
14975 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14976   MVT VT = Op.getSimpleValueType();
14977
14978   assert(VT.is256BitVector() && VT.isInteger() &&
14979          "Unsupported value type for operation");
14980
14981   unsigned NumElems = VT.getVectorNumElements();
14982   SDLoc dl(Op);
14983
14984   // Extract the LHS vectors
14985   SDValue LHS = Op.getOperand(0);
14986   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14987   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14988
14989   // Extract the RHS vectors
14990   SDValue RHS = Op.getOperand(1);
14991   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14992   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14993
14994   MVT EltVT = VT.getVectorElementType();
14995   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14996
14997   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
14998                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
14999                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15000 }
15001
15002 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15003   assert(Op.getSimpleValueType().is256BitVector() &&
15004          Op.getSimpleValueType().isInteger() &&
15005          "Only handle AVX 256-bit vector integer operation");
15006   return Lower256IntArith(Op, DAG);
15007 }
15008
15009 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15010   assert(Op.getSimpleValueType().is256BitVector() &&
15011          Op.getSimpleValueType().isInteger() &&
15012          "Only handle AVX 256-bit vector integer operation");
15013   return Lower256IntArith(Op, DAG);
15014 }
15015
15016 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15017                         SelectionDAG &DAG) {
15018   SDLoc dl(Op);
15019   MVT VT = Op.getSimpleValueType();
15020
15021   // Decompose 256-bit ops into smaller 128-bit ops.
15022   if (VT.is256BitVector() && !Subtarget->hasInt256())
15023     return Lower256IntArith(Op, DAG);
15024
15025   SDValue A = Op.getOperand(0);
15026   SDValue B = Op.getOperand(1);
15027
15028   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15029   if (VT == MVT::v4i32) {
15030     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15031            "Should not custom lower when pmuldq is available!");
15032
15033     // Extract the odd parts.
15034     static const int UnpackMask[] = { 1, -1, 3, -1 };
15035     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15036     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15037
15038     // Multiply the even parts.
15039     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15040     // Now multiply odd parts.
15041     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15042
15043     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15044     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15045
15046     // Merge the two vectors back together with a shuffle. This expands into 2
15047     // shuffles.
15048     static const int ShufMask[] = { 0, 4, 2, 6 };
15049     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15050   }
15051
15052   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15053          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15054
15055   //  Ahi = psrlqi(a, 32);
15056   //  Bhi = psrlqi(b, 32);
15057   //
15058   //  AloBlo = pmuludq(a, b);
15059   //  AloBhi = pmuludq(a, Bhi);
15060   //  AhiBlo = pmuludq(Ahi, b);
15061
15062   //  AloBhi = psllqi(AloBhi, 32);
15063   //  AhiBlo = psllqi(AhiBlo, 32);
15064   //  return AloBlo + AloBhi + AhiBlo;
15065
15066   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15067   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15068
15069   // Bit cast to 32-bit vectors for MULUDQ
15070   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15071                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15072   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15073   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15074   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15075   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15076
15077   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15078   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15079   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15080
15081   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15082   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15083
15084   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15085   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15086 }
15087
15088 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15089   assert(Subtarget->isTargetWin64() && "Unexpected target");
15090   EVT VT = Op.getValueType();
15091   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15092          "Unexpected return type for lowering");
15093
15094   RTLIB::Libcall LC;
15095   bool isSigned;
15096   switch (Op->getOpcode()) {
15097   default: llvm_unreachable("Unexpected request for libcall!");
15098   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15099   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15100   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15101   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15102   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15103   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15104   }
15105
15106   SDLoc dl(Op);
15107   SDValue InChain = DAG.getEntryNode();
15108
15109   TargetLowering::ArgListTy Args;
15110   TargetLowering::ArgListEntry Entry;
15111   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15112     EVT ArgVT = Op->getOperand(i).getValueType();
15113     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15114            "Unexpected argument type for lowering");
15115     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15116     Entry.Node = StackPtr;
15117     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15118                            false, false, 16);
15119     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15120     Entry.Ty = PointerType::get(ArgTy,0);
15121     Entry.isSExt = false;
15122     Entry.isZExt = false;
15123     Args.push_back(Entry);
15124   }
15125
15126   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15127                                          getPointerTy());
15128
15129   TargetLowering::CallLoweringInfo CLI(DAG);
15130   CLI.setDebugLoc(dl).setChain(InChain)
15131     .setCallee(getLibcallCallingConv(LC),
15132                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15133                Callee, std::move(Args), 0)
15134     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15135
15136   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15137   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15138 }
15139
15140 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15141                              SelectionDAG &DAG) {
15142   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15143   EVT VT = Op0.getValueType();
15144   SDLoc dl(Op);
15145
15146   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15147          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15148
15149   // Get the high parts.
15150   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15151   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15152   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15153
15154   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15155   // ints.
15156   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15157   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15158   unsigned Opcode =
15159       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15160   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15161                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15162   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15163                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15164
15165   // Shuffle it back into the right order.
15166   SDValue Highs, Lows;
15167   if (VT == MVT::v8i32) {
15168     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15169     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15170     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15171     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15172   } else {
15173     const int HighMask[] = {1, 5, 3, 7};
15174     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15175     const int LowMask[] = {0, 4, 2, 6};
15176     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15177   }
15178
15179   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15180   // unsigned multiply.
15181   if (IsSigned && !Subtarget->hasSSE41()) {
15182     SDValue ShAmt =
15183         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15184     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15185                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15186     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15187                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15188
15189     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15190     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15191   }
15192
15193   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15194 }
15195
15196 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15197                                          const X86Subtarget *Subtarget) {
15198   MVT VT = Op.getSimpleValueType();
15199   SDLoc dl(Op);
15200   SDValue R = Op.getOperand(0);
15201   SDValue Amt = Op.getOperand(1);
15202
15203   // Optimize shl/srl/sra with constant shift amount.
15204   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15205     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15206       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15207
15208       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15209           (Subtarget->hasInt256() &&
15210            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15211           (Subtarget->hasAVX512() &&
15212            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15213         if (Op.getOpcode() == ISD::SHL)
15214           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15215                                             DAG);
15216         if (Op.getOpcode() == ISD::SRL)
15217           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15218                                             DAG);
15219         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15220           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15221                                             DAG);
15222       }
15223
15224       if (VT == MVT::v16i8) {
15225         if (Op.getOpcode() == ISD::SHL) {
15226           // Make a large shift.
15227           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15228                                                    MVT::v8i16, R, ShiftAmt,
15229                                                    DAG);
15230           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15231           // Zero out the rightmost bits.
15232           SmallVector<SDValue, 16> V(16,
15233                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15234                                                      MVT::i8));
15235           return DAG.getNode(ISD::AND, dl, VT, SHL,
15236                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15237         }
15238         if (Op.getOpcode() == ISD::SRL) {
15239           // Make a large shift.
15240           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15241                                                    MVT::v8i16, R, ShiftAmt,
15242                                                    DAG);
15243           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15244           // Zero out the leftmost bits.
15245           SmallVector<SDValue, 16> V(16,
15246                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15247                                                      MVT::i8));
15248           return DAG.getNode(ISD::AND, dl, VT, SRL,
15249                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15250         }
15251         if (Op.getOpcode() == ISD::SRA) {
15252           if (ShiftAmt == 7) {
15253             // R s>> 7  ===  R s< 0
15254             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15255             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15256           }
15257
15258           // R s>> a === ((R u>> a) ^ m) - m
15259           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15260           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15261                                                          MVT::i8));
15262           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15263           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15264           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15265           return Res;
15266         }
15267         llvm_unreachable("Unknown shift opcode.");
15268       }
15269
15270       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15271         if (Op.getOpcode() == ISD::SHL) {
15272           // Make a large shift.
15273           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15274                                                    MVT::v16i16, R, ShiftAmt,
15275                                                    DAG);
15276           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15277           // Zero out the rightmost bits.
15278           SmallVector<SDValue, 32> V(32,
15279                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15280                                                      MVT::i8));
15281           return DAG.getNode(ISD::AND, dl, VT, SHL,
15282                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15283         }
15284         if (Op.getOpcode() == ISD::SRL) {
15285           // Make a large shift.
15286           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15287                                                    MVT::v16i16, R, ShiftAmt,
15288                                                    DAG);
15289           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15290           // Zero out the leftmost bits.
15291           SmallVector<SDValue, 32> V(32,
15292                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15293                                                      MVT::i8));
15294           return DAG.getNode(ISD::AND, dl, VT, SRL,
15295                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15296         }
15297         if (Op.getOpcode() == ISD::SRA) {
15298           if (ShiftAmt == 7) {
15299             // R s>> 7  ===  R s< 0
15300             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15301             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15302           }
15303
15304           // R s>> a === ((R u>> a) ^ m) - m
15305           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15306           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15307                                                          MVT::i8));
15308           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15309           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15310           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15311           return Res;
15312         }
15313         llvm_unreachable("Unknown shift opcode.");
15314       }
15315     }
15316   }
15317
15318   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15319   if (!Subtarget->is64Bit() &&
15320       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15321       Amt.getOpcode() == ISD::BITCAST &&
15322       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15323     Amt = Amt.getOperand(0);
15324     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15325                      VT.getVectorNumElements();
15326     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15327     uint64_t ShiftAmt = 0;
15328     for (unsigned i = 0; i != Ratio; ++i) {
15329       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15330       if (!C)
15331         return SDValue();
15332       // 6 == Log2(64)
15333       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15334     }
15335     // Check remaining shift amounts.
15336     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15337       uint64_t ShAmt = 0;
15338       for (unsigned j = 0; j != Ratio; ++j) {
15339         ConstantSDNode *C =
15340           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15341         if (!C)
15342           return SDValue();
15343         // 6 == Log2(64)
15344         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15345       }
15346       if (ShAmt != ShiftAmt)
15347         return SDValue();
15348     }
15349     switch (Op.getOpcode()) {
15350     default:
15351       llvm_unreachable("Unknown shift opcode!");
15352     case ISD::SHL:
15353       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15354                                         DAG);
15355     case ISD::SRL:
15356       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15357                                         DAG);
15358     case ISD::SRA:
15359       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15360                                         DAG);
15361     }
15362   }
15363
15364   return SDValue();
15365 }
15366
15367 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15368                                         const X86Subtarget* Subtarget) {
15369   MVT VT = Op.getSimpleValueType();
15370   SDLoc dl(Op);
15371   SDValue R = Op.getOperand(0);
15372   SDValue Amt = Op.getOperand(1);
15373
15374   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15375       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15376       (Subtarget->hasInt256() &&
15377        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15378         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15379        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15380     SDValue BaseShAmt;
15381     EVT EltVT = VT.getVectorElementType();
15382
15383     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15384       unsigned NumElts = VT.getVectorNumElements();
15385       unsigned i, j;
15386       for (i = 0; i != NumElts; ++i) {
15387         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15388           continue;
15389         break;
15390       }
15391       for (j = i; j != NumElts; ++j) {
15392         SDValue Arg = Amt.getOperand(j);
15393         if (Arg.getOpcode() == ISD::UNDEF) continue;
15394         if (Arg != Amt.getOperand(i))
15395           break;
15396       }
15397       if (i != NumElts && j == NumElts)
15398         BaseShAmt = Amt.getOperand(i);
15399     } else {
15400       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15401         Amt = Amt.getOperand(0);
15402       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15403                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15404         SDValue InVec = Amt.getOperand(0);
15405         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15406           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15407           unsigned i = 0;
15408           for (; i != NumElts; ++i) {
15409             SDValue Arg = InVec.getOperand(i);
15410             if (Arg.getOpcode() == ISD::UNDEF) continue;
15411             BaseShAmt = Arg;
15412             break;
15413           }
15414         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15415            if (ConstantSDNode *C =
15416                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15417              unsigned SplatIdx =
15418                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15419              if (C->getZExtValue() == SplatIdx)
15420                BaseShAmt = InVec.getOperand(1);
15421            }
15422         }
15423         if (!BaseShAmt.getNode())
15424           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15425                                   DAG.getIntPtrConstant(0));
15426       }
15427     }
15428
15429     if (BaseShAmt.getNode()) {
15430       if (EltVT.bitsGT(MVT::i32))
15431         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15432       else if (EltVT.bitsLT(MVT::i32))
15433         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15434
15435       switch (Op.getOpcode()) {
15436       default:
15437         llvm_unreachable("Unknown shift opcode!");
15438       case ISD::SHL:
15439         switch (VT.SimpleTy) {
15440         default: return SDValue();
15441         case MVT::v2i64:
15442         case MVT::v4i32:
15443         case MVT::v8i16:
15444         case MVT::v4i64:
15445         case MVT::v8i32:
15446         case MVT::v16i16:
15447         case MVT::v16i32:
15448         case MVT::v8i64:
15449           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15450         }
15451       case ISD::SRA:
15452         switch (VT.SimpleTy) {
15453         default: return SDValue();
15454         case MVT::v4i32:
15455         case MVT::v8i16:
15456         case MVT::v8i32:
15457         case MVT::v16i16:
15458         case MVT::v16i32:
15459         case MVT::v8i64:
15460           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15461         }
15462       case ISD::SRL:
15463         switch (VT.SimpleTy) {
15464         default: return SDValue();
15465         case MVT::v2i64:
15466         case MVT::v4i32:
15467         case MVT::v8i16:
15468         case MVT::v4i64:
15469         case MVT::v8i32:
15470         case MVT::v16i16:
15471         case MVT::v16i32:
15472         case MVT::v8i64:
15473           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15474         }
15475       }
15476     }
15477   }
15478
15479   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15480   if (!Subtarget->is64Bit() &&
15481       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15482       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15483       Amt.getOpcode() == ISD::BITCAST &&
15484       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15485     Amt = Amt.getOperand(0);
15486     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15487                      VT.getVectorNumElements();
15488     std::vector<SDValue> Vals(Ratio);
15489     for (unsigned i = 0; i != Ratio; ++i)
15490       Vals[i] = Amt.getOperand(i);
15491     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15492       for (unsigned j = 0; j != Ratio; ++j)
15493         if (Vals[j] != Amt.getOperand(i + j))
15494           return SDValue();
15495     }
15496     switch (Op.getOpcode()) {
15497     default:
15498       llvm_unreachable("Unknown shift opcode!");
15499     case ISD::SHL:
15500       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15501     case ISD::SRL:
15502       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15503     case ISD::SRA:
15504       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15505     }
15506   }
15507
15508   return SDValue();
15509 }
15510
15511 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15512                           SelectionDAG &DAG) {
15513   MVT VT = Op.getSimpleValueType();
15514   SDLoc dl(Op);
15515   SDValue R = Op.getOperand(0);
15516   SDValue Amt = Op.getOperand(1);
15517   SDValue V;
15518
15519   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15520   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15521
15522   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15523   if (V.getNode())
15524     return V;
15525
15526   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15527   if (V.getNode())
15528       return V;
15529
15530   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15531     return Op;
15532   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15533   if (Subtarget->hasInt256()) {
15534     if (Op.getOpcode() == ISD::SRL &&
15535         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15536          VT == MVT::v4i64 || VT == MVT::v8i32))
15537       return Op;
15538     if (Op.getOpcode() == ISD::SHL &&
15539         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15540          VT == MVT::v4i64 || VT == MVT::v8i32))
15541       return Op;
15542     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15543       return Op;
15544   }
15545
15546   // If possible, lower this packed shift into a vector multiply instead of
15547   // expanding it into a sequence of scalar shifts.
15548   // Do this only if the vector shift count is a constant build_vector.
15549   if (Op.getOpcode() == ISD::SHL && 
15550       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15551        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15552       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15553     SmallVector<SDValue, 8> Elts;
15554     EVT SVT = VT.getScalarType();
15555     unsigned SVTBits = SVT.getSizeInBits();
15556     const APInt &One = APInt(SVTBits, 1);
15557     unsigned NumElems = VT.getVectorNumElements();
15558
15559     for (unsigned i=0; i !=NumElems; ++i) {
15560       SDValue Op = Amt->getOperand(i);
15561       if (Op->getOpcode() == ISD::UNDEF) {
15562         Elts.push_back(Op);
15563         continue;
15564       }
15565
15566       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15567       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15568       uint64_t ShAmt = C.getZExtValue();
15569       if (ShAmt >= SVTBits) {
15570         Elts.push_back(DAG.getUNDEF(SVT));
15571         continue;
15572       }
15573       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15574     }
15575     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15576     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15577   }
15578
15579   // Lower SHL with variable shift amount.
15580   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15581     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15582
15583     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15584     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15585     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15586     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15587   }
15588
15589   // If possible, lower this shift as a sequence of two shifts by
15590   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15591   // Example:
15592   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15593   //
15594   // Could be rewritten as:
15595   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15596   //
15597   // The advantage is that the two shifts from the example would be
15598   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15599   // the vector shift into four scalar shifts plus four pairs of vector
15600   // insert/extract.
15601   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15602       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15603     unsigned TargetOpcode = X86ISD::MOVSS;
15604     bool CanBeSimplified;
15605     // The splat value for the first packed shift (the 'X' from the example).
15606     SDValue Amt1 = Amt->getOperand(0);
15607     // The splat value for the second packed shift (the 'Y' from the example).
15608     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15609                                         Amt->getOperand(2);
15610
15611     // See if it is possible to replace this node with a sequence of
15612     // two shifts followed by a MOVSS/MOVSD
15613     if (VT == MVT::v4i32) {
15614       // Check if it is legal to use a MOVSS.
15615       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15616                         Amt2 == Amt->getOperand(3);
15617       if (!CanBeSimplified) {
15618         // Otherwise, check if we can still simplify this node using a MOVSD.
15619         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15620                           Amt->getOperand(2) == Amt->getOperand(3);
15621         TargetOpcode = X86ISD::MOVSD;
15622         Amt2 = Amt->getOperand(2);
15623       }
15624     } else {
15625       // Do similar checks for the case where the machine value type
15626       // is MVT::v8i16.
15627       CanBeSimplified = Amt1 == Amt->getOperand(1);
15628       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15629         CanBeSimplified = Amt2 == Amt->getOperand(i);
15630
15631       if (!CanBeSimplified) {
15632         TargetOpcode = X86ISD::MOVSD;
15633         CanBeSimplified = true;
15634         Amt2 = Amt->getOperand(4);
15635         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15636           CanBeSimplified = Amt1 == Amt->getOperand(i);
15637         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15638           CanBeSimplified = Amt2 == Amt->getOperand(j);
15639       }
15640     }
15641     
15642     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15643         isa<ConstantSDNode>(Amt2)) {
15644       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15645       EVT CastVT = MVT::v4i32;
15646       SDValue Splat1 = 
15647         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15648       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15649       SDValue Splat2 = 
15650         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15651       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15652       if (TargetOpcode == X86ISD::MOVSD)
15653         CastVT = MVT::v2i64;
15654       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15655       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15656       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15657                                             BitCast1, DAG);
15658       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15659     }
15660   }
15661
15662   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15663     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15664
15665     // a = a << 5;
15666     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15667     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15668
15669     // Turn 'a' into a mask suitable for VSELECT
15670     SDValue VSelM = DAG.getConstant(0x80, VT);
15671     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15672     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15673
15674     SDValue CM1 = DAG.getConstant(0x0f, VT);
15675     SDValue CM2 = DAG.getConstant(0x3f, VT);
15676
15677     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15678     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15679     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15680     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15681     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15682
15683     // a += a
15684     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15685     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15686     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15687
15688     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15689     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15690     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15691     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15692     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15693
15694     // a += a
15695     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15696     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15697     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15698
15699     // return VSELECT(r, r+r, a);
15700     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15701                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15702     return R;
15703   }
15704
15705   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15706   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15707   // solution better.
15708   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15709     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15710     unsigned ExtOpc =
15711         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15712     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15713     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15714     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15715                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15716     }
15717
15718   // Decompose 256-bit shifts into smaller 128-bit shifts.
15719   if (VT.is256BitVector()) {
15720     unsigned NumElems = VT.getVectorNumElements();
15721     MVT EltVT = VT.getVectorElementType();
15722     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15723
15724     // Extract the two vectors
15725     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15726     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15727
15728     // Recreate the shift amount vectors
15729     SDValue Amt1, Amt2;
15730     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15731       // Constant shift amount
15732       SmallVector<SDValue, 4> Amt1Csts;
15733       SmallVector<SDValue, 4> Amt2Csts;
15734       for (unsigned i = 0; i != NumElems/2; ++i)
15735         Amt1Csts.push_back(Amt->getOperand(i));
15736       for (unsigned i = NumElems/2; i != NumElems; ++i)
15737         Amt2Csts.push_back(Amt->getOperand(i));
15738
15739       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15740       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15741     } else {
15742       // Variable shift amount
15743       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15744       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15745     }
15746
15747     // Issue new vector shifts for the smaller types
15748     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15749     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15750
15751     // Concatenate the result back
15752     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15753   }
15754
15755   return SDValue();
15756 }
15757
15758 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15759   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15760   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15761   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15762   // has only one use.
15763   SDNode *N = Op.getNode();
15764   SDValue LHS = N->getOperand(0);
15765   SDValue RHS = N->getOperand(1);
15766   unsigned BaseOp = 0;
15767   unsigned Cond = 0;
15768   SDLoc DL(Op);
15769   switch (Op.getOpcode()) {
15770   default: llvm_unreachable("Unknown ovf instruction!");
15771   case ISD::SADDO:
15772     // A subtract of one will be selected as a INC. Note that INC doesn't
15773     // set CF, so we can't do this for UADDO.
15774     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15775       if (C->isOne()) {
15776         BaseOp = X86ISD::INC;
15777         Cond = X86::COND_O;
15778         break;
15779       }
15780     BaseOp = X86ISD::ADD;
15781     Cond = X86::COND_O;
15782     break;
15783   case ISD::UADDO:
15784     BaseOp = X86ISD::ADD;
15785     Cond = X86::COND_B;
15786     break;
15787   case ISD::SSUBO:
15788     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15789     // set CF, so we can't do this for USUBO.
15790     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15791       if (C->isOne()) {
15792         BaseOp = X86ISD::DEC;
15793         Cond = X86::COND_O;
15794         break;
15795       }
15796     BaseOp = X86ISD::SUB;
15797     Cond = X86::COND_O;
15798     break;
15799   case ISD::USUBO:
15800     BaseOp = X86ISD::SUB;
15801     Cond = X86::COND_B;
15802     break;
15803   case ISD::SMULO:
15804     BaseOp = X86ISD::SMUL;
15805     Cond = X86::COND_O;
15806     break;
15807   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15808     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15809                                  MVT::i32);
15810     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15811
15812     SDValue SetCC =
15813       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15814                   DAG.getConstant(X86::COND_O, MVT::i32),
15815                   SDValue(Sum.getNode(), 2));
15816
15817     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15818   }
15819   }
15820
15821   // Also sets EFLAGS.
15822   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15823   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15824
15825   SDValue SetCC =
15826     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15827                 DAG.getConstant(Cond, MVT::i32),
15828                 SDValue(Sum.getNode(), 1));
15829
15830   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15831 }
15832
15833 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15834                                                   SelectionDAG &DAG) const {
15835   SDLoc dl(Op);
15836   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15837   MVT VT = Op.getSimpleValueType();
15838
15839   if (!Subtarget->hasSSE2() || !VT.isVector())
15840     return SDValue();
15841
15842   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15843                       ExtraVT.getScalarType().getSizeInBits();
15844
15845   switch (VT.SimpleTy) {
15846     default: return SDValue();
15847     case MVT::v8i32:
15848     case MVT::v16i16:
15849       if (!Subtarget->hasFp256())
15850         return SDValue();
15851       if (!Subtarget->hasInt256()) {
15852         // needs to be split
15853         unsigned NumElems = VT.getVectorNumElements();
15854
15855         // Extract the LHS vectors
15856         SDValue LHS = Op.getOperand(0);
15857         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15858         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15859
15860         MVT EltVT = VT.getVectorElementType();
15861         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15862
15863         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15864         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15865         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15866                                    ExtraNumElems/2);
15867         SDValue Extra = DAG.getValueType(ExtraVT);
15868
15869         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15870         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15871
15872         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15873       }
15874       // fall through
15875     case MVT::v4i32:
15876     case MVT::v8i16: {
15877       SDValue Op0 = Op.getOperand(0);
15878       SDValue Op00 = Op0.getOperand(0);
15879       SDValue Tmp1;
15880       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15881       if (Op0.getOpcode() == ISD::BITCAST &&
15882           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15883         // (sext (vzext x)) -> (vsext x)
15884         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15885         if (Tmp1.getNode()) {
15886           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15887           // This folding is only valid when the in-reg type is a vector of i8,
15888           // i16, or i32.
15889           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15890               ExtraEltVT == MVT::i32) {
15891             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15892             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15893                    "This optimization is invalid without a VZEXT.");
15894             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15895           }
15896           Op0 = Tmp1;
15897         }
15898       }
15899
15900       // If the above didn't work, then just use Shift-Left + Shift-Right.
15901       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15902                                         DAG);
15903       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15904                                         DAG);
15905     }
15906   }
15907 }
15908
15909 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15910                                  SelectionDAG &DAG) {
15911   SDLoc dl(Op);
15912   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15913     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15914   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15915     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15916
15917   // The only fence that needs an instruction is a sequentially-consistent
15918   // cross-thread fence.
15919   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15920     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15921     // no-sse2). There isn't any reason to disable it if the target processor
15922     // supports it.
15923     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15924       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15925
15926     SDValue Chain = Op.getOperand(0);
15927     SDValue Zero = DAG.getConstant(0, MVT::i32);
15928     SDValue Ops[] = {
15929       DAG.getRegister(X86::ESP, MVT::i32), // Base
15930       DAG.getTargetConstant(1, MVT::i8),   // Scale
15931       DAG.getRegister(0, MVT::i32),        // Index
15932       DAG.getTargetConstant(0, MVT::i32),  // Disp
15933       DAG.getRegister(0, MVT::i32),        // Segment.
15934       Zero,
15935       Chain
15936     };
15937     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15938     return SDValue(Res, 0);
15939   }
15940
15941   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15942   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15943 }
15944
15945 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15946                              SelectionDAG &DAG) {
15947   MVT T = Op.getSimpleValueType();
15948   SDLoc DL(Op);
15949   unsigned Reg = 0;
15950   unsigned size = 0;
15951   switch(T.SimpleTy) {
15952   default: llvm_unreachable("Invalid value type!");
15953   case MVT::i8:  Reg = X86::AL;  size = 1; break;
15954   case MVT::i16: Reg = X86::AX;  size = 2; break;
15955   case MVT::i32: Reg = X86::EAX; size = 4; break;
15956   case MVT::i64:
15957     assert(Subtarget->is64Bit() && "Node not type legal!");
15958     Reg = X86::RAX; size = 8;
15959     break;
15960   }
15961   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15962                                   Op.getOperand(2), SDValue());
15963   SDValue Ops[] = { cpIn.getValue(0),
15964                     Op.getOperand(1),
15965                     Op.getOperand(3),
15966                     DAG.getTargetConstant(size, MVT::i8),
15967                     cpIn.getValue(1) };
15968   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15969   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15970   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15971                                            Ops, T, MMO);
15972
15973   SDValue cpOut =
15974     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15975   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15976                                       MVT::i32, cpOut.getValue(2));
15977   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15978                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15979
15980   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15981   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15982   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15983   return SDValue();
15984 }
15985
15986 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15987                             SelectionDAG &DAG) {
15988   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
15989   MVT DstVT = Op.getSimpleValueType();
15990
15991   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
15992     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15993     if (DstVT != MVT::f64)
15994       // This conversion needs to be expanded.
15995       return SDValue();
15996
15997     SDValue InVec = Op->getOperand(0);
15998     SDLoc dl(Op);
15999     unsigned NumElts = SrcVT.getVectorNumElements();
16000     EVT SVT = SrcVT.getVectorElementType();
16001
16002     // Widen the vector in input in the case of MVT::v2i32.
16003     // Example: from MVT::v2i32 to MVT::v4i32.
16004     SmallVector<SDValue, 16> Elts;
16005     for (unsigned i = 0, e = NumElts; i != e; ++i)
16006       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16007                                  DAG.getIntPtrConstant(i)));
16008
16009     // Explicitly mark the extra elements as Undef.
16010     SDValue Undef = DAG.getUNDEF(SVT);
16011     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16012       Elts.push_back(Undef);
16013
16014     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16015     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16016     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16017     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16018                        DAG.getIntPtrConstant(0));
16019   }
16020
16021   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16022          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16023   assert((DstVT == MVT::i64 ||
16024           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16025          "Unexpected custom BITCAST");
16026   // i64 <=> MMX conversions are Legal.
16027   if (SrcVT==MVT::i64 && DstVT.isVector())
16028     return Op;
16029   if (DstVT==MVT::i64 && SrcVT.isVector())
16030     return Op;
16031   // MMX <=> MMX conversions are Legal.
16032   if (SrcVT.isVector() && DstVT.isVector())
16033     return Op;
16034   // All other conversions need to be expanded.
16035   return SDValue();
16036 }
16037
16038 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16039   SDNode *Node = Op.getNode();
16040   SDLoc dl(Node);
16041   EVT T = Node->getValueType(0);
16042   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16043                               DAG.getConstant(0, T), Node->getOperand(2));
16044   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16045                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16046                        Node->getOperand(0),
16047                        Node->getOperand(1), negOp,
16048                        cast<AtomicSDNode>(Node)->getMemOperand(),
16049                        cast<AtomicSDNode>(Node)->getOrdering(),
16050                        cast<AtomicSDNode>(Node)->getSynchScope());
16051 }
16052
16053 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16054   SDNode *Node = Op.getNode();
16055   SDLoc dl(Node);
16056   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16057
16058   // Convert seq_cst store -> xchg
16059   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16060   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16061   //        (The only way to get a 16-byte store is cmpxchg16b)
16062   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16063   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16064       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16065     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16066                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16067                                  Node->getOperand(0),
16068                                  Node->getOperand(1), Node->getOperand(2),
16069                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16070                                  cast<AtomicSDNode>(Node)->getOrdering(),
16071                                  cast<AtomicSDNode>(Node)->getSynchScope());
16072     return Swap.getValue(1);
16073   }
16074   // Other atomic stores have a simple pattern.
16075   return Op;
16076 }
16077
16078 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16079   EVT VT = Op.getNode()->getSimpleValueType(0);
16080
16081   // Let legalize expand this if it isn't a legal type yet.
16082   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16083     return SDValue();
16084
16085   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16086
16087   unsigned Opc;
16088   bool ExtraOp = false;
16089   switch (Op.getOpcode()) {
16090   default: llvm_unreachable("Invalid code");
16091   case ISD::ADDC: Opc = X86ISD::ADD; break;
16092   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16093   case ISD::SUBC: Opc = X86ISD::SUB; break;
16094   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16095   }
16096
16097   if (!ExtraOp)
16098     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16099                        Op.getOperand(1));
16100   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16101                      Op.getOperand(1), Op.getOperand(2));
16102 }
16103
16104 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16105                             SelectionDAG &DAG) {
16106   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16107
16108   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16109   // which returns the values as { float, float } (in XMM0) or
16110   // { double, double } (which is returned in XMM0, XMM1).
16111   SDLoc dl(Op);
16112   SDValue Arg = Op.getOperand(0);
16113   EVT ArgVT = Arg.getValueType();
16114   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16115
16116   TargetLowering::ArgListTy Args;
16117   TargetLowering::ArgListEntry Entry;
16118
16119   Entry.Node = Arg;
16120   Entry.Ty = ArgTy;
16121   Entry.isSExt = false;
16122   Entry.isZExt = false;
16123   Args.push_back(Entry);
16124
16125   bool isF64 = ArgVT == MVT::f64;
16126   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16127   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16128   // the results are returned via SRet in memory.
16129   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16130   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16131   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16132
16133   Type *RetTy = isF64
16134     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16135     : (Type*)VectorType::get(ArgTy, 4);
16136
16137   TargetLowering::CallLoweringInfo CLI(DAG);
16138   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16139     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16140
16141   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16142
16143   if (isF64)
16144     // Returned in xmm0 and xmm1.
16145     return CallResult.first;
16146
16147   // Returned in bits 0:31 and 32:64 xmm0.
16148   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16149                                CallResult.first, DAG.getIntPtrConstant(0));
16150   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16151                                CallResult.first, DAG.getIntPtrConstant(1));
16152   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16153   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16154 }
16155
16156 /// LowerOperation - Provide custom lowering hooks for some operations.
16157 ///
16158 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16159   switch (Op.getOpcode()) {
16160   default: llvm_unreachable("Should not custom lower this!");
16161   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16162   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16163   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16164     return LowerCMP_SWAP(Op, Subtarget, DAG);
16165   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16166   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16167   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16168   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16169   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16170   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16171   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16172   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16173   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16174   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16175   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16176   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16177   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16178   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16179   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16180   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16181   case ISD::SHL_PARTS:
16182   case ISD::SRA_PARTS:
16183   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16184   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16185   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16186   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16187   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16188   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16189   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16190   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16191   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16192   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16193   case ISD::FABS:               return LowerFABS(Op, DAG);
16194   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16195   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16196   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16197   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16198   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16199   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16200   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16201   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16202   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16203   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16204   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16205   case ISD::INTRINSIC_VOID:
16206   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16207   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16208   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16209   case ISD::FRAME_TO_ARGS_OFFSET:
16210                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16211   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16212   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16213   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16214   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16215   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16216   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16217   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16218   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16219   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16220   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16221   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16222   case ISD::UMUL_LOHI:
16223   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16224   case ISD::SRA:
16225   case ISD::SRL:
16226   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16227   case ISD::SADDO:
16228   case ISD::UADDO:
16229   case ISD::SSUBO:
16230   case ISD::USUBO:
16231   case ISD::SMULO:
16232   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16233   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16234   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16235   case ISD::ADDC:
16236   case ISD::ADDE:
16237   case ISD::SUBC:
16238   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16239   case ISD::ADD:                return LowerADD(Op, DAG);
16240   case ISD::SUB:                return LowerSUB(Op, DAG);
16241   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16242   }
16243 }
16244
16245 static void ReplaceATOMIC_LOAD(SDNode *Node,
16246                                SmallVectorImpl<SDValue> &Results,
16247                                SelectionDAG &DAG) {
16248   SDLoc dl(Node);
16249   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16250
16251   // Convert wide load -> cmpxchg8b/cmpxchg16b
16252   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16253   //        (The only way to get a 16-byte load is cmpxchg16b)
16254   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16255   SDValue Zero = DAG.getConstant(0, VT);
16256   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16257   SDValue Swap =
16258       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16259                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16260                            cast<AtomicSDNode>(Node)->getMemOperand(),
16261                            cast<AtomicSDNode>(Node)->getOrdering(),
16262                            cast<AtomicSDNode>(Node)->getOrdering(),
16263                            cast<AtomicSDNode>(Node)->getSynchScope());
16264   Results.push_back(Swap.getValue(0));
16265   Results.push_back(Swap.getValue(2));
16266 }
16267
16268 /// ReplaceNodeResults - Replace a node with an illegal result type
16269 /// with a new node built out of custom code.
16270 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16271                                            SmallVectorImpl<SDValue>&Results,
16272                                            SelectionDAG &DAG) const {
16273   SDLoc dl(N);
16274   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16275   switch (N->getOpcode()) {
16276   default:
16277     llvm_unreachable("Do not know how to custom type legalize this operation!");
16278   case ISD::SIGN_EXTEND_INREG:
16279   case ISD::ADDC:
16280   case ISD::ADDE:
16281   case ISD::SUBC:
16282   case ISD::SUBE:
16283     // We don't want to expand or promote these.
16284     return;
16285   case ISD::SDIV:
16286   case ISD::UDIV:
16287   case ISD::SREM:
16288   case ISD::UREM:
16289   case ISD::SDIVREM:
16290   case ISD::UDIVREM: {
16291     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16292     Results.push_back(V);
16293     return;
16294   }
16295   case ISD::FP_TO_SINT:
16296   case ISD::FP_TO_UINT: {
16297     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16298
16299     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16300       return;
16301
16302     std::pair<SDValue,SDValue> Vals =
16303         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16304     SDValue FIST = Vals.first, StackSlot = Vals.second;
16305     if (FIST.getNode()) {
16306       EVT VT = N->getValueType(0);
16307       // Return a load from the stack slot.
16308       if (StackSlot.getNode())
16309         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16310                                       MachinePointerInfo(),
16311                                       false, false, false, 0));
16312       else
16313         Results.push_back(FIST);
16314     }
16315     return;
16316   }
16317   case ISD::UINT_TO_FP: {
16318     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16319     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16320         N->getValueType(0) != MVT::v2f32)
16321       return;
16322     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16323                                  N->getOperand(0));
16324     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16325                                      MVT::f64);
16326     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16327     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16328                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16329     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16330     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16331     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16332     return;
16333   }
16334   case ISD::FP_ROUND: {
16335     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16336         return;
16337     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16338     Results.push_back(V);
16339     return;
16340   }
16341   case ISD::INTRINSIC_W_CHAIN: {
16342     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16343     switch (IntNo) {
16344     default : llvm_unreachable("Do not know how to custom type "
16345                                "legalize this intrinsic operation!");
16346     case Intrinsic::x86_rdtsc:
16347       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16348                                      Results);
16349     case Intrinsic::x86_rdtscp:
16350       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16351                                      Results);
16352     case Intrinsic::x86_rdpmc:
16353       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16354     }
16355   }
16356   case ISD::READCYCLECOUNTER: {
16357     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16358                                    Results);
16359   }
16360   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16361     EVT T = N->getValueType(0);
16362     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16363     bool Regs64bit = T == MVT::i128;
16364     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16365     SDValue cpInL, cpInH;
16366     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16367                         DAG.getConstant(0, HalfT));
16368     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16369                         DAG.getConstant(1, HalfT));
16370     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16371                              Regs64bit ? X86::RAX : X86::EAX,
16372                              cpInL, SDValue());
16373     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16374                              Regs64bit ? X86::RDX : X86::EDX,
16375                              cpInH, cpInL.getValue(1));
16376     SDValue swapInL, swapInH;
16377     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16378                           DAG.getConstant(0, HalfT));
16379     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16380                           DAG.getConstant(1, HalfT));
16381     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16382                                Regs64bit ? X86::RBX : X86::EBX,
16383                                swapInL, cpInH.getValue(1));
16384     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16385                                Regs64bit ? X86::RCX : X86::ECX,
16386                                swapInH, swapInL.getValue(1));
16387     SDValue Ops[] = { swapInH.getValue(0),
16388                       N->getOperand(1),
16389                       swapInH.getValue(1) };
16390     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16391     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16392     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16393                                   X86ISD::LCMPXCHG8_DAG;
16394     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16395     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16396                                         Regs64bit ? X86::RAX : X86::EAX,
16397                                         HalfT, Result.getValue(1));
16398     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16399                                         Regs64bit ? X86::RDX : X86::EDX,
16400                                         HalfT, cpOutL.getValue(2));
16401     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16402
16403     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16404                                         MVT::i32, cpOutH.getValue(2));
16405     SDValue Success =
16406         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16407                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16408     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16409
16410     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16411     Results.push_back(Success);
16412     Results.push_back(EFLAGS.getValue(1));
16413     return;
16414   }
16415   case ISD::ATOMIC_SWAP:
16416   case ISD::ATOMIC_LOAD_ADD:
16417   case ISD::ATOMIC_LOAD_SUB:
16418   case ISD::ATOMIC_LOAD_AND:
16419   case ISD::ATOMIC_LOAD_OR:
16420   case ISD::ATOMIC_LOAD_XOR:
16421   case ISD::ATOMIC_LOAD_NAND:
16422   case ISD::ATOMIC_LOAD_MIN:
16423   case ISD::ATOMIC_LOAD_MAX:
16424   case ISD::ATOMIC_LOAD_UMIN:
16425   case ISD::ATOMIC_LOAD_UMAX:
16426     // Delegate to generic TypeLegalization. Situations we can really handle
16427     // should have already been dealt with by X86AtomicExpand.cpp.
16428     break;
16429   case ISD::ATOMIC_LOAD: {
16430     ReplaceATOMIC_LOAD(N, Results, DAG);
16431     return;
16432   }
16433   case ISD::BITCAST: {
16434     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16435     EVT DstVT = N->getValueType(0);
16436     EVT SrcVT = N->getOperand(0)->getValueType(0);
16437
16438     if (SrcVT != MVT::f64 ||
16439         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16440       return;
16441
16442     unsigned NumElts = DstVT.getVectorNumElements();
16443     EVT SVT = DstVT.getVectorElementType();
16444     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16445     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16446                                    MVT::v2f64, N->getOperand(0));
16447     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16448
16449     if (ExperimentalVectorWideningLegalization) {
16450       // If we are legalizing vectors by widening, we already have the desired
16451       // legal vector type, just return it.
16452       Results.push_back(ToVecInt);
16453       return;
16454     }
16455
16456     SmallVector<SDValue, 8> Elts;
16457     for (unsigned i = 0, e = NumElts; i != e; ++i)
16458       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16459                                    ToVecInt, DAG.getIntPtrConstant(i)));
16460
16461     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16462   }
16463   }
16464 }
16465
16466 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16467   switch (Opcode) {
16468   default: return nullptr;
16469   case X86ISD::BSF:                return "X86ISD::BSF";
16470   case X86ISD::BSR:                return "X86ISD::BSR";
16471   case X86ISD::SHLD:               return "X86ISD::SHLD";
16472   case X86ISD::SHRD:               return "X86ISD::SHRD";
16473   case X86ISD::FAND:               return "X86ISD::FAND";
16474   case X86ISD::FANDN:              return "X86ISD::FANDN";
16475   case X86ISD::FOR:                return "X86ISD::FOR";
16476   case X86ISD::FXOR:               return "X86ISD::FXOR";
16477   case X86ISD::FSRL:               return "X86ISD::FSRL";
16478   case X86ISD::FILD:               return "X86ISD::FILD";
16479   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16480   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16481   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16482   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16483   case X86ISD::FLD:                return "X86ISD::FLD";
16484   case X86ISD::FST:                return "X86ISD::FST";
16485   case X86ISD::CALL:               return "X86ISD::CALL";
16486   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16487   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16488   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16489   case X86ISD::BT:                 return "X86ISD::BT";
16490   case X86ISD::CMP:                return "X86ISD::CMP";
16491   case X86ISD::COMI:               return "X86ISD::COMI";
16492   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16493   case X86ISD::CMPM:               return "X86ISD::CMPM";
16494   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16495   case X86ISD::SETCC:              return "X86ISD::SETCC";
16496   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16497   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16498   case X86ISD::CMOV:               return "X86ISD::CMOV";
16499   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16500   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16501   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16502   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16503   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16504   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16505   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16506   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16507   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16508   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16509   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16510   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16511   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16512   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16513   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16514   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16515   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16516   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16517   case X86ISD::HADD:               return "X86ISD::HADD";
16518   case X86ISD::HSUB:               return "X86ISD::HSUB";
16519   case X86ISD::FHADD:              return "X86ISD::FHADD";
16520   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16521   case X86ISD::UMAX:               return "X86ISD::UMAX";
16522   case X86ISD::UMIN:               return "X86ISD::UMIN";
16523   case X86ISD::SMAX:               return "X86ISD::SMAX";
16524   case X86ISD::SMIN:               return "X86ISD::SMIN";
16525   case X86ISD::FMAX:               return "X86ISD::FMAX";
16526   case X86ISD::FMIN:               return "X86ISD::FMIN";
16527   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16528   case X86ISD::FMINC:              return "X86ISD::FMINC";
16529   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16530   case X86ISD::FRCP:               return "X86ISD::FRCP";
16531   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16532   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16533   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16534   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16535   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16536   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16537   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16538   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16539   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16540   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16541   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16542   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16543   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16544   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16545   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16546   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16547   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16548   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16549   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16550   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16551   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16552   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16553   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16554   case X86ISD::VSHL:               return "X86ISD::VSHL";
16555   case X86ISD::VSRL:               return "X86ISD::VSRL";
16556   case X86ISD::VSRA:               return "X86ISD::VSRA";
16557   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16558   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16559   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16560   case X86ISD::CMPP:               return "X86ISD::CMPP";
16561   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16562   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16563   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16564   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16565   case X86ISD::ADD:                return "X86ISD::ADD";
16566   case X86ISD::SUB:                return "X86ISD::SUB";
16567   case X86ISD::ADC:                return "X86ISD::ADC";
16568   case X86ISD::SBB:                return "X86ISD::SBB";
16569   case X86ISD::SMUL:               return "X86ISD::SMUL";
16570   case X86ISD::UMUL:               return "X86ISD::UMUL";
16571   case X86ISD::INC:                return "X86ISD::INC";
16572   case X86ISD::DEC:                return "X86ISD::DEC";
16573   case X86ISD::OR:                 return "X86ISD::OR";
16574   case X86ISD::XOR:                return "X86ISD::XOR";
16575   case X86ISD::AND:                return "X86ISD::AND";
16576   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16577   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16578   case X86ISD::PTEST:              return "X86ISD::PTEST";
16579   case X86ISD::TESTP:              return "X86ISD::TESTP";
16580   case X86ISD::TESTM:              return "X86ISD::TESTM";
16581   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16582   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16583   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16584   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16585   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16586   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16587   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16588   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16589   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16590   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16591   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16592   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16593   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16594   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16595   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16596   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16597   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16598   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16599   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16600   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16601   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16602   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16603   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16604   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16605   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16606   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16607   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16608   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16609   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16610   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16611   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16612   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16613   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16614   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16615   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16616   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16617   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16618   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16619   case X86ISD::SAHF:               return "X86ISD::SAHF";
16620   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16621   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16622   case X86ISD::FMADD:              return "X86ISD::FMADD";
16623   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16624   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16625   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16626   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16627   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16628   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16629   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16630   case X86ISD::XTEST:              return "X86ISD::XTEST";
16631   }
16632 }
16633
16634 // isLegalAddressingMode - Return true if the addressing mode represented
16635 // by AM is legal for this target, for a load/store of the specified type.
16636 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16637                                               Type *Ty) const {
16638   // X86 supports extremely general addressing modes.
16639   CodeModel::Model M = getTargetMachine().getCodeModel();
16640   Reloc::Model R = getTargetMachine().getRelocationModel();
16641
16642   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16643   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16644     return false;
16645
16646   if (AM.BaseGV) {
16647     unsigned GVFlags =
16648       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16649
16650     // If a reference to this global requires an extra load, we can't fold it.
16651     if (isGlobalStubReference(GVFlags))
16652       return false;
16653
16654     // If BaseGV requires a register for the PIC base, we cannot also have a
16655     // BaseReg specified.
16656     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16657       return false;
16658
16659     // If lower 4G is not available, then we must use rip-relative addressing.
16660     if ((M != CodeModel::Small || R != Reloc::Static) &&
16661         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16662       return false;
16663   }
16664
16665   switch (AM.Scale) {
16666   case 0:
16667   case 1:
16668   case 2:
16669   case 4:
16670   case 8:
16671     // These scales always work.
16672     break;
16673   case 3:
16674   case 5:
16675   case 9:
16676     // These scales are formed with basereg+scalereg.  Only accept if there is
16677     // no basereg yet.
16678     if (AM.HasBaseReg)
16679       return false;
16680     break;
16681   default:  // Other stuff never works.
16682     return false;
16683   }
16684
16685   return true;
16686 }
16687
16688 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16689   unsigned Bits = Ty->getScalarSizeInBits();
16690
16691   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16692   // particularly cheaper than those without.
16693   if (Bits == 8)
16694     return false;
16695
16696   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16697   // variable shifts just as cheap as scalar ones.
16698   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16699     return false;
16700
16701   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16702   // fully general vector.
16703   return true;
16704 }
16705
16706 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16707   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16708     return false;
16709   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16710   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16711   return NumBits1 > NumBits2;
16712 }
16713
16714 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16715   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16716     return false;
16717
16718   if (!isTypeLegal(EVT::getEVT(Ty1)))
16719     return false;
16720
16721   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16722
16723   // Assuming the caller doesn't have a zeroext or signext return parameter,
16724   // truncation all the way down to i1 is valid.
16725   return true;
16726 }
16727
16728 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16729   return isInt<32>(Imm);
16730 }
16731
16732 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16733   // Can also use sub to handle negated immediates.
16734   return isInt<32>(Imm);
16735 }
16736
16737 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16738   if (!VT1.isInteger() || !VT2.isInteger())
16739     return false;
16740   unsigned NumBits1 = VT1.getSizeInBits();
16741   unsigned NumBits2 = VT2.getSizeInBits();
16742   return NumBits1 > NumBits2;
16743 }
16744
16745 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16746   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16747   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16748 }
16749
16750 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16751   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16752   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16753 }
16754
16755 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16756   EVT VT1 = Val.getValueType();
16757   if (isZExtFree(VT1, VT2))
16758     return true;
16759
16760   if (Val.getOpcode() != ISD::LOAD)
16761     return false;
16762
16763   if (!VT1.isSimple() || !VT1.isInteger() ||
16764       !VT2.isSimple() || !VT2.isInteger())
16765     return false;
16766
16767   switch (VT1.getSimpleVT().SimpleTy) {
16768   default: break;
16769   case MVT::i8:
16770   case MVT::i16:
16771   case MVT::i32:
16772     // X86 has 8, 16, and 32-bit zero-extending loads.
16773     return true;
16774   }
16775
16776   return false;
16777 }
16778
16779 bool
16780 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16781   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16782     return false;
16783
16784   VT = VT.getScalarType();
16785
16786   if (!VT.isSimple())
16787     return false;
16788
16789   switch (VT.getSimpleVT().SimpleTy) {
16790   case MVT::f32:
16791   case MVT::f64:
16792     return true;
16793   default:
16794     break;
16795   }
16796
16797   return false;
16798 }
16799
16800 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16801   // i16 instructions are longer (0x66 prefix) and potentially slower.
16802   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16803 }
16804
16805 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16806 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16807 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16808 /// are assumed to be legal.
16809 bool
16810 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16811                                       EVT VT) const {
16812   if (!VT.isSimple())
16813     return false;
16814
16815   MVT SVT = VT.getSimpleVT();
16816
16817   // Very little shuffling can be done for 64-bit vectors right now.
16818   if (VT.getSizeInBits() == 64)
16819     return false;
16820
16821   // If this is a single-input shuffle with no 128 bit lane crossings we can
16822   // lower it into pshufb.
16823   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16824       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16825     bool isLegal = true;
16826     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16827       if (M[I] >= (int)SVT.getVectorNumElements() ||
16828           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16829         isLegal = false;
16830         break;
16831       }
16832     }
16833     if (isLegal)
16834       return true;
16835   }
16836
16837   // FIXME: blends, shifts.
16838   return (SVT.getVectorNumElements() == 2 ||
16839           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16840           isMOVLMask(M, SVT) ||
16841           isSHUFPMask(M, SVT) ||
16842           isPSHUFDMask(M, SVT) ||
16843           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16844           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16845           isPALIGNRMask(M, SVT, Subtarget) ||
16846           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16847           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16848           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16849           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16850           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16851 }
16852
16853 bool
16854 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16855                                           EVT VT) const {
16856   if (!VT.isSimple())
16857     return false;
16858
16859   MVT SVT = VT.getSimpleVT();
16860   unsigned NumElts = SVT.getVectorNumElements();
16861   // FIXME: This collection of masks seems suspect.
16862   if (NumElts == 2)
16863     return true;
16864   if (NumElts == 4 && SVT.is128BitVector()) {
16865     return (isMOVLMask(Mask, SVT)  ||
16866             isCommutedMOVLMask(Mask, SVT, true) ||
16867             isSHUFPMask(Mask, SVT) ||
16868             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16869   }
16870   return false;
16871 }
16872
16873 //===----------------------------------------------------------------------===//
16874 //                           X86 Scheduler Hooks
16875 //===----------------------------------------------------------------------===//
16876
16877 /// Utility function to emit xbegin specifying the start of an RTM region.
16878 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16879                                      const TargetInstrInfo *TII) {
16880   DebugLoc DL = MI->getDebugLoc();
16881
16882   const BasicBlock *BB = MBB->getBasicBlock();
16883   MachineFunction::iterator I = MBB;
16884   ++I;
16885
16886   // For the v = xbegin(), we generate
16887   //
16888   // thisMBB:
16889   //  xbegin sinkMBB
16890   //
16891   // mainMBB:
16892   //  eax = -1
16893   //
16894   // sinkMBB:
16895   //  v = eax
16896
16897   MachineBasicBlock *thisMBB = MBB;
16898   MachineFunction *MF = MBB->getParent();
16899   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16900   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16901   MF->insert(I, mainMBB);
16902   MF->insert(I, sinkMBB);
16903
16904   // Transfer the remainder of BB and its successor edges to sinkMBB.
16905   sinkMBB->splice(sinkMBB->begin(), MBB,
16906                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16907   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16908
16909   // thisMBB:
16910   //  xbegin sinkMBB
16911   //  # fallthrough to mainMBB
16912   //  # abortion to sinkMBB
16913   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16914   thisMBB->addSuccessor(mainMBB);
16915   thisMBB->addSuccessor(sinkMBB);
16916
16917   // mainMBB:
16918   //  EAX = -1
16919   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16920   mainMBB->addSuccessor(sinkMBB);
16921
16922   // sinkMBB:
16923   // EAX is live into the sinkMBB
16924   sinkMBB->addLiveIn(X86::EAX);
16925   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16926           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16927     .addReg(X86::EAX);
16928
16929   MI->eraseFromParent();
16930   return sinkMBB;
16931 }
16932
16933 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16934 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16935 // in the .td file.
16936 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16937                                        const TargetInstrInfo *TII) {
16938   unsigned Opc;
16939   switch (MI->getOpcode()) {
16940   default: llvm_unreachable("illegal opcode!");
16941   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16942   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16943   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16944   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16945   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16946   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16947   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16948   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16949   }
16950
16951   DebugLoc dl = MI->getDebugLoc();
16952   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16953
16954   unsigned NumArgs = MI->getNumOperands();
16955   for (unsigned i = 1; i < NumArgs; ++i) {
16956     MachineOperand &Op = MI->getOperand(i);
16957     if (!(Op.isReg() && Op.isImplicit()))
16958       MIB.addOperand(Op);
16959   }
16960   if (MI->hasOneMemOperand())
16961     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16962
16963   BuildMI(*BB, MI, dl,
16964     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16965     .addReg(X86::XMM0);
16966
16967   MI->eraseFromParent();
16968   return BB;
16969 }
16970
16971 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16972 // defs in an instruction pattern
16973 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16974                                        const TargetInstrInfo *TII) {
16975   unsigned Opc;
16976   switch (MI->getOpcode()) {
16977   default: llvm_unreachable("illegal opcode!");
16978   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16979   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16980   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16981   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16982   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16983   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16984   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16985   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16986   }
16987
16988   DebugLoc dl = MI->getDebugLoc();
16989   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16990
16991   unsigned NumArgs = MI->getNumOperands(); // remove the results
16992   for (unsigned i = 1; i < NumArgs; ++i) {
16993     MachineOperand &Op = MI->getOperand(i);
16994     if (!(Op.isReg() && Op.isImplicit()))
16995       MIB.addOperand(Op);
16996   }
16997   if (MI->hasOneMemOperand())
16998     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16999
17000   BuildMI(*BB, MI, dl,
17001     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17002     .addReg(X86::ECX);
17003
17004   MI->eraseFromParent();
17005   return BB;
17006 }
17007
17008 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17009                                        const TargetInstrInfo *TII,
17010                                        const X86Subtarget* Subtarget) {
17011   DebugLoc dl = MI->getDebugLoc();
17012
17013   // Address into RAX/EAX, other two args into ECX, EDX.
17014   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17015   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17016   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17017   for (int i = 0; i < X86::AddrNumOperands; ++i)
17018     MIB.addOperand(MI->getOperand(i));
17019
17020   unsigned ValOps = X86::AddrNumOperands;
17021   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17022     .addReg(MI->getOperand(ValOps).getReg());
17023   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17024     .addReg(MI->getOperand(ValOps+1).getReg());
17025
17026   // The instruction doesn't actually take any operands though.
17027   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17028
17029   MI->eraseFromParent(); // The pseudo is gone now.
17030   return BB;
17031 }
17032
17033 MachineBasicBlock *
17034 X86TargetLowering::EmitVAARG64WithCustomInserter(
17035                    MachineInstr *MI,
17036                    MachineBasicBlock *MBB) const {
17037   // Emit va_arg instruction on X86-64.
17038
17039   // Operands to this pseudo-instruction:
17040   // 0  ) Output        : destination address (reg)
17041   // 1-5) Input         : va_list address (addr, i64mem)
17042   // 6  ) ArgSize       : Size (in bytes) of vararg type
17043   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17044   // 8  ) Align         : Alignment of type
17045   // 9  ) EFLAGS (implicit-def)
17046
17047   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17048   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17049
17050   unsigned DestReg = MI->getOperand(0).getReg();
17051   MachineOperand &Base = MI->getOperand(1);
17052   MachineOperand &Scale = MI->getOperand(2);
17053   MachineOperand &Index = MI->getOperand(3);
17054   MachineOperand &Disp = MI->getOperand(4);
17055   MachineOperand &Segment = MI->getOperand(5);
17056   unsigned ArgSize = MI->getOperand(6).getImm();
17057   unsigned ArgMode = MI->getOperand(7).getImm();
17058   unsigned Align = MI->getOperand(8).getImm();
17059
17060   // Memory Reference
17061   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17062   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17063   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17064
17065   // Machine Information
17066   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17067   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17068   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17069   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17070   DebugLoc DL = MI->getDebugLoc();
17071
17072   // struct va_list {
17073   //   i32   gp_offset
17074   //   i32   fp_offset
17075   //   i64   overflow_area (address)
17076   //   i64   reg_save_area (address)
17077   // }
17078   // sizeof(va_list) = 24
17079   // alignment(va_list) = 8
17080
17081   unsigned TotalNumIntRegs = 6;
17082   unsigned TotalNumXMMRegs = 8;
17083   bool UseGPOffset = (ArgMode == 1);
17084   bool UseFPOffset = (ArgMode == 2);
17085   unsigned MaxOffset = TotalNumIntRegs * 8 +
17086                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17087
17088   /* Align ArgSize to a multiple of 8 */
17089   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17090   bool NeedsAlign = (Align > 8);
17091
17092   MachineBasicBlock *thisMBB = MBB;
17093   MachineBasicBlock *overflowMBB;
17094   MachineBasicBlock *offsetMBB;
17095   MachineBasicBlock *endMBB;
17096
17097   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17098   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17099   unsigned OffsetReg = 0;
17100
17101   if (!UseGPOffset && !UseFPOffset) {
17102     // If we only pull from the overflow region, we don't create a branch.
17103     // We don't need to alter control flow.
17104     OffsetDestReg = 0; // unused
17105     OverflowDestReg = DestReg;
17106
17107     offsetMBB = nullptr;
17108     overflowMBB = thisMBB;
17109     endMBB = thisMBB;
17110   } else {
17111     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17112     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17113     // If not, pull from overflow_area. (branch to overflowMBB)
17114     //
17115     //       thisMBB
17116     //         |     .
17117     //         |        .
17118     //     offsetMBB   overflowMBB
17119     //         |        .
17120     //         |     .
17121     //        endMBB
17122
17123     // Registers for the PHI in endMBB
17124     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17125     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17126
17127     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17128     MachineFunction *MF = MBB->getParent();
17129     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17130     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17131     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17132
17133     MachineFunction::iterator MBBIter = MBB;
17134     ++MBBIter;
17135
17136     // Insert the new basic blocks
17137     MF->insert(MBBIter, offsetMBB);
17138     MF->insert(MBBIter, overflowMBB);
17139     MF->insert(MBBIter, endMBB);
17140
17141     // Transfer the remainder of MBB and its successor edges to endMBB.
17142     endMBB->splice(endMBB->begin(), thisMBB,
17143                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17144     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17145
17146     // Make offsetMBB and overflowMBB successors of thisMBB
17147     thisMBB->addSuccessor(offsetMBB);
17148     thisMBB->addSuccessor(overflowMBB);
17149
17150     // endMBB is a successor of both offsetMBB and overflowMBB
17151     offsetMBB->addSuccessor(endMBB);
17152     overflowMBB->addSuccessor(endMBB);
17153
17154     // Load the offset value into a register
17155     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17156     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17157       .addOperand(Base)
17158       .addOperand(Scale)
17159       .addOperand(Index)
17160       .addDisp(Disp, UseFPOffset ? 4 : 0)
17161       .addOperand(Segment)
17162       .setMemRefs(MMOBegin, MMOEnd);
17163
17164     // Check if there is enough room left to pull this argument.
17165     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17166       .addReg(OffsetReg)
17167       .addImm(MaxOffset + 8 - ArgSizeA8);
17168
17169     // Branch to "overflowMBB" if offset >= max
17170     // Fall through to "offsetMBB" otherwise
17171     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17172       .addMBB(overflowMBB);
17173   }
17174
17175   // In offsetMBB, emit code to use the reg_save_area.
17176   if (offsetMBB) {
17177     assert(OffsetReg != 0);
17178
17179     // Read the reg_save_area address.
17180     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17181     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17182       .addOperand(Base)
17183       .addOperand(Scale)
17184       .addOperand(Index)
17185       .addDisp(Disp, 16)
17186       .addOperand(Segment)
17187       .setMemRefs(MMOBegin, MMOEnd);
17188
17189     // Zero-extend the offset
17190     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17191       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17192         .addImm(0)
17193         .addReg(OffsetReg)
17194         .addImm(X86::sub_32bit);
17195
17196     // Add the offset to the reg_save_area to get the final address.
17197     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17198       .addReg(OffsetReg64)
17199       .addReg(RegSaveReg);
17200
17201     // Compute the offset for the next argument
17202     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17203     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17204       .addReg(OffsetReg)
17205       .addImm(UseFPOffset ? 16 : 8);
17206
17207     // Store it back into the va_list.
17208     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17209       .addOperand(Base)
17210       .addOperand(Scale)
17211       .addOperand(Index)
17212       .addDisp(Disp, UseFPOffset ? 4 : 0)
17213       .addOperand(Segment)
17214       .addReg(NextOffsetReg)
17215       .setMemRefs(MMOBegin, MMOEnd);
17216
17217     // Jump to endMBB
17218     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17219       .addMBB(endMBB);
17220   }
17221
17222   //
17223   // Emit code to use overflow area
17224   //
17225
17226   // Load the overflow_area address into a register.
17227   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17228   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17229     .addOperand(Base)
17230     .addOperand(Scale)
17231     .addOperand(Index)
17232     .addDisp(Disp, 8)
17233     .addOperand(Segment)
17234     .setMemRefs(MMOBegin, MMOEnd);
17235
17236   // If we need to align it, do so. Otherwise, just copy the address
17237   // to OverflowDestReg.
17238   if (NeedsAlign) {
17239     // Align the overflow address
17240     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17241     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17242
17243     // aligned_addr = (addr + (align-1)) & ~(align-1)
17244     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17245       .addReg(OverflowAddrReg)
17246       .addImm(Align-1);
17247
17248     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17249       .addReg(TmpReg)
17250       .addImm(~(uint64_t)(Align-1));
17251   } else {
17252     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17253       .addReg(OverflowAddrReg);
17254   }
17255
17256   // Compute the next overflow address after this argument.
17257   // (the overflow address should be kept 8-byte aligned)
17258   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17259   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17260     .addReg(OverflowDestReg)
17261     .addImm(ArgSizeA8);
17262
17263   // Store the new overflow address.
17264   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17265     .addOperand(Base)
17266     .addOperand(Scale)
17267     .addOperand(Index)
17268     .addDisp(Disp, 8)
17269     .addOperand(Segment)
17270     .addReg(NextAddrReg)
17271     .setMemRefs(MMOBegin, MMOEnd);
17272
17273   // If we branched, emit the PHI to the front of endMBB.
17274   if (offsetMBB) {
17275     BuildMI(*endMBB, endMBB->begin(), DL,
17276             TII->get(X86::PHI), DestReg)
17277       .addReg(OffsetDestReg).addMBB(offsetMBB)
17278       .addReg(OverflowDestReg).addMBB(overflowMBB);
17279   }
17280
17281   // Erase the pseudo instruction
17282   MI->eraseFromParent();
17283
17284   return endMBB;
17285 }
17286
17287 MachineBasicBlock *
17288 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17289                                                  MachineInstr *MI,
17290                                                  MachineBasicBlock *MBB) const {
17291   // Emit code to save XMM registers to the stack. The ABI says that the
17292   // number of registers to save is given in %al, so it's theoretically
17293   // possible to do an indirect jump trick to avoid saving all of them,
17294   // however this code takes a simpler approach and just executes all
17295   // of the stores if %al is non-zero. It's less code, and it's probably
17296   // easier on the hardware branch predictor, and stores aren't all that
17297   // expensive anyway.
17298
17299   // Create the new basic blocks. One block contains all the XMM stores,
17300   // and one block is the final destination regardless of whether any
17301   // stores were performed.
17302   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17303   MachineFunction *F = MBB->getParent();
17304   MachineFunction::iterator MBBIter = MBB;
17305   ++MBBIter;
17306   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17307   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17308   F->insert(MBBIter, XMMSaveMBB);
17309   F->insert(MBBIter, EndMBB);
17310
17311   // Transfer the remainder of MBB and its successor edges to EndMBB.
17312   EndMBB->splice(EndMBB->begin(), MBB,
17313                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17314   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17315
17316   // The original block will now fall through to the XMM save block.
17317   MBB->addSuccessor(XMMSaveMBB);
17318   // The XMMSaveMBB will fall through to the end block.
17319   XMMSaveMBB->addSuccessor(EndMBB);
17320
17321   // Now add the instructions.
17322   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17323   DebugLoc DL = MI->getDebugLoc();
17324
17325   unsigned CountReg = MI->getOperand(0).getReg();
17326   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17327   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17328
17329   if (!Subtarget->isTargetWin64()) {
17330     // If %al is 0, branch around the XMM save block.
17331     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17332     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17333     MBB->addSuccessor(EndMBB);
17334   }
17335
17336   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17337   // that was just emitted, but clearly shouldn't be "saved".
17338   assert((MI->getNumOperands() <= 3 ||
17339           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17340           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17341          && "Expected last argument to be EFLAGS");
17342   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17343   // In the XMM save block, save all the XMM argument registers.
17344   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17345     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17346     MachineMemOperand *MMO =
17347       F->getMachineMemOperand(
17348           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17349         MachineMemOperand::MOStore,
17350         /*Size=*/16, /*Align=*/16);
17351     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17352       .addFrameIndex(RegSaveFrameIndex)
17353       .addImm(/*Scale=*/1)
17354       .addReg(/*IndexReg=*/0)
17355       .addImm(/*Disp=*/Offset)
17356       .addReg(/*Segment=*/0)
17357       .addReg(MI->getOperand(i).getReg())
17358       .addMemOperand(MMO);
17359   }
17360
17361   MI->eraseFromParent();   // The pseudo instruction is gone now.
17362
17363   return EndMBB;
17364 }
17365
17366 // The EFLAGS operand of SelectItr might be missing a kill marker
17367 // because there were multiple uses of EFLAGS, and ISel didn't know
17368 // which to mark. Figure out whether SelectItr should have had a
17369 // kill marker, and set it if it should. Returns the correct kill
17370 // marker value.
17371 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17372                                      MachineBasicBlock* BB,
17373                                      const TargetRegisterInfo* TRI) {
17374   // Scan forward through BB for a use/def of EFLAGS.
17375   MachineBasicBlock::iterator miI(std::next(SelectItr));
17376   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17377     const MachineInstr& mi = *miI;
17378     if (mi.readsRegister(X86::EFLAGS))
17379       return false;
17380     if (mi.definesRegister(X86::EFLAGS))
17381       break; // Should have kill-flag - update below.
17382   }
17383
17384   // If we hit the end of the block, check whether EFLAGS is live into a
17385   // successor.
17386   if (miI == BB->end()) {
17387     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17388                                           sEnd = BB->succ_end();
17389          sItr != sEnd; ++sItr) {
17390       MachineBasicBlock* succ = *sItr;
17391       if (succ->isLiveIn(X86::EFLAGS))
17392         return false;
17393     }
17394   }
17395
17396   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17397   // out. SelectMI should have a kill flag on EFLAGS.
17398   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17399   return true;
17400 }
17401
17402 MachineBasicBlock *
17403 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17404                                      MachineBasicBlock *BB) const {
17405   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17406   DebugLoc DL = MI->getDebugLoc();
17407
17408   // To "insert" a SELECT_CC instruction, we actually have to insert the
17409   // diamond control-flow pattern.  The incoming instruction knows the
17410   // destination vreg to set, the condition code register to branch on, the
17411   // true/false values to select between, and a branch opcode to use.
17412   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17413   MachineFunction::iterator It = BB;
17414   ++It;
17415
17416   //  thisMBB:
17417   //  ...
17418   //   TrueVal = ...
17419   //   cmpTY ccX, r1, r2
17420   //   bCC copy1MBB
17421   //   fallthrough --> copy0MBB
17422   MachineBasicBlock *thisMBB = BB;
17423   MachineFunction *F = BB->getParent();
17424   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17425   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17426   F->insert(It, copy0MBB);
17427   F->insert(It, sinkMBB);
17428
17429   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17430   // live into the sink and copy blocks.
17431   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17432   if (!MI->killsRegister(X86::EFLAGS) &&
17433       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17434     copy0MBB->addLiveIn(X86::EFLAGS);
17435     sinkMBB->addLiveIn(X86::EFLAGS);
17436   }
17437
17438   // Transfer the remainder of BB and its successor edges to sinkMBB.
17439   sinkMBB->splice(sinkMBB->begin(), BB,
17440                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17441   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17442
17443   // Add the true and fallthrough blocks as its successors.
17444   BB->addSuccessor(copy0MBB);
17445   BB->addSuccessor(sinkMBB);
17446
17447   // Create the conditional branch instruction.
17448   unsigned Opc =
17449     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17450   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17451
17452   //  copy0MBB:
17453   //   %FalseValue = ...
17454   //   # fallthrough to sinkMBB
17455   copy0MBB->addSuccessor(sinkMBB);
17456
17457   //  sinkMBB:
17458   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17459   //  ...
17460   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17461           TII->get(X86::PHI), MI->getOperand(0).getReg())
17462     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17463     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17464
17465   MI->eraseFromParent();   // The pseudo instruction is gone now.
17466   return sinkMBB;
17467 }
17468
17469 MachineBasicBlock *
17470 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17471                                         bool Is64Bit) const {
17472   MachineFunction *MF = BB->getParent();
17473   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17474   DebugLoc DL = MI->getDebugLoc();
17475   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17476
17477   assert(MF->shouldSplitStack());
17478
17479   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17480   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17481
17482   // BB:
17483   //  ... [Till the alloca]
17484   // If stacklet is not large enough, jump to mallocMBB
17485   //
17486   // bumpMBB:
17487   //  Allocate by subtracting from RSP
17488   //  Jump to continueMBB
17489   //
17490   // mallocMBB:
17491   //  Allocate by call to runtime
17492   //
17493   // continueMBB:
17494   //  ...
17495   //  [rest of original BB]
17496   //
17497
17498   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17499   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17500   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17501
17502   MachineRegisterInfo &MRI = MF->getRegInfo();
17503   const TargetRegisterClass *AddrRegClass =
17504     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17505
17506   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17507     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17508     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17509     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17510     sizeVReg = MI->getOperand(1).getReg(),
17511     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17512
17513   MachineFunction::iterator MBBIter = BB;
17514   ++MBBIter;
17515
17516   MF->insert(MBBIter, bumpMBB);
17517   MF->insert(MBBIter, mallocMBB);
17518   MF->insert(MBBIter, continueMBB);
17519
17520   continueMBB->splice(continueMBB->begin(), BB,
17521                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17522   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17523
17524   // Add code to the main basic block to check if the stack limit has been hit,
17525   // and if so, jump to mallocMBB otherwise to bumpMBB.
17526   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17527   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17528     .addReg(tmpSPVReg).addReg(sizeVReg);
17529   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17530     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17531     .addReg(SPLimitVReg);
17532   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17533
17534   // bumpMBB simply decreases the stack pointer, since we know the current
17535   // stacklet has enough space.
17536   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17537     .addReg(SPLimitVReg);
17538   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17539     .addReg(SPLimitVReg);
17540   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17541
17542   // Calls into a routine in libgcc to allocate more space from the heap.
17543   const uint32_t *RegMask =
17544     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17545   if (Is64Bit) {
17546     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17547       .addReg(sizeVReg);
17548     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17549       .addExternalSymbol("__morestack_allocate_stack_space")
17550       .addRegMask(RegMask)
17551       .addReg(X86::RDI, RegState::Implicit)
17552       .addReg(X86::RAX, RegState::ImplicitDefine);
17553   } else {
17554     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17555       .addImm(12);
17556     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17557     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17558       .addExternalSymbol("__morestack_allocate_stack_space")
17559       .addRegMask(RegMask)
17560       .addReg(X86::EAX, RegState::ImplicitDefine);
17561   }
17562
17563   if (!Is64Bit)
17564     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17565       .addImm(16);
17566
17567   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17568     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17569   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17570
17571   // Set up the CFG correctly.
17572   BB->addSuccessor(bumpMBB);
17573   BB->addSuccessor(mallocMBB);
17574   mallocMBB->addSuccessor(continueMBB);
17575   bumpMBB->addSuccessor(continueMBB);
17576
17577   // Take care of the PHI nodes.
17578   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17579           MI->getOperand(0).getReg())
17580     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17581     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17582
17583   // Delete the original pseudo instruction.
17584   MI->eraseFromParent();
17585
17586   // And we're done.
17587   return continueMBB;
17588 }
17589
17590 MachineBasicBlock *
17591 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17592                                         MachineBasicBlock *BB) const {
17593   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17594   DebugLoc DL = MI->getDebugLoc();
17595
17596   assert(!Subtarget->isTargetMacho());
17597
17598   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17599   // non-trivial part is impdef of ESP.
17600
17601   if (Subtarget->isTargetWin64()) {
17602     if (Subtarget->isTargetCygMing()) {
17603       // ___chkstk(Mingw64):
17604       // Clobbers R10, R11, RAX and EFLAGS.
17605       // Updates RSP.
17606       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17607         .addExternalSymbol("___chkstk")
17608         .addReg(X86::RAX, RegState::Implicit)
17609         .addReg(X86::RSP, RegState::Implicit)
17610         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17611         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17612         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17613     } else {
17614       // __chkstk(MSVCRT): does not update stack pointer.
17615       // Clobbers R10, R11 and EFLAGS.
17616       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17617         .addExternalSymbol("__chkstk")
17618         .addReg(X86::RAX, RegState::Implicit)
17619         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17620       // RAX has the offset to be subtracted from RSP.
17621       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17622         .addReg(X86::RSP)
17623         .addReg(X86::RAX);
17624     }
17625   } else {
17626     const char *StackProbeSymbol =
17627       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17628
17629     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17630       .addExternalSymbol(StackProbeSymbol)
17631       .addReg(X86::EAX, RegState::Implicit)
17632       .addReg(X86::ESP, RegState::Implicit)
17633       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17634       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17635       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17636   }
17637
17638   MI->eraseFromParent();   // The pseudo instruction is gone now.
17639   return BB;
17640 }
17641
17642 MachineBasicBlock *
17643 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17644                                       MachineBasicBlock *BB) const {
17645   // This is pretty easy.  We're taking the value that we received from
17646   // our load from the relocation, sticking it in either RDI (x86-64)
17647   // or EAX and doing an indirect call.  The return value will then
17648   // be in the normal return register.
17649   MachineFunction *F = BB->getParent();
17650   const X86InstrInfo *TII
17651     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17652   DebugLoc DL = MI->getDebugLoc();
17653
17654   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17655   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17656
17657   // Get a register mask for the lowered call.
17658   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17659   // proper register mask.
17660   const uint32_t *RegMask =
17661     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17662   if (Subtarget->is64Bit()) {
17663     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17664                                       TII->get(X86::MOV64rm), X86::RDI)
17665     .addReg(X86::RIP)
17666     .addImm(0).addReg(0)
17667     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17668                       MI->getOperand(3).getTargetFlags())
17669     .addReg(0);
17670     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17671     addDirectMem(MIB, X86::RDI);
17672     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17673   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17674     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17675                                       TII->get(X86::MOV32rm), X86::EAX)
17676     .addReg(0)
17677     .addImm(0).addReg(0)
17678     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17679                       MI->getOperand(3).getTargetFlags())
17680     .addReg(0);
17681     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17682     addDirectMem(MIB, X86::EAX);
17683     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17684   } else {
17685     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17686                                       TII->get(X86::MOV32rm), X86::EAX)
17687     .addReg(TII->getGlobalBaseReg(F))
17688     .addImm(0).addReg(0)
17689     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17690                       MI->getOperand(3).getTargetFlags())
17691     .addReg(0);
17692     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17693     addDirectMem(MIB, X86::EAX);
17694     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17695   }
17696
17697   MI->eraseFromParent(); // The pseudo instruction is gone now.
17698   return BB;
17699 }
17700
17701 MachineBasicBlock *
17702 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17703                                     MachineBasicBlock *MBB) const {
17704   DebugLoc DL = MI->getDebugLoc();
17705   MachineFunction *MF = MBB->getParent();
17706   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17707   MachineRegisterInfo &MRI = MF->getRegInfo();
17708
17709   const BasicBlock *BB = MBB->getBasicBlock();
17710   MachineFunction::iterator I = MBB;
17711   ++I;
17712
17713   // Memory Reference
17714   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17715   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17716
17717   unsigned DstReg;
17718   unsigned MemOpndSlot = 0;
17719
17720   unsigned CurOp = 0;
17721
17722   DstReg = MI->getOperand(CurOp++).getReg();
17723   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17724   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17725   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17726   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17727
17728   MemOpndSlot = CurOp;
17729
17730   MVT PVT = getPointerTy();
17731   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17732          "Invalid Pointer Size!");
17733
17734   // For v = setjmp(buf), we generate
17735   //
17736   // thisMBB:
17737   //  buf[LabelOffset] = restoreMBB
17738   //  SjLjSetup restoreMBB
17739   //
17740   // mainMBB:
17741   //  v_main = 0
17742   //
17743   // sinkMBB:
17744   //  v = phi(main, restore)
17745   //
17746   // restoreMBB:
17747   //  v_restore = 1
17748
17749   MachineBasicBlock *thisMBB = MBB;
17750   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17751   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17752   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17753   MF->insert(I, mainMBB);
17754   MF->insert(I, sinkMBB);
17755   MF->push_back(restoreMBB);
17756
17757   MachineInstrBuilder MIB;
17758
17759   // Transfer the remainder of BB and its successor edges to sinkMBB.
17760   sinkMBB->splice(sinkMBB->begin(), MBB,
17761                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17762   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17763
17764   // thisMBB:
17765   unsigned PtrStoreOpc = 0;
17766   unsigned LabelReg = 0;
17767   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17768   Reloc::Model RM = MF->getTarget().getRelocationModel();
17769   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17770                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17771
17772   // Prepare IP either in reg or imm.
17773   if (!UseImmLabel) {
17774     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17775     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17776     LabelReg = MRI.createVirtualRegister(PtrRC);
17777     if (Subtarget->is64Bit()) {
17778       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17779               .addReg(X86::RIP)
17780               .addImm(0)
17781               .addReg(0)
17782               .addMBB(restoreMBB)
17783               .addReg(0);
17784     } else {
17785       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17786       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17787               .addReg(XII->getGlobalBaseReg(MF))
17788               .addImm(0)
17789               .addReg(0)
17790               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17791               .addReg(0);
17792     }
17793   } else
17794     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17795   // Store IP
17796   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17797   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17798     if (i == X86::AddrDisp)
17799       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17800     else
17801       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17802   }
17803   if (!UseImmLabel)
17804     MIB.addReg(LabelReg);
17805   else
17806     MIB.addMBB(restoreMBB);
17807   MIB.setMemRefs(MMOBegin, MMOEnd);
17808   // Setup
17809   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17810           .addMBB(restoreMBB);
17811
17812   const X86RegisterInfo *RegInfo =
17813     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17814   MIB.addRegMask(RegInfo->getNoPreservedMask());
17815   thisMBB->addSuccessor(mainMBB);
17816   thisMBB->addSuccessor(restoreMBB);
17817
17818   // mainMBB:
17819   //  EAX = 0
17820   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17821   mainMBB->addSuccessor(sinkMBB);
17822
17823   // sinkMBB:
17824   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17825           TII->get(X86::PHI), DstReg)
17826     .addReg(mainDstReg).addMBB(mainMBB)
17827     .addReg(restoreDstReg).addMBB(restoreMBB);
17828
17829   // restoreMBB:
17830   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17831   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17832   restoreMBB->addSuccessor(sinkMBB);
17833
17834   MI->eraseFromParent();
17835   return sinkMBB;
17836 }
17837
17838 MachineBasicBlock *
17839 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17840                                      MachineBasicBlock *MBB) const {
17841   DebugLoc DL = MI->getDebugLoc();
17842   MachineFunction *MF = MBB->getParent();
17843   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17844   MachineRegisterInfo &MRI = MF->getRegInfo();
17845
17846   // Memory Reference
17847   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17848   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17849
17850   MVT PVT = getPointerTy();
17851   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17852          "Invalid Pointer Size!");
17853
17854   const TargetRegisterClass *RC =
17855     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17856   unsigned Tmp = MRI.createVirtualRegister(RC);
17857   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17858   const X86RegisterInfo *RegInfo =
17859     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17860   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17861   unsigned SP = RegInfo->getStackRegister();
17862
17863   MachineInstrBuilder MIB;
17864
17865   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17866   const int64_t SPOffset = 2 * PVT.getStoreSize();
17867
17868   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17869   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17870
17871   // Reload FP
17872   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17873   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17874     MIB.addOperand(MI->getOperand(i));
17875   MIB.setMemRefs(MMOBegin, MMOEnd);
17876   // Reload IP
17877   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17878   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17879     if (i == X86::AddrDisp)
17880       MIB.addDisp(MI->getOperand(i), LabelOffset);
17881     else
17882       MIB.addOperand(MI->getOperand(i));
17883   }
17884   MIB.setMemRefs(MMOBegin, MMOEnd);
17885   // Reload SP
17886   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17887   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17888     if (i == X86::AddrDisp)
17889       MIB.addDisp(MI->getOperand(i), SPOffset);
17890     else
17891       MIB.addOperand(MI->getOperand(i));
17892   }
17893   MIB.setMemRefs(MMOBegin, MMOEnd);
17894   // Jump
17895   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17896
17897   MI->eraseFromParent();
17898   return MBB;
17899 }
17900
17901 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17902 // accumulator loops. Writing back to the accumulator allows the coalescer
17903 // to remove extra copies in the loop.   
17904 MachineBasicBlock *
17905 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17906                                  MachineBasicBlock *MBB) const {
17907   MachineOperand &AddendOp = MI->getOperand(3);
17908
17909   // Bail out early if the addend isn't a register - we can't switch these.
17910   if (!AddendOp.isReg())
17911     return MBB;
17912
17913   MachineFunction &MF = *MBB->getParent();
17914   MachineRegisterInfo &MRI = MF.getRegInfo();
17915
17916   // Check whether the addend is defined by a PHI:
17917   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17918   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17919   if (!AddendDef.isPHI())
17920     return MBB;
17921
17922   // Look for the following pattern:
17923   // loop:
17924   //   %addend = phi [%entry, 0], [%loop, %result]
17925   //   ...
17926   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17927
17928   // Replace with:
17929   //   loop:
17930   //   %addend = phi [%entry, 0], [%loop, %result]
17931   //   ...
17932   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17933
17934   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17935     assert(AddendDef.getOperand(i).isReg());
17936     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17937     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17938     if (&PHISrcInst == MI) {
17939       // Found a matching instruction.
17940       unsigned NewFMAOpc = 0;
17941       switch (MI->getOpcode()) {
17942         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17943         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17944         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17945         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17946         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17947         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17948         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17949         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17950         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17951         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17952         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17953         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17954         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17955         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17956         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17957         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17958         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17959         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17960         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17961         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17962         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17963         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17964         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17965         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17966         default: llvm_unreachable("Unrecognized FMA variant.");
17967       }
17968
17969       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17970       MachineInstrBuilder MIB =
17971         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17972         .addOperand(MI->getOperand(0))
17973         .addOperand(MI->getOperand(3))
17974         .addOperand(MI->getOperand(2))
17975         .addOperand(MI->getOperand(1));
17976       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17977       MI->eraseFromParent();
17978     }
17979   }
17980
17981   return MBB;
17982 }
17983
17984 MachineBasicBlock *
17985 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17986                                                MachineBasicBlock *BB) const {
17987   switch (MI->getOpcode()) {
17988   default: llvm_unreachable("Unexpected instr type to insert");
17989   case X86::TAILJMPd64:
17990   case X86::TAILJMPr64:
17991   case X86::TAILJMPm64:
17992     llvm_unreachable("TAILJMP64 would not be touched here.");
17993   case X86::TCRETURNdi64:
17994   case X86::TCRETURNri64:
17995   case X86::TCRETURNmi64:
17996     return BB;
17997   case X86::WIN_ALLOCA:
17998     return EmitLoweredWinAlloca(MI, BB);
17999   case X86::SEG_ALLOCA_32:
18000     return EmitLoweredSegAlloca(MI, BB, false);
18001   case X86::SEG_ALLOCA_64:
18002     return EmitLoweredSegAlloca(MI, BB, true);
18003   case X86::TLSCall_32:
18004   case X86::TLSCall_64:
18005     return EmitLoweredTLSCall(MI, BB);
18006   case X86::CMOV_GR8:
18007   case X86::CMOV_FR32:
18008   case X86::CMOV_FR64:
18009   case X86::CMOV_V4F32:
18010   case X86::CMOV_V2F64:
18011   case X86::CMOV_V2I64:
18012   case X86::CMOV_V8F32:
18013   case X86::CMOV_V4F64:
18014   case X86::CMOV_V4I64:
18015   case X86::CMOV_V16F32:
18016   case X86::CMOV_V8F64:
18017   case X86::CMOV_V8I64:
18018   case X86::CMOV_GR16:
18019   case X86::CMOV_GR32:
18020   case X86::CMOV_RFP32:
18021   case X86::CMOV_RFP64:
18022   case X86::CMOV_RFP80:
18023     return EmitLoweredSelect(MI, BB);
18024
18025   case X86::FP32_TO_INT16_IN_MEM:
18026   case X86::FP32_TO_INT32_IN_MEM:
18027   case X86::FP32_TO_INT64_IN_MEM:
18028   case X86::FP64_TO_INT16_IN_MEM:
18029   case X86::FP64_TO_INT32_IN_MEM:
18030   case X86::FP64_TO_INT64_IN_MEM:
18031   case X86::FP80_TO_INT16_IN_MEM:
18032   case X86::FP80_TO_INT32_IN_MEM:
18033   case X86::FP80_TO_INT64_IN_MEM: {
18034     MachineFunction *F = BB->getParent();
18035     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18036     DebugLoc DL = MI->getDebugLoc();
18037
18038     // Change the floating point control register to use "round towards zero"
18039     // mode when truncating to an integer value.
18040     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18041     addFrameReference(BuildMI(*BB, MI, DL,
18042                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18043
18044     // Load the old value of the high byte of the control word...
18045     unsigned OldCW =
18046       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18047     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18048                       CWFrameIdx);
18049
18050     // Set the high part to be round to zero...
18051     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18052       .addImm(0xC7F);
18053
18054     // Reload the modified control word now...
18055     addFrameReference(BuildMI(*BB, MI, DL,
18056                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18057
18058     // Restore the memory image of control word to original value
18059     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18060       .addReg(OldCW);
18061
18062     // Get the X86 opcode to use.
18063     unsigned Opc;
18064     switch (MI->getOpcode()) {
18065     default: llvm_unreachable("illegal opcode!");
18066     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18067     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18068     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18069     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18070     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18071     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18072     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18073     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18074     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18075     }
18076
18077     X86AddressMode AM;
18078     MachineOperand &Op = MI->getOperand(0);
18079     if (Op.isReg()) {
18080       AM.BaseType = X86AddressMode::RegBase;
18081       AM.Base.Reg = Op.getReg();
18082     } else {
18083       AM.BaseType = X86AddressMode::FrameIndexBase;
18084       AM.Base.FrameIndex = Op.getIndex();
18085     }
18086     Op = MI->getOperand(1);
18087     if (Op.isImm())
18088       AM.Scale = Op.getImm();
18089     Op = MI->getOperand(2);
18090     if (Op.isImm())
18091       AM.IndexReg = Op.getImm();
18092     Op = MI->getOperand(3);
18093     if (Op.isGlobal()) {
18094       AM.GV = Op.getGlobal();
18095     } else {
18096       AM.Disp = Op.getImm();
18097     }
18098     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18099                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18100
18101     // Reload the original control word now.
18102     addFrameReference(BuildMI(*BB, MI, DL,
18103                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18104
18105     MI->eraseFromParent();   // The pseudo instruction is gone now.
18106     return BB;
18107   }
18108     // String/text processing lowering.
18109   case X86::PCMPISTRM128REG:
18110   case X86::VPCMPISTRM128REG:
18111   case X86::PCMPISTRM128MEM:
18112   case X86::VPCMPISTRM128MEM:
18113   case X86::PCMPESTRM128REG:
18114   case X86::VPCMPESTRM128REG:
18115   case X86::PCMPESTRM128MEM:
18116   case X86::VPCMPESTRM128MEM:
18117     assert(Subtarget->hasSSE42() &&
18118            "Target must have SSE4.2 or AVX features enabled");
18119     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18120
18121   // String/text processing lowering.
18122   case X86::PCMPISTRIREG:
18123   case X86::VPCMPISTRIREG:
18124   case X86::PCMPISTRIMEM:
18125   case X86::VPCMPISTRIMEM:
18126   case X86::PCMPESTRIREG:
18127   case X86::VPCMPESTRIREG:
18128   case X86::PCMPESTRIMEM:
18129   case X86::VPCMPESTRIMEM:
18130     assert(Subtarget->hasSSE42() &&
18131            "Target must have SSE4.2 or AVX features enabled");
18132     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18133
18134   // Thread synchronization.
18135   case X86::MONITOR:
18136     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18137
18138   // xbegin
18139   case X86::XBEGIN:
18140     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18141
18142   case X86::VASTART_SAVE_XMM_REGS:
18143     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18144
18145   case X86::VAARG_64:
18146     return EmitVAARG64WithCustomInserter(MI, BB);
18147
18148   case X86::EH_SjLj_SetJmp32:
18149   case X86::EH_SjLj_SetJmp64:
18150     return emitEHSjLjSetJmp(MI, BB);
18151
18152   case X86::EH_SjLj_LongJmp32:
18153   case X86::EH_SjLj_LongJmp64:
18154     return emitEHSjLjLongJmp(MI, BB);
18155
18156   case TargetOpcode::STACKMAP:
18157   case TargetOpcode::PATCHPOINT:
18158     return emitPatchPoint(MI, BB);
18159
18160   case X86::VFMADDPDr213r:
18161   case X86::VFMADDPSr213r:
18162   case X86::VFMADDSDr213r:
18163   case X86::VFMADDSSr213r:
18164   case X86::VFMSUBPDr213r:
18165   case X86::VFMSUBPSr213r:
18166   case X86::VFMSUBSDr213r:
18167   case X86::VFMSUBSSr213r:
18168   case X86::VFNMADDPDr213r:
18169   case X86::VFNMADDPSr213r:
18170   case X86::VFNMADDSDr213r:
18171   case X86::VFNMADDSSr213r:
18172   case X86::VFNMSUBPDr213r:
18173   case X86::VFNMSUBPSr213r:
18174   case X86::VFNMSUBSDr213r:
18175   case X86::VFNMSUBSSr213r:
18176   case X86::VFMADDPDr213rY:
18177   case X86::VFMADDPSr213rY:
18178   case X86::VFMSUBPDr213rY:
18179   case X86::VFMSUBPSr213rY:
18180   case X86::VFNMADDPDr213rY:
18181   case X86::VFNMADDPSr213rY:
18182   case X86::VFNMSUBPDr213rY:
18183   case X86::VFNMSUBPSr213rY:
18184     return emitFMA3Instr(MI, BB);
18185   }
18186 }
18187
18188 //===----------------------------------------------------------------------===//
18189 //                           X86 Optimization Hooks
18190 //===----------------------------------------------------------------------===//
18191
18192 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18193                                                       APInt &KnownZero,
18194                                                       APInt &KnownOne,
18195                                                       const SelectionDAG &DAG,
18196                                                       unsigned Depth) const {
18197   unsigned BitWidth = KnownZero.getBitWidth();
18198   unsigned Opc = Op.getOpcode();
18199   assert((Opc >= ISD::BUILTIN_OP_END ||
18200           Opc == ISD::INTRINSIC_WO_CHAIN ||
18201           Opc == ISD::INTRINSIC_W_CHAIN ||
18202           Opc == ISD::INTRINSIC_VOID) &&
18203          "Should use MaskedValueIsZero if you don't know whether Op"
18204          " is a target node!");
18205
18206   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18207   switch (Opc) {
18208   default: break;
18209   case X86ISD::ADD:
18210   case X86ISD::SUB:
18211   case X86ISD::ADC:
18212   case X86ISD::SBB:
18213   case X86ISD::SMUL:
18214   case X86ISD::UMUL:
18215   case X86ISD::INC:
18216   case X86ISD::DEC:
18217   case X86ISD::OR:
18218   case X86ISD::XOR:
18219   case X86ISD::AND:
18220     // These nodes' second result is a boolean.
18221     if (Op.getResNo() == 0)
18222       break;
18223     // Fallthrough
18224   case X86ISD::SETCC:
18225     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18226     break;
18227   case ISD::INTRINSIC_WO_CHAIN: {
18228     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18229     unsigned NumLoBits = 0;
18230     switch (IntId) {
18231     default: break;
18232     case Intrinsic::x86_sse_movmsk_ps:
18233     case Intrinsic::x86_avx_movmsk_ps_256:
18234     case Intrinsic::x86_sse2_movmsk_pd:
18235     case Intrinsic::x86_avx_movmsk_pd_256:
18236     case Intrinsic::x86_mmx_pmovmskb:
18237     case Intrinsic::x86_sse2_pmovmskb_128:
18238     case Intrinsic::x86_avx2_pmovmskb: {
18239       // High bits of movmskp{s|d}, pmovmskb are known zero.
18240       switch (IntId) {
18241         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18242         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18243         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18244         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18245         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18246         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18247         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18248         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18249       }
18250       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18251       break;
18252     }
18253     }
18254     break;
18255   }
18256   }
18257 }
18258
18259 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18260   SDValue Op,
18261   const SelectionDAG &,
18262   unsigned Depth) const {
18263   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18264   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18265     return Op.getValueType().getScalarType().getSizeInBits();
18266
18267   // Fallback case.
18268   return 1;
18269 }
18270
18271 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18272 /// node is a GlobalAddress + offset.
18273 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18274                                        const GlobalValue* &GA,
18275                                        int64_t &Offset) const {
18276   if (N->getOpcode() == X86ISD::Wrapper) {
18277     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18278       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18279       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18280       return true;
18281     }
18282   }
18283   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18284 }
18285
18286 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18287 /// same as extracting the high 128-bit part of 256-bit vector and then
18288 /// inserting the result into the low part of a new 256-bit vector
18289 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18290   EVT VT = SVOp->getValueType(0);
18291   unsigned NumElems = VT.getVectorNumElements();
18292
18293   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18294   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18295     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18296         SVOp->getMaskElt(j) >= 0)
18297       return false;
18298
18299   return true;
18300 }
18301
18302 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18303 /// same as extracting the low 128-bit part of 256-bit vector and then
18304 /// inserting the result into the high part of a new 256-bit vector
18305 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18306   EVT VT = SVOp->getValueType(0);
18307   unsigned NumElems = VT.getVectorNumElements();
18308
18309   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18310   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18311     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18312         SVOp->getMaskElt(j) >= 0)
18313       return false;
18314
18315   return true;
18316 }
18317
18318 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18319 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18320                                         TargetLowering::DAGCombinerInfo &DCI,
18321                                         const X86Subtarget* Subtarget) {
18322   SDLoc dl(N);
18323   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18324   SDValue V1 = SVOp->getOperand(0);
18325   SDValue V2 = SVOp->getOperand(1);
18326   EVT VT = SVOp->getValueType(0);
18327   unsigned NumElems = VT.getVectorNumElements();
18328
18329   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18330       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18331     //
18332     //                   0,0,0,...
18333     //                      |
18334     //    V      UNDEF    BUILD_VECTOR    UNDEF
18335     //     \      /           \           /
18336     //  CONCAT_VECTOR         CONCAT_VECTOR
18337     //         \                  /
18338     //          \                /
18339     //          RESULT: V + zero extended
18340     //
18341     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18342         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18343         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18344       return SDValue();
18345
18346     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18347       return SDValue();
18348
18349     // To match the shuffle mask, the first half of the mask should
18350     // be exactly the first vector, and all the rest a splat with the
18351     // first element of the second one.
18352     for (unsigned i = 0; i != NumElems/2; ++i)
18353       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18354           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18355         return SDValue();
18356
18357     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18358     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18359       if (Ld->hasNUsesOfValue(1, 0)) {
18360         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18361         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18362         SDValue ResNode =
18363           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18364                                   Ld->getMemoryVT(),
18365                                   Ld->getPointerInfo(),
18366                                   Ld->getAlignment(),
18367                                   false/*isVolatile*/, true/*ReadMem*/,
18368                                   false/*WriteMem*/);
18369
18370         // Make sure the newly-created LOAD is in the same position as Ld in
18371         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18372         // and update uses of Ld's output chain to use the TokenFactor.
18373         if (Ld->hasAnyUseOfValue(1)) {
18374           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18375                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18376           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18377           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18378                                  SDValue(ResNode.getNode(), 1));
18379         }
18380
18381         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18382       }
18383     }
18384
18385     // Emit a zeroed vector and insert the desired subvector on its
18386     // first half.
18387     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18388     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18389     return DCI.CombineTo(N, InsV);
18390   }
18391
18392   //===--------------------------------------------------------------------===//
18393   // Combine some shuffles into subvector extracts and inserts:
18394   //
18395
18396   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18397   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18398     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18399     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18400     return DCI.CombineTo(N, InsV);
18401   }
18402
18403   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18404   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18405     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18406     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18407     return DCI.CombineTo(N, InsV);
18408   }
18409
18410   return SDValue();
18411 }
18412
18413 /// \brief Get the PSHUF-style mask from PSHUF node.
18414 ///
18415 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18416 /// PSHUF-style masks that can be reused with such instructions.
18417 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18418   SmallVector<int, 4> Mask;
18419   bool IsUnary;
18420   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18421   (void)HaveMask;
18422   assert(HaveMask);
18423
18424   switch (N.getOpcode()) {
18425   case X86ISD::PSHUFD:
18426     return Mask;
18427   case X86ISD::PSHUFLW:
18428     Mask.resize(4);
18429     return Mask;
18430   case X86ISD::PSHUFHW:
18431     Mask.erase(Mask.begin(), Mask.begin() + 4);
18432     for (int &M : Mask)
18433       M -= 4;
18434     return Mask;
18435   default:
18436     llvm_unreachable("No valid shuffle instruction found!");
18437   }
18438 }
18439
18440 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18441 ///
18442 /// We walk up the chain and look for a combinable shuffle, skipping over
18443 /// shuffles that we could hoist this shuffle's transformation past without
18444 /// altering anything.
18445 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18446                                          SelectionDAG &DAG,
18447                                          TargetLowering::DAGCombinerInfo &DCI) {
18448   assert(N.getOpcode() == X86ISD::PSHUFD &&
18449          "Called with something other than an x86 128-bit half shuffle!");
18450   SDLoc DL(N);
18451
18452   // Walk up a single-use chain looking for a combinable shuffle.
18453   SDValue V = N.getOperand(0);
18454   for (; V.hasOneUse(); V = V.getOperand(0)) {
18455     switch (V.getOpcode()) {
18456     default:
18457       return false; // Nothing combined!
18458
18459     case ISD::BITCAST:
18460       // Skip bitcasts as we always know the type for the target specific
18461       // instructions.
18462       continue;
18463
18464     case X86ISD::PSHUFD:
18465       // Found another dword shuffle.
18466       break;
18467
18468     case X86ISD::PSHUFLW:
18469       // Check that the low words (being shuffled) are the identity in the
18470       // dword shuffle, and the high words are self-contained.
18471       if (Mask[0] != 0 || Mask[1] != 1 ||
18472           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18473         return false;
18474
18475       continue;
18476
18477     case X86ISD::PSHUFHW:
18478       // Check that the high words (being shuffled) are the identity in the
18479       // dword shuffle, and the low words are self-contained.
18480       if (Mask[2] != 2 || Mask[3] != 3 ||
18481           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18482         return false;
18483
18484       continue;
18485     }
18486     // Break out of the loop if we break out of the switch.
18487     break;
18488   }
18489
18490   if (!V.hasOneUse())
18491     // We fell out of the loop without finding a viable combining instruction.
18492     return false;
18493
18494   // Record the old value to use in RAUW-ing.
18495   SDValue Old = V;
18496
18497   // Merge this node's mask and our incoming mask.
18498   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18499   for (int &M : Mask)
18500     M = VMask[M];
18501   V = DAG.getNode(X86ISD::PSHUFD, DL, V.getValueType(), V.getOperand(0),
18502                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18503
18504   // It is possible that one of the combinable shuffles was completely absorbed
18505   // by the other, just replace it and revisit all users in that case.
18506   if (Old.getNode() == V.getNode()) {
18507     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18508     return true;
18509   }
18510
18511   // Replace N with its operand as we're going to combine that shuffle away.
18512   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18513
18514   // Replace the combinable shuffle with the combined one, updating all users
18515   // so that we re-evaluate the chain here.
18516   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18517   return true;
18518 }
18519
18520 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18521 ///
18522 /// We walk up the chain, skipping shuffles of the other half and looking
18523 /// through shuffles which switch halves trying to find a shuffle of the same
18524 /// pair of dwords.
18525 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18526                                         SelectionDAG &DAG,
18527                                         TargetLowering::DAGCombinerInfo &DCI) {
18528   assert(
18529       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18530       "Called with something other than an x86 128-bit half shuffle!");
18531   SDLoc DL(N);
18532   unsigned CombineOpcode = N.getOpcode();
18533
18534   // Walk up a single-use chain looking for a combinable shuffle.
18535   SDValue V = N.getOperand(0);
18536   for (; V.hasOneUse(); V = V.getOperand(0)) {
18537     switch (V.getOpcode()) {
18538     default:
18539       return false; // Nothing combined!
18540
18541     case ISD::BITCAST:
18542       // Skip bitcasts as we always know the type for the target specific
18543       // instructions.
18544       continue;
18545
18546     case X86ISD::PSHUFLW:
18547     case X86ISD::PSHUFHW:
18548       if (V.getOpcode() == CombineOpcode)
18549         break;
18550
18551       // Other-half shuffles are no-ops.
18552       continue;
18553
18554     case X86ISD::PSHUFD: {
18555       // We can only handle pshufd if the half we are combining either stays in
18556       // its half, or switches to the other half. Bail if one of these isn't
18557       // true.
18558       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18559       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18560       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18561             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18562         return false;
18563
18564       // Map the mask through the pshufd and keep walking up the chain.
18565       for (int i = 0; i < 4; ++i)
18566         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18567
18568       // Switch halves if the pshufd does.
18569       CombineOpcode =
18570           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18571       continue;
18572     }
18573     }
18574     // Break out of the loop if we break out of the switch.
18575     break;
18576   }
18577
18578   if (!V.hasOneUse())
18579     // We fell out of the loop without finding a viable combining instruction.
18580     return false;
18581
18582   // Record the old value to use in RAUW-ing.
18583   SDValue Old = V;
18584
18585   // Merge this node's mask and our incoming mask (adjusted to account for all
18586   // the pshufd instructions encountered).
18587   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18588   for (int &M : Mask)
18589     M = VMask[M];
18590   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18591                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18592
18593   // Replace N with its operand as we're going to combine that shuffle away.
18594   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18595
18596   // Replace the combinable shuffle with the combined one, updating all users
18597   // so that we re-evaluate the chain here.
18598   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18599   return true;
18600 }
18601
18602 /// \brief Try to combine x86 target specific shuffles.
18603 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18604                                            TargetLowering::DAGCombinerInfo &DCI,
18605                                            const X86Subtarget *Subtarget) {
18606   SDLoc DL(N);
18607   MVT VT = N.getSimpleValueType();
18608   SmallVector<int, 4> Mask;
18609
18610   switch (N.getOpcode()) {
18611   case X86ISD::PSHUFD:
18612   case X86ISD::PSHUFLW:
18613   case X86ISD::PSHUFHW:
18614     Mask = getPSHUFShuffleMask(N);
18615     assert(Mask.size() == 4);
18616     break;
18617   default:
18618     return SDValue();
18619   }
18620
18621   // Nuke no-op shuffles that show up after combining.
18622   if (isNoopShuffleMask(Mask))
18623     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18624
18625   // Look for simplifications involving one or two shuffle instructions.
18626   SDValue V = N.getOperand(0);
18627   switch (N.getOpcode()) {
18628   default:
18629     break;
18630   case X86ISD::PSHUFLW:
18631   case X86ISD::PSHUFHW:
18632     assert(VT == MVT::v8i16);
18633     (void)VT;
18634
18635     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18636       return SDValue(); // We combined away this shuffle, so we're done.
18637
18638     // See if this reduces to a PSHUFD which is no more expensive and can
18639     // combine with more operations.
18640     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18641         areAdjacentMasksSequential(Mask)) {
18642       int DMask[] = {-1, -1, -1, -1};
18643       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18644       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18645       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18646       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18647       DCI.AddToWorklist(V.getNode());
18648       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18649                       getV4X86ShuffleImm8ForMask(DMask, DAG));
18650       DCI.AddToWorklist(V.getNode());
18651       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18652     }
18653
18654     break;
18655
18656   case X86ISD::PSHUFD:
18657     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18658       return SDValue(); // We combined away this shuffle.
18659
18660     break;
18661   }
18662
18663   return SDValue();
18664 }
18665
18666 /// PerformShuffleCombine - Performs several different shuffle combines.
18667 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18668                                      TargetLowering::DAGCombinerInfo &DCI,
18669                                      const X86Subtarget *Subtarget) {
18670   SDLoc dl(N);
18671   SDValue N0 = N->getOperand(0);
18672   SDValue N1 = N->getOperand(1);
18673   EVT VT = N->getValueType(0);
18674
18675   // Canonicalize shuffles that perform 'addsub' on packed float vectors
18676   // according to the rule:
18677   //  (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18678   //  (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18679   //
18680   // Where 'Mask' is:
18681   //  <0,5,2,7>             -- for v4f32 and v4f64 shuffles;
18682   //  <0,3>                 -- for v2f64 shuffles;
18683   //  <0,9,2,11,4,13,6,15>  -- for v8f32 shuffles.
18684   //
18685   // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18686   // during ISel stage.
18687   if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18688       ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18689        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18690       N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18691       // Operands to the FADD and FSUB must be the same.
18692       ((N0->getOperand(0) == N1->getOperand(0) &&
18693         N0->getOperand(1) == N1->getOperand(1)) ||
18694        // FADD is commutable. See if by commuting the operands of the FADD
18695        // we would still be able to match the operands of the FSUB dag node.
18696        (N0->getOperand(1) == N1->getOperand(0) &&
18697         N0->getOperand(0) == N1->getOperand(1))) &&
18698       N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18699       N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18700     
18701     ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18702     unsigned NumElts = VT.getVectorNumElements();
18703     ArrayRef<int> Mask = SV->getMask();
18704     bool CanFold = true;
18705
18706     for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18707       CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18708
18709     if (CanFold) {
18710       SDValue Op0 = N1->getOperand(0);
18711       SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18712       SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18713       SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18714       return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18715     }
18716   }
18717
18718   // Don't create instructions with illegal types after legalize types has run.
18719   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18720   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18721     return SDValue();
18722
18723   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18724   if (Subtarget->hasFp256() && VT.is256BitVector() &&
18725       N->getOpcode() == ISD::VECTOR_SHUFFLE)
18726     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18727
18728   // During Type Legalization, when promoting illegal vector types,
18729   // the backend might introduce new shuffle dag nodes and bitcasts.
18730   //
18731   // This code performs the following transformation:
18732   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18733   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18734   //
18735   // We do this only if both the bitcast and the BINOP dag nodes have
18736   // one use. Also, perform this transformation only if the new binary
18737   // operation is legal. This is to avoid introducing dag nodes that
18738   // potentially need to be further expanded (or custom lowered) into a
18739   // less optimal sequence of dag nodes.
18740   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18741       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18742       N0.getOpcode() == ISD::BITCAST) {
18743     SDValue BC0 = N0.getOperand(0);
18744     EVT SVT = BC0.getValueType();
18745     unsigned Opcode = BC0.getOpcode();
18746     unsigned NumElts = VT.getVectorNumElements();
18747     
18748     if (BC0.hasOneUse() && SVT.isVector() &&
18749         SVT.getVectorNumElements() * 2 == NumElts &&
18750         TLI.isOperationLegal(Opcode, VT)) {
18751       bool CanFold = false;
18752       switch (Opcode) {
18753       default : break;
18754       case ISD::ADD :
18755       case ISD::FADD :
18756       case ISD::SUB :
18757       case ISD::FSUB :
18758       case ISD::MUL :
18759       case ISD::FMUL :
18760         CanFold = true;
18761       }
18762
18763       unsigned SVTNumElts = SVT.getVectorNumElements();
18764       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18765       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18766         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18767       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18768         CanFold = SVOp->getMaskElt(i) < 0;
18769
18770       if (CanFold) {
18771         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18772         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18773         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18774         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18775       }
18776     }
18777   }
18778
18779   // Only handle 128 wide vector from here on.
18780   if (!VT.is128BitVector())
18781     return SDValue();
18782
18783   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18784   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18785   // consecutive, non-overlapping, and in the right order.
18786   SmallVector<SDValue, 16> Elts;
18787   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18788     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18789
18790   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18791   if (LD.getNode())
18792     return LD;
18793
18794   if (isTargetShuffle(N->getOpcode())) {
18795     SDValue Shuffle =
18796         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18797     if (Shuffle.getNode())
18798       return Shuffle;
18799   }
18800
18801   return SDValue();
18802 }
18803
18804 /// PerformTruncateCombine - Converts truncate operation to
18805 /// a sequence of vector shuffle operations.
18806 /// It is possible when we truncate 256-bit vector to 128-bit vector
18807 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18808                                       TargetLowering::DAGCombinerInfo &DCI,
18809                                       const X86Subtarget *Subtarget)  {
18810   return SDValue();
18811 }
18812
18813 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18814 /// specific shuffle of a load can be folded into a single element load.
18815 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18816 /// shuffles have been customed lowered so we need to handle those here.
18817 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18818                                          TargetLowering::DAGCombinerInfo &DCI) {
18819   if (DCI.isBeforeLegalizeOps())
18820     return SDValue();
18821
18822   SDValue InVec = N->getOperand(0);
18823   SDValue EltNo = N->getOperand(1);
18824
18825   if (!isa<ConstantSDNode>(EltNo))
18826     return SDValue();
18827
18828   EVT VT = InVec.getValueType();
18829
18830   bool HasShuffleIntoBitcast = false;
18831   if (InVec.getOpcode() == ISD::BITCAST) {
18832     // Don't duplicate a load with other uses.
18833     if (!InVec.hasOneUse())
18834       return SDValue();
18835     EVT BCVT = InVec.getOperand(0).getValueType();
18836     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18837       return SDValue();
18838     InVec = InVec.getOperand(0);
18839     HasShuffleIntoBitcast = true;
18840   }
18841
18842   if (!isTargetShuffle(InVec.getOpcode()))
18843     return SDValue();
18844
18845   // Don't duplicate a load with other uses.
18846   if (!InVec.hasOneUse())
18847     return SDValue();
18848
18849   SmallVector<int, 16> ShuffleMask;
18850   bool UnaryShuffle;
18851   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18852                             UnaryShuffle))
18853     return SDValue();
18854
18855   // Select the input vector, guarding against out of range extract vector.
18856   unsigned NumElems = VT.getVectorNumElements();
18857   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18858   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18859   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18860                                          : InVec.getOperand(1);
18861
18862   // If inputs to shuffle are the same for both ops, then allow 2 uses
18863   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18864
18865   if (LdNode.getOpcode() == ISD::BITCAST) {
18866     // Don't duplicate a load with other uses.
18867     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18868       return SDValue();
18869
18870     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18871     LdNode = LdNode.getOperand(0);
18872   }
18873
18874   if (!ISD::isNormalLoad(LdNode.getNode()))
18875     return SDValue();
18876
18877   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18878
18879   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18880     return SDValue();
18881
18882   if (HasShuffleIntoBitcast) {
18883     // If there's a bitcast before the shuffle, check if the load type and
18884     // alignment is valid.
18885     unsigned Align = LN0->getAlignment();
18886     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18887     unsigned NewAlign = TLI.getDataLayout()->
18888       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18889
18890     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18891       return SDValue();
18892   }
18893
18894   // All checks match so transform back to vector_shuffle so that DAG combiner
18895   // can finish the job
18896   SDLoc dl(N);
18897
18898   // Create shuffle node taking into account the case that its a unary shuffle
18899   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18900   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18901                                  InVec.getOperand(0), Shuffle,
18902                                  &ShuffleMask[0]);
18903   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18904   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18905                      EltNo);
18906 }
18907
18908 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18909 /// generation and convert it from being a bunch of shuffles and extracts
18910 /// to a simple store and scalar loads to extract the elements.
18911 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18912                                          TargetLowering::DAGCombinerInfo &DCI) {
18913   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18914   if (NewOp.getNode())
18915     return NewOp;
18916
18917   SDValue InputVector = N->getOperand(0);
18918
18919   // Detect whether we are trying to convert from mmx to i32 and the bitcast
18920   // from mmx to v2i32 has a single usage.
18921   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18922       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18923       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18924     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18925                        N->getValueType(0),
18926                        InputVector.getNode()->getOperand(0));
18927
18928   // Only operate on vectors of 4 elements, where the alternative shuffling
18929   // gets to be more expensive.
18930   if (InputVector.getValueType() != MVT::v4i32)
18931     return SDValue();
18932
18933   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18934   // single use which is a sign-extend or zero-extend, and all elements are
18935   // used.
18936   SmallVector<SDNode *, 4> Uses;
18937   unsigned ExtractedElements = 0;
18938   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18939        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18940     if (UI.getUse().getResNo() != InputVector.getResNo())
18941       return SDValue();
18942
18943     SDNode *Extract = *UI;
18944     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18945       return SDValue();
18946
18947     if (Extract->getValueType(0) != MVT::i32)
18948       return SDValue();
18949     if (!Extract->hasOneUse())
18950       return SDValue();
18951     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18952         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18953       return SDValue();
18954     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18955       return SDValue();
18956
18957     // Record which element was extracted.
18958     ExtractedElements |=
18959       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18960
18961     Uses.push_back(Extract);
18962   }
18963
18964   // If not all the elements were used, this may not be worthwhile.
18965   if (ExtractedElements != 15)
18966     return SDValue();
18967
18968   // Ok, we've now decided to do the transformation.
18969   SDLoc dl(InputVector);
18970
18971   // Store the value to a temporary stack slot.
18972   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18973   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18974                             MachinePointerInfo(), false, false, 0);
18975
18976   // Replace each use (extract) with a load of the appropriate element.
18977   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18978        UE = Uses.end(); UI != UE; ++UI) {
18979     SDNode *Extract = *UI;
18980
18981     // cOMpute the element's address.
18982     SDValue Idx = Extract->getOperand(1);
18983     unsigned EltSize =
18984         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18985     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18986     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18987     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18988
18989     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18990                                      StackPtr, OffsetVal);
18991
18992     // Load the scalar.
18993     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18994                                      ScalarAddr, MachinePointerInfo(),
18995                                      false, false, false, 0);
18996
18997     // Replace the exact with the load.
18998     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18999   }
19000
19001   // The replacement was made in place; don't return anything.
19002   return SDValue();
19003 }
19004
19005 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19006 static std::pair<unsigned, bool>
19007 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19008                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19009   if (!VT.isVector())
19010     return std::make_pair(0, false);
19011
19012   bool NeedSplit = false;
19013   switch (VT.getSimpleVT().SimpleTy) {
19014   default: return std::make_pair(0, false);
19015   case MVT::v32i8:
19016   case MVT::v16i16:
19017   case MVT::v8i32:
19018     if (!Subtarget->hasAVX2())
19019       NeedSplit = true;
19020     if (!Subtarget->hasAVX())
19021       return std::make_pair(0, false);
19022     break;
19023   case MVT::v16i8:
19024   case MVT::v8i16:
19025   case MVT::v4i32:
19026     if (!Subtarget->hasSSE2())
19027       return std::make_pair(0, false);
19028   }
19029
19030   // SSE2 has only a small subset of the operations.
19031   bool hasUnsigned = Subtarget->hasSSE41() ||
19032                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19033   bool hasSigned = Subtarget->hasSSE41() ||
19034                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19035
19036   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19037
19038   unsigned Opc = 0;
19039   // Check for x CC y ? x : y.
19040   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19041       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19042     switch (CC) {
19043     default: break;
19044     case ISD::SETULT:
19045     case ISD::SETULE:
19046       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19047     case ISD::SETUGT:
19048     case ISD::SETUGE:
19049       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19050     case ISD::SETLT:
19051     case ISD::SETLE:
19052       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19053     case ISD::SETGT:
19054     case ISD::SETGE:
19055       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19056     }
19057   // Check for x CC y ? y : x -- a min/max with reversed arms.
19058   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19059              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19060     switch (CC) {
19061     default: break;
19062     case ISD::SETULT:
19063     case ISD::SETULE:
19064       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19065     case ISD::SETUGT:
19066     case ISD::SETUGE:
19067       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19068     case ISD::SETLT:
19069     case ISD::SETLE:
19070       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19071     case ISD::SETGT:
19072     case ISD::SETGE:
19073       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19074     }
19075   }
19076
19077   return std::make_pair(Opc, NeedSplit);
19078 }
19079
19080 static SDValue
19081 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19082                                       const X86Subtarget *Subtarget) {
19083   SDLoc dl(N);
19084   SDValue Cond = N->getOperand(0);
19085   SDValue LHS = N->getOperand(1);
19086   SDValue RHS = N->getOperand(2);
19087
19088   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19089     SDValue CondSrc = Cond->getOperand(0);
19090     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19091       Cond = CondSrc->getOperand(0);
19092   }
19093
19094   MVT VT = N->getSimpleValueType(0);
19095   MVT EltVT = VT.getVectorElementType();
19096   unsigned NumElems = VT.getVectorNumElements();
19097   // There is no blend with immediate in AVX-512.
19098   if (VT.is512BitVector())
19099     return SDValue();
19100
19101   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19102     return SDValue();
19103   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19104     return SDValue();
19105
19106   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19107     return SDValue();
19108
19109   unsigned MaskValue = 0;
19110   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19111     return SDValue();
19112
19113   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19114   for (unsigned i = 0; i < NumElems; ++i) {
19115     // Be sure we emit undef where we can.
19116     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19117       ShuffleMask[i] = -1;
19118     else
19119       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19120   }
19121
19122   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19123 }
19124
19125 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19126 /// nodes.
19127 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19128                                     TargetLowering::DAGCombinerInfo &DCI,
19129                                     const X86Subtarget *Subtarget) {
19130   SDLoc DL(N);
19131   SDValue Cond = N->getOperand(0);
19132   // Get the LHS/RHS of the select.
19133   SDValue LHS = N->getOperand(1);
19134   SDValue RHS = N->getOperand(2);
19135   EVT VT = LHS.getValueType();
19136   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19137
19138   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19139   // instructions match the semantics of the common C idiom x<y?x:y but not
19140   // x<=y?x:y, because of how they handle negative zero (which can be
19141   // ignored in unsafe-math mode).
19142   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19143       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19144       (Subtarget->hasSSE2() ||
19145        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19146     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19147
19148     unsigned Opcode = 0;
19149     // Check for x CC y ? x : y.
19150     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19151         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19152       switch (CC) {
19153       default: break;
19154       case ISD::SETULT:
19155         // Converting this to a min would handle NaNs incorrectly, and swapping
19156         // the operands would cause it to handle comparisons between positive
19157         // and negative zero incorrectly.
19158         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19159           if (!DAG.getTarget().Options.UnsafeFPMath &&
19160               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19161             break;
19162           std::swap(LHS, RHS);
19163         }
19164         Opcode = X86ISD::FMIN;
19165         break;
19166       case ISD::SETOLE:
19167         // Converting this to a min would handle comparisons between positive
19168         // and negative zero incorrectly.
19169         if (!DAG.getTarget().Options.UnsafeFPMath &&
19170             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19171           break;
19172         Opcode = X86ISD::FMIN;
19173         break;
19174       case ISD::SETULE:
19175         // Converting this to a min would handle both negative zeros and NaNs
19176         // incorrectly, but we can swap the operands to fix both.
19177         std::swap(LHS, RHS);
19178       case ISD::SETOLT:
19179       case ISD::SETLT:
19180       case ISD::SETLE:
19181         Opcode = X86ISD::FMIN;
19182         break;
19183
19184       case ISD::SETOGE:
19185         // Converting this to a max would handle comparisons between positive
19186         // and negative zero incorrectly.
19187         if (!DAG.getTarget().Options.UnsafeFPMath &&
19188             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19189           break;
19190         Opcode = X86ISD::FMAX;
19191         break;
19192       case ISD::SETUGT:
19193         // Converting this to a max would handle NaNs incorrectly, and swapping
19194         // the operands would cause it to handle comparisons between positive
19195         // and negative zero incorrectly.
19196         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19197           if (!DAG.getTarget().Options.UnsafeFPMath &&
19198               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19199             break;
19200           std::swap(LHS, RHS);
19201         }
19202         Opcode = X86ISD::FMAX;
19203         break;
19204       case ISD::SETUGE:
19205         // Converting this to a max would handle both negative zeros and NaNs
19206         // incorrectly, but we can swap the operands to fix both.
19207         std::swap(LHS, RHS);
19208       case ISD::SETOGT:
19209       case ISD::SETGT:
19210       case ISD::SETGE:
19211         Opcode = X86ISD::FMAX;
19212         break;
19213       }
19214     // Check for x CC y ? y : x -- a min/max with reversed arms.
19215     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19216                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19217       switch (CC) {
19218       default: break;
19219       case ISD::SETOGE:
19220         // Converting this to a min would handle comparisons between positive
19221         // and negative zero incorrectly, and swapping the operands would
19222         // cause it to handle NaNs incorrectly.
19223         if (!DAG.getTarget().Options.UnsafeFPMath &&
19224             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19225           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19226             break;
19227           std::swap(LHS, RHS);
19228         }
19229         Opcode = X86ISD::FMIN;
19230         break;
19231       case ISD::SETUGT:
19232         // Converting this to a min would handle NaNs incorrectly.
19233         if (!DAG.getTarget().Options.UnsafeFPMath &&
19234             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19235           break;
19236         Opcode = X86ISD::FMIN;
19237         break;
19238       case ISD::SETUGE:
19239         // Converting this to a min would handle both negative zeros and NaNs
19240         // incorrectly, but we can swap the operands to fix both.
19241         std::swap(LHS, RHS);
19242       case ISD::SETOGT:
19243       case ISD::SETGT:
19244       case ISD::SETGE:
19245         Opcode = X86ISD::FMIN;
19246         break;
19247
19248       case ISD::SETULT:
19249         // Converting this to a max would handle NaNs incorrectly.
19250         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19251           break;
19252         Opcode = X86ISD::FMAX;
19253         break;
19254       case ISD::SETOLE:
19255         // Converting this to a max would handle comparisons between positive
19256         // and negative zero incorrectly, and swapping the operands would
19257         // cause it to handle NaNs incorrectly.
19258         if (!DAG.getTarget().Options.UnsafeFPMath &&
19259             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19260           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19261             break;
19262           std::swap(LHS, RHS);
19263         }
19264         Opcode = X86ISD::FMAX;
19265         break;
19266       case ISD::SETULE:
19267         // Converting this to a max would handle both negative zeros and NaNs
19268         // incorrectly, but we can swap the operands to fix both.
19269         std::swap(LHS, RHS);
19270       case ISD::SETOLT:
19271       case ISD::SETLT:
19272       case ISD::SETLE:
19273         Opcode = X86ISD::FMAX;
19274         break;
19275       }
19276     }
19277
19278     if (Opcode)
19279       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19280   }
19281
19282   EVT CondVT = Cond.getValueType();
19283   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19284       CondVT.getVectorElementType() == MVT::i1) {
19285     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19286     // lowering on AVX-512. In this case we convert it to
19287     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19288     // The same situation for all 128 and 256-bit vectors of i8 and i16
19289     EVT OpVT = LHS.getValueType();
19290     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19291         (OpVT.getVectorElementType() == MVT::i8 ||
19292          OpVT.getVectorElementType() == MVT::i16)) {
19293       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19294       DCI.AddToWorklist(Cond.getNode());
19295       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19296     }
19297   }
19298   // If this is a select between two integer constants, try to do some
19299   // optimizations.
19300   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19301     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19302       // Don't do this for crazy integer types.
19303       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19304         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19305         // so that TrueC (the true value) is larger than FalseC.
19306         bool NeedsCondInvert = false;
19307
19308         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19309             // Efficiently invertible.
19310             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19311              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19312               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19313           NeedsCondInvert = true;
19314           std::swap(TrueC, FalseC);
19315         }
19316
19317         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19318         if (FalseC->getAPIntValue() == 0 &&
19319             TrueC->getAPIntValue().isPowerOf2()) {
19320           if (NeedsCondInvert) // Invert the condition if needed.
19321             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19322                                DAG.getConstant(1, Cond.getValueType()));
19323
19324           // Zero extend the condition if needed.
19325           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19326
19327           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19328           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19329                              DAG.getConstant(ShAmt, MVT::i8));
19330         }
19331
19332         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19333         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19334           if (NeedsCondInvert) // Invert the condition if needed.
19335             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19336                                DAG.getConstant(1, Cond.getValueType()));
19337
19338           // Zero extend the condition if needed.
19339           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19340                              FalseC->getValueType(0), Cond);
19341           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19342                              SDValue(FalseC, 0));
19343         }
19344
19345         // Optimize cases that will turn into an LEA instruction.  This requires
19346         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19347         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19348           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19349           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19350
19351           bool isFastMultiplier = false;
19352           if (Diff < 10) {
19353             switch ((unsigned char)Diff) {
19354               default: break;
19355               case 1:  // result = add base, cond
19356               case 2:  // result = lea base(    , cond*2)
19357               case 3:  // result = lea base(cond, cond*2)
19358               case 4:  // result = lea base(    , cond*4)
19359               case 5:  // result = lea base(cond, cond*4)
19360               case 8:  // result = lea base(    , cond*8)
19361               case 9:  // result = lea base(cond, cond*8)
19362                 isFastMultiplier = true;
19363                 break;
19364             }
19365           }
19366
19367           if (isFastMultiplier) {
19368             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19369             if (NeedsCondInvert) // Invert the condition if needed.
19370               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19371                                  DAG.getConstant(1, Cond.getValueType()));
19372
19373             // Zero extend the condition if needed.
19374             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19375                                Cond);
19376             // Scale the condition by the difference.
19377             if (Diff != 1)
19378               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19379                                  DAG.getConstant(Diff, Cond.getValueType()));
19380
19381             // Add the base if non-zero.
19382             if (FalseC->getAPIntValue() != 0)
19383               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19384                                  SDValue(FalseC, 0));
19385             return Cond;
19386           }
19387         }
19388       }
19389   }
19390
19391   // Canonicalize max and min:
19392   // (x > y) ? x : y -> (x >= y) ? x : y
19393   // (x < y) ? x : y -> (x <= y) ? x : y
19394   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19395   // the need for an extra compare
19396   // against zero. e.g.
19397   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19398   // subl   %esi, %edi
19399   // testl  %edi, %edi
19400   // movl   $0, %eax
19401   // cmovgl %edi, %eax
19402   // =>
19403   // xorl   %eax, %eax
19404   // subl   %esi, $edi
19405   // cmovsl %eax, %edi
19406   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19407       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19408       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19409     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19410     switch (CC) {
19411     default: break;
19412     case ISD::SETLT:
19413     case ISD::SETGT: {
19414       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19415       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19416                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19417       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19418     }
19419     }
19420   }
19421
19422   // Early exit check
19423   if (!TLI.isTypeLegal(VT))
19424     return SDValue();
19425
19426   // Match VSELECTs into subs with unsigned saturation.
19427   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19428       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19429       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19430        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19431     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19432
19433     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19434     // left side invert the predicate to simplify logic below.
19435     SDValue Other;
19436     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19437       Other = RHS;
19438       CC = ISD::getSetCCInverse(CC, true);
19439     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19440       Other = LHS;
19441     }
19442
19443     if (Other.getNode() && Other->getNumOperands() == 2 &&
19444         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19445       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19446       SDValue CondRHS = Cond->getOperand(1);
19447
19448       // Look for a general sub with unsigned saturation first.
19449       // x >= y ? x-y : 0 --> subus x, y
19450       // x >  y ? x-y : 0 --> subus x, y
19451       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19452           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19453         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19454
19455       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19456         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19457           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19458             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19459               // If the RHS is a constant we have to reverse the const
19460               // canonicalization.
19461               // x > C-1 ? x+-C : 0 --> subus x, C
19462               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19463                   CondRHSConst->getAPIntValue() ==
19464                       (-OpRHSConst->getAPIntValue() - 1))
19465                 return DAG.getNode(
19466                     X86ISD::SUBUS, DL, VT, OpLHS,
19467                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19468
19469           // Another special case: If C was a sign bit, the sub has been
19470           // canonicalized into a xor.
19471           // FIXME: Would it be better to use computeKnownBits to determine
19472           //        whether it's safe to decanonicalize the xor?
19473           // x s< 0 ? x^C : 0 --> subus x, C
19474           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19475               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19476               OpRHSConst->getAPIntValue().isSignBit())
19477             // Note that we have to rebuild the RHS constant here to ensure we
19478             // don't rely on particular values of undef lanes.
19479             return DAG.getNode(
19480                 X86ISD::SUBUS, DL, VT, OpLHS,
19481                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19482         }
19483     }
19484   }
19485
19486   // Try to match a min/max vector operation.
19487   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19488     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19489     unsigned Opc = ret.first;
19490     bool NeedSplit = ret.second;
19491
19492     if (Opc && NeedSplit) {
19493       unsigned NumElems = VT.getVectorNumElements();
19494       // Extract the LHS vectors
19495       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19496       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19497
19498       // Extract the RHS vectors
19499       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19500       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19501
19502       // Create min/max for each subvector
19503       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19504       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19505
19506       // Merge the result
19507       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19508     } else if (Opc)
19509       return DAG.getNode(Opc, DL, VT, LHS, RHS);
19510   }
19511
19512   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19513   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19514       // Check if SETCC has already been promoted
19515       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19516       // Check that condition value type matches vselect operand type
19517       CondVT == VT) { 
19518
19519     assert(Cond.getValueType().isVector() &&
19520            "vector select expects a vector selector!");
19521
19522     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19523     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19524
19525     if (!TValIsAllOnes && !FValIsAllZeros) {
19526       // Try invert the condition if true value is not all 1s and false value
19527       // is not all 0s.
19528       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19529       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19530
19531       if (TValIsAllZeros || FValIsAllOnes) {
19532         SDValue CC = Cond.getOperand(2);
19533         ISD::CondCode NewCC =
19534           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19535                                Cond.getOperand(0).getValueType().isInteger());
19536         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19537         std::swap(LHS, RHS);
19538         TValIsAllOnes = FValIsAllOnes;
19539         FValIsAllZeros = TValIsAllZeros;
19540       }
19541     }
19542
19543     if (TValIsAllOnes || FValIsAllZeros) {
19544       SDValue Ret;
19545
19546       if (TValIsAllOnes && FValIsAllZeros)
19547         Ret = Cond;
19548       else if (TValIsAllOnes)
19549         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19550                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19551       else if (FValIsAllZeros)
19552         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19553                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19554
19555       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19556     }
19557   }
19558
19559   // Try to fold this VSELECT into a MOVSS/MOVSD
19560   if (N->getOpcode() == ISD::VSELECT &&
19561       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19562     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19563         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19564       bool CanFold = false;
19565       unsigned NumElems = Cond.getNumOperands();
19566       SDValue A = LHS;
19567       SDValue B = RHS;
19568       
19569       if (isZero(Cond.getOperand(0))) {
19570         CanFold = true;
19571
19572         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19573         // fold (vselect <0,-1> -> (movsd A, B)
19574         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19575           CanFold = isAllOnes(Cond.getOperand(i));
19576       } else if (isAllOnes(Cond.getOperand(0))) {
19577         CanFold = true;
19578         std::swap(A, B);
19579
19580         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19581         // fold (vselect <-1,0> -> (movsd B, A)
19582         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19583           CanFold = isZero(Cond.getOperand(i));
19584       }
19585
19586       if (CanFold) {
19587         if (VT == MVT::v4i32 || VT == MVT::v4f32)
19588           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19589         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19590       }
19591
19592       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19593         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19594         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19595         //                             (v2i64 (bitcast B)))))
19596         //
19597         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19598         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19599         //                             (v2f64 (bitcast B)))))
19600         //
19601         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19602         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19603         //                             (v2i64 (bitcast A)))))
19604         //
19605         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19606         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19607         //                             (v2f64 (bitcast A)))))
19608
19609         CanFold = (isZero(Cond.getOperand(0)) &&
19610                    isZero(Cond.getOperand(1)) &&
19611                    isAllOnes(Cond.getOperand(2)) &&
19612                    isAllOnes(Cond.getOperand(3)));
19613
19614         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19615             isAllOnes(Cond.getOperand(1)) &&
19616             isZero(Cond.getOperand(2)) &&
19617             isZero(Cond.getOperand(3))) {
19618           CanFold = true;
19619           std::swap(LHS, RHS);
19620         }
19621
19622         if (CanFold) {
19623           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19624           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19625           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19626           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19627                                                 NewB, DAG);
19628           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19629         }
19630       }
19631     }
19632   }
19633
19634   // If we know that this node is legal then we know that it is going to be
19635   // matched by one of the SSE/AVX BLEND instructions. These instructions only
19636   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19637   // to simplify previous instructions.
19638   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19639       !DCI.isBeforeLegalize() &&
19640       // We explicitly check against v8i16 and v16i16 because, although
19641       // they're marked as Custom, they might only be legal when Cond is a
19642       // build_vector of constants. This will be taken care in a later
19643       // condition.
19644       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19645        VT != MVT::v8i16)) {
19646     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19647
19648     // Don't optimize vector selects that map to mask-registers.
19649     if (BitWidth == 1)
19650       return SDValue();
19651
19652     // Check all uses of that condition operand to check whether it will be
19653     // consumed by non-BLEND instructions, which may depend on all bits are set
19654     // properly.
19655     for (SDNode::use_iterator I = Cond->use_begin(),
19656                               E = Cond->use_end(); I != E; ++I)
19657       if (I->getOpcode() != ISD::VSELECT)
19658         // TODO: Add other opcodes eventually lowered into BLEND.
19659         return SDValue();
19660
19661     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19662     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19663
19664     APInt KnownZero, KnownOne;
19665     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19666                                           DCI.isBeforeLegalizeOps());
19667     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19668         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19669       DCI.CommitTargetLoweringOpt(TLO);
19670   }
19671
19672   // We should generate an X86ISD::BLENDI from a vselect if its argument
19673   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19674   // constants. This specific pattern gets generated when we split a
19675   // selector for a 512 bit vector in a machine without AVX512 (but with
19676   // 256-bit vectors), during legalization:
19677   //
19678   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19679   //
19680   // Iff we find this pattern and the build_vectors are built from
19681   // constants, we translate the vselect into a shuffle_vector that we
19682   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19683   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19684     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19685     if (Shuffle.getNode())
19686       return Shuffle;
19687   }
19688
19689   return SDValue();
19690 }
19691
19692 // Check whether a boolean test is testing a boolean value generated by
19693 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19694 // code.
19695 //
19696 // Simplify the following patterns:
19697 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19698 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19699 // to (Op EFLAGS Cond)
19700 //
19701 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19702 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19703 // to (Op EFLAGS !Cond)
19704 //
19705 // where Op could be BRCOND or CMOV.
19706 //
19707 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19708   // Quit if not CMP and SUB with its value result used.
19709   if (Cmp.getOpcode() != X86ISD::CMP &&
19710       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19711       return SDValue();
19712
19713   // Quit if not used as a boolean value.
19714   if (CC != X86::COND_E && CC != X86::COND_NE)
19715     return SDValue();
19716
19717   // Check CMP operands. One of them should be 0 or 1 and the other should be
19718   // an SetCC or extended from it.
19719   SDValue Op1 = Cmp.getOperand(0);
19720   SDValue Op2 = Cmp.getOperand(1);
19721
19722   SDValue SetCC;
19723   const ConstantSDNode* C = nullptr;
19724   bool needOppositeCond = (CC == X86::COND_E);
19725   bool checkAgainstTrue = false; // Is it a comparison against 1?
19726
19727   if ((C = dyn_cast<ConstantSDNode>(Op1)))
19728     SetCC = Op2;
19729   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19730     SetCC = Op1;
19731   else // Quit if all operands are not constants.
19732     return SDValue();
19733
19734   if (C->getZExtValue() == 1) {
19735     needOppositeCond = !needOppositeCond;
19736     checkAgainstTrue = true;
19737   } else if (C->getZExtValue() != 0)
19738     // Quit if the constant is neither 0 or 1.
19739     return SDValue();
19740
19741   bool truncatedToBoolWithAnd = false;
19742   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19743   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19744          SetCC.getOpcode() == ISD::TRUNCATE ||
19745          SetCC.getOpcode() == ISD::AND) {
19746     if (SetCC.getOpcode() == ISD::AND) {
19747       int OpIdx = -1;
19748       ConstantSDNode *CS;
19749       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19750           CS->getZExtValue() == 1)
19751         OpIdx = 1;
19752       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19753           CS->getZExtValue() == 1)
19754         OpIdx = 0;
19755       if (OpIdx == -1)
19756         break;
19757       SetCC = SetCC.getOperand(OpIdx);
19758       truncatedToBoolWithAnd = true;
19759     } else
19760       SetCC = SetCC.getOperand(0);
19761   }
19762
19763   switch (SetCC.getOpcode()) {
19764   case X86ISD::SETCC_CARRY:
19765     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19766     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19767     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19768     // truncated to i1 using 'and'.
19769     if (checkAgainstTrue && !truncatedToBoolWithAnd)
19770       break;
19771     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19772            "Invalid use of SETCC_CARRY!");
19773     // FALL THROUGH
19774   case X86ISD::SETCC:
19775     // Set the condition code or opposite one if necessary.
19776     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19777     if (needOppositeCond)
19778       CC = X86::GetOppositeBranchCondition(CC);
19779     return SetCC.getOperand(1);
19780   case X86ISD::CMOV: {
19781     // Check whether false/true value has canonical one, i.e. 0 or 1.
19782     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19783     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19784     // Quit if true value is not a constant.
19785     if (!TVal)
19786       return SDValue();
19787     // Quit if false value is not a constant.
19788     if (!FVal) {
19789       SDValue Op = SetCC.getOperand(0);
19790       // Skip 'zext' or 'trunc' node.
19791       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19792           Op.getOpcode() == ISD::TRUNCATE)
19793         Op = Op.getOperand(0);
19794       // A special case for rdrand/rdseed, where 0 is set if false cond is
19795       // found.
19796       if ((Op.getOpcode() != X86ISD::RDRAND &&
19797            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19798         return SDValue();
19799     }
19800     // Quit if false value is not the constant 0 or 1.
19801     bool FValIsFalse = true;
19802     if (FVal && FVal->getZExtValue() != 0) {
19803       if (FVal->getZExtValue() != 1)
19804         return SDValue();
19805       // If FVal is 1, opposite cond is needed.
19806       needOppositeCond = !needOppositeCond;
19807       FValIsFalse = false;
19808     }
19809     // Quit if TVal is not the constant opposite of FVal.
19810     if (FValIsFalse && TVal->getZExtValue() != 1)
19811       return SDValue();
19812     if (!FValIsFalse && TVal->getZExtValue() != 0)
19813       return SDValue();
19814     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19815     if (needOppositeCond)
19816       CC = X86::GetOppositeBranchCondition(CC);
19817     return SetCC.getOperand(3);
19818   }
19819   }
19820
19821   return SDValue();
19822 }
19823
19824 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19825 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19826                                   TargetLowering::DAGCombinerInfo &DCI,
19827                                   const X86Subtarget *Subtarget) {
19828   SDLoc DL(N);
19829
19830   // If the flag operand isn't dead, don't touch this CMOV.
19831   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19832     return SDValue();
19833
19834   SDValue FalseOp = N->getOperand(0);
19835   SDValue TrueOp = N->getOperand(1);
19836   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19837   SDValue Cond = N->getOperand(3);
19838
19839   if (CC == X86::COND_E || CC == X86::COND_NE) {
19840     switch (Cond.getOpcode()) {
19841     default: break;
19842     case X86ISD::BSR:
19843     case X86ISD::BSF:
19844       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19845       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19846         return (CC == X86::COND_E) ? FalseOp : TrueOp;
19847     }
19848   }
19849
19850   SDValue Flags;
19851
19852   Flags = checkBoolTestSetCCCombine(Cond, CC);
19853   if (Flags.getNode() &&
19854       // Extra check as FCMOV only supports a subset of X86 cond.
19855       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19856     SDValue Ops[] = { FalseOp, TrueOp,
19857                       DAG.getConstant(CC, MVT::i8), Flags };
19858     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19859   }
19860
19861   // If this is a select between two integer constants, try to do some
19862   // optimizations.  Note that the operands are ordered the opposite of SELECT
19863   // operands.
19864   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19865     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19866       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19867       // larger than FalseC (the false value).
19868       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19869         CC = X86::GetOppositeBranchCondition(CC);
19870         std::swap(TrueC, FalseC);
19871         std::swap(TrueOp, FalseOp);
19872       }
19873
19874       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19875       // This is efficient for any integer data type (including i8/i16) and
19876       // shift amount.
19877       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19878         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19879                            DAG.getConstant(CC, MVT::i8), Cond);
19880
19881         // Zero extend the condition if needed.
19882         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19883
19884         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19885         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19886                            DAG.getConstant(ShAmt, MVT::i8));
19887         if (N->getNumValues() == 2)  // Dead flag value?
19888           return DCI.CombineTo(N, Cond, SDValue());
19889         return Cond;
19890       }
19891
19892       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
19893       // for any integer data type, including i8/i16.
19894       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19895         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19896                            DAG.getConstant(CC, MVT::i8), Cond);
19897
19898         // Zero extend the condition if needed.
19899         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19900                            FalseC->getValueType(0), Cond);
19901         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19902                            SDValue(FalseC, 0));
19903
19904         if (N->getNumValues() == 2)  // Dead flag value?
19905           return DCI.CombineTo(N, Cond, SDValue());
19906         return Cond;
19907       }
19908
19909       // Optimize cases that will turn into an LEA instruction.  This requires
19910       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19911       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19912         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19913         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19914
19915         bool isFastMultiplier = false;
19916         if (Diff < 10) {
19917           switch ((unsigned char)Diff) {
19918           default: break;
19919           case 1:  // result = add base, cond
19920           case 2:  // result = lea base(    , cond*2)
19921           case 3:  // result = lea base(cond, cond*2)
19922           case 4:  // result = lea base(    , cond*4)
19923           case 5:  // result = lea base(cond, cond*4)
19924           case 8:  // result = lea base(    , cond*8)
19925           case 9:  // result = lea base(cond, cond*8)
19926             isFastMultiplier = true;
19927             break;
19928           }
19929         }
19930
19931         if (isFastMultiplier) {
19932           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19933           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19934                              DAG.getConstant(CC, MVT::i8), Cond);
19935           // Zero extend the condition if needed.
19936           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19937                              Cond);
19938           // Scale the condition by the difference.
19939           if (Diff != 1)
19940             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19941                                DAG.getConstant(Diff, Cond.getValueType()));
19942
19943           // Add the base if non-zero.
19944           if (FalseC->getAPIntValue() != 0)
19945             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19946                                SDValue(FalseC, 0));
19947           if (N->getNumValues() == 2)  // Dead flag value?
19948             return DCI.CombineTo(N, Cond, SDValue());
19949           return Cond;
19950         }
19951       }
19952     }
19953   }
19954
19955   // Handle these cases:
19956   //   (select (x != c), e, c) -> select (x != c), e, x),
19957   //   (select (x == c), c, e) -> select (x == c), x, e)
19958   // where the c is an integer constant, and the "select" is the combination
19959   // of CMOV and CMP.
19960   //
19961   // The rationale for this change is that the conditional-move from a constant
19962   // needs two instructions, however, conditional-move from a register needs
19963   // only one instruction.
19964   //
19965   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19966   //  some instruction-combining opportunities. This opt needs to be
19967   //  postponed as late as possible.
19968   //
19969   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19970     // the DCI.xxxx conditions are provided to postpone the optimization as
19971     // late as possible.
19972
19973     ConstantSDNode *CmpAgainst = nullptr;
19974     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19975         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19976         !isa<ConstantSDNode>(Cond.getOperand(0))) {
19977
19978       if (CC == X86::COND_NE &&
19979           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19980         CC = X86::GetOppositeBranchCondition(CC);
19981         std::swap(TrueOp, FalseOp);
19982       }
19983
19984       if (CC == X86::COND_E &&
19985           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19986         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19987                           DAG.getConstant(CC, MVT::i8), Cond };
19988         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19989       }
19990     }
19991   }
19992
19993   return SDValue();
19994 }
19995
19996 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19997                                                 const X86Subtarget *Subtarget) {
19998   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19999   switch (IntNo) {
20000   default: return SDValue();
20001   // SSE/AVX/AVX2 blend intrinsics.
20002   case Intrinsic::x86_avx2_pblendvb:
20003   case Intrinsic::x86_avx2_pblendw:
20004   case Intrinsic::x86_avx2_pblendd_128:
20005   case Intrinsic::x86_avx2_pblendd_256:
20006     // Don't try to simplify this intrinsic if we don't have AVX2.
20007     if (!Subtarget->hasAVX2())
20008       return SDValue();
20009     // FALL-THROUGH
20010   case Intrinsic::x86_avx_blend_pd_256:
20011   case Intrinsic::x86_avx_blend_ps_256:
20012   case Intrinsic::x86_avx_blendv_pd_256:
20013   case Intrinsic::x86_avx_blendv_ps_256:
20014     // Don't try to simplify this intrinsic if we don't have AVX.
20015     if (!Subtarget->hasAVX())
20016       return SDValue();
20017     // FALL-THROUGH
20018   case Intrinsic::x86_sse41_pblendw:
20019   case Intrinsic::x86_sse41_blendpd:
20020   case Intrinsic::x86_sse41_blendps:
20021   case Intrinsic::x86_sse41_blendvps:
20022   case Intrinsic::x86_sse41_blendvpd:
20023   case Intrinsic::x86_sse41_pblendvb: {
20024     SDValue Op0 = N->getOperand(1);
20025     SDValue Op1 = N->getOperand(2);
20026     SDValue Mask = N->getOperand(3);
20027
20028     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20029     if (!Subtarget->hasSSE41())
20030       return SDValue();
20031
20032     // fold (blend A, A, Mask) -> A
20033     if (Op0 == Op1)
20034       return Op0;
20035     // fold (blend A, B, allZeros) -> A
20036     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20037       return Op0;
20038     // fold (blend A, B, allOnes) -> B
20039     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20040       return Op1;
20041     
20042     // Simplify the case where the mask is a constant i32 value.
20043     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20044       if (C->isNullValue())
20045         return Op0;
20046       if (C->isAllOnesValue())
20047         return Op1;
20048     }
20049
20050     return SDValue();
20051   }
20052
20053   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20054   case Intrinsic::x86_sse2_psrai_w:
20055   case Intrinsic::x86_sse2_psrai_d:
20056   case Intrinsic::x86_avx2_psrai_w:
20057   case Intrinsic::x86_avx2_psrai_d:
20058   case Intrinsic::x86_sse2_psra_w:
20059   case Intrinsic::x86_sse2_psra_d:
20060   case Intrinsic::x86_avx2_psra_w:
20061   case Intrinsic::x86_avx2_psra_d: {
20062     SDValue Op0 = N->getOperand(1);
20063     SDValue Op1 = N->getOperand(2);
20064     EVT VT = Op0.getValueType();
20065     assert(VT.isVector() && "Expected a vector type!");
20066
20067     if (isa<BuildVectorSDNode>(Op1))
20068       Op1 = Op1.getOperand(0);
20069
20070     if (!isa<ConstantSDNode>(Op1))
20071       return SDValue();
20072
20073     EVT SVT = VT.getVectorElementType();
20074     unsigned SVTBits = SVT.getSizeInBits();
20075
20076     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20077     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20078     uint64_t ShAmt = C.getZExtValue();
20079
20080     // Don't try to convert this shift into a ISD::SRA if the shift
20081     // count is bigger than or equal to the element size.
20082     if (ShAmt >= SVTBits)
20083       return SDValue();
20084
20085     // Trivial case: if the shift count is zero, then fold this
20086     // into the first operand.
20087     if (ShAmt == 0)
20088       return Op0;
20089
20090     // Replace this packed shift intrinsic with a target independent
20091     // shift dag node.
20092     SDValue Splat = DAG.getConstant(C, VT);
20093     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20094   }
20095   }
20096 }
20097
20098 /// PerformMulCombine - Optimize a single multiply with constant into two
20099 /// in order to implement it with two cheaper instructions, e.g.
20100 /// LEA + SHL, LEA + LEA.
20101 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20102                                  TargetLowering::DAGCombinerInfo &DCI) {
20103   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20104     return SDValue();
20105
20106   EVT VT = N->getValueType(0);
20107   if (VT != MVT::i64)
20108     return SDValue();
20109
20110   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20111   if (!C)
20112     return SDValue();
20113   uint64_t MulAmt = C->getZExtValue();
20114   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20115     return SDValue();
20116
20117   uint64_t MulAmt1 = 0;
20118   uint64_t MulAmt2 = 0;
20119   if ((MulAmt % 9) == 0) {
20120     MulAmt1 = 9;
20121     MulAmt2 = MulAmt / 9;
20122   } else if ((MulAmt % 5) == 0) {
20123     MulAmt1 = 5;
20124     MulAmt2 = MulAmt / 5;
20125   } else if ((MulAmt % 3) == 0) {
20126     MulAmt1 = 3;
20127     MulAmt2 = MulAmt / 3;
20128   }
20129   if (MulAmt2 &&
20130       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20131     SDLoc DL(N);
20132
20133     if (isPowerOf2_64(MulAmt2) &&
20134         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20135       // If second multiplifer is pow2, issue it first. We want the multiply by
20136       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20137       // is an add.
20138       std::swap(MulAmt1, MulAmt2);
20139
20140     SDValue NewMul;
20141     if (isPowerOf2_64(MulAmt1))
20142       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20143                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20144     else
20145       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20146                            DAG.getConstant(MulAmt1, VT));
20147
20148     if (isPowerOf2_64(MulAmt2))
20149       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20150                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20151     else
20152       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20153                            DAG.getConstant(MulAmt2, VT));
20154
20155     // Do not add new nodes to DAG combiner worklist.
20156     DCI.CombineTo(N, NewMul, false);
20157   }
20158   return SDValue();
20159 }
20160
20161 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20162   SDValue N0 = N->getOperand(0);
20163   SDValue N1 = N->getOperand(1);
20164   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20165   EVT VT = N0.getValueType();
20166
20167   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20168   // since the result of setcc_c is all zero's or all ones.
20169   if (VT.isInteger() && !VT.isVector() &&
20170       N1C && N0.getOpcode() == ISD::AND &&
20171       N0.getOperand(1).getOpcode() == ISD::Constant) {
20172     SDValue N00 = N0.getOperand(0);
20173     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20174         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20175           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20176          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20177       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20178       APInt ShAmt = N1C->getAPIntValue();
20179       Mask = Mask.shl(ShAmt);
20180       if (Mask != 0)
20181         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20182                            N00, DAG.getConstant(Mask, VT));
20183     }
20184   }
20185
20186   // Hardware support for vector shifts is sparse which makes us scalarize the
20187   // vector operations in many cases. Also, on sandybridge ADD is faster than
20188   // shl.
20189   // (shl V, 1) -> add V,V
20190   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20191     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20192       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20193       // We shift all of the values by one. In many cases we do not have
20194       // hardware support for this operation. This is better expressed as an ADD
20195       // of two values.
20196       if (N1SplatC->getZExtValue() == 1)
20197         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20198     }
20199
20200   return SDValue();
20201 }
20202
20203 /// \brief Returns a vector of 0s if the node in input is a vector logical
20204 /// shift by a constant amount which is known to be bigger than or equal
20205 /// to the vector element size in bits.
20206 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20207                                       const X86Subtarget *Subtarget) {
20208   EVT VT = N->getValueType(0);
20209
20210   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20211       (!Subtarget->hasInt256() ||
20212        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20213     return SDValue();
20214
20215   SDValue Amt = N->getOperand(1);
20216   SDLoc DL(N);
20217   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20218     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20219       APInt ShiftAmt = AmtSplat->getAPIntValue();
20220       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20221
20222       // SSE2/AVX2 logical shifts always return a vector of 0s
20223       // if the shift amount is bigger than or equal to
20224       // the element size. The constant shift amount will be
20225       // encoded as a 8-bit immediate.
20226       if (ShiftAmt.trunc(8).uge(MaxAmount))
20227         return getZeroVector(VT, Subtarget, DAG, DL);
20228     }
20229
20230   return SDValue();
20231 }
20232
20233 /// PerformShiftCombine - Combine shifts.
20234 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20235                                    TargetLowering::DAGCombinerInfo &DCI,
20236                                    const X86Subtarget *Subtarget) {
20237   if (N->getOpcode() == ISD::SHL) {
20238     SDValue V = PerformSHLCombine(N, DAG);
20239     if (V.getNode()) return V;
20240   }
20241
20242   if (N->getOpcode() != ISD::SRA) {
20243     // Try to fold this logical shift into a zero vector.
20244     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20245     if (V.getNode()) return V;
20246   }
20247
20248   return SDValue();
20249 }
20250
20251 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20252 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20253 // and friends.  Likewise for OR -> CMPNEQSS.
20254 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20255                             TargetLowering::DAGCombinerInfo &DCI,
20256                             const X86Subtarget *Subtarget) {
20257   unsigned opcode;
20258
20259   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20260   // we're requiring SSE2 for both.
20261   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20262     SDValue N0 = N->getOperand(0);
20263     SDValue N1 = N->getOperand(1);
20264     SDValue CMP0 = N0->getOperand(1);
20265     SDValue CMP1 = N1->getOperand(1);
20266     SDLoc DL(N);
20267
20268     // The SETCCs should both refer to the same CMP.
20269     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20270       return SDValue();
20271
20272     SDValue CMP00 = CMP0->getOperand(0);
20273     SDValue CMP01 = CMP0->getOperand(1);
20274     EVT     VT    = CMP00.getValueType();
20275
20276     if (VT == MVT::f32 || VT == MVT::f64) {
20277       bool ExpectingFlags = false;
20278       // Check for any users that want flags:
20279       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20280            !ExpectingFlags && UI != UE; ++UI)
20281         switch (UI->getOpcode()) {
20282         default:
20283         case ISD::BR_CC:
20284         case ISD::BRCOND:
20285         case ISD::SELECT:
20286           ExpectingFlags = true;
20287           break;
20288         case ISD::CopyToReg:
20289         case ISD::SIGN_EXTEND:
20290         case ISD::ZERO_EXTEND:
20291         case ISD::ANY_EXTEND:
20292           break;
20293         }
20294
20295       if (!ExpectingFlags) {
20296         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20297         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20298
20299         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20300           X86::CondCode tmp = cc0;
20301           cc0 = cc1;
20302           cc1 = tmp;
20303         }
20304
20305         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20306             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20307           // FIXME: need symbolic constants for these magic numbers.
20308           // See X86ATTInstPrinter.cpp:printSSECC().
20309           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20310           if (Subtarget->hasAVX512()) {
20311             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20312                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20313             if (N->getValueType(0) != MVT::i1)
20314               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20315                                  FSetCC);
20316             return FSetCC;
20317           }
20318           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20319                                               CMP00.getValueType(), CMP00, CMP01,
20320                                               DAG.getConstant(x86cc, MVT::i8));
20321
20322           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20323           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20324
20325           if (is64BitFP && !Subtarget->is64Bit()) {
20326             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20327             // 64-bit integer, since that's not a legal type. Since
20328             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20329             // bits, but can do this little dance to extract the lowest 32 bits
20330             // and work with those going forward.
20331             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20332                                            OnesOrZeroesF);
20333             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20334                                            Vector64);
20335             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20336                                         Vector32, DAG.getIntPtrConstant(0));
20337             IntVT = MVT::i32;
20338           }
20339
20340           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20341           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20342                                       DAG.getConstant(1, IntVT));
20343           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20344           return OneBitOfTruth;
20345         }
20346       }
20347     }
20348   }
20349   return SDValue();
20350 }
20351
20352 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20353 /// so it can be folded inside ANDNP.
20354 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20355   EVT VT = N->getValueType(0);
20356
20357   // Match direct AllOnes for 128 and 256-bit vectors
20358   if (ISD::isBuildVectorAllOnes(N))
20359     return true;
20360
20361   // Look through a bit convert.
20362   if (N->getOpcode() == ISD::BITCAST)
20363     N = N->getOperand(0).getNode();
20364
20365   // Sometimes the operand may come from a insert_subvector building a 256-bit
20366   // allones vector
20367   if (VT.is256BitVector() &&
20368       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20369     SDValue V1 = N->getOperand(0);
20370     SDValue V2 = N->getOperand(1);
20371
20372     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20373         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20374         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20375         ISD::isBuildVectorAllOnes(V2.getNode()))
20376       return true;
20377   }
20378
20379   return false;
20380 }
20381
20382 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20383 // register. In most cases we actually compare or select YMM-sized registers
20384 // and mixing the two types creates horrible code. This method optimizes
20385 // some of the transition sequences.
20386 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20387                                  TargetLowering::DAGCombinerInfo &DCI,
20388                                  const X86Subtarget *Subtarget) {
20389   EVT VT = N->getValueType(0);
20390   if (!VT.is256BitVector())
20391     return SDValue();
20392
20393   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20394           N->getOpcode() == ISD::ZERO_EXTEND ||
20395           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20396
20397   SDValue Narrow = N->getOperand(0);
20398   EVT NarrowVT = Narrow->getValueType(0);
20399   if (!NarrowVT.is128BitVector())
20400     return SDValue();
20401
20402   if (Narrow->getOpcode() != ISD::XOR &&
20403       Narrow->getOpcode() != ISD::AND &&
20404       Narrow->getOpcode() != ISD::OR)
20405     return SDValue();
20406
20407   SDValue N0  = Narrow->getOperand(0);
20408   SDValue N1  = Narrow->getOperand(1);
20409   SDLoc DL(Narrow);
20410
20411   // The Left side has to be a trunc.
20412   if (N0.getOpcode() != ISD::TRUNCATE)
20413     return SDValue();
20414
20415   // The type of the truncated inputs.
20416   EVT WideVT = N0->getOperand(0)->getValueType(0);
20417   if (WideVT != VT)
20418     return SDValue();
20419
20420   // The right side has to be a 'trunc' or a constant vector.
20421   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20422   ConstantSDNode *RHSConstSplat = nullptr;
20423   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20424     RHSConstSplat = RHSBV->getConstantSplatNode();
20425   if (!RHSTrunc && !RHSConstSplat)
20426     return SDValue();
20427
20428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20429
20430   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20431     return SDValue();
20432
20433   // Set N0 and N1 to hold the inputs to the new wide operation.
20434   N0 = N0->getOperand(0);
20435   if (RHSConstSplat) {
20436     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20437                      SDValue(RHSConstSplat, 0));
20438     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20439     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20440   } else if (RHSTrunc) {
20441     N1 = N1->getOperand(0);
20442   }
20443
20444   // Generate the wide operation.
20445   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20446   unsigned Opcode = N->getOpcode();
20447   switch (Opcode) {
20448   case ISD::ANY_EXTEND:
20449     return Op;
20450   case ISD::ZERO_EXTEND: {
20451     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20452     APInt Mask = APInt::getAllOnesValue(InBits);
20453     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20454     return DAG.getNode(ISD::AND, DL, VT,
20455                        Op, DAG.getConstant(Mask, VT));
20456   }
20457   case ISD::SIGN_EXTEND:
20458     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20459                        Op, DAG.getValueType(NarrowVT));
20460   default:
20461     llvm_unreachable("Unexpected opcode");
20462   }
20463 }
20464
20465 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20466                                  TargetLowering::DAGCombinerInfo &DCI,
20467                                  const X86Subtarget *Subtarget) {
20468   EVT VT = N->getValueType(0);
20469   if (DCI.isBeforeLegalizeOps())
20470     return SDValue();
20471
20472   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20473   if (R.getNode())
20474     return R;
20475
20476   // Create BEXTR instructions
20477   // BEXTR is ((X >> imm) & (2**size-1))
20478   if (VT == MVT::i32 || VT == MVT::i64) {
20479     SDValue N0 = N->getOperand(0);
20480     SDValue N1 = N->getOperand(1);
20481     SDLoc DL(N);
20482
20483     // Check for BEXTR.
20484     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20485         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20486       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20487       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20488       if (MaskNode && ShiftNode) {
20489         uint64_t Mask = MaskNode->getZExtValue();
20490         uint64_t Shift = ShiftNode->getZExtValue();
20491         if (isMask_64(Mask)) {
20492           uint64_t MaskSize = CountPopulation_64(Mask);
20493           if (Shift + MaskSize <= VT.getSizeInBits())
20494             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20495                                DAG.getConstant(Shift | (MaskSize << 8), VT));
20496         }
20497       }
20498     } // BEXTR
20499
20500     return SDValue();
20501   }
20502
20503   // Want to form ANDNP nodes:
20504   // 1) In the hopes of then easily combining them with OR and AND nodes
20505   //    to form PBLEND/PSIGN.
20506   // 2) To match ANDN packed intrinsics
20507   if (VT != MVT::v2i64 && VT != MVT::v4i64)
20508     return SDValue();
20509
20510   SDValue N0 = N->getOperand(0);
20511   SDValue N1 = N->getOperand(1);
20512   SDLoc DL(N);
20513
20514   // Check LHS for vnot
20515   if (N0.getOpcode() == ISD::XOR &&
20516       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20517       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20518     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20519
20520   // Check RHS for vnot
20521   if (N1.getOpcode() == ISD::XOR &&
20522       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20523       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20524     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20525
20526   return SDValue();
20527 }
20528
20529 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20530                                 TargetLowering::DAGCombinerInfo &DCI,
20531                                 const X86Subtarget *Subtarget) {
20532   if (DCI.isBeforeLegalizeOps())
20533     return SDValue();
20534
20535   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20536   if (R.getNode())
20537     return R;
20538
20539   SDValue N0 = N->getOperand(0);
20540   SDValue N1 = N->getOperand(1);
20541   EVT VT = N->getValueType(0);
20542
20543   // look for psign/blend
20544   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20545     if (!Subtarget->hasSSSE3() ||
20546         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20547       return SDValue();
20548
20549     // Canonicalize pandn to RHS
20550     if (N0.getOpcode() == X86ISD::ANDNP)
20551       std::swap(N0, N1);
20552     // or (and (m, y), (pandn m, x))
20553     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20554       SDValue Mask = N1.getOperand(0);
20555       SDValue X    = N1.getOperand(1);
20556       SDValue Y;
20557       if (N0.getOperand(0) == Mask)
20558         Y = N0.getOperand(1);
20559       if (N0.getOperand(1) == Mask)
20560         Y = N0.getOperand(0);
20561
20562       // Check to see if the mask appeared in both the AND and ANDNP and
20563       if (!Y.getNode())
20564         return SDValue();
20565
20566       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20567       // Look through mask bitcast.
20568       if (Mask.getOpcode() == ISD::BITCAST)
20569         Mask = Mask.getOperand(0);
20570       if (X.getOpcode() == ISD::BITCAST)
20571         X = X.getOperand(0);
20572       if (Y.getOpcode() == ISD::BITCAST)
20573         Y = Y.getOperand(0);
20574
20575       EVT MaskVT = Mask.getValueType();
20576
20577       // Validate that the Mask operand is a vector sra node.
20578       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20579       // there is no psrai.b
20580       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20581       unsigned SraAmt = ~0;
20582       if (Mask.getOpcode() == ISD::SRA) {
20583         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20584           if (auto *AmtConst = AmtBV->getConstantSplatNode())
20585             SraAmt = AmtConst->getZExtValue();
20586       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20587         SDValue SraC = Mask.getOperand(1);
20588         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
20589       }
20590       if ((SraAmt + 1) != EltBits)
20591         return SDValue();
20592
20593       SDLoc DL(N);
20594
20595       // Now we know we at least have a plendvb with the mask val.  See if
20596       // we can form a psignb/w/d.
20597       // psign = x.type == y.type == mask.type && y = sub(0, x);
20598       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20599           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20600           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20601         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20602                "Unsupported VT for PSIGN");
20603         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20604         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20605       }
20606       // PBLENDVB only available on SSE 4.1
20607       if (!Subtarget->hasSSE41())
20608         return SDValue();
20609
20610       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20611
20612       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20613       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20614       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20615       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20616       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20617     }
20618   }
20619
20620   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20621     return SDValue();
20622
20623   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20624   MachineFunction &MF = DAG.getMachineFunction();
20625   bool OptForSize = MF.getFunction()->getAttributes().
20626     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20627
20628   // SHLD/SHRD instructions have lower register pressure, but on some
20629   // platforms they have higher latency than the equivalent
20630   // series of shifts/or that would otherwise be generated.
20631   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20632   // have higher latencies and we are not optimizing for size.
20633   if (!OptForSize && Subtarget->isSHLDSlow())
20634     return SDValue();
20635
20636   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20637     std::swap(N0, N1);
20638   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20639     return SDValue();
20640   if (!N0.hasOneUse() || !N1.hasOneUse())
20641     return SDValue();
20642
20643   SDValue ShAmt0 = N0.getOperand(1);
20644   if (ShAmt0.getValueType() != MVT::i8)
20645     return SDValue();
20646   SDValue ShAmt1 = N1.getOperand(1);
20647   if (ShAmt1.getValueType() != MVT::i8)
20648     return SDValue();
20649   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20650     ShAmt0 = ShAmt0.getOperand(0);
20651   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20652     ShAmt1 = ShAmt1.getOperand(0);
20653
20654   SDLoc DL(N);
20655   unsigned Opc = X86ISD::SHLD;
20656   SDValue Op0 = N0.getOperand(0);
20657   SDValue Op1 = N1.getOperand(0);
20658   if (ShAmt0.getOpcode() == ISD::SUB) {
20659     Opc = X86ISD::SHRD;
20660     std::swap(Op0, Op1);
20661     std::swap(ShAmt0, ShAmt1);
20662   }
20663
20664   unsigned Bits = VT.getSizeInBits();
20665   if (ShAmt1.getOpcode() == ISD::SUB) {
20666     SDValue Sum = ShAmt1.getOperand(0);
20667     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20668       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20669       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20670         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20671       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20672         return DAG.getNode(Opc, DL, VT,
20673                            Op0, Op1,
20674                            DAG.getNode(ISD::TRUNCATE, DL,
20675                                        MVT::i8, ShAmt0));
20676     }
20677   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20678     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20679     if (ShAmt0C &&
20680         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20681       return DAG.getNode(Opc, DL, VT,
20682                          N0.getOperand(0), N1.getOperand(0),
20683                          DAG.getNode(ISD::TRUNCATE, DL,
20684                                        MVT::i8, ShAmt0));
20685   }
20686
20687   return SDValue();
20688 }
20689
20690 // Generate NEG and CMOV for integer abs.
20691 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20692   EVT VT = N->getValueType(0);
20693
20694   // Since X86 does not have CMOV for 8-bit integer, we don't convert
20695   // 8-bit integer abs to NEG and CMOV.
20696   if (VT.isInteger() && VT.getSizeInBits() == 8)
20697     return SDValue();
20698
20699   SDValue N0 = N->getOperand(0);
20700   SDValue N1 = N->getOperand(1);
20701   SDLoc DL(N);
20702
20703   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20704   // and change it to SUB and CMOV.
20705   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20706       N0.getOpcode() == ISD::ADD &&
20707       N0.getOperand(1) == N1 &&
20708       N1.getOpcode() == ISD::SRA &&
20709       N1.getOperand(0) == N0.getOperand(0))
20710     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20711       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20712         // Generate SUB & CMOV.
20713         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20714                                   DAG.getConstant(0, VT), N0.getOperand(0));
20715
20716         SDValue Ops[] = { N0.getOperand(0), Neg,
20717                           DAG.getConstant(X86::COND_GE, MVT::i8),
20718                           SDValue(Neg.getNode(), 1) };
20719         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20720       }
20721   return SDValue();
20722 }
20723
20724 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20725 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20726                                  TargetLowering::DAGCombinerInfo &DCI,
20727                                  const X86Subtarget *Subtarget) {
20728   if (DCI.isBeforeLegalizeOps())
20729     return SDValue();
20730
20731   if (Subtarget->hasCMov()) {
20732     SDValue RV = performIntegerAbsCombine(N, DAG);
20733     if (RV.getNode())
20734       return RV;
20735   }
20736
20737   return SDValue();
20738 }
20739
20740 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20741 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20742                                   TargetLowering::DAGCombinerInfo &DCI,
20743                                   const X86Subtarget *Subtarget) {
20744   LoadSDNode *Ld = cast<LoadSDNode>(N);
20745   EVT RegVT = Ld->getValueType(0);
20746   EVT MemVT = Ld->getMemoryVT();
20747   SDLoc dl(Ld);
20748   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20749   unsigned RegSz = RegVT.getSizeInBits();
20750
20751   // On Sandybridge unaligned 256bit loads are inefficient.
20752   ISD::LoadExtType Ext = Ld->getExtensionType();
20753   unsigned Alignment = Ld->getAlignment();
20754   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20755   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20756       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20757     unsigned NumElems = RegVT.getVectorNumElements();
20758     if (NumElems < 2)
20759       return SDValue();
20760
20761     SDValue Ptr = Ld->getBasePtr();
20762     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20763
20764     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20765                                   NumElems/2);
20766     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20767                                 Ld->getPointerInfo(), Ld->isVolatile(),
20768                                 Ld->isNonTemporal(), Ld->isInvariant(),
20769                                 Alignment);
20770     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20771     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20772                                 Ld->getPointerInfo(), Ld->isVolatile(),
20773                                 Ld->isNonTemporal(), Ld->isInvariant(),
20774                                 std::min(16U, Alignment));
20775     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20776                              Load1.getValue(1),
20777                              Load2.getValue(1));
20778
20779     SDValue NewVec = DAG.getUNDEF(RegVT);
20780     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20781     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20782     return DCI.CombineTo(N, NewVec, TF, true);
20783   }
20784
20785   // If this is a vector EXT Load then attempt to optimize it using a
20786   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20787   // expansion is still better than scalar code.
20788   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20789   // emit a shuffle and a arithmetic shift.
20790   // TODO: It is possible to support ZExt by zeroing the undef values
20791   // during the shuffle phase or after the shuffle.
20792   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20793       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20794     assert(MemVT != RegVT && "Cannot extend to the same type");
20795     assert(MemVT.isVector() && "Must load a vector from memory");
20796
20797     unsigned NumElems = RegVT.getVectorNumElements();
20798     unsigned MemSz = MemVT.getSizeInBits();
20799     assert(RegSz > MemSz && "Register size must be greater than the mem size");
20800
20801     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20802       return SDValue();
20803
20804     // All sizes must be a power of two.
20805     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20806       return SDValue();
20807
20808     // Attempt to load the original value using scalar loads.
20809     // Find the largest scalar type that divides the total loaded size.
20810     MVT SclrLoadTy = MVT::i8;
20811     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20812          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20813       MVT Tp = (MVT::SimpleValueType)tp;
20814       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20815         SclrLoadTy = Tp;
20816       }
20817     }
20818
20819     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20820     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20821         (64 <= MemSz))
20822       SclrLoadTy = MVT::f64;
20823
20824     // Calculate the number of scalar loads that we need to perform
20825     // in order to load our vector from memory.
20826     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20827     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20828       return SDValue();
20829
20830     unsigned loadRegZize = RegSz;
20831     if (Ext == ISD::SEXTLOAD && RegSz == 256)
20832       loadRegZize /= 2;
20833
20834     // Represent our vector as a sequence of elements which are the
20835     // largest scalar that we can load.
20836     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20837       loadRegZize/SclrLoadTy.getSizeInBits());
20838
20839     // Represent the data using the same element type that is stored in
20840     // memory. In practice, we ''widen'' MemVT.
20841     EVT WideVecVT =
20842           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20843                        loadRegZize/MemVT.getScalarType().getSizeInBits());
20844
20845     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20846       "Invalid vector type");
20847
20848     // We can't shuffle using an illegal type.
20849     if (!TLI.isTypeLegal(WideVecVT))
20850       return SDValue();
20851
20852     SmallVector<SDValue, 8> Chains;
20853     SDValue Ptr = Ld->getBasePtr();
20854     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20855                                         TLI.getPointerTy());
20856     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20857
20858     for (unsigned i = 0; i < NumLoads; ++i) {
20859       // Perform a single load.
20860       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20861                                        Ptr, Ld->getPointerInfo(),
20862                                        Ld->isVolatile(), Ld->isNonTemporal(),
20863                                        Ld->isInvariant(), Ld->getAlignment());
20864       Chains.push_back(ScalarLoad.getValue(1));
20865       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20866       // another round of DAGCombining.
20867       if (i == 0)
20868         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20869       else
20870         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20871                           ScalarLoad, DAG.getIntPtrConstant(i));
20872
20873       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20874     }
20875
20876     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20877
20878     // Bitcast the loaded value to a vector of the original element type, in
20879     // the size of the target vector type.
20880     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20881     unsigned SizeRatio = RegSz/MemSz;
20882
20883     if (Ext == ISD::SEXTLOAD) {
20884       // If we have SSE4.1 we can directly emit a VSEXT node.
20885       if (Subtarget->hasSSE41()) {
20886         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20887         return DCI.CombineTo(N, Sext, TF, true);
20888       }
20889
20890       // Otherwise we'll shuffle the small elements in the high bits of the
20891       // larger type and perform an arithmetic shift. If the shift is not legal
20892       // it's better to scalarize.
20893       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20894         return SDValue();
20895
20896       // Redistribute the loaded elements into the different locations.
20897       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20898       for (unsigned i = 0; i != NumElems; ++i)
20899         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20900
20901       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20902                                            DAG.getUNDEF(WideVecVT),
20903                                            &ShuffleVec[0]);
20904
20905       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20906
20907       // Build the arithmetic shift.
20908       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20909                      MemVT.getVectorElementType().getSizeInBits();
20910       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20911                           DAG.getConstant(Amt, RegVT));
20912
20913       return DCI.CombineTo(N, Shuff, TF, true);
20914     }
20915
20916     // Redistribute the loaded elements into the different locations.
20917     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20918     for (unsigned i = 0; i != NumElems; ++i)
20919       ShuffleVec[i*SizeRatio] = i;
20920
20921     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20922                                          DAG.getUNDEF(WideVecVT),
20923                                          &ShuffleVec[0]);
20924
20925     // Bitcast to the requested type.
20926     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20927     // Replace the original load with the new sequence
20928     // and return the new chain.
20929     return DCI.CombineTo(N, Shuff, TF, true);
20930   }
20931
20932   return SDValue();
20933 }
20934
20935 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20936 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20937                                    const X86Subtarget *Subtarget) {
20938   StoreSDNode *St = cast<StoreSDNode>(N);
20939   EVT VT = St->getValue().getValueType();
20940   EVT StVT = St->getMemoryVT();
20941   SDLoc dl(St);
20942   SDValue StoredVal = St->getOperand(1);
20943   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20944
20945   // If we are saving a concatenation of two XMM registers, perform two stores.
20946   // On Sandy Bridge, 256-bit memory operations are executed by two
20947   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20948   // memory  operation.
20949   unsigned Alignment = St->getAlignment();
20950   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20951   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20952       StVT == VT && !IsAligned) {
20953     unsigned NumElems = VT.getVectorNumElements();
20954     if (NumElems < 2)
20955       return SDValue();
20956
20957     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20958     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20959
20960     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20961     SDValue Ptr0 = St->getBasePtr();
20962     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20963
20964     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20965                                 St->getPointerInfo(), St->isVolatile(),
20966                                 St->isNonTemporal(), Alignment);
20967     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20968                                 St->getPointerInfo(), St->isVolatile(),
20969                                 St->isNonTemporal(),
20970                                 std::min(16U, Alignment));
20971     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20972   }
20973
20974   // Optimize trunc store (of multiple scalars) to shuffle and store.
20975   // First, pack all of the elements in one place. Next, store to memory
20976   // in fewer chunks.
20977   if (St->isTruncatingStore() && VT.isVector()) {
20978     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20979     unsigned NumElems = VT.getVectorNumElements();
20980     assert(StVT != VT && "Cannot truncate to the same type");
20981     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20982     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20983
20984     // From, To sizes and ElemCount must be pow of two
20985     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20986     // We are going to use the original vector elt for storing.
20987     // Accumulated smaller vector elements must be a multiple of the store size.
20988     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20989
20990     unsigned SizeRatio  = FromSz / ToSz;
20991
20992     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20993
20994     // Create a type on which we perform the shuffle
20995     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20996             StVT.getScalarType(), NumElems*SizeRatio);
20997
20998     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20999
21000     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21001     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21002     for (unsigned i = 0; i != NumElems; ++i)
21003       ShuffleVec[i] = i * SizeRatio;
21004
21005     // Can't shuffle using an illegal type.
21006     if (!TLI.isTypeLegal(WideVecVT))
21007       return SDValue();
21008
21009     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21010                                          DAG.getUNDEF(WideVecVT),
21011                                          &ShuffleVec[0]);
21012     // At this point all of the data is stored at the bottom of the
21013     // register. We now need to save it to mem.
21014
21015     // Find the largest store unit
21016     MVT StoreType = MVT::i8;
21017     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21018          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21019       MVT Tp = (MVT::SimpleValueType)tp;
21020       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21021         StoreType = Tp;
21022     }
21023
21024     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21025     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21026         (64 <= NumElems * ToSz))
21027       StoreType = MVT::f64;
21028
21029     // Bitcast the original vector into a vector of store-size units
21030     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21031             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21032     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21033     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21034     SmallVector<SDValue, 8> Chains;
21035     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21036                                         TLI.getPointerTy());
21037     SDValue Ptr = St->getBasePtr();
21038
21039     // Perform one or more big stores into memory.
21040     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21041       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21042                                    StoreType, ShuffWide,
21043                                    DAG.getIntPtrConstant(i));
21044       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21045                                 St->getPointerInfo(), St->isVolatile(),
21046                                 St->isNonTemporal(), St->getAlignment());
21047       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21048       Chains.push_back(Ch);
21049     }
21050
21051     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21052   }
21053
21054   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21055   // the FP state in cases where an emms may be missing.
21056   // A preferable solution to the general problem is to figure out the right
21057   // places to insert EMMS.  This qualifies as a quick hack.
21058
21059   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21060   if (VT.getSizeInBits() != 64)
21061     return SDValue();
21062
21063   const Function *F = DAG.getMachineFunction().getFunction();
21064   bool NoImplicitFloatOps = F->getAttributes().
21065     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21066   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21067                      && Subtarget->hasSSE2();
21068   if ((VT.isVector() ||
21069        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21070       isa<LoadSDNode>(St->getValue()) &&
21071       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21072       St->getChain().hasOneUse() && !St->isVolatile()) {
21073     SDNode* LdVal = St->getValue().getNode();
21074     LoadSDNode *Ld = nullptr;
21075     int TokenFactorIndex = -1;
21076     SmallVector<SDValue, 8> Ops;
21077     SDNode* ChainVal = St->getChain().getNode();
21078     // Must be a store of a load.  We currently handle two cases:  the load
21079     // is a direct child, and it's under an intervening TokenFactor.  It is
21080     // possible to dig deeper under nested TokenFactors.
21081     if (ChainVal == LdVal)
21082       Ld = cast<LoadSDNode>(St->getChain());
21083     else if (St->getValue().hasOneUse() &&
21084              ChainVal->getOpcode() == ISD::TokenFactor) {
21085       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21086         if (ChainVal->getOperand(i).getNode() == LdVal) {
21087           TokenFactorIndex = i;
21088           Ld = cast<LoadSDNode>(St->getValue());
21089         } else
21090           Ops.push_back(ChainVal->getOperand(i));
21091       }
21092     }
21093
21094     if (!Ld || !ISD::isNormalLoad(Ld))
21095       return SDValue();
21096
21097     // If this is not the MMX case, i.e. we are just turning i64 load/store
21098     // into f64 load/store, avoid the transformation if there are multiple
21099     // uses of the loaded value.
21100     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21101       return SDValue();
21102
21103     SDLoc LdDL(Ld);
21104     SDLoc StDL(N);
21105     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21106     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21107     // pair instead.
21108     if (Subtarget->is64Bit() || F64IsLegal) {
21109       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21110       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21111                                   Ld->getPointerInfo(), Ld->isVolatile(),
21112                                   Ld->isNonTemporal(), Ld->isInvariant(),
21113                                   Ld->getAlignment());
21114       SDValue NewChain = NewLd.getValue(1);
21115       if (TokenFactorIndex != -1) {
21116         Ops.push_back(NewChain);
21117         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21118       }
21119       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21120                           St->getPointerInfo(),
21121                           St->isVolatile(), St->isNonTemporal(),
21122                           St->getAlignment());
21123     }
21124
21125     // Otherwise, lower to two pairs of 32-bit loads / stores.
21126     SDValue LoAddr = Ld->getBasePtr();
21127     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21128                                  DAG.getConstant(4, MVT::i32));
21129
21130     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21131                                Ld->getPointerInfo(),
21132                                Ld->isVolatile(), Ld->isNonTemporal(),
21133                                Ld->isInvariant(), Ld->getAlignment());
21134     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21135                                Ld->getPointerInfo().getWithOffset(4),
21136                                Ld->isVolatile(), Ld->isNonTemporal(),
21137                                Ld->isInvariant(),
21138                                MinAlign(Ld->getAlignment(), 4));
21139
21140     SDValue NewChain = LoLd.getValue(1);
21141     if (TokenFactorIndex != -1) {
21142       Ops.push_back(LoLd);
21143       Ops.push_back(HiLd);
21144       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21145     }
21146
21147     LoAddr = St->getBasePtr();
21148     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21149                          DAG.getConstant(4, MVT::i32));
21150
21151     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21152                                 St->getPointerInfo(),
21153                                 St->isVolatile(), St->isNonTemporal(),
21154                                 St->getAlignment());
21155     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21156                                 St->getPointerInfo().getWithOffset(4),
21157                                 St->isVolatile(),
21158                                 St->isNonTemporal(),
21159                                 MinAlign(St->getAlignment(), 4));
21160     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21161   }
21162   return SDValue();
21163 }
21164
21165 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21166 /// and return the operands for the horizontal operation in LHS and RHS.  A
21167 /// horizontal operation performs the binary operation on successive elements
21168 /// of its first operand, then on successive elements of its second operand,
21169 /// returning the resulting values in a vector.  For example, if
21170 ///   A = < float a0, float a1, float a2, float a3 >
21171 /// and
21172 ///   B = < float b0, float b1, float b2, float b3 >
21173 /// then the result of doing a horizontal operation on A and B is
21174 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21175 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21176 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21177 /// set to A, RHS to B, and the routine returns 'true'.
21178 /// Note that the binary operation should have the property that if one of the
21179 /// operands is UNDEF then the result is UNDEF.
21180 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21181   // Look for the following pattern: if
21182   //   A = < float a0, float a1, float a2, float a3 >
21183   //   B = < float b0, float b1, float b2, float b3 >
21184   // and
21185   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21186   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21187   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21188   // which is A horizontal-op B.
21189
21190   // At least one of the operands should be a vector shuffle.
21191   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21192       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21193     return false;
21194
21195   MVT VT = LHS.getSimpleValueType();
21196
21197   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21198          "Unsupported vector type for horizontal add/sub");
21199
21200   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21201   // operate independently on 128-bit lanes.
21202   unsigned NumElts = VT.getVectorNumElements();
21203   unsigned NumLanes = VT.getSizeInBits()/128;
21204   unsigned NumLaneElts = NumElts / NumLanes;
21205   assert((NumLaneElts % 2 == 0) &&
21206          "Vector type should have an even number of elements in each lane");
21207   unsigned HalfLaneElts = NumLaneElts/2;
21208
21209   // View LHS in the form
21210   //   LHS = VECTOR_SHUFFLE A, B, LMask
21211   // If LHS is not a shuffle then pretend it is the shuffle
21212   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21213   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21214   // type VT.
21215   SDValue A, B;
21216   SmallVector<int, 16> LMask(NumElts);
21217   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21218     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21219       A = LHS.getOperand(0);
21220     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21221       B = LHS.getOperand(1);
21222     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21223     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21224   } else {
21225     if (LHS.getOpcode() != ISD::UNDEF)
21226       A = LHS;
21227     for (unsigned i = 0; i != NumElts; ++i)
21228       LMask[i] = i;
21229   }
21230
21231   // Likewise, view RHS in the form
21232   //   RHS = VECTOR_SHUFFLE C, D, RMask
21233   SDValue C, D;
21234   SmallVector<int, 16> RMask(NumElts);
21235   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21236     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21237       C = RHS.getOperand(0);
21238     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21239       D = RHS.getOperand(1);
21240     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21241     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21242   } else {
21243     if (RHS.getOpcode() != ISD::UNDEF)
21244       C = RHS;
21245     for (unsigned i = 0; i != NumElts; ++i)
21246       RMask[i] = i;
21247   }
21248
21249   // Check that the shuffles are both shuffling the same vectors.
21250   if (!(A == C && B == D) && !(A == D && B == C))
21251     return false;
21252
21253   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21254   if (!A.getNode() && !B.getNode())
21255     return false;
21256
21257   // If A and B occur in reverse order in RHS, then "swap" them (which means
21258   // rewriting the mask).
21259   if (A != C)
21260     CommuteVectorShuffleMask(RMask, NumElts);
21261
21262   // At this point LHS and RHS are equivalent to
21263   //   LHS = VECTOR_SHUFFLE A, B, LMask
21264   //   RHS = VECTOR_SHUFFLE A, B, RMask
21265   // Check that the masks correspond to performing a horizontal operation.
21266   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21267     for (unsigned i = 0; i != NumLaneElts; ++i) {
21268       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21269
21270       // Ignore any UNDEF components.
21271       if (LIdx < 0 || RIdx < 0 ||
21272           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21273           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21274         continue;
21275
21276       // Check that successive elements are being operated on.  If not, this is
21277       // not a horizontal operation.
21278       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21279       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21280       if (!(LIdx == Index && RIdx == Index + 1) &&
21281           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21282         return false;
21283     }
21284   }
21285
21286   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21287   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21288   return true;
21289 }
21290
21291 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21292 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21293                                   const X86Subtarget *Subtarget) {
21294   EVT VT = N->getValueType(0);
21295   SDValue LHS = N->getOperand(0);
21296   SDValue RHS = N->getOperand(1);
21297
21298   // Try to synthesize horizontal adds from adds of shuffles.
21299   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21300        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21301       isHorizontalBinOp(LHS, RHS, true))
21302     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21303   return SDValue();
21304 }
21305
21306 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21307 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21308                                   const X86Subtarget *Subtarget) {
21309   EVT VT = N->getValueType(0);
21310   SDValue LHS = N->getOperand(0);
21311   SDValue RHS = N->getOperand(1);
21312
21313   // Try to synthesize horizontal subs from subs of shuffles.
21314   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21315        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21316       isHorizontalBinOp(LHS, RHS, false))
21317     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21318   return SDValue();
21319 }
21320
21321 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21322 /// X86ISD::FXOR nodes.
21323 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21324   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21325   // F[X]OR(0.0, x) -> x
21326   // F[X]OR(x, 0.0) -> x
21327   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21328     if (C->getValueAPF().isPosZero())
21329       return N->getOperand(1);
21330   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21331     if (C->getValueAPF().isPosZero())
21332       return N->getOperand(0);
21333   return SDValue();
21334 }
21335
21336 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21337 /// X86ISD::FMAX nodes.
21338 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21339   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21340
21341   // Only perform optimizations if UnsafeMath is used.
21342   if (!DAG.getTarget().Options.UnsafeFPMath)
21343     return SDValue();
21344
21345   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21346   // into FMINC and FMAXC, which are Commutative operations.
21347   unsigned NewOp = 0;
21348   switch (N->getOpcode()) {
21349     default: llvm_unreachable("unknown opcode");
21350     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21351     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21352   }
21353
21354   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21355                      N->getOperand(0), N->getOperand(1));
21356 }
21357
21358 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21359 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21360   // FAND(0.0, x) -> 0.0
21361   // FAND(x, 0.0) -> 0.0
21362   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21363     if (C->getValueAPF().isPosZero())
21364       return N->getOperand(0);
21365   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21366     if (C->getValueAPF().isPosZero())
21367       return N->getOperand(1);
21368   return SDValue();
21369 }
21370
21371 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21372 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21373   // FANDN(x, 0.0) -> 0.0
21374   // FANDN(0.0, x) -> x
21375   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21376     if (C->getValueAPF().isPosZero())
21377       return N->getOperand(1);
21378   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21379     if (C->getValueAPF().isPosZero())
21380       return N->getOperand(1);
21381   return SDValue();
21382 }
21383
21384 static SDValue PerformBTCombine(SDNode *N,
21385                                 SelectionDAG &DAG,
21386                                 TargetLowering::DAGCombinerInfo &DCI) {
21387   // BT ignores high bits in the bit index operand.
21388   SDValue Op1 = N->getOperand(1);
21389   if (Op1.hasOneUse()) {
21390     unsigned BitWidth = Op1.getValueSizeInBits();
21391     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21392     APInt KnownZero, KnownOne;
21393     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21394                                           !DCI.isBeforeLegalizeOps());
21395     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21396     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21397         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21398       DCI.CommitTargetLoweringOpt(TLO);
21399   }
21400   return SDValue();
21401 }
21402
21403 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21404   SDValue Op = N->getOperand(0);
21405   if (Op.getOpcode() == ISD::BITCAST)
21406     Op = Op.getOperand(0);
21407   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21408   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21409       VT.getVectorElementType().getSizeInBits() ==
21410       OpVT.getVectorElementType().getSizeInBits()) {
21411     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21412   }
21413   return SDValue();
21414 }
21415
21416 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21417                                                const X86Subtarget *Subtarget) {
21418   EVT VT = N->getValueType(0);
21419   if (!VT.isVector())
21420     return SDValue();
21421
21422   SDValue N0 = N->getOperand(0);
21423   SDValue N1 = N->getOperand(1);
21424   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21425   SDLoc dl(N);
21426
21427   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21428   // both SSE and AVX2 since there is no sign-extended shift right
21429   // operation on a vector with 64-bit elements.
21430   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21431   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21432   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21433       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21434     SDValue N00 = N0.getOperand(0);
21435
21436     // EXTLOAD has a better solution on AVX2,
21437     // it may be replaced with X86ISD::VSEXT node.
21438     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21439       if (!ISD::isNormalLoad(N00.getNode()))
21440         return SDValue();
21441
21442     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21443         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21444                                   N00, N1);
21445       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21446     }
21447   }
21448   return SDValue();
21449 }
21450
21451 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21452                                   TargetLowering::DAGCombinerInfo &DCI,
21453                                   const X86Subtarget *Subtarget) {
21454   if (!DCI.isBeforeLegalizeOps())
21455     return SDValue();
21456
21457   if (!Subtarget->hasFp256())
21458     return SDValue();
21459
21460   EVT VT = N->getValueType(0);
21461   if (VT.isVector() && VT.getSizeInBits() == 256) {
21462     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21463     if (R.getNode())
21464       return R;
21465   }
21466
21467   return SDValue();
21468 }
21469
21470 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21471                                  const X86Subtarget* Subtarget) {
21472   SDLoc dl(N);
21473   EVT VT = N->getValueType(0);
21474
21475   // Let legalize expand this if it isn't a legal type yet.
21476   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21477     return SDValue();
21478
21479   EVT ScalarVT = VT.getScalarType();
21480   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21481       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21482     return SDValue();
21483
21484   SDValue A = N->getOperand(0);
21485   SDValue B = N->getOperand(1);
21486   SDValue C = N->getOperand(2);
21487
21488   bool NegA = (A.getOpcode() == ISD::FNEG);
21489   bool NegB = (B.getOpcode() == ISD::FNEG);
21490   bool NegC = (C.getOpcode() == ISD::FNEG);
21491
21492   // Negative multiplication when NegA xor NegB
21493   bool NegMul = (NegA != NegB);
21494   if (NegA)
21495     A = A.getOperand(0);
21496   if (NegB)
21497     B = B.getOperand(0);
21498   if (NegC)
21499     C = C.getOperand(0);
21500
21501   unsigned Opcode;
21502   if (!NegMul)
21503     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21504   else
21505     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21506
21507   return DAG.getNode(Opcode, dl, VT, A, B, C);
21508 }
21509
21510 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21511                                   TargetLowering::DAGCombinerInfo &DCI,
21512                                   const X86Subtarget *Subtarget) {
21513   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21514   //           (and (i32 x86isd::setcc_carry), 1)
21515   // This eliminates the zext. This transformation is necessary because
21516   // ISD::SETCC is always legalized to i8.
21517   SDLoc dl(N);
21518   SDValue N0 = N->getOperand(0);
21519   EVT VT = N->getValueType(0);
21520
21521   if (N0.getOpcode() == ISD::AND &&
21522       N0.hasOneUse() &&
21523       N0.getOperand(0).hasOneUse()) {
21524     SDValue N00 = N0.getOperand(0);
21525     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21526       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21527       if (!C || C->getZExtValue() != 1)
21528         return SDValue();
21529       return DAG.getNode(ISD::AND, dl, VT,
21530                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21531                                      N00.getOperand(0), N00.getOperand(1)),
21532                          DAG.getConstant(1, VT));
21533     }
21534   }
21535
21536   if (N0.getOpcode() == ISD::TRUNCATE &&
21537       N0.hasOneUse() &&
21538       N0.getOperand(0).hasOneUse()) {
21539     SDValue N00 = N0.getOperand(0);
21540     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21541       return DAG.getNode(ISD::AND, dl, VT,
21542                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21543                                      N00.getOperand(0), N00.getOperand(1)),
21544                          DAG.getConstant(1, VT));
21545     }
21546   }
21547   if (VT.is256BitVector()) {
21548     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21549     if (R.getNode())
21550       return R;
21551   }
21552
21553   return SDValue();
21554 }
21555
21556 // Optimize x == -y --> x+y == 0
21557 //          x != -y --> x+y != 0
21558 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21559                                       const X86Subtarget* Subtarget) {
21560   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21561   SDValue LHS = N->getOperand(0);
21562   SDValue RHS = N->getOperand(1);
21563   EVT VT = N->getValueType(0);
21564   SDLoc DL(N);
21565
21566   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21567     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21568       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21569         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21570                                    LHS.getValueType(), RHS, LHS.getOperand(1));
21571         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21572                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21573       }
21574   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21575     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21576       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21577         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21578                                    RHS.getValueType(), LHS, RHS.getOperand(1));
21579         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21580                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21581       }
21582
21583   if (VT.getScalarType() == MVT::i1) {
21584     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21585       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21586     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21587     if (!IsSEXT0 && !IsVZero0)
21588       return SDValue();
21589     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21590       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21591     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21592
21593     if (!IsSEXT1 && !IsVZero1)
21594       return SDValue();
21595
21596     if (IsSEXT0 && IsVZero1) {
21597       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21598       if (CC == ISD::SETEQ)
21599         return DAG.getNOT(DL, LHS.getOperand(0), VT);
21600       return LHS.getOperand(0);
21601     }
21602     if (IsSEXT1 && IsVZero0) {
21603       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21604       if (CC == ISD::SETEQ)
21605         return DAG.getNOT(DL, RHS.getOperand(0), VT);
21606       return RHS.getOperand(0);
21607     }
21608   }
21609
21610   return SDValue();
21611 }
21612
21613 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21614                                       const X86Subtarget *Subtarget) {
21615   SDLoc dl(N);
21616   MVT VT = N->getOperand(1)->getSimpleValueType(0);
21617   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21618          "X86insertps is only defined for v4x32");
21619
21620   SDValue Ld = N->getOperand(1);
21621   if (MayFoldLoad(Ld)) {
21622     // Extract the countS bits from the immediate so we can get the proper
21623     // address when narrowing the vector load to a specific element.
21624     // When the second source op is a memory address, interps doesn't use
21625     // countS and just gets an f32 from that address.
21626     unsigned DestIndex =
21627         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21628     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21629   } else
21630     return SDValue();
21631
21632   // Create this as a scalar to vector to match the instruction pattern.
21633   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21634   // countS bits are ignored when loading from memory on insertps, which
21635   // means we don't need to explicitly set them to 0.
21636   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21637                      LoadScalarToVector, N->getOperand(2));
21638 }
21639
21640 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21641 // as "sbb reg,reg", since it can be extended without zext and produces
21642 // an all-ones bit which is more useful than 0/1 in some cases.
21643 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21644                                MVT VT) {
21645   if (VT == MVT::i8)
21646     return DAG.getNode(ISD::AND, DL, VT,
21647                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21648                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21649                        DAG.getConstant(1, VT));
21650   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21651   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21652                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21653                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21654 }
21655
21656 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21657 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21658                                    TargetLowering::DAGCombinerInfo &DCI,
21659                                    const X86Subtarget *Subtarget) {
21660   SDLoc DL(N);
21661   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21662   SDValue EFLAGS = N->getOperand(1);
21663
21664   if (CC == X86::COND_A) {
21665     // Try to convert COND_A into COND_B in an attempt to facilitate
21666     // materializing "setb reg".
21667     //
21668     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21669     // cannot take an immediate as its first operand.
21670     //
21671     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21672         EFLAGS.getValueType().isInteger() &&
21673         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21674       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21675                                    EFLAGS.getNode()->getVTList(),
21676                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21677       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21678       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21679     }
21680   }
21681
21682   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21683   // a zext and produces an all-ones bit which is more useful than 0/1 in some
21684   // cases.
21685   if (CC == X86::COND_B)
21686     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21687
21688   SDValue Flags;
21689
21690   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21691   if (Flags.getNode()) {
21692     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21693     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21694   }
21695
21696   return SDValue();
21697 }
21698
21699 // Optimize branch condition evaluation.
21700 //
21701 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21702                                     TargetLowering::DAGCombinerInfo &DCI,
21703                                     const X86Subtarget *Subtarget) {
21704   SDLoc DL(N);
21705   SDValue Chain = N->getOperand(0);
21706   SDValue Dest = N->getOperand(1);
21707   SDValue EFLAGS = N->getOperand(3);
21708   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21709
21710   SDValue Flags;
21711
21712   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21713   if (Flags.getNode()) {
21714     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21715     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21716                        Flags);
21717   }
21718
21719   return SDValue();
21720 }
21721
21722 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21723                                         const X86TargetLowering *XTLI) {
21724   SDValue Op0 = N->getOperand(0);
21725   EVT InVT = Op0->getValueType(0);
21726
21727   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21728   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21729     SDLoc dl(N);
21730     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21731     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21732     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21733   }
21734
21735   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21736   // a 32-bit target where SSE doesn't support i64->FP operations.
21737   if (Op0.getOpcode() == ISD::LOAD) {
21738     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21739     EVT VT = Ld->getValueType(0);
21740     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21741         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21742         !XTLI->getSubtarget()->is64Bit() &&
21743         VT == MVT::i64) {
21744       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21745                                           Ld->getChain(), Op0, DAG);
21746       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21747       return FILDChain;
21748     }
21749   }
21750   return SDValue();
21751 }
21752
21753 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21754 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21755                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21756   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21757   // the result is either zero or one (depending on the input carry bit).
21758   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21759   if (X86::isZeroNode(N->getOperand(0)) &&
21760       X86::isZeroNode(N->getOperand(1)) &&
21761       // We don't have a good way to replace an EFLAGS use, so only do this when
21762       // dead right now.
21763       SDValue(N, 1).use_empty()) {
21764     SDLoc DL(N);
21765     EVT VT = N->getValueType(0);
21766     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21767     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21768                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21769                                            DAG.getConstant(X86::COND_B,MVT::i8),
21770                                            N->getOperand(2)),
21771                                DAG.getConstant(1, VT));
21772     return DCI.CombineTo(N, Res1, CarryOut);
21773   }
21774
21775   return SDValue();
21776 }
21777
21778 // fold (add Y, (sete  X, 0)) -> adc  0, Y
21779 //      (add Y, (setne X, 0)) -> sbb -1, Y
21780 //      (sub (sete  X, 0), Y) -> sbb  0, Y
21781 //      (sub (setne X, 0), Y) -> adc -1, Y
21782 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21783   SDLoc DL(N);
21784
21785   // Look through ZExts.
21786   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21787   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21788     return SDValue();
21789
21790   SDValue SetCC = Ext.getOperand(0);
21791   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21792     return SDValue();
21793
21794   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21795   if (CC != X86::COND_E && CC != X86::COND_NE)
21796     return SDValue();
21797
21798   SDValue Cmp = SetCC.getOperand(1);
21799   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21800       !X86::isZeroNode(Cmp.getOperand(1)) ||
21801       !Cmp.getOperand(0).getValueType().isInteger())
21802     return SDValue();
21803
21804   SDValue CmpOp0 = Cmp.getOperand(0);
21805   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21806                                DAG.getConstant(1, CmpOp0.getValueType()));
21807
21808   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21809   if (CC == X86::COND_NE)
21810     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21811                        DL, OtherVal.getValueType(), OtherVal,
21812                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21813   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21814                      DL, OtherVal.getValueType(), OtherVal,
21815                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21816 }
21817
21818 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21819 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21820                                  const X86Subtarget *Subtarget) {
21821   EVT VT = N->getValueType(0);
21822   SDValue Op0 = N->getOperand(0);
21823   SDValue Op1 = N->getOperand(1);
21824
21825   // Try to synthesize horizontal adds from adds of shuffles.
21826   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21827        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21828       isHorizontalBinOp(Op0, Op1, true))
21829     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21830
21831   return OptimizeConditionalInDecrement(N, DAG);
21832 }
21833
21834 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21835                                  const X86Subtarget *Subtarget) {
21836   SDValue Op0 = N->getOperand(0);
21837   SDValue Op1 = N->getOperand(1);
21838
21839   // X86 can't encode an immediate LHS of a sub. See if we can push the
21840   // negation into a preceding instruction.
21841   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21842     // If the RHS of the sub is a XOR with one use and a constant, invert the
21843     // immediate. Then add one to the LHS of the sub so we can turn
21844     // X-Y -> X+~Y+1, saving one register.
21845     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21846         isa<ConstantSDNode>(Op1.getOperand(1))) {
21847       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21848       EVT VT = Op0.getValueType();
21849       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21850                                    Op1.getOperand(0),
21851                                    DAG.getConstant(~XorC, VT));
21852       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21853                          DAG.getConstant(C->getAPIntValue()+1, VT));
21854     }
21855   }
21856
21857   // Try to synthesize horizontal adds from adds of shuffles.
21858   EVT VT = N->getValueType(0);
21859   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21860        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21861       isHorizontalBinOp(Op0, Op1, true))
21862     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21863
21864   return OptimizeConditionalInDecrement(N, DAG);
21865 }
21866
21867 /// performVZEXTCombine - Performs build vector combines
21868 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21869                                         TargetLowering::DAGCombinerInfo &DCI,
21870                                         const X86Subtarget *Subtarget) {
21871   // (vzext (bitcast (vzext (x)) -> (vzext x)
21872   SDValue In = N->getOperand(0);
21873   while (In.getOpcode() == ISD::BITCAST)
21874     In = In.getOperand(0);
21875
21876   if (In.getOpcode() != X86ISD::VZEXT)
21877     return SDValue();
21878
21879   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21880                      In.getOperand(0));
21881 }
21882
21883 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21884                                              DAGCombinerInfo &DCI) const {
21885   SelectionDAG &DAG = DCI.DAG;
21886   switch (N->getOpcode()) {
21887   default: break;
21888   case ISD::EXTRACT_VECTOR_ELT:
21889     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21890   case ISD::VSELECT:
21891   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21892   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21893   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
21894   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
21895   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
21896   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
21897   case ISD::SHL:
21898   case ISD::SRA:
21899   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
21900   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
21901   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
21902   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
21903   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
21904   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
21905   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
21906   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
21907   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
21908   case X86ISD::FXOR:
21909   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
21910   case X86ISD::FMIN:
21911   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
21912   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
21913   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
21914   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
21915   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
21916   case ISD::ANY_EXTEND:
21917   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
21918   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
21919   case ISD::SIGN_EXTEND_INREG:
21920     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21921   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21922   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
21923   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21924   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21925   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
21926   case X86ISD::SHUFP:       // Handle all target specific shuffles
21927   case X86ISD::PALIGNR:
21928   case X86ISD::UNPCKH:
21929   case X86ISD::UNPCKL:
21930   case X86ISD::MOVHLPS:
21931   case X86ISD::MOVLHPS:
21932   case X86ISD::PSHUFD:
21933   case X86ISD::PSHUFHW:
21934   case X86ISD::PSHUFLW:
21935   case X86ISD::MOVSS:
21936   case X86ISD::MOVSD:
21937   case X86ISD::VPERMILP:
21938   case X86ISD::VPERM2X128:
21939   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21940   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
21941   case ISD::INTRINSIC_WO_CHAIN:
21942     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21943   case X86ISD::INSERTPS:
21944     return PerformINSERTPSCombine(N, DAG, Subtarget);
21945   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21946   }
21947
21948   return SDValue();
21949 }
21950
21951 /// isTypeDesirableForOp - Return true if the target has native support for
21952 /// the specified value type and it is 'desirable' to use the type for the
21953 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21954 /// instruction encodings are longer and some i16 instructions are slow.
21955 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21956   if (!isTypeLegal(VT))
21957     return false;
21958   if (VT != MVT::i16)
21959     return true;
21960
21961   switch (Opc) {
21962   default:
21963     return true;
21964   case ISD::LOAD:
21965   case ISD::SIGN_EXTEND:
21966   case ISD::ZERO_EXTEND:
21967   case ISD::ANY_EXTEND:
21968   case ISD::SHL:
21969   case ISD::SRL:
21970   case ISD::SUB:
21971   case ISD::ADD:
21972   case ISD::MUL:
21973   case ISD::AND:
21974   case ISD::OR:
21975   case ISD::XOR:
21976     return false;
21977   }
21978 }
21979
21980 /// IsDesirableToPromoteOp - This method query the target whether it is
21981 /// beneficial for dag combiner to promote the specified node. If true, it
21982 /// should return the desired promotion type by reference.
21983 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21984   EVT VT = Op.getValueType();
21985   if (VT != MVT::i16)
21986     return false;
21987
21988   bool Promote = false;
21989   bool Commute = false;
21990   switch (Op.getOpcode()) {
21991   default: break;
21992   case ISD::LOAD: {
21993     LoadSDNode *LD = cast<LoadSDNode>(Op);
21994     // If the non-extending load has a single use and it's not live out, then it
21995     // might be folded.
21996     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21997                                                      Op.hasOneUse()*/) {
21998       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21999              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22000         // The only case where we'd want to promote LOAD (rather then it being
22001         // promoted as an operand is when it's only use is liveout.
22002         if (UI->getOpcode() != ISD::CopyToReg)
22003           return false;
22004       }
22005     }
22006     Promote = true;
22007     break;
22008   }
22009   case ISD::SIGN_EXTEND:
22010   case ISD::ZERO_EXTEND:
22011   case ISD::ANY_EXTEND:
22012     Promote = true;
22013     break;
22014   case ISD::SHL:
22015   case ISD::SRL: {
22016     SDValue N0 = Op.getOperand(0);
22017     // Look out for (store (shl (load), x)).
22018     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22019       return false;
22020     Promote = true;
22021     break;
22022   }
22023   case ISD::ADD:
22024   case ISD::MUL:
22025   case ISD::AND:
22026   case ISD::OR:
22027   case ISD::XOR:
22028     Commute = true;
22029     // fallthrough
22030   case ISD::SUB: {
22031     SDValue N0 = Op.getOperand(0);
22032     SDValue N1 = Op.getOperand(1);
22033     if (!Commute && MayFoldLoad(N1))
22034       return false;
22035     // Avoid disabling potential load folding opportunities.
22036     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22037       return false;
22038     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22039       return false;
22040     Promote = true;
22041   }
22042   }
22043
22044   PVT = MVT::i32;
22045   return Promote;
22046 }
22047
22048 //===----------------------------------------------------------------------===//
22049 //                           X86 Inline Assembly Support
22050 //===----------------------------------------------------------------------===//
22051
22052 namespace {
22053   // Helper to match a string separated by whitespace.
22054   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22055     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22056
22057     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22058       StringRef piece(*args[i]);
22059       if (!s.startswith(piece)) // Check if the piece matches.
22060         return false;
22061
22062       s = s.substr(piece.size());
22063       StringRef::size_type pos = s.find_first_not_of(" \t");
22064       if (pos == 0) // We matched a prefix.
22065         return false;
22066
22067       s = s.substr(pos);
22068     }
22069
22070     return s.empty();
22071   }
22072   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22073 }
22074
22075 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22076
22077   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22078     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22079         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22080         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22081
22082       if (AsmPieces.size() == 3)
22083         return true;
22084       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22085         return true;
22086     }
22087   }
22088   return false;
22089 }
22090
22091 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22092   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22093
22094   std::string AsmStr = IA->getAsmString();
22095
22096   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22097   if (!Ty || Ty->getBitWidth() % 16 != 0)
22098     return false;
22099
22100   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22101   SmallVector<StringRef, 4> AsmPieces;
22102   SplitString(AsmStr, AsmPieces, ";\n");
22103
22104   switch (AsmPieces.size()) {
22105   default: return false;
22106   case 1:
22107     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22108     // we will turn this bswap into something that will be lowered to logical
22109     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22110     // lower so don't worry about this.
22111     // bswap $0
22112     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22113         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22114         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22115         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22116         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22117         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22118       // No need to check constraints, nothing other than the equivalent of
22119       // "=r,0" would be valid here.
22120       return IntrinsicLowering::LowerToByteSwap(CI);
22121     }
22122
22123     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22124     if (CI->getType()->isIntegerTy(16) &&
22125         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22126         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22127          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22128       AsmPieces.clear();
22129       const std::string &ConstraintsStr = IA->getConstraintString();
22130       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22131       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22132       if (clobbersFlagRegisters(AsmPieces))
22133         return IntrinsicLowering::LowerToByteSwap(CI);
22134     }
22135     break;
22136   case 3:
22137     if (CI->getType()->isIntegerTy(32) &&
22138         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22139         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22140         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22141         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22142       AsmPieces.clear();
22143       const std::string &ConstraintsStr = IA->getConstraintString();
22144       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22145       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22146       if (clobbersFlagRegisters(AsmPieces))
22147         return IntrinsicLowering::LowerToByteSwap(CI);
22148     }
22149
22150     if (CI->getType()->isIntegerTy(64)) {
22151       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22152       if (Constraints.size() >= 2 &&
22153           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22154           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22155         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22156         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22157             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22158             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22159           return IntrinsicLowering::LowerToByteSwap(CI);
22160       }
22161     }
22162     break;
22163   }
22164   return false;
22165 }
22166
22167 /// getConstraintType - Given a constraint letter, return the type of
22168 /// constraint it is for this target.
22169 X86TargetLowering::ConstraintType
22170 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22171   if (Constraint.size() == 1) {
22172     switch (Constraint[0]) {
22173     case 'R':
22174     case 'q':
22175     case 'Q':
22176     case 'f':
22177     case 't':
22178     case 'u':
22179     case 'y':
22180     case 'x':
22181     case 'Y':
22182     case 'l':
22183       return C_RegisterClass;
22184     case 'a':
22185     case 'b':
22186     case 'c':
22187     case 'd':
22188     case 'S':
22189     case 'D':
22190     case 'A':
22191       return C_Register;
22192     case 'I':
22193     case 'J':
22194     case 'K':
22195     case 'L':
22196     case 'M':
22197     case 'N':
22198     case 'G':
22199     case 'C':
22200     case 'e':
22201     case 'Z':
22202       return C_Other;
22203     default:
22204       break;
22205     }
22206   }
22207   return TargetLowering::getConstraintType(Constraint);
22208 }
22209
22210 /// Examine constraint type and operand type and determine a weight value.
22211 /// This object must already have been set up with the operand type
22212 /// and the current alternative constraint selected.
22213 TargetLowering::ConstraintWeight
22214   X86TargetLowering::getSingleConstraintMatchWeight(
22215     AsmOperandInfo &info, const char *constraint) const {
22216   ConstraintWeight weight = CW_Invalid;
22217   Value *CallOperandVal = info.CallOperandVal;
22218     // If we don't have a value, we can't do a match,
22219     // but allow it at the lowest weight.
22220   if (!CallOperandVal)
22221     return CW_Default;
22222   Type *type = CallOperandVal->getType();
22223   // Look at the constraint type.
22224   switch (*constraint) {
22225   default:
22226     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22227   case 'R':
22228   case 'q':
22229   case 'Q':
22230   case 'a':
22231   case 'b':
22232   case 'c':
22233   case 'd':
22234   case 'S':
22235   case 'D':
22236   case 'A':
22237     if (CallOperandVal->getType()->isIntegerTy())
22238       weight = CW_SpecificReg;
22239     break;
22240   case 'f':
22241   case 't':
22242   case 'u':
22243     if (type->isFloatingPointTy())
22244       weight = CW_SpecificReg;
22245     break;
22246   case 'y':
22247     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22248       weight = CW_SpecificReg;
22249     break;
22250   case 'x':
22251   case 'Y':
22252     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22253         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22254       weight = CW_Register;
22255     break;
22256   case 'I':
22257     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22258       if (C->getZExtValue() <= 31)
22259         weight = CW_Constant;
22260     }
22261     break;
22262   case 'J':
22263     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22264       if (C->getZExtValue() <= 63)
22265         weight = CW_Constant;
22266     }
22267     break;
22268   case 'K':
22269     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22270       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22271         weight = CW_Constant;
22272     }
22273     break;
22274   case 'L':
22275     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22276       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22277         weight = CW_Constant;
22278     }
22279     break;
22280   case 'M':
22281     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22282       if (C->getZExtValue() <= 3)
22283         weight = CW_Constant;
22284     }
22285     break;
22286   case 'N':
22287     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22288       if (C->getZExtValue() <= 0xff)
22289         weight = CW_Constant;
22290     }
22291     break;
22292   case 'G':
22293   case 'C':
22294     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22295       weight = CW_Constant;
22296     }
22297     break;
22298   case 'e':
22299     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22300       if ((C->getSExtValue() >= -0x80000000LL) &&
22301           (C->getSExtValue() <= 0x7fffffffLL))
22302         weight = CW_Constant;
22303     }
22304     break;
22305   case 'Z':
22306     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22307       if (C->getZExtValue() <= 0xffffffff)
22308         weight = CW_Constant;
22309     }
22310     break;
22311   }
22312   return weight;
22313 }
22314
22315 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22316 /// with another that has more specific requirements based on the type of the
22317 /// corresponding operand.
22318 const char *X86TargetLowering::
22319 LowerXConstraint(EVT ConstraintVT) const {
22320   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22321   // 'f' like normal targets.
22322   if (ConstraintVT.isFloatingPoint()) {
22323     if (Subtarget->hasSSE2())
22324       return "Y";
22325     if (Subtarget->hasSSE1())
22326       return "x";
22327   }
22328
22329   return TargetLowering::LowerXConstraint(ConstraintVT);
22330 }
22331
22332 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22333 /// vector.  If it is invalid, don't add anything to Ops.
22334 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22335                                                      std::string &Constraint,
22336                                                      std::vector<SDValue>&Ops,
22337                                                      SelectionDAG &DAG) const {
22338   SDValue Result;
22339
22340   // Only support length 1 constraints for now.
22341   if (Constraint.length() > 1) return;
22342
22343   char ConstraintLetter = Constraint[0];
22344   switch (ConstraintLetter) {
22345   default: break;
22346   case 'I':
22347     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22348       if (C->getZExtValue() <= 31) {
22349         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22350         break;
22351       }
22352     }
22353     return;
22354   case 'J':
22355     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22356       if (C->getZExtValue() <= 63) {
22357         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22358         break;
22359       }
22360     }
22361     return;
22362   case 'K':
22363     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22364       if (isInt<8>(C->getSExtValue())) {
22365         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22366         break;
22367       }
22368     }
22369     return;
22370   case 'N':
22371     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22372       if (C->getZExtValue() <= 255) {
22373         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22374         break;
22375       }
22376     }
22377     return;
22378   case 'e': {
22379     // 32-bit signed value
22380     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22381       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22382                                            C->getSExtValue())) {
22383         // Widen to 64 bits here to get it sign extended.
22384         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22385         break;
22386       }
22387     // FIXME gcc accepts some relocatable values here too, but only in certain
22388     // memory models; it's complicated.
22389     }
22390     return;
22391   }
22392   case 'Z': {
22393     // 32-bit unsigned value
22394     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22395       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22396                                            C->getZExtValue())) {
22397         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22398         break;
22399       }
22400     }
22401     // FIXME gcc accepts some relocatable values here too, but only in certain
22402     // memory models; it's complicated.
22403     return;
22404   }
22405   case 'i': {
22406     // Literal immediates are always ok.
22407     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22408       // Widen to 64 bits here to get it sign extended.
22409       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22410       break;
22411     }
22412
22413     // In any sort of PIC mode addresses need to be computed at runtime by
22414     // adding in a register or some sort of table lookup.  These can't
22415     // be used as immediates.
22416     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22417       return;
22418
22419     // If we are in non-pic codegen mode, we allow the address of a global (with
22420     // an optional displacement) to be used with 'i'.
22421     GlobalAddressSDNode *GA = nullptr;
22422     int64_t Offset = 0;
22423
22424     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22425     while (1) {
22426       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22427         Offset += GA->getOffset();
22428         break;
22429       } else if (Op.getOpcode() == ISD::ADD) {
22430         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22431           Offset += C->getZExtValue();
22432           Op = Op.getOperand(0);
22433           continue;
22434         }
22435       } else if (Op.getOpcode() == ISD::SUB) {
22436         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22437           Offset += -C->getZExtValue();
22438           Op = Op.getOperand(0);
22439           continue;
22440         }
22441       }
22442
22443       // Otherwise, this isn't something we can handle, reject it.
22444       return;
22445     }
22446
22447     const GlobalValue *GV = GA->getGlobal();
22448     // If we require an extra load to get this address, as in PIC mode, we
22449     // can't accept it.
22450     if (isGlobalStubReference(
22451             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22452       return;
22453
22454     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22455                                         GA->getValueType(0), Offset);
22456     break;
22457   }
22458   }
22459
22460   if (Result.getNode()) {
22461     Ops.push_back(Result);
22462     return;
22463   }
22464   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22465 }
22466
22467 std::pair<unsigned, const TargetRegisterClass*>
22468 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22469                                                 MVT VT) const {
22470   // First, see if this is a constraint that directly corresponds to an LLVM
22471   // register class.
22472   if (Constraint.size() == 1) {
22473     // GCC Constraint Letters
22474     switch (Constraint[0]) {
22475     default: break;
22476       // TODO: Slight differences here in allocation order and leaving
22477       // RIP in the class. Do they matter any more here than they do
22478       // in the normal allocation?
22479     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22480       if (Subtarget->is64Bit()) {
22481         if (VT == MVT::i32 || VT == MVT::f32)
22482           return std::make_pair(0U, &X86::GR32RegClass);
22483         if (VT == MVT::i16)
22484           return std::make_pair(0U, &X86::GR16RegClass);
22485         if (VT == MVT::i8 || VT == MVT::i1)
22486           return std::make_pair(0U, &X86::GR8RegClass);
22487         if (VT == MVT::i64 || VT == MVT::f64)
22488           return std::make_pair(0U, &X86::GR64RegClass);
22489         break;
22490       }
22491       // 32-bit fallthrough
22492     case 'Q':   // Q_REGS
22493       if (VT == MVT::i32 || VT == MVT::f32)
22494         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22495       if (VT == MVT::i16)
22496         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22497       if (VT == MVT::i8 || VT == MVT::i1)
22498         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22499       if (VT == MVT::i64)
22500         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22501       break;
22502     case 'r':   // GENERAL_REGS
22503     case 'l':   // INDEX_REGS
22504       if (VT == MVT::i8 || VT == MVT::i1)
22505         return std::make_pair(0U, &X86::GR8RegClass);
22506       if (VT == MVT::i16)
22507         return std::make_pair(0U, &X86::GR16RegClass);
22508       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22509         return std::make_pair(0U, &X86::GR32RegClass);
22510       return std::make_pair(0U, &X86::GR64RegClass);
22511     case 'R':   // LEGACY_REGS
22512       if (VT == MVT::i8 || VT == MVT::i1)
22513         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22514       if (VT == MVT::i16)
22515         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22516       if (VT == MVT::i32 || !Subtarget->is64Bit())
22517         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22518       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22519     case 'f':  // FP Stack registers.
22520       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22521       // value to the correct fpstack register class.
22522       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22523         return std::make_pair(0U, &X86::RFP32RegClass);
22524       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22525         return std::make_pair(0U, &X86::RFP64RegClass);
22526       return std::make_pair(0U, &X86::RFP80RegClass);
22527     case 'y':   // MMX_REGS if MMX allowed.
22528       if (!Subtarget->hasMMX()) break;
22529       return std::make_pair(0U, &X86::VR64RegClass);
22530     case 'Y':   // SSE_REGS if SSE2 allowed
22531       if (!Subtarget->hasSSE2()) break;
22532       // FALL THROUGH.
22533     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22534       if (!Subtarget->hasSSE1()) break;
22535
22536       switch (VT.SimpleTy) {
22537       default: break;
22538       // Scalar SSE types.
22539       case MVT::f32:
22540       case MVT::i32:
22541         return std::make_pair(0U, &X86::FR32RegClass);
22542       case MVT::f64:
22543       case MVT::i64:
22544         return std::make_pair(0U, &X86::FR64RegClass);
22545       // Vector types.
22546       case MVT::v16i8:
22547       case MVT::v8i16:
22548       case MVT::v4i32:
22549       case MVT::v2i64:
22550       case MVT::v4f32:
22551       case MVT::v2f64:
22552         return std::make_pair(0U, &X86::VR128RegClass);
22553       // AVX types.
22554       case MVT::v32i8:
22555       case MVT::v16i16:
22556       case MVT::v8i32:
22557       case MVT::v4i64:
22558       case MVT::v8f32:
22559       case MVT::v4f64:
22560         return std::make_pair(0U, &X86::VR256RegClass);
22561       case MVT::v8f64:
22562       case MVT::v16f32:
22563       case MVT::v16i32:
22564       case MVT::v8i64:
22565         return std::make_pair(0U, &X86::VR512RegClass);
22566       }
22567       break;
22568     }
22569   }
22570
22571   // Use the default implementation in TargetLowering to convert the register
22572   // constraint into a member of a register class.
22573   std::pair<unsigned, const TargetRegisterClass*> Res;
22574   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22575
22576   // Not found as a standard register?
22577   if (!Res.second) {
22578     // Map st(0) -> st(7) -> ST0
22579     if (Constraint.size() == 7 && Constraint[0] == '{' &&
22580         tolower(Constraint[1]) == 's' &&
22581         tolower(Constraint[2]) == 't' &&
22582         Constraint[3] == '(' &&
22583         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22584         Constraint[5] == ')' &&
22585         Constraint[6] == '}') {
22586
22587       Res.first = X86::ST0+Constraint[4]-'0';
22588       Res.second = &X86::RFP80RegClass;
22589       return Res;
22590     }
22591
22592     // GCC allows "st(0)" to be called just plain "st".
22593     if (StringRef("{st}").equals_lower(Constraint)) {
22594       Res.first = X86::ST0;
22595       Res.second = &X86::RFP80RegClass;
22596       return Res;
22597     }
22598
22599     // flags -> EFLAGS
22600     if (StringRef("{flags}").equals_lower(Constraint)) {
22601       Res.first = X86::EFLAGS;
22602       Res.second = &X86::CCRRegClass;
22603       return Res;
22604     }
22605
22606     // 'A' means EAX + EDX.
22607     if (Constraint == "A") {
22608       Res.first = X86::EAX;
22609       Res.second = &X86::GR32_ADRegClass;
22610       return Res;
22611     }
22612     return Res;
22613   }
22614
22615   // Otherwise, check to see if this is a register class of the wrong value
22616   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22617   // turn into {ax},{dx}.
22618   if (Res.second->hasType(VT))
22619     return Res;   // Correct type already, nothing to do.
22620
22621   // All of the single-register GCC register classes map their values onto
22622   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
22623   // really want an 8-bit or 32-bit register, map to the appropriate register
22624   // class and return the appropriate register.
22625   if (Res.second == &X86::GR16RegClass) {
22626     if (VT == MVT::i8 || VT == MVT::i1) {
22627       unsigned DestReg = 0;
22628       switch (Res.first) {
22629       default: break;
22630       case X86::AX: DestReg = X86::AL; break;
22631       case X86::DX: DestReg = X86::DL; break;
22632       case X86::CX: DestReg = X86::CL; break;
22633       case X86::BX: DestReg = X86::BL; break;
22634       }
22635       if (DestReg) {
22636         Res.first = DestReg;
22637         Res.second = &X86::GR8RegClass;
22638       }
22639     } else if (VT == MVT::i32 || VT == MVT::f32) {
22640       unsigned DestReg = 0;
22641       switch (Res.first) {
22642       default: break;
22643       case X86::AX: DestReg = X86::EAX; break;
22644       case X86::DX: DestReg = X86::EDX; break;
22645       case X86::CX: DestReg = X86::ECX; break;
22646       case X86::BX: DestReg = X86::EBX; break;
22647       case X86::SI: DestReg = X86::ESI; break;
22648       case X86::DI: DestReg = X86::EDI; break;
22649       case X86::BP: DestReg = X86::EBP; break;
22650       case X86::SP: DestReg = X86::ESP; break;
22651       }
22652       if (DestReg) {
22653         Res.first = DestReg;
22654         Res.second = &X86::GR32RegClass;
22655       }
22656     } else if (VT == MVT::i64 || VT == MVT::f64) {
22657       unsigned DestReg = 0;
22658       switch (Res.first) {
22659       default: break;
22660       case X86::AX: DestReg = X86::RAX; break;
22661       case X86::DX: DestReg = X86::RDX; break;
22662       case X86::CX: DestReg = X86::RCX; break;
22663       case X86::BX: DestReg = X86::RBX; break;
22664       case X86::SI: DestReg = X86::RSI; break;
22665       case X86::DI: DestReg = X86::RDI; break;
22666       case X86::BP: DestReg = X86::RBP; break;
22667       case X86::SP: DestReg = X86::RSP; break;
22668       }
22669       if (DestReg) {
22670         Res.first = DestReg;
22671         Res.second = &X86::GR64RegClass;
22672       }
22673     }
22674   } else if (Res.second == &X86::FR32RegClass ||
22675              Res.second == &X86::FR64RegClass ||
22676              Res.second == &X86::VR128RegClass ||
22677              Res.second == &X86::VR256RegClass ||
22678              Res.second == &X86::FR32XRegClass ||
22679              Res.second == &X86::FR64XRegClass ||
22680              Res.second == &X86::VR128XRegClass ||
22681              Res.second == &X86::VR256XRegClass ||
22682              Res.second == &X86::VR512RegClass) {
22683     // Handle references to XMM physical registers that got mapped into the
22684     // wrong class.  This can happen with constraints like {xmm0} where the
22685     // target independent register mapper will just pick the first match it can
22686     // find, ignoring the required type.
22687
22688     if (VT == MVT::f32 || VT == MVT::i32)
22689       Res.second = &X86::FR32RegClass;
22690     else if (VT == MVT::f64 || VT == MVT::i64)
22691       Res.second = &X86::FR64RegClass;
22692     else if (X86::VR128RegClass.hasType(VT))
22693       Res.second = &X86::VR128RegClass;
22694     else if (X86::VR256RegClass.hasType(VT))
22695       Res.second = &X86::VR256RegClass;
22696     else if (X86::VR512RegClass.hasType(VT))
22697       Res.second = &X86::VR512RegClass;
22698   }
22699
22700   return Res;
22701 }
22702
22703 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22704                                             Type *Ty) const {
22705   // Scaling factors are not free at all.
22706   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22707   // will take 2 allocations in the out of order engine instead of 1
22708   // for plain addressing mode, i.e. inst (reg1).
22709   // E.g.,
22710   // vaddps (%rsi,%drx), %ymm0, %ymm1
22711   // Requires two allocations (one for the load, one for the computation)
22712   // whereas:
22713   // vaddps (%rsi), %ymm0, %ymm1
22714   // Requires just 1 allocation, i.e., freeing allocations for other operations
22715   // and having less micro operations to execute.
22716   //
22717   // For some X86 architectures, this is even worse because for instance for
22718   // stores, the complex addressing mode forces the instruction to use the
22719   // "load" ports instead of the dedicated "store" port.
22720   // E.g., on Haswell:
22721   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22722   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
22723   if (isLegalAddressingMode(AM, Ty))
22724     // Scale represents reg2 * scale, thus account for 1
22725     // as soon as we use a second register.
22726     return AM.Scale != 0;
22727   return -1;
22728 }
22729
22730 bool X86TargetLowering::isTargetFTOL() const {
22731   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22732 }