Revert r211771. It was: "[X86] Improve the selection of SSE3/AVX addsub instructions".
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1015     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1016     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1017     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1018     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1019     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1020
1021     if (Subtarget->is64Bit()) {
1022       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1023       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1024     }
1025
1026     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1027     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1028       MVT VT = (MVT::SimpleValueType)i;
1029
1030       // Do not attempt to promote non-128-bit vectors
1031       if (!VT.is128BitVector())
1032         continue;
1033
1034       setOperationAction(ISD::AND,    VT, Promote);
1035       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1036       setOperationAction(ISD::OR,     VT, Promote);
1037       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1038       setOperationAction(ISD::XOR,    VT, Promote);
1039       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1040       setOperationAction(ISD::LOAD,   VT, Promote);
1041       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1042       setOperationAction(ISD::SELECT, VT, Promote);
1043       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1044     }
1045
1046     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1047
1048     // Custom lower v2i64 and v2f64 selects.
1049     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1050     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1051     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1052     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1053
1054     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1055     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1056
1057     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1058     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1059     // As there is no 64-bit GPR available, we need build a special custom
1060     // sequence to convert from v2i32 to v2f32.
1061     if (!Subtarget->is64Bit())
1062       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1063
1064     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1065     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1066
1067     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1068
1069     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1070     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1071     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1072   }
1073
1074   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1075     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1076     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1077     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1078     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1079     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1080     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1081     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1082     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1083     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1084     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1085
1086     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1087     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1088     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1089     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1090     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1091     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1094     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1096
1097     // FIXME: Do we need to handle scalar-to-vector here?
1098     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1099
1100     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1101     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1102     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1103     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1104     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1105     // There is no BLENDI for byte vectors. We don't need to custom lower
1106     // some vselects for now.
1107     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1108
1109     // i8 and i16 vectors are custom , because the source register and source
1110     // source memory operand types are not the same width.  f32 vectors are
1111     // custom since the immediate controlling the insert encodes additional
1112     // information.
1113     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1114     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1115     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1116     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1117
1118     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1119     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1120     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1121     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1122
1123     // FIXME: these should be Legal but thats only for the case where
1124     // the index is constant.  For now custom expand to deal with that.
1125     if (Subtarget->is64Bit()) {
1126       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1127       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1128     }
1129   }
1130
1131   if (Subtarget->hasSSE2()) {
1132     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1133     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1134
1135     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1136     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1137
1138     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1139     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1140
1141     // In the customized shift lowering, the legal cases in AVX2 will be
1142     // recognized.
1143     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1144     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1145
1146     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1147     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1148
1149     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1150   }
1151
1152   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1153     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1154     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1155     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1156     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1157     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1158     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1159
1160     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1161     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1162     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1163
1164     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1165     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1166     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1167     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1168     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1169     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1170     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1171     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1172     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1173     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1174     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1175     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1176
1177     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1178     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1179     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1180     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1181     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1182     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1183     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1184     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1185     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1186     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1187     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1188     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1189
1190     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1191     // even though v8i16 is a legal type.
1192     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1193     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1194     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1195
1196     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1197     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1198     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1199
1200     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1201     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1202
1203     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1204
1205     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1206     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1207
1208     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1209     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1210
1211     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1212     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1213
1214     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1215     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1216     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1217     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1218
1219     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1220     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1221     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1222
1223     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1224     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1225     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1226     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1227
1228     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1229     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1230     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1231     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1232     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1233     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1234     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1235     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1236     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1237     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1238     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1239     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1240
1241     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1242       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1243       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1244       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1245       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1246       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1247       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1248     }
1249
1250     if (Subtarget->hasInt256()) {
1251       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1252       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1253       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1254       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1255
1256       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1257       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1258       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1259       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1260
1261       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1262       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1263       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1264       // Don't lower v32i8 because there is no 128-bit byte mul
1265
1266       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1267       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1268       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1269       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1270
1271       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1272       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1273     } else {
1274       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1275       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1276       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1277       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1278
1279       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1280       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1281       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1282       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1283
1284       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1285       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1286       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1287       // Don't lower v32i8 because there is no 128-bit byte mul
1288     }
1289
1290     // In the customized shift lowering, the legal cases in AVX2 will be
1291     // recognized.
1292     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1293     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1294
1295     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1296     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1297
1298     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1299
1300     // Custom lower several nodes for 256-bit types.
1301     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1302              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1303       MVT VT = (MVT::SimpleValueType)i;
1304
1305       // Extract subvector is special because the value type
1306       // (result) is 128-bit but the source is 256-bit wide.
1307       if (VT.is128BitVector())
1308         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1309
1310       // Do not attempt to custom lower other non-256-bit vectors
1311       if (!VT.is256BitVector())
1312         continue;
1313
1314       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1315       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1316       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1317       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1318       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1319       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1320       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1321     }
1322
1323     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1324     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Do not attempt to promote non-256-bit vectors
1328       if (!VT.is256BitVector())
1329         continue;
1330
1331       setOperationAction(ISD::AND,    VT, Promote);
1332       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1333       setOperationAction(ISD::OR,     VT, Promote);
1334       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1335       setOperationAction(ISD::XOR,    VT, Promote);
1336       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1337       setOperationAction(ISD::LOAD,   VT, Promote);
1338       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1339       setOperationAction(ISD::SELECT, VT, Promote);
1340       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1341     }
1342   }
1343
1344   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1345     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1346     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1347     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1348     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1349
1350     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1351     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1352     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1353
1354     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1355     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1356     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1357     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1358     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1359     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1360     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1361     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1362     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1363     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1364     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1365
1366     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1367     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1368     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1369     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1370     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1371     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1372
1373     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1374     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1375     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1376     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1377     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1378     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1379     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1380     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1381
1382     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1383     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1384     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1385     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1386     if (Subtarget->is64Bit()) {
1387       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1388       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1389       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1390       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1391     }
1392     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1393     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1394     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1395     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1396     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1397     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1398     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1399     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1400     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1401     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1402
1403     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1404     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1405     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1406     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1407     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1408     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1409     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1410     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1411     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1412     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1413     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1414     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1415     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1416
1417     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1418     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1419     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1420     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1421     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1422     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1423
1424     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1425     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1426
1427     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1428
1429     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1430     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1431     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1432     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1433     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1434     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1435     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1436     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1437     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1438
1439     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1440     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1441
1442     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1443     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1444
1445     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1446
1447     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1448     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1449
1450     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1451     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1452
1453     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1454     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1455
1456     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1457     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1458     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1459     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1460     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1461     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1462
1463     if (Subtarget->hasCDI()) {
1464       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1465       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1466     }
1467
1468     // Custom lower several nodes.
1469     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1470              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1471       MVT VT = (MVT::SimpleValueType)i;
1472
1473       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1474       // Extract subvector is special because the value type
1475       // (result) is 256/128-bit but the source is 512-bit wide.
1476       if (VT.is128BitVector() || VT.is256BitVector())
1477         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1478
1479       if (VT.getVectorElementType() == MVT::i1)
1480         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1481
1482       // Do not attempt to custom lower other non-512-bit vectors
1483       if (!VT.is512BitVector())
1484         continue;
1485
1486       if ( EltSize >= 32) {
1487         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1488         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1489         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1490         setOperationAction(ISD::VSELECT,             VT, Legal);
1491         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1492         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1493         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1494       }
1495     }
1496     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1497       MVT VT = (MVT::SimpleValueType)i;
1498
1499       // Do not attempt to promote non-256-bit vectors
1500       if (!VT.is512BitVector())
1501         continue;
1502
1503       setOperationAction(ISD::SELECT, VT, Promote);
1504       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1505     }
1506   }// has  AVX-512
1507
1508   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1509   // of this type with custom code.
1510   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1511            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1512     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1513                        Custom);
1514   }
1515
1516   // We want to custom lower some of our intrinsics.
1517   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1518   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1519   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1520   if (!Subtarget->is64Bit())
1521     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1522
1523   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1524   // handle type legalization for these operations here.
1525   //
1526   // FIXME: We really should do custom legalization for addition and
1527   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1528   // than generic legalization for 64-bit multiplication-with-overflow, though.
1529   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1530     // Add/Sub/Mul with overflow operations are custom lowered.
1531     MVT VT = IntVTs[i];
1532     setOperationAction(ISD::SADDO, VT, Custom);
1533     setOperationAction(ISD::UADDO, VT, Custom);
1534     setOperationAction(ISD::SSUBO, VT, Custom);
1535     setOperationAction(ISD::USUBO, VT, Custom);
1536     setOperationAction(ISD::SMULO, VT, Custom);
1537     setOperationAction(ISD::UMULO, VT, Custom);
1538   }
1539
1540   // There are no 8-bit 3-address imul/mul instructions
1541   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1542   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1543
1544   if (!Subtarget->is64Bit()) {
1545     // These libcalls are not available in 32-bit.
1546     setLibcallName(RTLIB::SHL_I128, nullptr);
1547     setLibcallName(RTLIB::SRL_I128, nullptr);
1548     setLibcallName(RTLIB::SRA_I128, nullptr);
1549   }
1550
1551   // Combine sin / cos into one node or libcall if possible.
1552   if (Subtarget->hasSinCos()) {
1553     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1554     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1555     if (Subtarget->isTargetDarwin()) {
1556       // For MacOSX, we don't want to the normal expansion of a libcall to
1557       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1558       // traffic.
1559       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1560       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1561     }
1562   }
1563
1564   if (Subtarget->isTargetWin64()) {
1565     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1566     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1567     setOperationAction(ISD::SREM, MVT::i128, Custom);
1568     setOperationAction(ISD::UREM, MVT::i128, Custom);
1569     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1570     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1571   }
1572
1573   // We have target-specific dag combine patterns for the following nodes:
1574   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1575   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1576   setTargetDAGCombine(ISD::VSELECT);
1577   setTargetDAGCombine(ISD::SELECT);
1578   setTargetDAGCombine(ISD::SHL);
1579   setTargetDAGCombine(ISD::SRA);
1580   setTargetDAGCombine(ISD::SRL);
1581   setTargetDAGCombine(ISD::OR);
1582   setTargetDAGCombine(ISD::AND);
1583   setTargetDAGCombine(ISD::ADD);
1584   setTargetDAGCombine(ISD::FADD);
1585   setTargetDAGCombine(ISD::FSUB);
1586   setTargetDAGCombine(ISD::FMA);
1587   setTargetDAGCombine(ISD::SUB);
1588   setTargetDAGCombine(ISD::LOAD);
1589   setTargetDAGCombine(ISD::STORE);
1590   setTargetDAGCombine(ISD::ZERO_EXTEND);
1591   setTargetDAGCombine(ISD::ANY_EXTEND);
1592   setTargetDAGCombine(ISD::SIGN_EXTEND);
1593   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1594   setTargetDAGCombine(ISD::TRUNCATE);
1595   setTargetDAGCombine(ISD::SINT_TO_FP);
1596   setTargetDAGCombine(ISD::SETCC);
1597   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1598   setTargetDAGCombine(ISD::BUILD_VECTOR);
1599   if (Subtarget->is64Bit())
1600     setTargetDAGCombine(ISD::MUL);
1601   setTargetDAGCombine(ISD::XOR);
1602
1603   computeRegisterProperties();
1604
1605   // On Darwin, -Os means optimize for size without hurting performance,
1606   // do not reduce the limit.
1607   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1608   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1609   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1610   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1611   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1612   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1613   setPrefLoopAlignment(4); // 2^4 bytes.
1614
1615   // Predictable cmov don't hurt on atom because it's in-order.
1616   PredictableSelectIsExpensive = !Subtarget->isAtom();
1617
1618   setPrefFunctionAlignment(4); // 2^4 bytes.
1619 }
1620
1621 TargetLoweringBase::LegalizeTypeAction
1622 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1623   if (ExperimentalVectorWideningLegalization &&
1624       VT.getVectorNumElements() != 1 &&
1625       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1626     return TypeWidenVector;
1627
1628   return TargetLoweringBase::getPreferredVectorAction(VT);
1629 }
1630
1631 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1632   if (!VT.isVector())
1633     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1634
1635   if (Subtarget->hasAVX512())
1636     switch(VT.getVectorNumElements()) {
1637     case  8: return MVT::v8i1;
1638     case 16: return MVT::v16i1;
1639   }
1640
1641   return VT.changeVectorElementTypeToInteger();
1642 }
1643
1644 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1645 /// the desired ByVal argument alignment.
1646 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1647   if (MaxAlign == 16)
1648     return;
1649   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1650     if (VTy->getBitWidth() == 128)
1651       MaxAlign = 16;
1652   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1653     unsigned EltAlign = 0;
1654     getMaxByValAlign(ATy->getElementType(), EltAlign);
1655     if (EltAlign > MaxAlign)
1656       MaxAlign = EltAlign;
1657   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1658     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1659       unsigned EltAlign = 0;
1660       getMaxByValAlign(STy->getElementType(i), EltAlign);
1661       if (EltAlign > MaxAlign)
1662         MaxAlign = EltAlign;
1663       if (MaxAlign == 16)
1664         break;
1665     }
1666   }
1667 }
1668
1669 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1670 /// function arguments in the caller parameter area. For X86, aggregates
1671 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1672 /// are at 4-byte boundaries.
1673 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1674   if (Subtarget->is64Bit()) {
1675     // Max of 8 and alignment of type.
1676     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1677     if (TyAlign > 8)
1678       return TyAlign;
1679     return 8;
1680   }
1681
1682   unsigned Align = 4;
1683   if (Subtarget->hasSSE1())
1684     getMaxByValAlign(Ty, Align);
1685   return Align;
1686 }
1687
1688 /// getOptimalMemOpType - Returns the target specific optimal type for load
1689 /// and store operations as a result of memset, memcpy, and memmove
1690 /// lowering. If DstAlign is zero that means it's safe to destination
1691 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1692 /// means there isn't a need to check it against alignment requirement,
1693 /// probably because the source does not need to be loaded. If 'IsMemset' is
1694 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1695 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1696 /// source is constant so it does not need to be loaded.
1697 /// It returns EVT::Other if the type should be determined using generic
1698 /// target-independent logic.
1699 EVT
1700 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1701                                        unsigned DstAlign, unsigned SrcAlign,
1702                                        bool IsMemset, bool ZeroMemset,
1703                                        bool MemcpyStrSrc,
1704                                        MachineFunction &MF) const {
1705   const Function *F = MF.getFunction();
1706   if ((!IsMemset || ZeroMemset) &&
1707       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1708                                        Attribute::NoImplicitFloat)) {
1709     if (Size >= 16 &&
1710         (Subtarget->isUnalignedMemAccessFast() ||
1711          ((DstAlign == 0 || DstAlign >= 16) &&
1712           (SrcAlign == 0 || SrcAlign >= 16)))) {
1713       if (Size >= 32) {
1714         if (Subtarget->hasInt256())
1715           return MVT::v8i32;
1716         if (Subtarget->hasFp256())
1717           return MVT::v8f32;
1718       }
1719       if (Subtarget->hasSSE2())
1720         return MVT::v4i32;
1721       if (Subtarget->hasSSE1())
1722         return MVT::v4f32;
1723     } else if (!MemcpyStrSrc && Size >= 8 &&
1724                !Subtarget->is64Bit() &&
1725                Subtarget->hasSSE2()) {
1726       // Do not use f64 to lower memcpy if source is string constant. It's
1727       // better to use i32 to avoid the loads.
1728       return MVT::f64;
1729     }
1730   }
1731   if (Subtarget->is64Bit() && Size >= 8)
1732     return MVT::i64;
1733   return MVT::i32;
1734 }
1735
1736 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1737   if (VT == MVT::f32)
1738     return X86ScalarSSEf32;
1739   else if (VT == MVT::f64)
1740     return X86ScalarSSEf64;
1741   return true;
1742 }
1743
1744 bool
1745 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1746                                                  unsigned,
1747                                                  bool *Fast) const {
1748   if (Fast)
1749     *Fast = Subtarget->isUnalignedMemAccessFast();
1750   return true;
1751 }
1752
1753 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1754 /// current function.  The returned value is a member of the
1755 /// MachineJumpTableInfo::JTEntryKind enum.
1756 unsigned X86TargetLowering::getJumpTableEncoding() const {
1757   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1758   // symbol.
1759   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1760       Subtarget->isPICStyleGOT())
1761     return MachineJumpTableInfo::EK_Custom32;
1762
1763   // Otherwise, use the normal jump table encoding heuristics.
1764   return TargetLowering::getJumpTableEncoding();
1765 }
1766
1767 const MCExpr *
1768 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1769                                              const MachineBasicBlock *MBB,
1770                                              unsigned uid,MCContext &Ctx) const{
1771   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1772          Subtarget->isPICStyleGOT());
1773   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1774   // entries.
1775   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1776                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1777 }
1778
1779 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1780 /// jumptable.
1781 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1782                                                     SelectionDAG &DAG) const {
1783   if (!Subtarget->is64Bit())
1784     // This doesn't have SDLoc associated with it, but is not really the
1785     // same as a Register.
1786     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1787   return Table;
1788 }
1789
1790 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1791 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1792 /// MCExpr.
1793 const MCExpr *X86TargetLowering::
1794 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1795                              MCContext &Ctx) const {
1796   // X86-64 uses RIP relative addressing based on the jump table label.
1797   if (Subtarget->isPICStyleRIPRel())
1798     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1799
1800   // Otherwise, the reference is relative to the PIC base.
1801   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1802 }
1803
1804 // FIXME: Why this routine is here? Move to RegInfo!
1805 std::pair<const TargetRegisterClass*, uint8_t>
1806 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1807   const TargetRegisterClass *RRC = nullptr;
1808   uint8_t Cost = 1;
1809   switch (VT.SimpleTy) {
1810   default:
1811     return TargetLowering::findRepresentativeClass(VT);
1812   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1813     RRC = Subtarget->is64Bit() ?
1814       (const TargetRegisterClass*)&X86::GR64RegClass :
1815       (const TargetRegisterClass*)&X86::GR32RegClass;
1816     break;
1817   case MVT::x86mmx:
1818     RRC = &X86::VR64RegClass;
1819     break;
1820   case MVT::f32: case MVT::f64:
1821   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1822   case MVT::v4f32: case MVT::v2f64:
1823   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1824   case MVT::v4f64:
1825     RRC = &X86::VR128RegClass;
1826     break;
1827   }
1828   return std::make_pair(RRC, Cost);
1829 }
1830
1831 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1832                                                unsigned &Offset) const {
1833   if (!Subtarget->isTargetLinux())
1834     return false;
1835
1836   if (Subtarget->is64Bit()) {
1837     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1838     Offset = 0x28;
1839     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1840       AddressSpace = 256;
1841     else
1842       AddressSpace = 257;
1843   } else {
1844     // %gs:0x14 on i386
1845     Offset = 0x14;
1846     AddressSpace = 256;
1847   }
1848   return true;
1849 }
1850
1851 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1852                                             unsigned DestAS) const {
1853   assert(SrcAS != DestAS && "Expected different address spaces!");
1854
1855   return SrcAS < 256 && DestAS < 256;
1856 }
1857
1858 //===----------------------------------------------------------------------===//
1859 //               Return Value Calling Convention Implementation
1860 //===----------------------------------------------------------------------===//
1861
1862 #include "X86GenCallingConv.inc"
1863
1864 bool
1865 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1866                                   MachineFunction &MF, bool isVarArg,
1867                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1868                         LLVMContext &Context) const {
1869   SmallVector<CCValAssign, 16> RVLocs;
1870   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1871                  RVLocs, Context);
1872   return CCInfo.CheckReturn(Outs, RetCC_X86);
1873 }
1874
1875 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1876   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1877   return ScratchRegs;
1878 }
1879
1880 SDValue
1881 X86TargetLowering::LowerReturn(SDValue Chain,
1882                                CallingConv::ID CallConv, bool isVarArg,
1883                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1884                                const SmallVectorImpl<SDValue> &OutVals,
1885                                SDLoc dl, SelectionDAG &DAG) const {
1886   MachineFunction &MF = DAG.getMachineFunction();
1887   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1888
1889   SmallVector<CCValAssign, 16> RVLocs;
1890   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1891                  RVLocs, *DAG.getContext());
1892   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1893
1894   SDValue Flag;
1895   SmallVector<SDValue, 6> RetOps;
1896   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1897   // Operand #1 = Bytes To Pop
1898   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1899                    MVT::i16));
1900
1901   // Copy the result values into the output registers.
1902   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1903     CCValAssign &VA = RVLocs[i];
1904     assert(VA.isRegLoc() && "Can only return in registers!");
1905     SDValue ValToCopy = OutVals[i];
1906     EVT ValVT = ValToCopy.getValueType();
1907
1908     // Promote values to the appropriate types
1909     if (VA.getLocInfo() == CCValAssign::SExt)
1910       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1911     else if (VA.getLocInfo() == CCValAssign::ZExt)
1912       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1913     else if (VA.getLocInfo() == CCValAssign::AExt)
1914       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1915     else if (VA.getLocInfo() == CCValAssign::BCvt)
1916       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1917
1918     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1919            "Unexpected FP-extend for return value.");  
1920
1921     // If this is x86-64, and we disabled SSE, we can't return FP values,
1922     // or SSE or MMX vectors.
1923     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1924          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1925           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1926       report_fatal_error("SSE register return with SSE disabled");
1927     }
1928     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1929     // llvm-gcc has never done it right and no one has noticed, so this
1930     // should be OK for now.
1931     if (ValVT == MVT::f64 &&
1932         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1933       report_fatal_error("SSE2 register return with SSE2 disabled");
1934
1935     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1936     // the RET instruction and handled by the FP Stackifier.
1937     if (VA.getLocReg() == X86::ST0 ||
1938         VA.getLocReg() == X86::ST1) {
1939       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1940       // change the value to the FP stack register class.
1941       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1942         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1943       RetOps.push_back(ValToCopy);
1944       // Don't emit a copytoreg.
1945       continue;
1946     }
1947
1948     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1949     // which is returned in RAX / RDX.
1950     if (Subtarget->is64Bit()) {
1951       if (ValVT == MVT::x86mmx) {
1952         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1953           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1954           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1955                                   ValToCopy);
1956           // If we don't have SSE2 available, convert to v4f32 so the generated
1957           // register is legal.
1958           if (!Subtarget->hasSSE2())
1959             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1960         }
1961       }
1962     }
1963
1964     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1965     Flag = Chain.getValue(1);
1966     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1967   }
1968
1969   // The x86-64 ABIs require that for returning structs by value we copy
1970   // the sret argument into %rax/%eax (depending on ABI) for the return.
1971   // Win32 requires us to put the sret argument to %eax as well.
1972   // We saved the argument into a virtual register in the entry block,
1973   // so now we copy the value out and into %rax/%eax.
1974   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1975       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1976     MachineFunction &MF = DAG.getMachineFunction();
1977     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1978     unsigned Reg = FuncInfo->getSRetReturnReg();
1979     assert(Reg &&
1980            "SRetReturnReg should have been set in LowerFormalArguments().");
1981     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1982
1983     unsigned RetValReg
1984         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1985           X86::RAX : X86::EAX;
1986     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1987     Flag = Chain.getValue(1);
1988
1989     // RAX/EAX now acts like a return value.
1990     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1991   }
1992
1993   RetOps[0] = Chain;  // Update chain.
1994
1995   // Add the flag if we have it.
1996   if (Flag.getNode())
1997     RetOps.push_back(Flag);
1998
1999   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2000 }
2001
2002 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2003   if (N->getNumValues() != 1)
2004     return false;
2005   if (!N->hasNUsesOfValue(1, 0))
2006     return false;
2007
2008   SDValue TCChain = Chain;
2009   SDNode *Copy = *N->use_begin();
2010   if (Copy->getOpcode() == ISD::CopyToReg) {
2011     // If the copy has a glue operand, we conservatively assume it isn't safe to
2012     // perform a tail call.
2013     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2014       return false;
2015     TCChain = Copy->getOperand(0);
2016   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2017     return false;
2018
2019   bool HasRet = false;
2020   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2021        UI != UE; ++UI) {
2022     if (UI->getOpcode() != X86ISD::RET_FLAG)
2023       return false;
2024     HasRet = true;
2025   }
2026
2027   if (!HasRet)
2028     return false;
2029
2030   Chain = TCChain;
2031   return true;
2032 }
2033
2034 MVT
2035 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2036                                             ISD::NodeType ExtendKind) const {
2037   MVT ReturnMVT;
2038   // TODO: Is this also valid on 32-bit?
2039   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2040     ReturnMVT = MVT::i8;
2041   else
2042     ReturnMVT = MVT::i32;
2043
2044   MVT MinVT = getRegisterType(ReturnMVT);
2045   return VT.bitsLT(MinVT) ? MinVT : VT;
2046 }
2047
2048 /// LowerCallResult - Lower the result values of a call into the
2049 /// appropriate copies out of appropriate physical registers.
2050 ///
2051 SDValue
2052 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2053                                    CallingConv::ID CallConv, bool isVarArg,
2054                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2055                                    SDLoc dl, SelectionDAG &DAG,
2056                                    SmallVectorImpl<SDValue> &InVals) const {
2057
2058   // Assign locations to each value returned by this call.
2059   SmallVector<CCValAssign, 16> RVLocs;
2060   bool Is64Bit = Subtarget->is64Bit();
2061   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2062                  DAG.getTarget(), RVLocs, *DAG.getContext());
2063   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2064
2065   // Copy all of the result registers out of their specified physreg.
2066   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2067     CCValAssign &VA = RVLocs[i];
2068     EVT CopyVT = VA.getValVT();
2069
2070     // If this is x86-64, and we disabled SSE, we can't return FP values
2071     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2072         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2073       report_fatal_error("SSE register return with SSE disabled");
2074     }
2075
2076     SDValue Val;
2077
2078     // If this is a call to a function that returns an fp value on the floating
2079     // point stack, we must guarantee the value is popped from the stack, so
2080     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2081     // if the return value is not used. We use the FpPOP_RETVAL instruction
2082     // instead.
2083     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2084       // If we prefer to use the value in xmm registers, copy it out as f80 and
2085       // use a truncate to move it from fp stack reg to xmm reg.
2086       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2087       SDValue Ops[] = { Chain, InFlag };
2088       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2089                                          MVT::Other, MVT::Glue, Ops), 1);
2090       Val = Chain.getValue(0);
2091
2092       // Round the f80 to the right size, which also moves it to the appropriate
2093       // xmm register.
2094       if (CopyVT != VA.getValVT())
2095         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2096                           // This truncation won't change the value.
2097                           DAG.getIntPtrConstant(1));
2098     } else {
2099       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2100                                  CopyVT, InFlag).getValue(1);
2101       Val = Chain.getValue(0);
2102     }
2103     InFlag = Chain.getValue(2);
2104     InVals.push_back(Val);
2105   }
2106
2107   return Chain;
2108 }
2109
2110 //===----------------------------------------------------------------------===//
2111 //                C & StdCall & Fast Calling Convention implementation
2112 //===----------------------------------------------------------------------===//
2113 //  StdCall calling convention seems to be standard for many Windows' API
2114 //  routines and around. It differs from C calling convention just a little:
2115 //  callee should clean up the stack, not caller. Symbols should be also
2116 //  decorated in some fancy way :) It doesn't support any vector arguments.
2117 //  For info on fast calling convention see Fast Calling Convention (tail call)
2118 //  implementation LowerX86_32FastCCCallTo.
2119
2120 /// CallIsStructReturn - Determines whether a call uses struct return
2121 /// semantics.
2122 enum StructReturnType {
2123   NotStructReturn,
2124   RegStructReturn,
2125   StackStructReturn
2126 };
2127 static StructReturnType
2128 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2129   if (Outs.empty())
2130     return NotStructReturn;
2131
2132   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2133   if (!Flags.isSRet())
2134     return NotStructReturn;
2135   if (Flags.isInReg())
2136     return RegStructReturn;
2137   return StackStructReturn;
2138 }
2139
2140 /// ArgsAreStructReturn - Determines whether a function uses struct
2141 /// return semantics.
2142 static StructReturnType
2143 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2144   if (Ins.empty())
2145     return NotStructReturn;
2146
2147   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2148   if (!Flags.isSRet())
2149     return NotStructReturn;
2150   if (Flags.isInReg())
2151     return RegStructReturn;
2152   return StackStructReturn;
2153 }
2154
2155 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2156 /// by "Src" to address "Dst" with size and alignment information specified by
2157 /// the specific parameter attribute. The copy will be passed as a byval
2158 /// function parameter.
2159 static SDValue
2160 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2161                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2162                           SDLoc dl) {
2163   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2164
2165   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2166                        /*isVolatile*/false, /*AlwaysInline=*/true,
2167                        MachinePointerInfo(), MachinePointerInfo());
2168 }
2169
2170 /// IsTailCallConvention - Return true if the calling convention is one that
2171 /// supports tail call optimization.
2172 static bool IsTailCallConvention(CallingConv::ID CC) {
2173   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2174           CC == CallingConv::HiPE);
2175 }
2176
2177 /// \brief Return true if the calling convention is a C calling convention.
2178 static bool IsCCallConvention(CallingConv::ID CC) {
2179   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2180           CC == CallingConv::X86_64_SysV);
2181 }
2182
2183 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2184   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2185     return false;
2186
2187   CallSite CS(CI);
2188   CallingConv::ID CalleeCC = CS.getCallingConv();
2189   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2190     return false;
2191
2192   return true;
2193 }
2194
2195 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2196 /// a tailcall target by changing its ABI.
2197 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2198                                    bool GuaranteedTailCallOpt) {
2199   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2200 }
2201
2202 SDValue
2203 X86TargetLowering::LowerMemArgument(SDValue Chain,
2204                                     CallingConv::ID CallConv,
2205                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2206                                     SDLoc dl, SelectionDAG &DAG,
2207                                     const CCValAssign &VA,
2208                                     MachineFrameInfo *MFI,
2209                                     unsigned i) const {
2210   // Create the nodes corresponding to a load from this parameter slot.
2211   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2212   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2213       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2214   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2215   EVT ValVT;
2216
2217   // If value is passed by pointer we have address passed instead of the value
2218   // itself.
2219   if (VA.getLocInfo() == CCValAssign::Indirect)
2220     ValVT = VA.getLocVT();
2221   else
2222     ValVT = VA.getValVT();
2223
2224   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2225   // changed with more analysis.
2226   // In case of tail call optimization mark all arguments mutable. Since they
2227   // could be overwritten by lowering of arguments in case of a tail call.
2228   if (Flags.isByVal()) {
2229     unsigned Bytes = Flags.getByValSize();
2230     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2231     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2232     return DAG.getFrameIndex(FI, getPointerTy());
2233   } else {
2234     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2235                                     VA.getLocMemOffset(), isImmutable);
2236     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2237     return DAG.getLoad(ValVT, dl, Chain, FIN,
2238                        MachinePointerInfo::getFixedStack(FI),
2239                        false, false, false, 0);
2240   }
2241 }
2242
2243 SDValue
2244 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2245                                         CallingConv::ID CallConv,
2246                                         bool isVarArg,
2247                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2248                                         SDLoc dl,
2249                                         SelectionDAG &DAG,
2250                                         SmallVectorImpl<SDValue> &InVals)
2251                                           const {
2252   MachineFunction &MF = DAG.getMachineFunction();
2253   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2254
2255   const Function* Fn = MF.getFunction();
2256   if (Fn->hasExternalLinkage() &&
2257       Subtarget->isTargetCygMing() &&
2258       Fn->getName() == "main")
2259     FuncInfo->setForceFramePointer(true);
2260
2261   MachineFrameInfo *MFI = MF.getFrameInfo();
2262   bool Is64Bit = Subtarget->is64Bit();
2263   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2264
2265   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2266          "Var args not supported with calling convention fastcc, ghc or hipe");
2267
2268   // Assign locations to all of the incoming arguments.
2269   SmallVector<CCValAssign, 16> ArgLocs;
2270   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2271                  ArgLocs, *DAG.getContext());
2272
2273   // Allocate shadow area for Win64
2274   if (IsWin64)
2275     CCInfo.AllocateStack(32, 8);
2276
2277   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2278
2279   unsigned LastVal = ~0U;
2280   SDValue ArgValue;
2281   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2282     CCValAssign &VA = ArgLocs[i];
2283     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2284     // places.
2285     assert(VA.getValNo() != LastVal &&
2286            "Don't support value assigned to multiple locs yet");
2287     (void)LastVal;
2288     LastVal = VA.getValNo();
2289
2290     if (VA.isRegLoc()) {
2291       EVT RegVT = VA.getLocVT();
2292       const TargetRegisterClass *RC;
2293       if (RegVT == MVT::i32)
2294         RC = &X86::GR32RegClass;
2295       else if (Is64Bit && RegVT == MVT::i64)
2296         RC = &X86::GR64RegClass;
2297       else if (RegVT == MVT::f32)
2298         RC = &X86::FR32RegClass;
2299       else if (RegVT == MVT::f64)
2300         RC = &X86::FR64RegClass;
2301       else if (RegVT.is512BitVector())
2302         RC = &X86::VR512RegClass;
2303       else if (RegVT.is256BitVector())
2304         RC = &X86::VR256RegClass;
2305       else if (RegVT.is128BitVector())
2306         RC = &X86::VR128RegClass;
2307       else if (RegVT == MVT::x86mmx)
2308         RC = &X86::VR64RegClass;
2309       else if (RegVT == MVT::i1)
2310         RC = &X86::VK1RegClass;
2311       else if (RegVT == MVT::v8i1)
2312         RC = &X86::VK8RegClass;
2313       else if (RegVT == MVT::v16i1)
2314         RC = &X86::VK16RegClass;
2315       else
2316         llvm_unreachable("Unknown argument type!");
2317
2318       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2319       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2320
2321       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2322       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2323       // right size.
2324       if (VA.getLocInfo() == CCValAssign::SExt)
2325         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2326                                DAG.getValueType(VA.getValVT()));
2327       else if (VA.getLocInfo() == CCValAssign::ZExt)
2328         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2329                                DAG.getValueType(VA.getValVT()));
2330       else if (VA.getLocInfo() == CCValAssign::BCvt)
2331         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2332
2333       if (VA.isExtInLoc()) {
2334         // Handle MMX values passed in XMM regs.
2335         if (RegVT.isVector())
2336           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2337         else
2338           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2339       }
2340     } else {
2341       assert(VA.isMemLoc());
2342       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2343     }
2344
2345     // If value is passed via pointer - do a load.
2346     if (VA.getLocInfo() == CCValAssign::Indirect)
2347       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2348                              MachinePointerInfo(), false, false, false, 0);
2349
2350     InVals.push_back(ArgValue);
2351   }
2352
2353   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2354     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2355       // The x86-64 ABIs require that for returning structs by value we copy
2356       // the sret argument into %rax/%eax (depending on ABI) for the return.
2357       // Win32 requires us to put the sret argument to %eax as well.
2358       // Save the argument into a virtual register so that we can access it
2359       // from the return points.
2360       if (Ins[i].Flags.isSRet()) {
2361         unsigned Reg = FuncInfo->getSRetReturnReg();
2362         if (!Reg) {
2363           MVT PtrTy = getPointerTy();
2364           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2365           FuncInfo->setSRetReturnReg(Reg);
2366         }
2367         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2368         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2369         break;
2370       }
2371     }
2372   }
2373
2374   unsigned StackSize = CCInfo.getNextStackOffset();
2375   // Align stack specially for tail calls.
2376   if (FuncIsMadeTailCallSafe(CallConv,
2377                              MF.getTarget().Options.GuaranteedTailCallOpt))
2378     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2379
2380   // If the function takes variable number of arguments, make a frame index for
2381   // the start of the first vararg value... for expansion of llvm.va_start.
2382   if (isVarArg) {
2383     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2384                     CallConv != CallingConv::X86_ThisCall)) {
2385       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2386     }
2387     if (Is64Bit) {
2388       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2389
2390       // FIXME: We should really autogenerate these arrays
2391       static const MCPhysReg GPR64ArgRegsWin64[] = {
2392         X86::RCX, X86::RDX, X86::R8,  X86::R9
2393       };
2394       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2395         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2396       };
2397       static const MCPhysReg XMMArgRegs64Bit[] = {
2398         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2399         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2400       };
2401       const MCPhysReg *GPR64ArgRegs;
2402       unsigned NumXMMRegs = 0;
2403
2404       if (IsWin64) {
2405         // The XMM registers which might contain var arg parameters are shadowed
2406         // in their paired GPR.  So we only need to save the GPR to their home
2407         // slots.
2408         TotalNumIntRegs = 4;
2409         GPR64ArgRegs = GPR64ArgRegsWin64;
2410       } else {
2411         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2412         GPR64ArgRegs = GPR64ArgRegs64Bit;
2413
2414         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2415                                                 TotalNumXMMRegs);
2416       }
2417       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2418                                                        TotalNumIntRegs);
2419
2420       bool NoImplicitFloatOps = Fn->getAttributes().
2421         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2422       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2423              "SSE register cannot be used when SSE is disabled!");
2424       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2425                NoImplicitFloatOps) &&
2426              "SSE register cannot be used when SSE is disabled!");
2427       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2428           !Subtarget->hasSSE1())
2429         // Kernel mode asks for SSE to be disabled, so don't push them
2430         // on the stack.
2431         TotalNumXMMRegs = 0;
2432
2433       if (IsWin64) {
2434         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2435         // Get to the caller-allocated home save location.  Add 8 to account
2436         // for the return address.
2437         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2438         FuncInfo->setRegSaveFrameIndex(
2439           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2440         // Fixup to set vararg frame on shadow area (4 x i64).
2441         if (NumIntRegs < 4)
2442           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2443       } else {
2444         // For X86-64, if there are vararg parameters that are passed via
2445         // registers, then we must store them to their spots on the stack so
2446         // they may be loaded by deferencing the result of va_next.
2447         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2448         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2449         FuncInfo->setRegSaveFrameIndex(
2450           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2451                                false));
2452       }
2453
2454       // Store the integer parameter registers.
2455       SmallVector<SDValue, 8> MemOps;
2456       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2457                                         getPointerTy());
2458       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2459       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2460         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2461                                   DAG.getIntPtrConstant(Offset));
2462         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2463                                      &X86::GR64RegClass);
2464         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2465         SDValue Store =
2466           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2467                        MachinePointerInfo::getFixedStack(
2468                          FuncInfo->getRegSaveFrameIndex(), Offset),
2469                        false, false, 0);
2470         MemOps.push_back(Store);
2471         Offset += 8;
2472       }
2473
2474       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2475         // Now store the XMM (fp + vector) parameter registers.
2476         SmallVector<SDValue, 11> SaveXMMOps;
2477         SaveXMMOps.push_back(Chain);
2478
2479         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2480         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2481         SaveXMMOps.push_back(ALVal);
2482
2483         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2484                                FuncInfo->getRegSaveFrameIndex()));
2485         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2486                                FuncInfo->getVarArgsFPOffset()));
2487
2488         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2489           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2490                                        &X86::VR128RegClass);
2491           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2492           SaveXMMOps.push_back(Val);
2493         }
2494         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2495                                      MVT::Other, SaveXMMOps));
2496       }
2497
2498       if (!MemOps.empty())
2499         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2500     }
2501   }
2502
2503   // Some CCs need callee pop.
2504   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2505                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2506     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2507   } else {
2508     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2509     // If this is an sret function, the return should pop the hidden pointer.
2510     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2511         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2512         argsAreStructReturn(Ins) == StackStructReturn)
2513       FuncInfo->setBytesToPopOnReturn(4);
2514   }
2515
2516   if (!Is64Bit) {
2517     // RegSaveFrameIndex is X86-64 only.
2518     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2519     if (CallConv == CallingConv::X86_FastCall ||
2520         CallConv == CallingConv::X86_ThisCall)
2521       // fastcc functions can't have varargs.
2522       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2523   }
2524
2525   FuncInfo->setArgumentStackSize(StackSize);
2526
2527   return Chain;
2528 }
2529
2530 SDValue
2531 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2532                                     SDValue StackPtr, SDValue Arg,
2533                                     SDLoc dl, SelectionDAG &DAG,
2534                                     const CCValAssign &VA,
2535                                     ISD::ArgFlagsTy Flags) const {
2536   unsigned LocMemOffset = VA.getLocMemOffset();
2537   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2538   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2539   if (Flags.isByVal())
2540     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2541
2542   return DAG.getStore(Chain, dl, Arg, PtrOff,
2543                       MachinePointerInfo::getStack(LocMemOffset),
2544                       false, false, 0);
2545 }
2546
2547 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2548 /// optimization is performed and it is required.
2549 SDValue
2550 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2551                                            SDValue &OutRetAddr, SDValue Chain,
2552                                            bool IsTailCall, bool Is64Bit,
2553                                            int FPDiff, SDLoc dl) const {
2554   // Adjust the Return address stack slot.
2555   EVT VT = getPointerTy();
2556   OutRetAddr = getReturnAddressFrameIndex(DAG);
2557
2558   // Load the "old" Return address.
2559   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2560                            false, false, false, 0);
2561   return SDValue(OutRetAddr.getNode(), 1);
2562 }
2563
2564 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2565 /// optimization is performed and it is required (FPDiff!=0).
2566 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2567                                         SDValue Chain, SDValue RetAddrFrIdx,
2568                                         EVT PtrVT, unsigned SlotSize,
2569                                         int FPDiff, SDLoc dl) {
2570   // Store the return address to the appropriate stack slot.
2571   if (!FPDiff) return Chain;
2572   // Calculate the new stack slot for the return address.
2573   int NewReturnAddrFI =
2574     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2575                                          false);
2576   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2577   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2578                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2579                        false, false, 0);
2580   return Chain;
2581 }
2582
2583 SDValue
2584 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2585                              SmallVectorImpl<SDValue> &InVals) const {
2586   SelectionDAG &DAG                     = CLI.DAG;
2587   SDLoc &dl                             = CLI.DL;
2588   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2589   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2590   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2591   SDValue Chain                         = CLI.Chain;
2592   SDValue Callee                        = CLI.Callee;
2593   CallingConv::ID CallConv              = CLI.CallConv;
2594   bool &isTailCall                      = CLI.IsTailCall;
2595   bool isVarArg                         = CLI.IsVarArg;
2596
2597   MachineFunction &MF = DAG.getMachineFunction();
2598   bool Is64Bit        = Subtarget->is64Bit();
2599   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2600   StructReturnType SR = callIsStructReturn(Outs);
2601   bool IsSibcall      = false;
2602
2603   if (MF.getTarget().Options.DisableTailCalls)
2604     isTailCall = false;
2605
2606   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2607   if (IsMustTail) {
2608     // Force this to be a tail call.  The verifier rules are enough to ensure
2609     // that we can lower this successfully without moving the return address
2610     // around.
2611     isTailCall = true;
2612   } else if (isTailCall) {
2613     // Check if it's really possible to do a tail call.
2614     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2615                     isVarArg, SR != NotStructReturn,
2616                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2617                     Outs, OutVals, Ins, DAG);
2618
2619     // Sibcalls are automatically detected tailcalls which do not require
2620     // ABI changes.
2621     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2622       IsSibcall = true;
2623
2624     if (isTailCall)
2625       ++NumTailCalls;
2626   }
2627
2628   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2629          "Var args not supported with calling convention fastcc, ghc or hipe");
2630
2631   // Analyze operands of the call, assigning locations to each operand.
2632   SmallVector<CCValAssign, 16> ArgLocs;
2633   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2634                  ArgLocs, *DAG.getContext());
2635
2636   // Allocate shadow area for Win64
2637   if (IsWin64)
2638     CCInfo.AllocateStack(32, 8);
2639
2640   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2641
2642   // Get a count of how many bytes are to be pushed on the stack.
2643   unsigned NumBytes = CCInfo.getNextStackOffset();
2644   if (IsSibcall)
2645     // This is a sibcall. The memory operands are available in caller's
2646     // own caller's stack.
2647     NumBytes = 0;
2648   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2649            IsTailCallConvention(CallConv))
2650     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2651
2652   int FPDiff = 0;
2653   if (isTailCall && !IsSibcall && !IsMustTail) {
2654     // Lower arguments at fp - stackoffset + fpdiff.
2655     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2656     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2657
2658     FPDiff = NumBytesCallerPushed - NumBytes;
2659
2660     // Set the delta of movement of the returnaddr stackslot.
2661     // But only set if delta is greater than previous delta.
2662     if (FPDiff < X86Info->getTCReturnAddrDelta())
2663       X86Info->setTCReturnAddrDelta(FPDiff);
2664   }
2665
2666   unsigned NumBytesToPush = NumBytes;
2667   unsigned NumBytesToPop = NumBytes;
2668
2669   // If we have an inalloca argument, all stack space has already been allocated
2670   // for us and be right at the top of the stack.  We don't support multiple
2671   // arguments passed in memory when using inalloca.
2672   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2673     NumBytesToPush = 0;
2674     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2675            "an inalloca argument must be the only memory argument");
2676   }
2677
2678   if (!IsSibcall)
2679     Chain = DAG.getCALLSEQ_START(
2680         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2681
2682   SDValue RetAddrFrIdx;
2683   // Load return address for tail calls.
2684   if (isTailCall && FPDiff)
2685     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2686                                     Is64Bit, FPDiff, dl);
2687
2688   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2689   SmallVector<SDValue, 8> MemOpChains;
2690   SDValue StackPtr;
2691
2692   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2693   // of tail call optimization arguments are handle later.
2694   const X86RegisterInfo *RegInfo =
2695     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2696   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2697     // Skip inalloca arguments, they have already been written.
2698     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2699     if (Flags.isInAlloca())
2700       continue;
2701
2702     CCValAssign &VA = ArgLocs[i];
2703     EVT RegVT = VA.getLocVT();
2704     SDValue Arg = OutVals[i];
2705     bool isByVal = Flags.isByVal();
2706
2707     // Promote the value if needed.
2708     switch (VA.getLocInfo()) {
2709     default: llvm_unreachable("Unknown loc info!");
2710     case CCValAssign::Full: break;
2711     case CCValAssign::SExt:
2712       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2713       break;
2714     case CCValAssign::ZExt:
2715       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2716       break;
2717     case CCValAssign::AExt:
2718       if (RegVT.is128BitVector()) {
2719         // Special case: passing MMX values in XMM registers.
2720         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2721         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2722         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2723       } else
2724         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2725       break;
2726     case CCValAssign::BCvt:
2727       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2728       break;
2729     case CCValAssign::Indirect: {
2730       // Store the argument.
2731       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2732       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2733       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2734                            MachinePointerInfo::getFixedStack(FI),
2735                            false, false, 0);
2736       Arg = SpillSlot;
2737       break;
2738     }
2739     }
2740
2741     if (VA.isRegLoc()) {
2742       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2743       if (isVarArg && IsWin64) {
2744         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2745         // shadow reg if callee is a varargs function.
2746         unsigned ShadowReg = 0;
2747         switch (VA.getLocReg()) {
2748         case X86::XMM0: ShadowReg = X86::RCX; break;
2749         case X86::XMM1: ShadowReg = X86::RDX; break;
2750         case X86::XMM2: ShadowReg = X86::R8; break;
2751         case X86::XMM3: ShadowReg = X86::R9; break;
2752         }
2753         if (ShadowReg)
2754           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2755       }
2756     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2757       assert(VA.isMemLoc());
2758       if (!StackPtr.getNode())
2759         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2760                                       getPointerTy());
2761       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2762                                              dl, DAG, VA, Flags));
2763     }
2764   }
2765
2766   if (!MemOpChains.empty())
2767     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2768
2769   if (Subtarget->isPICStyleGOT()) {
2770     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2771     // GOT pointer.
2772     if (!isTailCall) {
2773       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2774                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2775     } else {
2776       // If we are tail calling and generating PIC/GOT style code load the
2777       // address of the callee into ECX. The value in ecx is used as target of
2778       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2779       // for tail calls on PIC/GOT architectures. Normally we would just put the
2780       // address of GOT into ebx and then call target@PLT. But for tail calls
2781       // ebx would be restored (since ebx is callee saved) before jumping to the
2782       // target@PLT.
2783
2784       // Note: The actual moving to ECX is done further down.
2785       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2786       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2787           !G->getGlobal()->hasProtectedVisibility())
2788         Callee = LowerGlobalAddress(Callee, DAG);
2789       else if (isa<ExternalSymbolSDNode>(Callee))
2790         Callee = LowerExternalSymbol(Callee, DAG);
2791     }
2792   }
2793
2794   if (Is64Bit && isVarArg && !IsWin64) {
2795     // From AMD64 ABI document:
2796     // For calls that may call functions that use varargs or stdargs
2797     // (prototype-less calls or calls to functions containing ellipsis (...) in
2798     // the declaration) %al is used as hidden argument to specify the number
2799     // of SSE registers used. The contents of %al do not need to match exactly
2800     // the number of registers, but must be an ubound on the number of SSE
2801     // registers used and is in the range 0 - 8 inclusive.
2802
2803     // Count the number of XMM registers allocated.
2804     static const MCPhysReg XMMArgRegs[] = {
2805       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2806       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2807     };
2808     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2809     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2810            && "SSE registers cannot be used when SSE is disabled");
2811
2812     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2813                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2814   }
2815
2816   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2817   // don't need this because the eligibility check rejects calls that require
2818   // shuffling arguments passed in memory.
2819   if (!IsSibcall && isTailCall) {
2820     // Force all the incoming stack arguments to be loaded from the stack
2821     // before any new outgoing arguments are stored to the stack, because the
2822     // outgoing stack slots may alias the incoming argument stack slots, and
2823     // the alias isn't otherwise explicit. This is slightly more conservative
2824     // than necessary, because it means that each store effectively depends
2825     // on every argument instead of just those arguments it would clobber.
2826     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2827
2828     SmallVector<SDValue, 8> MemOpChains2;
2829     SDValue FIN;
2830     int FI = 0;
2831     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2832       CCValAssign &VA = ArgLocs[i];
2833       if (VA.isRegLoc())
2834         continue;
2835       assert(VA.isMemLoc());
2836       SDValue Arg = OutVals[i];
2837       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2838       // Skip inalloca arguments.  They don't require any work.
2839       if (Flags.isInAlloca())
2840         continue;
2841       // Create frame index.
2842       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2843       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2844       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2845       FIN = DAG.getFrameIndex(FI, getPointerTy());
2846
2847       if (Flags.isByVal()) {
2848         // Copy relative to framepointer.
2849         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2850         if (!StackPtr.getNode())
2851           StackPtr = DAG.getCopyFromReg(Chain, dl,
2852                                         RegInfo->getStackRegister(),
2853                                         getPointerTy());
2854         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2855
2856         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2857                                                          ArgChain,
2858                                                          Flags, DAG, dl));
2859       } else {
2860         // Store relative to framepointer.
2861         MemOpChains2.push_back(
2862           DAG.getStore(ArgChain, dl, Arg, FIN,
2863                        MachinePointerInfo::getFixedStack(FI),
2864                        false, false, 0));
2865       }
2866     }
2867
2868     if (!MemOpChains2.empty())
2869       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2870
2871     // Store the return address to the appropriate stack slot.
2872     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2873                                      getPointerTy(), RegInfo->getSlotSize(),
2874                                      FPDiff, dl);
2875   }
2876
2877   // Build a sequence of copy-to-reg nodes chained together with token chain
2878   // and flag operands which copy the outgoing args into registers.
2879   SDValue InFlag;
2880   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2881     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2882                              RegsToPass[i].second, InFlag);
2883     InFlag = Chain.getValue(1);
2884   }
2885
2886   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2887     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2888     // In the 64-bit large code model, we have to make all calls
2889     // through a register, since the call instruction's 32-bit
2890     // pc-relative offset may not be large enough to hold the whole
2891     // address.
2892   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2893     // If the callee is a GlobalAddress node (quite common, every direct call
2894     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2895     // it.
2896
2897     // We should use extra load for direct calls to dllimported functions in
2898     // non-JIT mode.
2899     const GlobalValue *GV = G->getGlobal();
2900     if (!GV->hasDLLImportStorageClass()) {
2901       unsigned char OpFlags = 0;
2902       bool ExtraLoad = false;
2903       unsigned WrapperKind = ISD::DELETED_NODE;
2904
2905       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2906       // external symbols most go through the PLT in PIC mode.  If the symbol
2907       // has hidden or protected visibility, or if it is static or local, then
2908       // we don't need to use the PLT - we can directly call it.
2909       if (Subtarget->isTargetELF() &&
2910           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2911           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2912         OpFlags = X86II::MO_PLT;
2913       } else if (Subtarget->isPICStyleStubAny() &&
2914                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2915                  (!Subtarget->getTargetTriple().isMacOSX() ||
2916                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2917         // PC-relative references to external symbols should go through $stub,
2918         // unless we're building with the leopard linker or later, which
2919         // automatically synthesizes these stubs.
2920         OpFlags = X86II::MO_DARWIN_STUB;
2921       } else if (Subtarget->isPICStyleRIPRel() &&
2922                  isa<Function>(GV) &&
2923                  cast<Function>(GV)->getAttributes().
2924                    hasAttribute(AttributeSet::FunctionIndex,
2925                                 Attribute::NonLazyBind)) {
2926         // If the function is marked as non-lazy, generate an indirect call
2927         // which loads from the GOT directly. This avoids runtime overhead
2928         // at the cost of eager binding (and one extra byte of encoding).
2929         OpFlags = X86II::MO_GOTPCREL;
2930         WrapperKind = X86ISD::WrapperRIP;
2931         ExtraLoad = true;
2932       }
2933
2934       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2935                                           G->getOffset(), OpFlags);
2936
2937       // Add a wrapper if needed.
2938       if (WrapperKind != ISD::DELETED_NODE)
2939         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2940       // Add extra indirection if needed.
2941       if (ExtraLoad)
2942         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2943                              MachinePointerInfo::getGOT(),
2944                              false, false, false, 0);
2945     }
2946   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2947     unsigned char OpFlags = 0;
2948
2949     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2950     // external symbols should go through the PLT.
2951     if (Subtarget->isTargetELF() &&
2952         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2953       OpFlags = X86II::MO_PLT;
2954     } else if (Subtarget->isPICStyleStubAny() &&
2955                (!Subtarget->getTargetTriple().isMacOSX() ||
2956                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2957       // PC-relative references to external symbols should go through $stub,
2958       // unless we're building with the leopard linker or later, which
2959       // automatically synthesizes these stubs.
2960       OpFlags = X86II::MO_DARWIN_STUB;
2961     }
2962
2963     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2964                                          OpFlags);
2965   }
2966
2967   // Returns a chain & a flag for retval copy to use.
2968   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2969   SmallVector<SDValue, 8> Ops;
2970
2971   if (!IsSibcall && isTailCall) {
2972     Chain = DAG.getCALLSEQ_END(Chain,
2973                                DAG.getIntPtrConstant(NumBytesToPop, true),
2974                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2975     InFlag = Chain.getValue(1);
2976   }
2977
2978   Ops.push_back(Chain);
2979   Ops.push_back(Callee);
2980
2981   if (isTailCall)
2982     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2983
2984   // Add argument registers to the end of the list so that they are known live
2985   // into the call.
2986   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2987     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2988                                   RegsToPass[i].second.getValueType()));
2989
2990   // Add a register mask operand representing the call-preserved registers.
2991   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2992   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2993   assert(Mask && "Missing call preserved mask for calling convention");
2994   Ops.push_back(DAG.getRegisterMask(Mask));
2995
2996   if (InFlag.getNode())
2997     Ops.push_back(InFlag);
2998
2999   if (isTailCall) {
3000     // We used to do:
3001     //// If this is the first return lowered for this function, add the regs
3002     //// to the liveout set for the function.
3003     // This isn't right, although it's probably harmless on x86; liveouts
3004     // should be computed from returns not tail calls.  Consider a void
3005     // function making a tail call to a function returning int.
3006     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3007   }
3008
3009   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3010   InFlag = Chain.getValue(1);
3011
3012   // Create the CALLSEQ_END node.
3013   unsigned NumBytesForCalleeToPop;
3014   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3015                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3016     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3017   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3018            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3019            SR == StackStructReturn)
3020     // If this is a call to a struct-return function, the callee
3021     // pops the hidden struct pointer, so we have to push it back.
3022     // This is common for Darwin/X86, Linux & Mingw32 targets.
3023     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3024     NumBytesForCalleeToPop = 4;
3025   else
3026     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3027
3028   // Returns a flag for retval copy to use.
3029   if (!IsSibcall) {
3030     Chain = DAG.getCALLSEQ_END(Chain,
3031                                DAG.getIntPtrConstant(NumBytesToPop, true),
3032                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3033                                                      true),
3034                                InFlag, dl);
3035     InFlag = Chain.getValue(1);
3036   }
3037
3038   // Handle result values, copying them out of physregs into vregs that we
3039   // return.
3040   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3041                          Ins, dl, DAG, InVals);
3042 }
3043
3044 //===----------------------------------------------------------------------===//
3045 //                Fast Calling Convention (tail call) implementation
3046 //===----------------------------------------------------------------------===//
3047
3048 //  Like std call, callee cleans arguments, convention except that ECX is
3049 //  reserved for storing the tail called function address. Only 2 registers are
3050 //  free for argument passing (inreg). Tail call optimization is performed
3051 //  provided:
3052 //                * tailcallopt is enabled
3053 //                * caller/callee are fastcc
3054 //  On X86_64 architecture with GOT-style position independent code only local
3055 //  (within module) calls are supported at the moment.
3056 //  To keep the stack aligned according to platform abi the function
3057 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3058 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3059 //  If a tail called function callee has more arguments than the caller the
3060 //  caller needs to make sure that there is room to move the RETADDR to. This is
3061 //  achieved by reserving an area the size of the argument delta right after the
3062 //  original RETADDR, but before the saved framepointer or the spilled registers
3063 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3064 //  stack layout:
3065 //    arg1
3066 //    arg2
3067 //    RETADDR
3068 //    [ new RETADDR
3069 //      move area ]
3070 //    (possible EBP)
3071 //    ESI
3072 //    EDI
3073 //    local1 ..
3074
3075 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3076 /// for a 16 byte align requirement.
3077 unsigned
3078 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3079                                                SelectionDAG& DAG) const {
3080   MachineFunction &MF = DAG.getMachineFunction();
3081   const TargetMachine &TM = MF.getTarget();
3082   const X86RegisterInfo *RegInfo =
3083     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3084   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3085   unsigned StackAlignment = TFI.getStackAlignment();
3086   uint64_t AlignMask = StackAlignment - 1;
3087   int64_t Offset = StackSize;
3088   unsigned SlotSize = RegInfo->getSlotSize();
3089   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3090     // Number smaller than 12 so just add the difference.
3091     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3092   } else {
3093     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3094     Offset = ((~AlignMask) & Offset) + StackAlignment +
3095       (StackAlignment-SlotSize);
3096   }
3097   return Offset;
3098 }
3099
3100 /// MatchingStackOffset - Return true if the given stack call argument is
3101 /// already available in the same position (relatively) of the caller's
3102 /// incoming argument stack.
3103 static
3104 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3105                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3106                          const X86InstrInfo *TII) {
3107   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3108   int FI = INT_MAX;
3109   if (Arg.getOpcode() == ISD::CopyFromReg) {
3110     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3111     if (!TargetRegisterInfo::isVirtualRegister(VR))
3112       return false;
3113     MachineInstr *Def = MRI->getVRegDef(VR);
3114     if (!Def)
3115       return false;
3116     if (!Flags.isByVal()) {
3117       if (!TII->isLoadFromStackSlot(Def, FI))
3118         return false;
3119     } else {
3120       unsigned Opcode = Def->getOpcode();
3121       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3122           Def->getOperand(1).isFI()) {
3123         FI = Def->getOperand(1).getIndex();
3124         Bytes = Flags.getByValSize();
3125       } else
3126         return false;
3127     }
3128   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3129     if (Flags.isByVal())
3130       // ByVal argument is passed in as a pointer but it's now being
3131       // dereferenced. e.g.
3132       // define @foo(%struct.X* %A) {
3133       //   tail call @bar(%struct.X* byval %A)
3134       // }
3135       return false;
3136     SDValue Ptr = Ld->getBasePtr();
3137     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3138     if (!FINode)
3139       return false;
3140     FI = FINode->getIndex();
3141   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3142     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3143     FI = FINode->getIndex();
3144     Bytes = Flags.getByValSize();
3145   } else
3146     return false;
3147
3148   assert(FI != INT_MAX);
3149   if (!MFI->isFixedObjectIndex(FI))
3150     return false;
3151   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3152 }
3153
3154 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3155 /// for tail call optimization. Targets which want to do tail call
3156 /// optimization should implement this function.
3157 bool
3158 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3159                                                      CallingConv::ID CalleeCC,
3160                                                      bool isVarArg,
3161                                                      bool isCalleeStructRet,
3162                                                      bool isCallerStructRet,
3163                                                      Type *RetTy,
3164                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3165                                     const SmallVectorImpl<SDValue> &OutVals,
3166                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3167                                                      SelectionDAG &DAG) const {
3168   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3169     return false;
3170
3171   // If -tailcallopt is specified, make fastcc functions tail-callable.
3172   const MachineFunction &MF = DAG.getMachineFunction();
3173   const Function *CallerF = MF.getFunction();
3174
3175   // If the function return type is x86_fp80 and the callee return type is not,
3176   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3177   // perform a tailcall optimization here.
3178   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3179     return false;
3180
3181   CallingConv::ID CallerCC = CallerF->getCallingConv();
3182   bool CCMatch = CallerCC == CalleeCC;
3183   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3184   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3185
3186   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3187     if (IsTailCallConvention(CalleeCC) && CCMatch)
3188       return true;
3189     return false;
3190   }
3191
3192   // Look for obvious safe cases to perform tail call optimization that do not
3193   // require ABI changes. This is what gcc calls sibcall.
3194
3195   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3196   // emit a special epilogue.
3197   const X86RegisterInfo *RegInfo =
3198     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3199   if (RegInfo->needsStackRealignment(MF))
3200     return false;
3201
3202   // Also avoid sibcall optimization if either caller or callee uses struct
3203   // return semantics.
3204   if (isCalleeStructRet || isCallerStructRet)
3205     return false;
3206
3207   // An stdcall/thiscall caller is expected to clean up its arguments; the
3208   // callee isn't going to do that.
3209   // FIXME: this is more restrictive than needed. We could produce a tailcall
3210   // when the stack adjustment matches. For example, with a thiscall that takes
3211   // only one argument.
3212   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3213                    CallerCC == CallingConv::X86_ThisCall))
3214     return false;
3215
3216   // Do not sibcall optimize vararg calls unless all arguments are passed via
3217   // registers.
3218   if (isVarArg && !Outs.empty()) {
3219
3220     // Optimizing for varargs on Win64 is unlikely to be safe without
3221     // additional testing.
3222     if (IsCalleeWin64 || IsCallerWin64)
3223       return false;
3224
3225     SmallVector<CCValAssign, 16> ArgLocs;
3226     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3227                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3228
3229     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3230     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3231       if (!ArgLocs[i].isRegLoc())
3232         return false;
3233   }
3234
3235   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3236   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3237   // this into a sibcall.
3238   bool Unused = false;
3239   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3240     if (!Ins[i].Used) {
3241       Unused = true;
3242       break;
3243     }
3244   }
3245   if (Unused) {
3246     SmallVector<CCValAssign, 16> RVLocs;
3247     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3248                    DAG.getTarget(), RVLocs, *DAG.getContext());
3249     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3250     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3251       CCValAssign &VA = RVLocs[i];
3252       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3253         return false;
3254     }
3255   }
3256
3257   // If the calling conventions do not match, then we'd better make sure the
3258   // results are returned in the same way as what the caller expects.
3259   if (!CCMatch) {
3260     SmallVector<CCValAssign, 16> RVLocs1;
3261     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3262                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3263     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3264
3265     SmallVector<CCValAssign, 16> RVLocs2;
3266     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3267                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3268     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3269
3270     if (RVLocs1.size() != RVLocs2.size())
3271       return false;
3272     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3273       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3274         return false;
3275       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3276         return false;
3277       if (RVLocs1[i].isRegLoc()) {
3278         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3279           return false;
3280       } else {
3281         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3282           return false;
3283       }
3284     }
3285   }
3286
3287   // If the callee takes no arguments then go on to check the results of the
3288   // call.
3289   if (!Outs.empty()) {
3290     // Check if stack adjustment is needed. For now, do not do this if any
3291     // argument is passed on the stack.
3292     SmallVector<CCValAssign, 16> ArgLocs;
3293     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3294                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3295
3296     // Allocate shadow area for Win64
3297     if (IsCalleeWin64)
3298       CCInfo.AllocateStack(32, 8);
3299
3300     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3301     if (CCInfo.getNextStackOffset()) {
3302       MachineFunction &MF = DAG.getMachineFunction();
3303       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3304         return false;
3305
3306       // Check if the arguments are already laid out in the right way as
3307       // the caller's fixed stack objects.
3308       MachineFrameInfo *MFI = MF.getFrameInfo();
3309       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3310       const X86InstrInfo *TII =
3311           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3312       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3313         CCValAssign &VA = ArgLocs[i];
3314         SDValue Arg = OutVals[i];
3315         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3316         if (VA.getLocInfo() == CCValAssign::Indirect)
3317           return false;
3318         if (!VA.isRegLoc()) {
3319           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3320                                    MFI, MRI, TII))
3321             return false;
3322         }
3323       }
3324     }
3325
3326     // If the tailcall address may be in a register, then make sure it's
3327     // possible to register allocate for it. In 32-bit, the call address can
3328     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3329     // callee-saved registers are restored. These happen to be the same
3330     // registers used to pass 'inreg' arguments so watch out for those.
3331     if (!Subtarget->is64Bit() &&
3332         ((!isa<GlobalAddressSDNode>(Callee) &&
3333           !isa<ExternalSymbolSDNode>(Callee)) ||
3334          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3335       unsigned NumInRegs = 0;
3336       // In PIC we need an extra register to formulate the address computation
3337       // for the callee.
3338       unsigned MaxInRegs =
3339         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3340
3341       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3342         CCValAssign &VA = ArgLocs[i];
3343         if (!VA.isRegLoc())
3344           continue;
3345         unsigned Reg = VA.getLocReg();
3346         switch (Reg) {
3347         default: break;
3348         case X86::EAX: case X86::EDX: case X86::ECX:
3349           if (++NumInRegs == MaxInRegs)
3350             return false;
3351           break;
3352         }
3353       }
3354     }
3355   }
3356
3357   return true;
3358 }
3359
3360 FastISel *
3361 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3362                                   const TargetLibraryInfo *libInfo) const {
3363   return X86::createFastISel(funcInfo, libInfo);
3364 }
3365
3366 //===----------------------------------------------------------------------===//
3367 //                           Other Lowering Hooks
3368 //===----------------------------------------------------------------------===//
3369
3370 static bool MayFoldLoad(SDValue Op) {
3371   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3372 }
3373
3374 static bool MayFoldIntoStore(SDValue Op) {
3375   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3376 }
3377
3378 static bool isTargetShuffle(unsigned Opcode) {
3379   switch(Opcode) {
3380   default: return false;
3381   case X86ISD::PSHUFD:
3382   case X86ISD::PSHUFHW:
3383   case X86ISD::PSHUFLW:
3384   case X86ISD::SHUFP:
3385   case X86ISD::PALIGNR:
3386   case X86ISD::MOVLHPS:
3387   case X86ISD::MOVLHPD:
3388   case X86ISD::MOVHLPS:
3389   case X86ISD::MOVLPS:
3390   case X86ISD::MOVLPD:
3391   case X86ISD::MOVSHDUP:
3392   case X86ISD::MOVSLDUP:
3393   case X86ISD::MOVDDUP:
3394   case X86ISD::MOVSS:
3395   case X86ISD::MOVSD:
3396   case X86ISD::UNPCKL:
3397   case X86ISD::UNPCKH:
3398   case X86ISD::VPERMILP:
3399   case X86ISD::VPERM2X128:
3400   case X86ISD::VPERMI:
3401     return true;
3402   }
3403 }
3404
3405 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3406                                     SDValue V1, SelectionDAG &DAG) {
3407   switch(Opc) {
3408   default: llvm_unreachable("Unknown x86 shuffle node");
3409   case X86ISD::MOVSHDUP:
3410   case X86ISD::MOVSLDUP:
3411   case X86ISD::MOVDDUP:
3412     return DAG.getNode(Opc, dl, VT, V1);
3413   }
3414 }
3415
3416 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3417                                     SDValue V1, unsigned TargetMask,
3418                                     SelectionDAG &DAG) {
3419   switch(Opc) {
3420   default: llvm_unreachable("Unknown x86 shuffle node");
3421   case X86ISD::PSHUFD:
3422   case X86ISD::PSHUFHW:
3423   case X86ISD::PSHUFLW:
3424   case X86ISD::VPERMILP:
3425   case X86ISD::VPERMI:
3426     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3427   }
3428 }
3429
3430 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3431                                     SDValue V1, SDValue V2, unsigned TargetMask,
3432                                     SelectionDAG &DAG) {
3433   switch(Opc) {
3434   default: llvm_unreachable("Unknown x86 shuffle node");
3435   case X86ISD::PALIGNR:
3436   case X86ISD::SHUFP:
3437   case X86ISD::VPERM2X128:
3438     return DAG.getNode(Opc, dl, VT, V1, V2,
3439                        DAG.getConstant(TargetMask, MVT::i8));
3440   }
3441 }
3442
3443 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3444                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3445   switch(Opc) {
3446   default: llvm_unreachable("Unknown x86 shuffle node");
3447   case X86ISD::MOVLHPS:
3448   case X86ISD::MOVLHPD:
3449   case X86ISD::MOVHLPS:
3450   case X86ISD::MOVLPS:
3451   case X86ISD::MOVLPD:
3452   case X86ISD::MOVSS:
3453   case X86ISD::MOVSD:
3454   case X86ISD::UNPCKL:
3455   case X86ISD::UNPCKH:
3456     return DAG.getNode(Opc, dl, VT, V1, V2);
3457   }
3458 }
3459
3460 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3461   MachineFunction &MF = DAG.getMachineFunction();
3462   const X86RegisterInfo *RegInfo =
3463     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3464   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3465   int ReturnAddrIndex = FuncInfo->getRAIndex();
3466
3467   if (ReturnAddrIndex == 0) {
3468     // Set up a frame object for the return address.
3469     unsigned SlotSize = RegInfo->getSlotSize();
3470     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3471                                                            -(int64_t)SlotSize,
3472                                                            false);
3473     FuncInfo->setRAIndex(ReturnAddrIndex);
3474   }
3475
3476   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3477 }
3478
3479 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3480                                        bool hasSymbolicDisplacement) {
3481   // Offset should fit into 32 bit immediate field.
3482   if (!isInt<32>(Offset))
3483     return false;
3484
3485   // If we don't have a symbolic displacement - we don't have any extra
3486   // restrictions.
3487   if (!hasSymbolicDisplacement)
3488     return true;
3489
3490   // FIXME: Some tweaks might be needed for medium code model.
3491   if (M != CodeModel::Small && M != CodeModel::Kernel)
3492     return false;
3493
3494   // For small code model we assume that latest object is 16MB before end of 31
3495   // bits boundary. We may also accept pretty large negative constants knowing
3496   // that all objects are in the positive half of address space.
3497   if (M == CodeModel::Small && Offset < 16*1024*1024)
3498     return true;
3499
3500   // For kernel code model we know that all object resist in the negative half
3501   // of 32bits address space. We may not accept negative offsets, since they may
3502   // be just off and we may accept pretty large positive ones.
3503   if (M == CodeModel::Kernel && Offset > 0)
3504     return true;
3505
3506   return false;
3507 }
3508
3509 /// isCalleePop - Determines whether the callee is required to pop its
3510 /// own arguments. Callee pop is necessary to support tail calls.
3511 bool X86::isCalleePop(CallingConv::ID CallingConv,
3512                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3513   if (IsVarArg)
3514     return false;
3515
3516   switch (CallingConv) {
3517   default:
3518     return false;
3519   case CallingConv::X86_StdCall:
3520     return !is64Bit;
3521   case CallingConv::X86_FastCall:
3522     return !is64Bit;
3523   case CallingConv::X86_ThisCall:
3524     return !is64Bit;
3525   case CallingConv::Fast:
3526     return TailCallOpt;
3527   case CallingConv::GHC:
3528     return TailCallOpt;
3529   case CallingConv::HiPE:
3530     return TailCallOpt;
3531   }
3532 }
3533
3534 /// \brief Return true if the condition is an unsigned comparison operation.
3535 static bool isX86CCUnsigned(unsigned X86CC) {
3536   switch (X86CC) {
3537   default: llvm_unreachable("Invalid integer condition!");
3538   case X86::COND_E:     return true;
3539   case X86::COND_G:     return false;
3540   case X86::COND_GE:    return false;
3541   case X86::COND_L:     return false;
3542   case X86::COND_LE:    return false;
3543   case X86::COND_NE:    return true;
3544   case X86::COND_B:     return true;
3545   case X86::COND_A:     return true;
3546   case X86::COND_BE:    return true;
3547   case X86::COND_AE:    return true;
3548   }
3549   llvm_unreachable("covered switch fell through?!");
3550 }
3551
3552 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3553 /// specific condition code, returning the condition code and the LHS/RHS of the
3554 /// comparison to make.
3555 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3556                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3557   if (!isFP) {
3558     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3559       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3560         // X > -1   -> X == 0, jump !sign.
3561         RHS = DAG.getConstant(0, RHS.getValueType());
3562         return X86::COND_NS;
3563       }
3564       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3565         // X < 0   -> X == 0, jump on sign.
3566         return X86::COND_S;
3567       }
3568       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3569         // X < 1   -> X <= 0
3570         RHS = DAG.getConstant(0, RHS.getValueType());
3571         return X86::COND_LE;
3572       }
3573     }
3574
3575     switch (SetCCOpcode) {
3576     default: llvm_unreachable("Invalid integer condition!");
3577     case ISD::SETEQ:  return X86::COND_E;
3578     case ISD::SETGT:  return X86::COND_G;
3579     case ISD::SETGE:  return X86::COND_GE;
3580     case ISD::SETLT:  return X86::COND_L;
3581     case ISD::SETLE:  return X86::COND_LE;
3582     case ISD::SETNE:  return X86::COND_NE;
3583     case ISD::SETULT: return X86::COND_B;
3584     case ISD::SETUGT: return X86::COND_A;
3585     case ISD::SETULE: return X86::COND_BE;
3586     case ISD::SETUGE: return X86::COND_AE;
3587     }
3588   }
3589
3590   // First determine if it is required or is profitable to flip the operands.
3591
3592   // If LHS is a foldable load, but RHS is not, flip the condition.
3593   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3594       !ISD::isNON_EXTLoad(RHS.getNode())) {
3595     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3596     std::swap(LHS, RHS);
3597   }
3598
3599   switch (SetCCOpcode) {
3600   default: break;
3601   case ISD::SETOLT:
3602   case ISD::SETOLE:
3603   case ISD::SETUGT:
3604   case ISD::SETUGE:
3605     std::swap(LHS, RHS);
3606     break;
3607   }
3608
3609   // On a floating point condition, the flags are set as follows:
3610   // ZF  PF  CF   op
3611   //  0 | 0 | 0 | X > Y
3612   //  0 | 0 | 1 | X < Y
3613   //  1 | 0 | 0 | X == Y
3614   //  1 | 1 | 1 | unordered
3615   switch (SetCCOpcode) {
3616   default: llvm_unreachable("Condcode should be pre-legalized away");
3617   case ISD::SETUEQ:
3618   case ISD::SETEQ:   return X86::COND_E;
3619   case ISD::SETOLT:              // flipped
3620   case ISD::SETOGT:
3621   case ISD::SETGT:   return X86::COND_A;
3622   case ISD::SETOLE:              // flipped
3623   case ISD::SETOGE:
3624   case ISD::SETGE:   return X86::COND_AE;
3625   case ISD::SETUGT:              // flipped
3626   case ISD::SETULT:
3627   case ISD::SETLT:   return X86::COND_B;
3628   case ISD::SETUGE:              // flipped
3629   case ISD::SETULE:
3630   case ISD::SETLE:   return X86::COND_BE;
3631   case ISD::SETONE:
3632   case ISD::SETNE:   return X86::COND_NE;
3633   case ISD::SETUO:   return X86::COND_P;
3634   case ISD::SETO:    return X86::COND_NP;
3635   case ISD::SETOEQ:
3636   case ISD::SETUNE:  return X86::COND_INVALID;
3637   }
3638 }
3639
3640 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3641 /// code. Current x86 isa includes the following FP cmov instructions:
3642 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3643 static bool hasFPCMov(unsigned X86CC) {
3644   switch (X86CC) {
3645   default:
3646     return false;
3647   case X86::COND_B:
3648   case X86::COND_BE:
3649   case X86::COND_E:
3650   case X86::COND_P:
3651   case X86::COND_A:
3652   case X86::COND_AE:
3653   case X86::COND_NE:
3654   case X86::COND_NP:
3655     return true;
3656   }
3657 }
3658
3659 /// isFPImmLegal - Returns true if the target can instruction select the
3660 /// specified FP immediate natively. If false, the legalizer will
3661 /// materialize the FP immediate as a load from a constant pool.
3662 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3663   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3664     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3665       return true;
3666   }
3667   return false;
3668 }
3669
3670 /// \brief Returns true if it is beneficial to convert a load of a constant
3671 /// to just the constant itself.
3672 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3673                                                           Type *Ty) const {
3674   assert(Ty->isIntegerTy());
3675
3676   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3677   if (BitSize == 0 || BitSize > 64)
3678     return false;
3679   return true;
3680 }
3681
3682 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3683 /// the specified range (L, H].
3684 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3685   return (Val < 0) || (Val >= Low && Val < Hi);
3686 }
3687
3688 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3689 /// specified value.
3690 static bool isUndefOrEqual(int Val, int CmpVal) {
3691   return (Val < 0 || Val == CmpVal);
3692 }
3693
3694 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3695 /// from position Pos and ending in Pos+Size, falls within the specified
3696 /// sequential range (L, L+Pos]. or is undef.
3697 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3698                                        unsigned Pos, unsigned Size, int Low) {
3699   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3700     if (!isUndefOrEqual(Mask[i], Low))
3701       return false;
3702   return true;
3703 }
3704
3705 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3706 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3707 /// the second operand.
3708 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3709   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3710     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3711   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3712     return (Mask[0] < 2 && Mask[1] < 2);
3713   return false;
3714 }
3715
3716 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3717 /// is suitable for input to PSHUFHW.
3718 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3719   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3720     return false;
3721
3722   // Lower quadword copied in order or undef.
3723   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3724     return false;
3725
3726   // Upper quadword shuffled.
3727   for (unsigned i = 4; i != 8; ++i)
3728     if (!isUndefOrInRange(Mask[i], 4, 8))
3729       return false;
3730
3731   if (VT == MVT::v16i16) {
3732     // Lower quadword copied in order or undef.
3733     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3734       return false;
3735
3736     // Upper quadword shuffled.
3737     for (unsigned i = 12; i != 16; ++i)
3738       if (!isUndefOrInRange(Mask[i], 12, 16))
3739         return false;
3740   }
3741
3742   return true;
3743 }
3744
3745 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3746 /// is suitable for input to PSHUFLW.
3747 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3748   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3749     return false;
3750
3751   // Upper quadword copied in order.
3752   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3753     return false;
3754
3755   // Lower quadword shuffled.
3756   for (unsigned i = 0; i != 4; ++i)
3757     if (!isUndefOrInRange(Mask[i], 0, 4))
3758       return false;
3759
3760   if (VT == MVT::v16i16) {
3761     // Upper quadword copied in order.
3762     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3763       return false;
3764
3765     // Lower quadword shuffled.
3766     for (unsigned i = 8; i != 12; ++i)
3767       if (!isUndefOrInRange(Mask[i], 8, 12))
3768         return false;
3769   }
3770
3771   return true;
3772 }
3773
3774 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3775 /// is suitable for input to PALIGNR.
3776 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3777                           const X86Subtarget *Subtarget) {
3778   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3779       (VT.is256BitVector() && !Subtarget->hasInt256()))
3780     return false;
3781
3782   unsigned NumElts = VT.getVectorNumElements();
3783   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3784   unsigned NumLaneElts = NumElts/NumLanes;
3785
3786   // Do not handle 64-bit element shuffles with palignr.
3787   if (NumLaneElts == 2)
3788     return false;
3789
3790   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3791     unsigned i;
3792     for (i = 0; i != NumLaneElts; ++i) {
3793       if (Mask[i+l] >= 0)
3794         break;
3795     }
3796
3797     // Lane is all undef, go to next lane
3798     if (i == NumLaneElts)
3799       continue;
3800
3801     int Start = Mask[i+l];
3802
3803     // Make sure its in this lane in one of the sources
3804     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3805         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3806       return false;
3807
3808     // If not lane 0, then we must match lane 0
3809     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3810       return false;
3811
3812     // Correct second source to be contiguous with first source
3813     if (Start >= (int)NumElts)
3814       Start -= NumElts - NumLaneElts;
3815
3816     // Make sure we're shifting in the right direction.
3817     if (Start <= (int)(i+l))
3818       return false;
3819
3820     Start -= i;
3821
3822     // Check the rest of the elements to see if they are consecutive.
3823     for (++i; i != NumLaneElts; ++i) {
3824       int Idx = Mask[i+l];
3825
3826       // Make sure its in this lane
3827       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3828           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3829         return false;
3830
3831       // If not lane 0, then we must match lane 0
3832       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3833         return false;
3834
3835       if (Idx >= (int)NumElts)
3836         Idx -= NumElts - NumLaneElts;
3837
3838       if (!isUndefOrEqual(Idx, Start+i))
3839         return false;
3840
3841     }
3842   }
3843
3844   return true;
3845 }
3846
3847 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3848 /// the two vector operands have swapped position.
3849 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3850                                      unsigned NumElems) {
3851   for (unsigned i = 0; i != NumElems; ++i) {
3852     int idx = Mask[i];
3853     if (idx < 0)
3854       continue;
3855     else if (idx < (int)NumElems)
3856       Mask[i] = idx + NumElems;
3857     else
3858       Mask[i] = idx - NumElems;
3859   }
3860 }
3861
3862 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3863 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3864 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3865 /// reverse of what x86 shuffles want.
3866 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3867
3868   unsigned NumElems = VT.getVectorNumElements();
3869   unsigned NumLanes = VT.getSizeInBits()/128;
3870   unsigned NumLaneElems = NumElems/NumLanes;
3871
3872   if (NumLaneElems != 2 && NumLaneElems != 4)
3873     return false;
3874
3875   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3876   bool symetricMaskRequired =
3877     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3878
3879   // VSHUFPSY divides the resulting vector into 4 chunks.
3880   // The sources are also splitted into 4 chunks, and each destination
3881   // chunk must come from a different source chunk.
3882   //
3883   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3884   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3885   //
3886   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3887   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3888   //
3889   // VSHUFPDY divides the resulting vector into 4 chunks.
3890   // The sources are also splitted into 4 chunks, and each destination
3891   // chunk must come from a different source chunk.
3892   //
3893   //  SRC1 =>      X3       X2       X1       X0
3894   //  SRC2 =>      Y3       Y2       Y1       Y0
3895   //
3896   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3897   //
3898   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3899   unsigned HalfLaneElems = NumLaneElems/2;
3900   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3901     for (unsigned i = 0; i != NumLaneElems; ++i) {
3902       int Idx = Mask[i+l];
3903       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3904       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3905         return false;
3906       // For VSHUFPSY, the mask of the second half must be the same as the
3907       // first but with the appropriate offsets. This works in the same way as
3908       // VPERMILPS works with masks.
3909       if (!symetricMaskRequired || Idx < 0)
3910         continue;
3911       if (MaskVal[i] < 0) {
3912         MaskVal[i] = Idx - l;
3913         continue;
3914       }
3915       if ((signed)(Idx - l) != MaskVal[i])
3916         return false;
3917     }
3918   }
3919
3920   return true;
3921 }
3922
3923 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3924 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3925 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3926   if (!VT.is128BitVector())
3927     return false;
3928
3929   unsigned NumElems = VT.getVectorNumElements();
3930
3931   if (NumElems != 4)
3932     return false;
3933
3934   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3935   return isUndefOrEqual(Mask[0], 6) &&
3936          isUndefOrEqual(Mask[1], 7) &&
3937          isUndefOrEqual(Mask[2], 2) &&
3938          isUndefOrEqual(Mask[3], 3);
3939 }
3940
3941 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3942 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3943 /// <2, 3, 2, 3>
3944 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3945   if (!VT.is128BitVector())
3946     return false;
3947
3948   unsigned NumElems = VT.getVectorNumElements();
3949
3950   if (NumElems != 4)
3951     return false;
3952
3953   return isUndefOrEqual(Mask[0], 2) &&
3954          isUndefOrEqual(Mask[1], 3) &&
3955          isUndefOrEqual(Mask[2], 2) &&
3956          isUndefOrEqual(Mask[3], 3);
3957 }
3958
3959 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3960 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3961 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3962   if (!VT.is128BitVector())
3963     return false;
3964
3965   unsigned NumElems = VT.getVectorNumElements();
3966
3967   if (NumElems != 2 && NumElems != 4)
3968     return false;
3969
3970   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3971     if (!isUndefOrEqual(Mask[i], i + NumElems))
3972       return false;
3973
3974   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3975     if (!isUndefOrEqual(Mask[i], i))
3976       return false;
3977
3978   return true;
3979 }
3980
3981 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3982 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3983 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3984   if (!VT.is128BitVector())
3985     return false;
3986
3987   unsigned NumElems = VT.getVectorNumElements();
3988
3989   if (NumElems != 2 && NumElems != 4)
3990     return false;
3991
3992   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3993     if (!isUndefOrEqual(Mask[i], i))
3994       return false;
3995
3996   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3997     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3998       return false;
3999
4000   return true;
4001 }
4002
4003 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4004 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4005 /// i. e: If all but one element come from the same vector.
4006 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4007   // TODO: Deal with AVX's VINSERTPS
4008   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4009     return false;
4010
4011   unsigned CorrectPosV1 = 0;
4012   unsigned CorrectPosV2 = 0;
4013   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4014     if (Mask[i] == -1) {
4015       ++CorrectPosV1;
4016       ++CorrectPosV2;
4017       continue;
4018     }
4019
4020     if (Mask[i] == i)
4021       ++CorrectPosV1;
4022     else if (Mask[i] == i + 4)
4023       ++CorrectPosV2;
4024   }
4025
4026   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4027     // We have 3 elements (undefs count as elements from any vector) from one
4028     // vector, and one from another.
4029     return true;
4030
4031   return false;
4032 }
4033
4034 //
4035 // Some special combinations that can be optimized.
4036 //
4037 static
4038 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4039                                SelectionDAG &DAG) {
4040   MVT VT = SVOp->getSimpleValueType(0);
4041   SDLoc dl(SVOp);
4042
4043   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4044     return SDValue();
4045
4046   ArrayRef<int> Mask = SVOp->getMask();
4047
4048   // These are the special masks that may be optimized.
4049   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4050   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4051   bool MatchEvenMask = true;
4052   bool MatchOddMask  = true;
4053   for (int i=0; i<8; ++i) {
4054     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4055       MatchEvenMask = false;
4056     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4057       MatchOddMask = false;
4058   }
4059
4060   if (!MatchEvenMask && !MatchOddMask)
4061     return SDValue();
4062
4063   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4064
4065   SDValue Op0 = SVOp->getOperand(0);
4066   SDValue Op1 = SVOp->getOperand(1);
4067
4068   if (MatchEvenMask) {
4069     // Shift the second operand right to 32 bits.
4070     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4071     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4072   } else {
4073     // Shift the first operand left to 32 bits.
4074     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4075     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4076   }
4077   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4078   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4079 }
4080
4081 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4082 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4083 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4084                          bool HasInt256, bool V2IsSplat = false) {
4085
4086   assert(VT.getSizeInBits() >= 128 &&
4087          "Unsupported vector type for unpckl");
4088
4089   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4090   unsigned NumLanes;
4091   unsigned NumOf256BitLanes;
4092   unsigned NumElts = VT.getVectorNumElements();
4093   if (VT.is256BitVector()) {
4094     if (NumElts != 4 && NumElts != 8 &&
4095         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4096     return false;
4097     NumLanes = 2;
4098     NumOf256BitLanes = 1;
4099   } else if (VT.is512BitVector()) {
4100     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4101            "Unsupported vector type for unpckh");
4102     NumLanes = 2;
4103     NumOf256BitLanes = 2;
4104   } else {
4105     NumLanes = 1;
4106     NumOf256BitLanes = 1;
4107   }
4108
4109   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4110   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4111
4112   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4113     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4114       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4115         int BitI  = Mask[l256*NumEltsInStride+l+i];
4116         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4117         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4118           return false;
4119         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4120           return false;
4121         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4122           return false;
4123       }
4124     }
4125   }
4126   return true;
4127 }
4128
4129 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4130 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4131 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4132                          bool HasInt256, bool V2IsSplat = false) {
4133   assert(VT.getSizeInBits() >= 128 &&
4134          "Unsupported vector type for unpckh");
4135
4136   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4137   unsigned NumLanes;
4138   unsigned NumOf256BitLanes;
4139   unsigned NumElts = VT.getVectorNumElements();
4140   if (VT.is256BitVector()) {
4141     if (NumElts != 4 && NumElts != 8 &&
4142         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4143     return false;
4144     NumLanes = 2;
4145     NumOf256BitLanes = 1;
4146   } else if (VT.is512BitVector()) {
4147     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4148            "Unsupported vector type for unpckh");
4149     NumLanes = 2;
4150     NumOf256BitLanes = 2;
4151   } else {
4152     NumLanes = 1;
4153     NumOf256BitLanes = 1;
4154   }
4155
4156   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4157   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4158
4159   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4160     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4161       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4162         int BitI  = Mask[l256*NumEltsInStride+l+i];
4163         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4164         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4165           return false;
4166         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4167           return false;
4168         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4169           return false;
4170       }
4171     }
4172   }
4173   return true;
4174 }
4175
4176 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4177 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4178 /// <0, 0, 1, 1>
4179 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4180   unsigned NumElts = VT.getVectorNumElements();
4181   bool Is256BitVec = VT.is256BitVector();
4182
4183   if (VT.is512BitVector())
4184     return false;
4185   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4186          "Unsupported vector type for unpckh");
4187
4188   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4189       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4190     return false;
4191
4192   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4193   // FIXME: Need a better way to get rid of this, there's no latency difference
4194   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4195   // the former later. We should also remove the "_undef" special mask.
4196   if (NumElts == 4 && Is256BitVec)
4197     return false;
4198
4199   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4200   // independently on 128-bit lanes.
4201   unsigned NumLanes = VT.getSizeInBits()/128;
4202   unsigned NumLaneElts = NumElts/NumLanes;
4203
4204   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4205     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4206       int BitI  = Mask[l+i];
4207       int BitI1 = Mask[l+i+1];
4208
4209       if (!isUndefOrEqual(BitI, j))
4210         return false;
4211       if (!isUndefOrEqual(BitI1, j))
4212         return false;
4213     }
4214   }
4215
4216   return true;
4217 }
4218
4219 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4220 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4221 /// <2, 2, 3, 3>
4222 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4223   unsigned NumElts = VT.getVectorNumElements();
4224
4225   if (VT.is512BitVector())
4226     return false;
4227
4228   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4229          "Unsupported vector type for unpckh");
4230
4231   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4232       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4233     return false;
4234
4235   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4236   // independently on 128-bit lanes.
4237   unsigned NumLanes = VT.getSizeInBits()/128;
4238   unsigned NumLaneElts = NumElts/NumLanes;
4239
4240   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4241     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4242       int BitI  = Mask[l+i];
4243       int BitI1 = Mask[l+i+1];
4244       if (!isUndefOrEqual(BitI, j))
4245         return false;
4246       if (!isUndefOrEqual(BitI1, j))
4247         return false;
4248     }
4249   }
4250   return true;
4251 }
4252
4253 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4254 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4255 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4256   if (!VT.is512BitVector())
4257     return false;
4258
4259   unsigned NumElts = VT.getVectorNumElements();
4260   unsigned HalfSize = NumElts/2;
4261   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4262     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4263       *Imm = 1;
4264       return true;
4265     }
4266   }
4267   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4268     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4269       *Imm = 0;
4270       return true;
4271     }
4272   }
4273   return false;
4274 }
4275
4276 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4277 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4278 /// MOVSD, and MOVD, i.e. setting the lowest element.
4279 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4280   if (VT.getVectorElementType().getSizeInBits() < 32)
4281     return false;
4282   if (!VT.is128BitVector())
4283     return false;
4284
4285   unsigned NumElts = VT.getVectorNumElements();
4286
4287   if (!isUndefOrEqual(Mask[0], NumElts))
4288     return false;
4289
4290   for (unsigned i = 1; i != NumElts; ++i)
4291     if (!isUndefOrEqual(Mask[i], i))
4292       return false;
4293
4294   return true;
4295 }
4296
4297 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4298 /// as permutations between 128-bit chunks or halves. As an example: this
4299 /// shuffle bellow:
4300 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4301 /// The first half comes from the second half of V1 and the second half from the
4302 /// the second half of V2.
4303 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4304   if (!HasFp256 || !VT.is256BitVector())
4305     return false;
4306
4307   // The shuffle result is divided into half A and half B. In total the two
4308   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4309   // B must come from C, D, E or F.
4310   unsigned HalfSize = VT.getVectorNumElements()/2;
4311   bool MatchA = false, MatchB = false;
4312
4313   // Check if A comes from one of C, D, E, F.
4314   for (unsigned Half = 0; Half != 4; ++Half) {
4315     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4316       MatchA = true;
4317       break;
4318     }
4319   }
4320
4321   // Check if B comes from one of C, D, E, F.
4322   for (unsigned Half = 0; Half != 4; ++Half) {
4323     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4324       MatchB = true;
4325       break;
4326     }
4327   }
4328
4329   return MatchA && MatchB;
4330 }
4331
4332 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4333 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4334 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4335   MVT VT = SVOp->getSimpleValueType(0);
4336
4337   unsigned HalfSize = VT.getVectorNumElements()/2;
4338
4339   unsigned FstHalf = 0, SndHalf = 0;
4340   for (unsigned i = 0; i < HalfSize; ++i) {
4341     if (SVOp->getMaskElt(i) > 0) {
4342       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4343       break;
4344     }
4345   }
4346   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4347     if (SVOp->getMaskElt(i) > 0) {
4348       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4349       break;
4350     }
4351   }
4352
4353   return (FstHalf | (SndHalf << 4));
4354 }
4355
4356 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4357 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4358   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4359   if (EltSize < 32)
4360     return false;
4361
4362   unsigned NumElts = VT.getVectorNumElements();
4363   Imm8 = 0;
4364   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4365     for (unsigned i = 0; i != NumElts; ++i) {
4366       if (Mask[i] < 0)
4367         continue;
4368       Imm8 |= Mask[i] << (i*2);
4369     }
4370     return true;
4371   }
4372
4373   unsigned LaneSize = 4;
4374   SmallVector<int, 4> MaskVal(LaneSize, -1);
4375
4376   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4377     for (unsigned i = 0; i != LaneSize; ++i) {
4378       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4379         return false;
4380       if (Mask[i+l] < 0)
4381         continue;
4382       if (MaskVal[i] < 0) {
4383         MaskVal[i] = Mask[i+l] - l;
4384         Imm8 |= MaskVal[i] << (i*2);
4385         continue;
4386       }
4387       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4388         return false;
4389     }
4390   }
4391   return true;
4392 }
4393
4394 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4395 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4396 /// Note that VPERMIL mask matching is different depending whether theunderlying
4397 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4398 /// to the same elements of the low, but to the higher half of the source.
4399 /// In VPERMILPD the two lanes could be shuffled independently of each other
4400 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4401 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4402   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4403   if (VT.getSizeInBits() < 256 || EltSize < 32)
4404     return false;
4405   bool symetricMaskRequired = (EltSize == 32);
4406   unsigned NumElts = VT.getVectorNumElements();
4407
4408   unsigned NumLanes = VT.getSizeInBits()/128;
4409   unsigned LaneSize = NumElts/NumLanes;
4410   // 2 or 4 elements in one lane
4411
4412   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4413   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4414     for (unsigned i = 0; i != LaneSize; ++i) {
4415       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4416         return false;
4417       if (symetricMaskRequired) {
4418         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4419           ExpectedMaskVal[i] = Mask[i+l] - l;
4420           continue;
4421         }
4422         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4423           return false;
4424       }
4425     }
4426   }
4427   return true;
4428 }
4429
4430 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4431 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4432 /// element of vector 2 and the other elements to come from vector 1 in order.
4433 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4434                                bool V2IsSplat = false, bool V2IsUndef = false) {
4435   if (!VT.is128BitVector())
4436     return false;
4437
4438   unsigned NumOps = VT.getVectorNumElements();
4439   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4440     return false;
4441
4442   if (!isUndefOrEqual(Mask[0], 0))
4443     return false;
4444
4445   for (unsigned i = 1; i != NumOps; ++i)
4446     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4447           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4448           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4449       return false;
4450
4451   return true;
4452 }
4453
4454 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4455 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4456 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4457 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4458                            const X86Subtarget *Subtarget) {
4459   if (!Subtarget->hasSSE3())
4460     return false;
4461
4462   unsigned NumElems = VT.getVectorNumElements();
4463
4464   if ((VT.is128BitVector() && NumElems != 4) ||
4465       (VT.is256BitVector() && NumElems != 8) ||
4466       (VT.is512BitVector() && NumElems != 16))
4467     return false;
4468
4469   // "i+1" is the value the indexed mask element must have
4470   for (unsigned i = 0; i != NumElems; i += 2)
4471     if (!isUndefOrEqual(Mask[i], i+1) ||
4472         !isUndefOrEqual(Mask[i+1], i+1))
4473       return false;
4474
4475   return true;
4476 }
4477
4478 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4479 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4480 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4481 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4482                            const X86Subtarget *Subtarget) {
4483   if (!Subtarget->hasSSE3())
4484     return false;
4485
4486   unsigned NumElems = VT.getVectorNumElements();
4487
4488   if ((VT.is128BitVector() && NumElems != 4) ||
4489       (VT.is256BitVector() && NumElems != 8) ||
4490       (VT.is512BitVector() && NumElems != 16))
4491     return false;
4492
4493   // "i" is the value the indexed mask element must have
4494   for (unsigned i = 0; i != NumElems; i += 2)
4495     if (!isUndefOrEqual(Mask[i], i) ||
4496         !isUndefOrEqual(Mask[i+1], i))
4497       return false;
4498
4499   return true;
4500 }
4501
4502 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4503 /// specifies a shuffle of elements that is suitable for input to 256-bit
4504 /// version of MOVDDUP.
4505 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4506   if (!HasFp256 || !VT.is256BitVector())
4507     return false;
4508
4509   unsigned NumElts = VT.getVectorNumElements();
4510   if (NumElts != 4)
4511     return false;
4512
4513   for (unsigned i = 0; i != NumElts/2; ++i)
4514     if (!isUndefOrEqual(Mask[i], 0))
4515       return false;
4516   for (unsigned i = NumElts/2; i != NumElts; ++i)
4517     if (!isUndefOrEqual(Mask[i], NumElts/2))
4518       return false;
4519   return true;
4520 }
4521
4522 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4523 /// specifies a shuffle of elements that is suitable for input to 128-bit
4524 /// version of MOVDDUP.
4525 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4526   if (!VT.is128BitVector())
4527     return false;
4528
4529   unsigned e = VT.getVectorNumElements() / 2;
4530   for (unsigned i = 0; i != e; ++i)
4531     if (!isUndefOrEqual(Mask[i], i))
4532       return false;
4533   for (unsigned i = 0; i != e; ++i)
4534     if (!isUndefOrEqual(Mask[e+i], i))
4535       return false;
4536   return true;
4537 }
4538
4539 /// isVEXTRACTIndex - Return true if the specified
4540 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4541 /// suitable for instruction that extract 128 or 256 bit vectors
4542 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4543   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4544   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4545     return false;
4546
4547   // The index should be aligned on a vecWidth-bit boundary.
4548   uint64_t Index =
4549     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4550
4551   MVT VT = N->getSimpleValueType(0);
4552   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4553   bool Result = (Index * ElSize) % vecWidth == 0;
4554
4555   return Result;
4556 }
4557
4558 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4559 /// operand specifies a subvector insert that is suitable for input to
4560 /// insertion of 128 or 256-bit subvectors
4561 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4562   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4563   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4564     return false;
4565   // The index should be aligned on a vecWidth-bit boundary.
4566   uint64_t Index =
4567     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4568
4569   MVT VT = N->getSimpleValueType(0);
4570   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4571   bool Result = (Index * ElSize) % vecWidth == 0;
4572
4573   return Result;
4574 }
4575
4576 bool X86::isVINSERT128Index(SDNode *N) {
4577   return isVINSERTIndex(N, 128);
4578 }
4579
4580 bool X86::isVINSERT256Index(SDNode *N) {
4581   return isVINSERTIndex(N, 256);
4582 }
4583
4584 bool X86::isVEXTRACT128Index(SDNode *N) {
4585   return isVEXTRACTIndex(N, 128);
4586 }
4587
4588 bool X86::isVEXTRACT256Index(SDNode *N) {
4589   return isVEXTRACTIndex(N, 256);
4590 }
4591
4592 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4593 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4594 /// Handles 128-bit and 256-bit.
4595 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4596   MVT VT = N->getSimpleValueType(0);
4597
4598   assert((VT.getSizeInBits() >= 128) &&
4599          "Unsupported vector type for PSHUF/SHUFP");
4600
4601   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4602   // independently on 128-bit lanes.
4603   unsigned NumElts = VT.getVectorNumElements();
4604   unsigned NumLanes = VT.getSizeInBits()/128;
4605   unsigned NumLaneElts = NumElts/NumLanes;
4606
4607   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4608          "Only supports 2, 4 or 8 elements per lane");
4609
4610   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4611   unsigned Mask = 0;
4612   for (unsigned i = 0; i != NumElts; ++i) {
4613     int Elt = N->getMaskElt(i);
4614     if (Elt < 0) continue;
4615     Elt &= NumLaneElts - 1;
4616     unsigned ShAmt = (i << Shift) % 8;
4617     Mask |= Elt << ShAmt;
4618   }
4619
4620   return Mask;
4621 }
4622
4623 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4624 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4625 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4626   MVT VT = N->getSimpleValueType(0);
4627
4628   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4629          "Unsupported vector type for PSHUFHW");
4630
4631   unsigned NumElts = VT.getVectorNumElements();
4632
4633   unsigned Mask = 0;
4634   for (unsigned l = 0; l != NumElts; l += 8) {
4635     // 8 nodes per lane, but we only care about the last 4.
4636     for (unsigned i = 0; i < 4; ++i) {
4637       int Elt = N->getMaskElt(l+i+4);
4638       if (Elt < 0) continue;
4639       Elt &= 0x3; // only 2-bits.
4640       Mask |= Elt << (i * 2);
4641     }
4642   }
4643
4644   return Mask;
4645 }
4646
4647 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4648 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4649 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4650   MVT VT = N->getSimpleValueType(0);
4651
4652   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4653          "Unsupported vector type for PSHUFHW");
4654
4655   unsigned NumElts = VT.getVectorNumElements();
4656
4657   unsigned Mask = 0;
4658   for (unsigned l = 0; l != NumElts; l += 8) {
4659     // 8 nodes per lane, but we only care about the first 4.
4660     for (unsigned i = 0; i < 4; ++i) {
4661       int Elt = N->getMaskElt(l+i);
4662       if (Elt < 0) continue;
4663       Elt &= 0x3; // only 2-bits
4664       Mask |= Elt << (i * 2);
4665     }
4666   }
4667
4668   return Mask;
4669 }
4670
4671 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4672 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4673 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4674   MVT VT = SVOp->getSimpleValueType(0);
4675   unsigned EltSize = VT.is512BitVector() ? 1 :
4676     VT.getVectorElementType().getSizeInBits() >> 3;
4677
4678   unsigned NumElts = VT.getVectorNumElements();
4679   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4680   unsigned NumLaneElts = NumElts/NumLanes;
4681
4682   int Val = 0;
4683   unsigned i;
4684   for (i = 0; i != NumElts; ++i) {
4685     Val = SVOp->getMaskElt(i);
4686     if (Val >= 0)
4687       break;
4688   }
4689   if (Val >= (int)NumElts)
4690     Val -= NumElts - NumLaneElts;
4691
4692   assert(Val - i > 0 && "PALIGNR imm should be positive");
4693   return (Val - i) * EltSize;
4694 }
4695
4696 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4697   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4698   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4699     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4700
4701   uint64_t Index =
4702     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4703
4704   MVT VecVT = N->getOperand(0).getSimpleValueType();
4705   MVT ElVT = VecVT.getVectorElementType();
4706
4707   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4708   return Index / NumElemsPerChunk;
4709 }
4710
4711 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4712   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4713   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4714     llvm_unreachable("Illegal insert subvector for VINSERT");
4715
4716   uint64_t Index =
4717     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4718
4719   MVT VecVT = N->getSimpleValueType(0);
4720   MVT ElVT = VecVT.getVectorElementType();
4721
4722   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4723   return Index / NumElemsPerChunk;
4724 }
4725
4726 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4727 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4728 /// and VINSERTI128 instructions.
4729 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4730   return getExtractVEXTRACTImmediate(N, 128);
4731 }
4732
4733 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4734 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4735 /// and VINSERTI64x4 instructions.
4736 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4737   return getExtractVEXTRACTImmediate(N, 256);
4738 }
4739
4740 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4741 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4742 /// and VINSERTI128 instructions.
4743 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4744   return getInsertVINSERTImmediate(N, 128);
4745 }
4746
4747 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4748 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4749 /// and VINSERTI64x4 instructions.
4750 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4751   return getInsertVINSERTImmediate(N, 256);
4752 }
4753
4754 /// isZero - Returns true if Elt is a constant integer zero
4755 static bool isZero(SDValue V) {
4756   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4757   return C && C->isNullValue();
4758 }
4759
4760 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4761 /// constant +0.0.
4762 bool X86::isZeroNode(SDValue Elt) {
4763   if (isZero(Elt))
4764     return true;
4765   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4766     return CFP->getValueAPF().isPosZero();
4767   return false;
4768 }
4769
4770 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4771 /// match movhlps. The lower half elements should come from upper half of
4772 /// V1 (and in order), and the upper half elements should come from the upper
4773 /// half of V2 (and in order).
4774 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4775   if (!VT.is128BitVector())
4776     return false;
4777   if (VT.getVectorNumElements() != 4)
4778     return false;
4779   for (unsigned i = 0, e = 2; i != e; ++i)
4780     if (!isUndefOrEqual(Mask[i], i+2))
4781       return false;
4782   for (unsigned i = 2; i != 4; ++i)
4783     if (!isUndefOrEqual(Mask[i], i+4))
4784       return false;
4785   return true;
4786 }
4787
4788 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4789 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4790 /// required.
4791 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4792   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4793     return false;
4794   N = N->getOperand(0).getNode();
4795   if (!ISD::isNON_EXTLoad(N))
4796     return false;
4797   if (LD)
4798     *LD = cast<LoadSDNode>(N);
4799   return true;
4800 }
4801
4802 // Test whether the given value is a vector value which will be legalized
4803 // into a load.
4804 static bool WillBeConstantPoolLoad(SDNode *N) {
4805   if (N->getOpcode() != ISD::BUILD_VECTOR)
4806     return false;
4807
4808   // Check for any non-constant elements.
4809   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4810     switch (N->getOperand(i).getNode()->getOpcode()) {
4811     case ISD::UNDEF:
4812     case ISD::ConstantFP:
4813     case ISD::Constant:
4814       break;
4815     default:
4816       return false;
4817     }
4818
4819   // Vectors of all-zeros and all-ones are materialized with special
4820   // instructions rather than being loaded.
4821   return !ISD::isBuildVectorAllZeros(N) &&
4822          !ISD::isBuildVectorAllOnes(N);
4823 }
4824
4825 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4826 /// match movlp{s|d}. The lower half elements should come from lower half of
4827 /// V1 (and in order), and the upper half elements should come from the upper
4828 /// half of V2 (and in order). And since V1 will become the source of the
4829 /// MOVLP, it must be either a vector load or a scalar load to vector.
4830 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4831                                ArrayRef<int> Mask, MVT VT) {
4832   if (!VT.is128BitVector())
4833     return false;
4834
4835   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4836     return false;
4837   // Is V2 is a vector load, don't do this transformation. We will try to use
4838   // load folding shufps op.
4839   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4840     return false;
4841
4842   unsigned NumElems = VT.getVectorNumElements();
4843
4844   if (NumElems != 2 && NumElems != 4)
4845     return false;
4846   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4847     if (!isUndefOrEqual(Mask[i], i))
4848       return false;
4849   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4850     if (!isUndefOrEqual(Mask[i], i+NumElems))
4851       return false;
4852   return true;
4853 }
4854
4855 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4856 /// to an zero vector.
4857 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4858 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4859   SDValue V1 = N->getOperand(0);
4860   SDValue V2 = N->getOperand(1);
4861   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4862   for (unsigned i = 0; i != NumElems; ++i) {
4863     int Idx = N->getMaskElt(i);
4864     if (Idx >= (int)NumElems) {
4865       unsigned Opc = V2.getOpcode();
4866       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4867         continue;
4868       if (Opc != ISD::BUILD_VECTOR ||
4869           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4870         return false;
4871     } else if (Idx >= 0) {
4872       unsigned Opc = V1.getOpcode();
4873       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4874         continue;
4875       if (Opc != ISD::BUILD_VECTOR ||
4876           !X86::isZeroNode(V1.getOperand(Idx)))
4877         return false;
4878     }
4879   }
4880   return true;
4881 }
4882
4883 /// getZeroVector - Returns a vector of specified type with all zero elements.
4884 ///
4885 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4886                              SelectionDAG &DAG, SDLoc dl) {
4887   assert(VT.isVector() && "Expected a vector type");
4888
4889   // Always build SSE zero vectors as <4 x i32> bitcasted
4890   // to their dest type. This ensures they get CSE'd.
4891   SDValue Vec;
4892   if (VT.is128BitVector()) {  // SSE
4893     if (Subtarget->hasSSE2()) {  // SSE2
4894       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4895       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4896     } else { // SSE1
4897       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4898       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4899     }
4900   } else if (VT.is256BitVector()) { // AVX
4901     if (Subtarget->hasInt256()) { // AVX2
4902       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4903       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4904       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4905     } else {
4906       // 256-bit logic and arithmetic instructions in AVX are all
4907       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4908       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4909       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4910       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4911     }
4912   } else if (VT.is512BitVector()) { // AVX-512
4913       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4914       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4915                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4916       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4917   } else if (VT.getScalarType() == MVT::i1) {
4918     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4919     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4920     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4921     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4922   } else
4923     llvm_unreachable("Unexpected vector type");
4924
4925   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4926 }
4927
4928 /// getOnesVector - Returns a vector of specified type with all bits set.
4929 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4930 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4931 /// Then bitcast to their original type, ensuring they get CSE'd.
4932 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4933                              SDLoc dl) {
4934   assert(VT.isVector() && "Expected a vector type");
4935
4936   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4937   SDValue Vec;
4938   if (VT.is256BitVector()) {
4939     if (HasInt256) { // AVX2
4940       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4941       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4942     } else { // AVX
4943       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4944       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4945     }
4946   } else if (VT.is128BitVector()) {
4947     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4948   } else
4949     llvm_unreachable("Unexpected vector type");
4950
4951   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4952 }
4953
4954 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4955 /// that point to V2 points to its first element.
4956 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4957   for (unsigned i = 0; i != NumElems; ++i) {
4958     if (Mask[i] > (int)NumElems) {
4959       Mask[i] = NumElems;
4960     }
4961   }
4962 }
4963
4964 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4965 /// operation of specified width.
4966 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4967                        SDValue V2) {
4968   unsigned NumElems = VT.getVectorNumElements();
4969   SmallVector<int, 8> Mask;
4970   Mask.push_back(NumElems);
4971   for (unsigned i = 1; i != NumElems; ++i)
4972     Mask.push_back(i);
4973   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4974 }
4975
4976 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4977 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4978                           SDValue V2) {
4979   unsigned NumElems = VT.getVectorNumElements();
4980   SmallVector<int, 8> Mask;
4981   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4982     Mask.push_back(i);
4983     Mask.push_back(i + NumElems);
4984   }
4985   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4986 }
4987
4988 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4989 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4990                           SDValue V2) {
4991   unsigned NumElems = VT.getVectorNumElements();
4992   SmallVector<int, 8> Mask;
4993   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4994     Mask.push_back(i + Half);
4995     Mask.push_back(i + NumElems + Half);
4996   }
4997   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4998 }
4999
5000 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5001 // a generic shuffle instruction because the target has no such instructions.
5002 // Generate shuffles which repeat i16 and i8 several times until they can be
5003 // represented by v4f32 and then be manipulated by target suported shuffles.
5004 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5005   MVT VT = V.getSimpleValueType();
5006   int NumElems = VT.getVectorNumElements();
5007   SDLoc dl(V);
5008
5009   while (NumElems > 4) {
5010     if (EltNo < NumElems/2) {
5011       V = getUnpackl(DAG, dl, VT, V, V);
5012     } else {
5013       V = getUnpackh(DAG, dl, VT, V, V);
5014       EltNo -= NumElems/2;
5015     }
5016     NumElems >>= 1;
5017   }
5018   return V;
5019 }
5020
5021 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5022 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5023   MVT VT = V.getSimpleValueType();
5024   SDLoc dl(V);
5025
5026   if (VT.is128BitVector()) {
5027     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5028     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5029     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5030                              &SplatMask[0]);
5031   } else if (VT.is256BitVector()) {
5032     // To use VPERMILPS to splat scalars, the second half of indicies must
5033     // refer to the higher part, which is a duplication of the lower one,
5034     // because VPERMILPS can only handle in-lane permutations.
5035     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5036                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5037
5038     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5039     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5040                              &SplatMask[0]);
5041   } else
5042     llvm_unreachable("Vector size not supported");
5043
5044   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5045 }
5046
5047 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5048 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5049   MVT SrcVT = SV->getSimpleValueType(0);
5050   SDValue V1 = SV->getOperand(0);
5051   SDLoc dl(SV);
5052
5053   int EltNo = SV->getSplatIndex();
5054   int NumElems = SrcVT.getVectorNumElements();
5055   bool Is256BitVec = SrcVT.is256BitVector();
5056
5057   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5058          "Unknown how to promote splat for type");
5059
5060   // Extract the 128-bit part containing the splat element and update
5061   // the splat element index when it refers to the higher register.
5062   if (Is256BitVec) {
5063     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5064     if (EltNo >= NumElems/2)
5065       EltNo -= NumElems/2;
5066   }
5067
5068   // All i16 and i8 vector types can't be used directly by a generic shuffle
5069   // instruction because the target has no such instruction. Generate shuffles
5070   // which repeat i16 and i8 several times until they fit in i32, and then can
5071   // be manipulated by target suported shuffles.
5072   MVT EltVT = SrcVT.getVectorElementType();
5073   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5074     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5075
5076   // Recreate the 256-bit vector and place the same 128-bit vector
5077   // into the low and high part. This is necessary because we want
5078   // to use VPERM* to shuffle the vectors
5079   if (Is256BitVec) {
5080     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5081   }
5082
5083   return getLegalSplat(DAG, V1, EltNo);
5084 }
5085
5086 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5087 /// vector of zero or undef vector.  This produces a shuffle where the low
5088 /// element of V2 is swizzled into the zero/undef vector, landing at element
5089 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5090 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5091                                            bool IsZero,
5092                                            const X86Subtarget *Subtarget,
5093                                            SelectionDAG &DAG) {
5094   MVT VT = V2.getSimpleValueType();
5095   SDValue V1 = IsZero
5096     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5097   unsigned NumElems = VT.getVectorNumElements();
5098   SmallVector<int, 16> MaskVec;
5099   for (unsigned i = 0; i != NumElems; ++i)
5100     // If this is the insertion idx, put the low elt of V2 here.
5101     MaskVec.push_back(i == Idx ? NumElems : i);
5102   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5103 }
5104
5105 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5106 /// target specific opcode. Returns true if the Mask could be calculated.
5107 /// Sets IsUnary to true if only uses one source.
5108 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5109                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5110   unsigned NumElems = VT.getVectorNumElements();
5111   SDValue ImmN;
5112
5113   IsUnary = false;
5114   switch(N->getOpcode()) {
5115   case X86ISD::SHUFP:
5116     ImmN = N->getOperand(N->getNumOperands()-1);
5117     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5118     break;
5119   case X86ISD::UNPCKH:
5120     DecodeUNPCKHMask(VT, Mask);
5121     break;
5122   case X86ISD::UNPCKL:
5123     DecodeUNPCKLMask(VT, Mask);
5124     break;
5125   case X86ISD::MOVHLPS:
5126     DecodeMOVHLPSMask(NumElems, Mask);
5127     break;
5128   case X86ISD::MOVLHPS:
5129     DecodeMOVLHPSMask(NumElems, Mask);
5130     break;
5131   case X86ISD::PALIGNR:
5132     ImmN = N->getOperand(N->getNumOperands()-1);
5133     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5134     break;
5135   case X86ISD::PSHUFD:
5136   case X86ISD::VPERMILP:
5137     ImmN = N->getOperand(N->getNumOperands()-1);
5138     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5139     IsUnary = true;
5140     break;
5141   case X86ISD::PSHUFHW:
5142     ImmN = N->getOperand(N->getNumOperands()-1);
5143     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5144     IsUnary = true;
5145     break;
5146   case X86ISD::PSHUFLW:
5147     ImmN = N->getOperand(N->getNumOperands()-1);
5148     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5149     IsUnary = true;
5150     break;
5151   case X86ISD::VPERMI:
5152     ImmN = N->getOperand(N->getNumOperands()-1);
5153     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154     IsUnary = true;
5155     break;
5156   case X86ISD::MOVSS:
5157   case X86ISD::MOVSD: {
5158     // The index 0 always comes from the first element of the second source,
5159     // this is why MOVSS and MOVSD are used in the first place. The other
5160     // elements come from the other positions of the first source vector
5161     Mask.push_back(NumElems);
5162     for (unsigned i = 1; i != NumElems; ++i) {
5163       Mask.push_back(i);
5164     }
5165     break;
5166   }
5167   case X86ISD::VPERM2X128:
5168     ImmN = N->getOperand(N->getNumOperands()-1);
5169     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5170     if (Mask.empty()) return false;
5171     break;
5172   case X86ISD::MOVDDUP:
5173   case X86ISD::MOVLHPD:
5174   case X86ISD::MOVLPD:
5175   case X86ISD::MOVLPS:
5176   case X86ISD::MOVSHDUP:
5177   case X86ISD::MOVSLDUP:
5178     // Not yet implemented
5179     return false;
5180   default: llvm_unreachable("unknown target shuffle node");
5181   }
5182
5183   return true;
5184 }
5185
5186 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5187 /// element of the result of the vector shuffle.
5188 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5189                                    unsigned Depth) {
5190   if (Depth == 6)
5191     return SDValue();  // Limit search depth.
5192
5193   SDValue V = SDValue(N, 0);
5194   EVT VT = V.getValueType();
5195   unsigned Opcode = V.getOpcode();
5196
5197   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5198   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5199     int Elt = SV->getMaskElt(Index);
5200
5201     if (Elt < 0)
5202       return DAG.getUNDEF(VT.getVectorElementType());
5203
5204     unsigned NumElems = VT.getVectorNumElements();
5205     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5206                                          : SV->getOperand(1);
5207     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5208   }
5209
5210   // Recurse into target specific vector shuffles to find scalars.
5211   if (isTargetShuffle(Opcode)) {
5212     MVT ShufVT = V.getSimpleValueType();
5213     unsigned NumElems = ShufVT.getVectorNumElements();
5214     SmallVector<int, 16> ShuffleMask;
5215     bool IsUnary;
5216
5217     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5218       return SDValue();
5219
5220     int Elt = ShuffleMask[Index];
5221     if (Elt < 0)
5222       return DAG.getUNDEF(ShufVT.getVectorElementType());
5223
5224     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5225                                          : N->getOperand(1);
5226     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5227                                Depth+1);
5228   }
5229
5230   // Actual nodes that may contain scalar elements
5231   if (Opcode == ISD::BITCAST) {
5232     V = V.getOperand(0);
5233     EVT SrcVT = V.getValueType();
5234     unsigned NumElems = VT.getVectorNumElements();
5235
5236     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5237       return SDValue();
5238   }
5239
5240   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5241     return (Index == 0) ? V.getOperand(0)
5242                         : DAG.getUNDEF(VT.getVectorElementType());
5243
5244   if (V.getOpcode() == ISD::BUILD_VECTOR)
5245     return V.getOperand(Index);
5246
5247   return SDValue();
5248 }
5249
5250 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5251 /// shuffle operation which come from a consecutively from a zero. The
5252 /// search can start in two different directions, from left or right.
5253 /// We count undefs as zeros until PreferredNum is reached.
5254 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5255                                          unsigned NumElems, bool ZerosFromLeft,
5256                                          SelectionDAG &DAG,
5257                                          unsigned PreferredNum = -1U) {
5258   unsigned NumZeros = 0;
5259   for (unsigned i = 0; i != NumElems; ++i) {
5260     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5261     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5262     if (!Elt.getNode())
5263       break;
5264
5265     if (X86::isZeroNode(Elt))
5266       ++NumZeros;
5267     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5268       NumZeros = std::min(NumZeros + 1, PreferredNum);
5269     else
5270       break;
5271   }
5272
5273   return NumZeros;
5274 }
5275
5276 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5277 /// correspond consecutively to elements from one of the vector operands,
5278 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5279 static
5280 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5281                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5282                               unsigned NumElems, unsigned &OpNum) {
5283   bool SeenV1 = false;
5284   bool SeenV2 = false;
5285
5286   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5287     int Idx = SVOp->getMaskElt(i);
5288     // Ignore undef indicies
5289     if (Idx < 0)
5290       continue;
5291
5292     if (Idx < (int)NumElems)
5293       SeenV1 = true;
5294     else
5295       SeenV2 = true;
5296
5297     // Only accept consecutive elements from the same vector
5298     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5299       return false;
5300   }
5301
5302   OpNum = SeenV1 ? 0 : 1;
5303   return true;
5304 }
5305
5306 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5307 /// logical left shift of a vector.
5308 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5309                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5310   unsigned NumElems =
5311     SVOp->getSimpleValueType(0).getVectorNumElements();
5312   unsigned NumZeros = getNumOfConsecutiveZeros(
5313       SVOp, NumElems, false /* check zeros from right */, DAG,
5314       SVOp->getMaskElt(0));
5315   unsigned OpSrc;
5316
5317   if (!NumZeros)
5318     return false;
5319
5320   // Considering the elements in the mask that are not consecutive zeros,
5321   // check if they consecutively come from only one of the source vectors.
5322   //
5323   //               V1 = {X, A, B, C}     0
5324   //                         \  \  \    /
5325   //   vector_shuffle V1, V2 <1, 2, 3, X>
5326   //
5327   if (!isShuffleMaskConsecutive(SVOp,
5328             0,                   // Mask Start Index
5329             NumElems-NumZeros,   // Mask End Index(exclusive)
5330             NumZeros,            // Where to start looking in the src vector
5331             NumElems,            // Number of elements in vector
5332             OpSrc))              // Which source operand ?
5333     return false;
5334
5335   isLeft = false;
5336   ShAmt = NumZeros;
5337   ShVal = SVOp->getOperand(OpSrc);
5338   return true;
5339 }
5340
5341 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5342 /// logical left shift of a vector.
5343 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5344                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5345   unsigned NumElems =
5346     SVOp->getSimpleValueType(0).getVectorNumElements();
5347   unsigned NumZeros = getNumOfConsecutiveZeros(
5348       SVOp, NumElems, true /* check zeros from left */, DAG,
5349       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5350   unsigned OpSrc;
5351
5352   if (!NumZeros)
5353     return false;
5354
5355   // Considering the elements in the mask that are not consecutive zeros,
5356   // check if they consecutively come from only one of the source vectors.
5357   //
5358   //                           0    { A, B, X, X } = V2
5359   //                          / \    /  /
5360   //   vector_shuffle V1, V2 <X, X, 4, 5>
5361   //
5362   if (!isShuffleMaskConsecutive(SVOp,
5363             NumZeros,     // Mask Start Index
5364             NumElems,     // Mask End Index(exclusive)
5365             0,            // Where to start looking in the src vector
5366             NumElems,     // Number of elements in vector
5367             OpSrc))       // Which source operand ?
5368     return false;
5369
5370   isLeft = true;
5371   ShAmt = NumZeros;
5372   ShVal = SVOp->getOperand(OpSrc);
5373   return true;
5374 }
5375
5376 /// isVectorShift - Returns true if the shuffle can be implemented as a
5377 /// logical left or right shift of a vector.
5378 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5379                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5380   // Although the logic below support any bitwidth size, there are no
5381   // shift instructions which handle more than 128-bit vectors.
5382   if (!SVOp->getSimpleValueType(0).is128BitVector())
5383     return false;
5384
5385   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5386       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5387     return true;
5388
5389   return false;
5390 }
5391
5392 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5393 ///
5394 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5395                                        unsigned NumNonZero, unsigned NumZero,
5396                                        SelectionDAG &DAG,
5397                                        const X86Subtarget* Subtarget,
5398                                        const TargetLowering &TLI) {
5399   if (NumNonZero > 8)
5400     return SDValue();
5401
5402   SDLoc dl(Op);
5403   SDValue V;
5404   bool First = true;
5405   for (unsigned i = 0; i < 16; ++i) {
5406     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5407     if (ThisIsNonZero && First) {
5408       if (NumZero)
5409         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5410       else
5411         V = DAG.getUNDEF(MVT::v8i16);
5412       First = false;
5413     }
5414
5415     if ((i & 1) != 0) {
5416       SDValue ThisElt, LastElt;
5417       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5418       if (LastIsNonZero) {
5419         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5420                               MVT::i16, Op.getOperand(i-1));
5421       }
5422       if (ThisIsNonZero) {
5423         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5424         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5425                               ThisElt, DAG.getConstant(8, MVT::i8));
5426         if (LastIsNonZero)
5427           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5428       } else
5429         ThisElt = LastElt;
5430
5431       if (ThisElt.getNode())
5432         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5433                         DAG.getIntPtrConstant(i/2));
5434     }
5435   }
5436
5437   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5438 }
5439
5440 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5441 ///
5442 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5443                                      unsigned NumNonZero, unsigned NumZero,
5444                                      SelectionDAG &DAG,
5445                                      const X86Subtarget* Subtarget,
5446                                      const TargetLowering &TLI) {
5447   if (NumNonZero > 4)
5448     return SDValue();
5449
5450   SDLoc dl(Op);
5451   SDValue V;
5452   bool First = true;
5453   for (unsigned i = 0; i < 8; ++i) {
5454     bool isNonZero = (NonZeros & (1 << i)) != 0;
5455     if (isNonZero) {
5456       if (First) {
5457         if (NumZero)
5458           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5459         else
5460           V = DAG.getUNDEF(MVT::v8i16);
5461         First = false;
5462       }
5463       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5464                       MVT::v8i16, V, Op.getOperand(i),
5465                       DAG.getIntPtrConstant(i));
5466     }
5467   }
5468
5469   return V;
5470 }
5471
5472 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5473 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5474                                      unsigned NonZeros, unsigned NumNonZero,
5475                                      unsigned NumZero, SelectionDAG &DAG,
5476                                      const X86Subtarget *Subtarget,
5477                                      const TargetLowering &TLI) {
5478   // We know there's at least one non-zero element
5479   unsigned FirstNonZeroIdx = 0;
5480   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5481   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5482          X86::isZeroNode(FirstNonZero)) {
5483     ++FirstNonZeroIdx;
5484     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5485   }
5486
5487   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5488       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5489     return SDValue();
5490
5491   SDValue V = FirstNonZero.getOperand(0);
5492   MVT VVT = V.getSimpleValueType();
5493   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5494     return SDValue();
5495
5496   unsigned FirstNonZeroDst =
5497       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5498   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5499   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5500   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5501
5502   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5503     SDValue Elem = Op.getOperand(Idx);
5504     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5505       continue;
5506
5507     // TODO: What else can be here? Deal with it.
5508     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5509       return SDValue();
5510
5511     // TODO: Some optimizations are still possible here
5512     // ex: Getting one element from a vector, and the rest from another.
5513     if (Elem.getOperand(0) != V)
5514       return SDValue();
5515
5516     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5517     if (Dst == Idx)
5518       ++CorrectIdx;
5519     else if (IncorrectIdx == -1U) {
5520       IncorrectIdx = Idx;
5521       IncorrectDst = Dst;
5522     } else
5523       // There was already one element with an incorrect index.
5524       // We can't optimize this case to an insertps.
5525       return SDValue();
5526   }
5527
5528   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5529     SDLoc dl(Op);
5530     EVT VT = Op.getSimpleValueType();
5531     unsigned ElementMoveMask = 0;
5532     if (IncorrectIdx == -1U)
5533       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5534     else
5535       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5536
5537     SDValue InsertpsMask =
5538         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5539     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5540   }
5541
5542   return SDValue();
5543 }
5544
5545 /// getVShift - Return a vector logical shift node.
5546 ///
5547 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5548                          unsigned NumBits, SelectionDAG &DAG,
5549                          const TargetLowering &TLI, SDLoc dl) {
5550   assert(VT.is128BitVector() && "Unknown type for VShift");
5551   EVT ShVT = MVT::v2i64;
5552   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5553   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5554   return DAG.getNode(ISD::BITCAST, dl, VT,
5555                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5556                              DAG.getConstant(NumBits,
5557                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5558 }
5559
5560 static SDValue
5561 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5562
5563   // Check if the scalar load can be widened into a vector load. And if
5564   // the address is "base + cst" see if the cst can be "absorbed" into
5565   // the shuffle mask.
5566   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5567     SDValue Ptr = LD->getBasePtr();
5568     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5569       return SDValue();
5570     EVT PVT = LD->getValueType(0);
5571     if (PVT != MVT::i32 && PVT != MVT::f32)
5572       return SDValue();
5573
5574     int FI = -1;
5575     int64_t Offset = 0;
5576     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5577       FI = FINode->getIndex();
5578       Offset = 0;
5579     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5580                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5581       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5582       Offset = Ptr.getConstantOperandVal(1);
5583       Ptr = Ptr.getOperand(0);
5584     } else {
5585       return SDValue();
5586     }
5587
5588     // FIXME: 256-bit vector instructions don't require a strict alignment,
5589     // improve this code to support it better.
5590     unsigned RequiredAlign = VT.getSizeInBits()/8;
5591     SDValue Chain = LD->getChain();
5592     // Make sure the stack object alignment is at least 16 or 32.
5593     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5594     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5595       if (MFI->isFixedObjectIndex(FI)) {
5596         // Can't change the alignment. FIXME: It's possible to compute
5597         // the exact stack offset and reference FI + adjust offset instead.
5598         // If someone *really* cares about this. That's the way to implement it.
5599         return SDValue();
5600       } else {
5601         MFI->setObjectAlignment(FI, RequiredAlign);
5602       }
5603     }
5604
5605     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5606     // Ptr + (Offset & ~15).
5607     if (Offset < 0)
5608       return SDValue();
5609     if ((Offset % RequiredAlign) & 3)
5610       return SDValue();
5611     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5612     if (StartOffset)
5613       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5614                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5615
5616     int EltNo = (Offset - StartOffset) >> 2;
5617     unsigned NumElems = VT.getVectorNumElements();
5618
5619     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5620     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5621                              LD->getPointerInfo().getWithOffset(StartOffset),
5622                              false, false, false, 0);
5623
5624     SmallVector<int, 8> Mask;
5625     for (unsigned i = 0; i != NumElems; ++i)
5626       Mask.push_back(EltNo);
5627
5628     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5629   }
5630
5631   return SDValue();
5632 }
5633
5634 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5635 /// vector of type 'VT', see if the elements can be replaced by a single large
5636 /// load which has the same value as a build_vector whose operands are 'elts'.
5637 ///
5638 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5639 ///
5640 /// FIXME: we'd also like to handle the case where the last elements are zero
5641 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5642 /// There's even a handy isZeroNode for that purpose.
5643 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5644                                         SDLoc &DL, SelectionDAG &DAG,
5645                                         bool isAfterLegalize) {
5646   EVT EltVT = VT.getVectorElementType();
5647   unsigned NumElems = Elts.size();
5648
5649   LoadSDNode *LDBase = nullptr;
5650   unsigned LastLoadedElt = -1U;
5651
5652   // For each element in the initializer, see if we've found a load or an undef.
5653   // If we don't find an initial load element, or later load elements are
5654   // non-consecutive, bail out.
5655   for (unsigned i = 0; i < NumElems; ++i) {
5656     SDValue Elt = Elts[i];
5657
5658     if (!Elt.getNode() ||
5659         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5660       return SDValue();
5661     if (!LDBase) {
5662       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5663         return SDValue();
5664       LDBase = cast<LoadSDNode>(Elt.getNode());
5665       LastLoadedElt = i;
5666       continue;
5667     }
5668     if (Elt.getOpcode() == ISD::UNDEF)
5669       continue;
5670
5671     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5672     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5673       return SDValue();
5674     LastLoadedElt = i;
5675   }
5676
5677   // If we have found an entire vector of loads and undefs, then return a large
5678   // load of the entire vector width starting at the base pointer.  If we found
5679   // consecutive loads for the low half, generate a vzext_load node.
5680   if (LastLoadedElt == NumElems - 1) {
5681
5682     if (isAfterLegalize &&
5683         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5684       return SDValue();
5685
5686     SDValue NewLd = SDValue();
5687
5688     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5689       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5690                           LDBase->getPointerInfo(),
5691                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5692                           LDBase->isInvariant(), 0);
5693     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5694                         LDBase->getPointerInfo(),
5695                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5696                         LDBase->isInvariant(), LDBase->getAlignment());
5697
5698     if (LDBase->hasAnyUseOfValue(1)) {
5699       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5700                                      SDValue(LDBase, 1),
5701                                      SDValue(NewLd.getNode(), 1));
5702       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5703       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5704                              SDValue(NewLd.getNode(), 1));
5705     }
5706
5707     return NewLd;
5708   }
5709   if (NumElems == 4 && LastLoadedElt == 1 &&
5710       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5711     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5712     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5713     SDValue ResNode =
5714         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5715                                 LDBase->getPointerInfo(),
5716                                 LDBase->getAlignment(),
5717                                 false/*isVolatile*/, true/*ReadMem*/,
5718                                 false/*WriteMem*/);
5719
5720     // Make sure the newly-created LOAD is in the same position as LDBase in
5721     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5722     // update uses of LDBase's output chain to use the TokenFactor.
5723     if (LDBase->hasAnyUseOfValue(1)) {
5724       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5725                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5726       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5727       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5728                              SDValue(ResNode.getNode(), 1));
5729     }
5730
5731     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5732   }
5733   return SDValue();
5734 }
5735
5736 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5737 /// to generate a splat value for the following cases:
5738 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5739 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5740 /// a scalar load, or a constant.
5741 /// The VBROADCAST node is returned when a pattern is found,
5742 /// or SDValue() otherwise.
5743 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5744                                     SelectionDAG &DAG) {
5745   if (!Subtarget->hasFp256())
5746     return SDValue();
5747
5748   MVT VT = Op.getSimpleValueType();
5749   SDLoc dl(Op);
5750
5751   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5752          "Unsupported vector type for broadcast.");
5753
5754   SDValue Ld;
5755   bool ConstSplatVal;
5756
5757   switch (Op.getOpcode()) {
5758     default:
5759       // Unknown pattern found.
5760       return SDValue();
5761
5762     case ISD::BUILD_VECTOR: {
5763       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5764       BitVector UndefElements;
5765       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5766
5767       // We need a splat of a single value to use broadcast, and it doesn't
5768       // make any sense if the value is only in one element of the vector.
5769       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5770         return SDValue();
5771
5772       Ld = Splat;
5773       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5774                        Ld.getOpcode() == ISD::ConstantFP);
5775
5776       // Make sure that all of the users of a non-constant load are from the
5777       // BUILD_VECTOR node.
5778       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5779         return SDValue();
5780       break;
5781     }
5782
5783     case ISD::VECTOR_SHUFFLE: {
5784       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5785
5786       // Shuffles must have a splat mask where the first element is
5787       // broadcasted.
5788       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5789         return SDValue();
5790
5791       SDValue Sc = Op.getOperand(0);
5792       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5793           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5794
5795         if (!Subtarget->hasInt256())
5796           return SDValue();
5797
5798         // Use the register form of the broadcast instruction available on AVX2.
5799         if (VT.getSizeInBits() >= 256)
5800           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5801         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5802       }
5803
5804       Ld = Sc.getOperand(0);
5805       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5806                        Ld.getOpcode() == ISD::ConstantFP);
5807
5808       // The scalar_to_vector node and the suspected
5809       // load node must have exactly one user.
5810       // Constants may have multiple users.
5811
5812       // AVX-512 has register version of the broadcast
5813       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5814         Ld.getValueType().getSizeInBits() >= 32;
5815       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5816           !hasRegVer))
5817         return SDValue();
5818       break;
5819     }
5820   }
5821
5822   bool IsGE256 = (VT.getSizeInBits() >= 256);
5823
5824   // Handle the broadcasting a single constant scalar from the constant pool
5825   // into a vector. On Sandybridge it is still better to load a constant vector
5826   // from the constant pool and not to broadcast it from a scalar.
5827   if (ConstSplatVal && Subtarget->hasInt256()) {
5828     EVT CVT = Ld.getValueType();
5829     assert(!CVT.isVector() && "Must not broadcast a vector type");
5830     unsigned ScalarSize = CVT.getSizeInBits();
5831
5832     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5833       const Constant *C = nullptr;
5834       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5835         C = CI->getConstantIntValue();
5836       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5837         C = CF->getConstantFPValue();
5838
5839       assert(C && "Invalid constant type");
5840
5841       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5842       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5843       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5844       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5845                        MachinePointerInfo::getConstantPool(),
5846                        false, false, false, Alignment);
5847
5848       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5849     }
5850   }
5851
5852   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5853   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5854
5855   // Handle AVX2 in-register broadcasts.
5856   if (!IsLoad && Subtarget->hasInt256() &&
5857       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5858     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5859
5860   // The scalar source must be a normal load.
5861   if (!IsLoad)
5862     return SDValue();
5863
5864   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5865     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5866
5867   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5868   // double since there is no vbroadcastsd xmm
5869   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5870     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5871       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5872   }
5873
5874   // Unsupported broadcast.
5875   return SDValue();
5876 }
5877
5878 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5879 /// underlying vector and index.
5880 ///
5881 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5882 /// index.
5883 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5884                                          SDValue ExtIdx) {
5885   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5886   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5887     return Idx;
5888
5889   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5890   // lowered this:
5891   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5892   // to:
5893   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5894   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5895   //                           undef)
5896   //                       Constant<0>)
5897   // In this case the vector is the extract_subvector expression and the index
5898   // is 2, as specified by the shuffle.
5899   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5900   SDValue ShuffleVec = SVOp->getOperand(0);
5901   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5902   assert(ShuffleVecVT.getVectorElementType() ==
5903          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5904
5905   int ShuffleIdx = SVOp->getMaskElt(Idx);
5906   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5907     ExtractedFromVec = ShuffleVec;
5908     return ShuffleIdx;
5909   }
5910   return Idx;
5911 }
5912
5913 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5914   MVT VT = Op.getSimpleValueType();
5915
5916   // Skip if insert_vec_elt is not supported.
5917   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5918   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5919     return SDValue();
5920
5921   SDLoc DL(Op);
5922   unsigned NumElems = Op.getNumOperands();
5923
5924   SDValue VecIn1;
5925   SDValue VecIn2;
5926   SmallVector<unsigned, 4> InsertIndices;
5927   SmallVector<int, 8> Mask(NumElems, -1);
5928
5929   for (unsigned i = 0; i != NumElems; ++i) {
5930     unsigned Opc = Op.getOperand(i).getOpcode();
5931
5932     if (Opc == ISD::UNDEF)
5933       continue;
5934
5935     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5936       // Quit if more than 1 elements need inserting.
5937       if (InsertIndices.size() > 1)
5938         return SDValue();
5939
5940       InsertIndices.push_back(i);
5941       continue;
5942     }
5943
5944     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5945     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5946     // Quit if non-constant index.
5947     if (!isa<ConstantSDNode>(ExtIdx))
5948       return SDValue();
5949     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5950
5951     // Quit if extracted from vector of different type.
5952     if (ExtractedFromVec.getValueType() != VT)
5953       return SDValue();
5954
5955     if (!VecIn1.getNode())
5956       VecIn1 = ExtractedFromVec;
5957     else if (VecIn1 != ExtractedFromVec) {
5958       if (!VecIn2.getNode())
5959         VecIn2 = ExtractedFromVec;
5960       else if (VecIn2 != ExtractedFromVec)
5961         // Quit if more than 2 vectors to shuffle
5962         return SDValue();
5963     }
5964
5965     if (ExtractedFromVec == VecIn1)
5966       Mask[i] = Idx;
5967     else if (ExtractedFromVec == VecIn2)
5968       Mask[i] = Idx + NumElems;
5969   }
5970
5971   if (!VecIn1.getNode())
5972     return SDValue();
5973
5974   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5975   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5976   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5977     unsigned Idx = InsertIndices[i];
5978     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5979                      DAG.getIntPtrConstant(Idx));
5980   }
5981
5982   return NV;
5983 }
5984
5985 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5986 SDValue
5987 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5988
5989   MVT VT = Op.getSimpleValueType();
5990   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5991          "Unexpected type in LowerBUILD_VECTORvXi1!");
5992
5993   SDLoc dl(Op);
5994   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5995     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5996     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5997     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5998   }
5999
6000   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6001     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6002     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6004   }
6005
6006   bool AllContants = true;
6007   uint64_t Immediate = 0;
6008   int NonConstIdx = -1;
6009   bool IsSplat = true;
6010   unsigned NumNonConsts = 0;
6011   unsigned NumConsts = 0;
6012   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6013     SDValue In = Op.getOperand(idx);
6014     if (In.getOpcode() == ISD::UNDEF)
6015       continue;
6016     if (!isa<ConstantSDNode>(In)) {
6017       AllContants = false;
6018       NonConstIdx = idx;
6019       NumNonConsts++;
6020     }
6021     else {
6022       NumConsts++;
6023       if (cast<ConstantSDNode>(In)->getZExtValue())
6024       Immediate |= (1ULL << idx);
6025     }
6026     if (In != Op.getOperand(0))
6027       IsSplat = false;
6028   }
6029
6030   if (AllContants) {
6031     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6032       DAG.getConstant(Immediate, MVT::i16));
6033     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6034                        DAG.getIntPtrConstant(0));
6035   }
6036
6037   if (NumNonConsts == 1 && NonConstIdx != 0) {
6038     SDValue DstVec;
6039     if (NumConsts) {
6040       SDValue VecAsImm = DAG.getConstant(Immediate,
6041                                          MVT::getIntegerVT(VT.getSizeInBits()));
6042       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6043     }
6044     else 
6045       DstVec = DAG.getUNDEF(VT);
6046     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6047                        Op.getOperand(NonConstIdx),
6048                        DAG.getIntPtrConstant(NonConstIdx));
6049   }
6050   if (!IsSplat && (NonConstIdx != 0))
6051     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6052   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6053   SDValue Select;
6054   if (IsSplat)
6055     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6056                           DAG.getConstant(-1, SelectVT),
6057                           DAG.getConstant(0, SelectVT));
6058   else
6059     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6060                          DAG.getConstant((Immediate | 1), SelectVT),
6061                          DAG.getConstant(Immediate, SelectVT));
6062   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6063 }
6064
6065 /// \brief Return true if \p N implements a horizontal binop and return the
6066 /// operands for the horizontal binop into V0 and V1.
6067 /// 
6068 /// This is a helper function of PerformBUILD_VECTORCombine.
6069 /// This function checks that the build_vector \p N in input implements a
6070 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6071 /// operation to match.
6072 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6073 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6074 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6075 /// arithmetic sub.
6076 ///
6077 /// This function only analyzes elements of \p N whose indices are
6078 /// in range [BaseIdx, LastIdx).
6079 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6080                               SelectionDAG &DAG,
6081                               unsigned BaseIdx, unsigned LastIdx,
6082                               SDValue &V0, SDValue &V1) {
6083   EVT VT = N->getValueType(0);
6084
6085   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6086   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6087          "Invalid Vector in input!");
6088   
6089   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6090   bool CanFold = true;
6091   unsigned ExpectedVExtractIdx = BaseIdx;
6092   unsigned NumElts = LastIdx - BaseIdx;
6093   V0 = DAG.getUNDEF(VT);
6094   V1 = DAG.getUNDEF(VT);
6095
6096   // Check if N implements a horizontal binop.
6097   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6098     SDValue Op = N->getOperand(i + BaseIdx);
6099
6100     // Skip UNDEFs.
6101     if (Op->getOpcode() == ISD::UNDEF) {
6102       // Update the expected vector extract index.
6103       if (i * 2 == NumElts)
6104         ExpectedVExtractIdx = BaseIdx;
6105       ExpectedVExtractIdx += 2;
6106       continue;
6107     }
6108
6109     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6110
6111     if (!CanFold)
6112       break;
6113
6114     SDValue Op0 = Op.getOperand(0);
6115     SDValue Op1 = Op.getOperand(1);
6116
6117     // Try to match the following pattern:
6118     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6119     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6120         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6121         Op0.getOperand(0) == Op1.getOperand(0) &&
6122         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6123         isa<ConstantSDNode>(Op1.getOperand(1)));
6124     if (!CanFold)
6125       break;
6126
6127     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6128     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6129
6130     if (i * 2 < NumElts) {
6131       if (V0.getOpcode() == ISD::UNDEF)
6132         V0 = Op0.getOperand(0);
6133     } else {
6134       if (V1.getOpcode() == ISD::UNDEF)
6135         V1 = Op0.getOperand(0);
6136       if (i * 2 == NumElts)
6137         ExpectedVExtractIdx = BaseIdx;
6138     }
6139
6140     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6141     if (I0 == ExpectedVExtractIdx)
6142       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6143     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6144       // Try to match the following dag sequence:
6145       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6146       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6147     } else
6148       CanFold = false;
6149
6150     ExpectedVExtractIdx += 2;
6151   }
6152
6153   return CanFold;
6154 }
6155
6156 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6157 /// a concat_vector. 
6158 ///
6159 /// This is a helper function of PerformBUILD_VECTORCombine.
6160 /// This function expects two 256-bit vectors called V0 and V1.
6161 /// At first, each vector is split into two separate 128-bit vectors.
6162 /// Then, the resulting 128-bit vectors are used to implement two
6163 /// horizontal binary operations. 
6164 ///
6165 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6166 ///
6167 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6168 /// the two new horizontal binop.
6169 /// When Mode is set, the first horizontal binop dag node would take as input
6170 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6171 /// horizontal binop dag node would take as input the lower 128-bit of V1
6172 /// and the upper 128-bit of V1.
6173 ///   Example:
6174 ///     HADD V0_LO, V0_HI
6175 ///     HADD V1_LO, V1_HI
6176 ///
6177 /// Otherwise, the first horizontal binop dag node takes as input the lower
6178 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6179 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6180 ///   Example:
6181 ///     HADD V0_LO, V1_LO
6182 ///     HADD V0_HI, V1_HI
6183 ///
6184 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6185 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6186 /// the upper 128-bits of the result.
6187 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6188                                      SDLoc DL, SelectionDAG &DAG,
6189                                      unsigned X86Opcode, bool Mode,
6190                                      bool isUndefLO, bool isUndefHI) {
6191   EVT VT = V0.getValueType();
6192   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6193          "Invalid nodes in input!");
6194
6195   unsigned NumElts = VT.getVectorNumElements();
6196   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6197   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6198   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6199   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6200   EVT NewVT = V0_LO.getValueType();
6201
6202   SDValue LO = DAG.getUNDEF(NewVT);
6203   SDValue HI = DAG.getUNDEF(NewVT);
6204
6205   if (Mode) {
6206     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6207     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6208       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6209     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6210       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6211   } else {
6212     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6214                        V1_LO->getOpcode() != ISD::UNDEF))
6215       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6216
6217     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6218                        V1_HI->getOpcode() != ISD::UNDEF))
6219       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6220   }
6221
6222   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6223 }
6224
6225 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6226 /// sequence of 'vadd + vsub + blendi'.
6227 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6228                            const X86Subtarget *Subtarget) {
6229   SDLoc DL(BV);
6230   EVT VT = BV->getValueType(0);
6231   unsigned NumElts = VT.getVectorNumElements();
6232   SDValue InVec0 = DAG.getUNDEF(VT);
6233   SDValue InVec1 = DAG.getUNDEF(VT);
6234
6235   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6236           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6237
6238   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6239   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6240   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6241     return SDValue();
6242
6243   // Odd-numbered elements in the input build vector are obtained from
6244   // adding two integer/float elements.
6245   // Even-numbered elements in the input build vector are obtained from
6246   // subtracting two integer/float elements.
6247   unsigned ExpectedOpcode = ISD::FSUB;
6248   unsigned NextExpectedOpcode = ISD::FADD;
6249   bool AddFound = false;
6250   bool SubFound = false;
6251
6252   for (unsigned i = 0, e = NumElts; i != e; i++) {
6253     SDValue Op = BV->getOperand(i);
6254       
6255     // Skip 'undef' values.
6256     unsigned Opcode = Op.getOpcode();
6257     if (Opcode == ISD::UNDEF) {
6258       std::swap(ExpectedOpcode, NextExpectedOpcode);
6259       continue;
6260     }
6261       
6262     // Early exit if we found an unexpected opcode.
6263     if (Opcode != ExpectedOpcode)
6264       return SDValue();
6265
6266     SDValue Op0 = Op.getOperand(0);
6267     SDValue Op1 = Op.getOperand(1);
6268
6269     // Try to match the following pattern:
6270     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6271     // Early exit if we cannot match that sequence.
6272     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6273         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6274         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6275         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6276         Op0.getOperand(1) != Op1.getOperand(1))
6277       return SDValue();
6278
6279     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6280     if (I0 != i)
6281       return SDValue();
6282
6283     // We found a valid add/sub node. Update the information accordingly.
6284     if (i & 1)
6285       AddFound = true;
6286     else
6287       SubFound = true;
6288
6289     // Update InVec0 and InVec1.
6290     if (InVec0.getOpcode() == ISD::UNDEF)
6291       InVec0 = Op0.getOperand(0);
6292     if (InVec1.getOpcode() == ISD::UNDEF)
6293       InVec1 = Op1.getOperand(0);
6294
6295     // Make sure that operands in input to each add/sub node always
6296     // come from a same pair of vectors.
6297     if (InVec0 != Op0.getOperand(0)) {
6298       if (ExpectedOpcode == ISD::FSUB)
6299         return SDValue();
6300
6301       // FADD is commutable. Try to commute the operands
6302       // and then test again.
6303       std::swap(Op0, Op1);
6304       if (InVec0 != Op0.getOperand(0))
6305         return SDValue();
6306     }
6307
6308     if (InVec1 != Op1.getOperand(0))
6309       return SDValue();
6310
6311     // Update the pair of expected opcodes.
6312     std::swap(ExpectedOpcode, NextExpectedOpcode);
6313   }
6314
6315   // Don't try to fold this build_vector into a VSELECT if it has
6316   // too many UNDEF operands.
6317   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6318       InVec1.getOpcode() != ISD::UNDEF) {
6319     // Emit a sequence of vector add and sub followed by a VSELECT.
6320     // The new VSELECT will be lowered into a BLENDI.
6321     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6322     // and emit a single ADDSUB instruction.
6323     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6324     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6325
6326     // Construct the VSELECT mask.
6327     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6328     EVT SVT = MaskVT.getVectorElementType();
6329     unsigned SVTBits = SVT.getSizeInBits();
6330     SmallVector<SDValue, 8> Ops;
6331
6332     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6333       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6334                             APInt::getAllOnesValue(SVTBits);
6335       SDValue Constant = DAG.getConstant(Value, SVT);
6336       Ops.push_back(Constant);
6337     }
6338
6339     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6340     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6341   }
6342   
6343   return SDValue();
6344 }
6345
6346 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6347                                           const X86Subtarget *Subtarget) {
6348   SDLoc DL(N);
6349   EVT VT = N->getValueType(0);
6350   unsigned NumElts = VT.getVectorNumElements();
6351   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6352   SDValue InVec0, InVec1;
6353
6354   // Try to match an ADDSUB.
6355   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6356       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6357     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6358     if (Value.getNode())
6359       return Value;
6360   }
6361
6362   // Try to match horizontal ADD/SUB.
6363   unsigned NumUndefsLO = 0;
6364   unsigned NumUndefsHI = 0;
6365   unsigned Half = NumElts/2;
6366
6367   // Count the number of UNDEF operands in the build_vector in input.
6368   for (unsigned i = 0, e = Half; i != e; ++i)
6369     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6370       NumUndefsLO++;
6371
6372   for (unsigned i = Half, e = NumElts; i != e; ++i)
6373     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6374       NumUndefsHI++;
6375
6376   // Early exit if this is either a build_vector of all UNDEFs or all the
6377   // operands but one are UNDEF.
6378   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6379     return SDValue();
6380
6381   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6382     // Try to match an SSE3 float HADD/HSUB.
6383     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6384       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6385     
6386     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6387       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6388   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6389     // Try to match an SSSE3 integer HADD/HSUB.
6390     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6391       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6392     
6393     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6394       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6395   }
6396   
6397   if (!Subtarget->hasAVX())
6398     return SDValue();
6399
6400   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6401     // Try to match an AVX horizontal add/sub of packed single/double
6402     // precision floating point values from 256-bit vectors.
6403     SDValue InVec2, InVec3;
6404     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6405         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6406         ((InVec0.getOpcode() == ISD::UNDEF ||
6407           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6408         ((InVec1.getOpcode() == ISD::UNDEF ||
6409           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6410       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6411
6412     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6413         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6414         ((InVec0.getOpcode() == ISD::UNDEF ||
6415           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6416         ((InVec1.getOpcode() == ISD::UNDEF ||
6417           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6418       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6419   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6420     // Try to match an AVX2 horizontal add/sub of signed integers.
6421     SDValue InVec2, InVec3;
6422     unsigned X86Opcode;
6423     bool CanFold = true;
6424
6425     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6426         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6427         ((InVec0.getOpcode() == ISD::UNDEF ||
6428           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6429         ((InVec1.getOpcode() == ISD::UNDEF ||
6430           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6431       X86Opcode = X86ISD::HADD;
6432     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6433         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6434         ((InVec0.getOpcode() == ISD::UNDEF ||
6435           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6436         ((InVec1.getOpcode() == ISD::UNDEF ||
6437           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6438       X86Opcode = X86ISD::HSUB;
6439     else
6440       CanFold = false;
6441
6442     if (CanFold) {
6443       // Fold this build_vector into a single horizontal add/sub.
6444       // Do this only if the target has AVX2.
6445       if (Subtarget->hasAVX2())
6446         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6447  
6448       // Do not try to expand this build_vector into a pair of horizontal
6449       // add/sub if we can emit a pair of scalar add/sub.
6450       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6451         return SDValue();
6452
6453       // Convert this build_vector into a pair of horizontal binop followed by
6454       // a concat vector.
6455       bool isUndefLO = NumUndefsLO == Half;
6456       bool isUndefHI = NumUndefsHI == Half;
6457       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6458                                    isUndefLO, isUndefHI);
6459     }
6460   }
6461
6462   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6463        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6464     unsigned X86Opcode;
6465     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6466       X86Opcode = X86ISD::HADD;
6467     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6468       X86Opcode = X86ISD::HSUB;
6469     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6470       X86Opcode = X86ISD::FHADD;
6471     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6472       X86Opcode = X86ISD::FHSUB;
6473     else
6474       return SDValue();
6475
6476     // Don't try to expand this build_vector into a pair of horizontal add/sub
6477     // if we can simply emit a pair of scalar add/sub.
6478     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6479       return SDValue();
6480
6481     // Convert this build_vector into two horizontal add/sub followed by
6482     // a concat vector.
6483     bool isUndefLO = NumUndefsLO == Half;
6484     bool isUndefHI = NumUndefsHI == Half;
6485     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6486                                  isUndefLO, isUndefHI);
6487   }
6488
6489   return SDValue();
6490 }
6491
6492 SDValue
6493 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6494   SDLoc dl(Op);
6495
6496   MVT VT = Op.getSimpleValueType();
6497   MVT ExtVT = VT.getVectorElementType();
6498   unsigned NumElems = Op.getNumOperands();
6499
6500   // Generate vectors for predicate vectors.
6501   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6502     return LowerBUILD_VECTORvXi1(Op, DAG);
6503
6504   // Vectors containing all zeros can be matched by pxor and xorps later
6505   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6506     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6507     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6508     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6509       return Op;
6510
6511     return getZeroVector(VT, Subtarget, DAG, dl);
6512   }
6513
6514   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6515   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6516   // vpcmpeqd on 256-bit vectors.
6517   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6518     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6519       return Op;
6520
6521     if (!VT.is512BitVector())
6522       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6523   }
6524
6525   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6526   if (Broadcast.getNode())
6527     return Broadcast;
6528
6529   unsigned EVTBits = ExtVT.getSizeInBits();
6530
6531   unsigned NumZero  = 0;
6532   unsigned NumNonZero = 0;
6533   unsigned NonZeros = 0;
6534   bool IsAllConstants = true;
6535   SmallSet<SDValue, 8> Values;
6536   for (unsigned i = 0; i < NumElems; ++i) {
6537     SDValue Elt = Op.getOperand(i);
6538     if (Elt.getOpcode() == ISD::UNDEF)
6539       continue;
6540     Values.insert(Elt);
6541     if (Elt.getOpcode() != ISD::Constant &&
6542         Elt.getOpcode() != ISD::ConstantFP)
6543       IsAllConstants = false;
6544     if (X86::isZeroNode(Elt))
6545       NumZero++;
6546     else {
6547       NonZeros |= (1 << i);
6548       NumNonZero++;
6549     }
6550   }
6551
6552   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6553   if (NumNonZero == 0)
6554     return DAG.getUNDEF(VT);
6555
6556   // Special case for single non-zero, non-undef, element.
6557   if (NumNonZero == 1) {
6558     unsigned Idx = countTrailingZeros(NonZeros);
6559     SDValue Item = Op.getOperand(Idx);
6560
6561     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6562     // the value are obviously zero, truncate the value to i32 and do the
6563     // insertion that way.  Only do this if the value is non-constant or if the
6564     // value is a constant being inserted into element 0.  It is cheaper to do
6565     // a constant pool load than it is to do a movd + shuffle.
6566     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6567         (!IsAllConstants || Idx == 0)) {
6568       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6569         // Handle SSE only.
6570         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6571         EVT VecVT = MVT::v4i32;
6572         unsigned VecElts = 4;
6573
6574         // Truncate the value (which may itself be a constant) to i32, and
6575         // convert it to a vector with movd (S2V+shuffle to zero extend).
6576         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6577         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6578         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6579
6580         // Now we have our 32-bit value zero extended in the low element of
6581         // a vector.  If Idx != 0, swizzle it into place.
6582         if (Idx != 0) {
6583           SmallVector<int, 4> Mask;
6584           Mask.push_back(Idx);
6585           for (unsigned i = 1; i != VecElts; ++i)
6586             Mask.push_back(i);
6587           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6588                                       &Mask[0]);
6589         }
6590         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6591       }
6592     }
6593
6594     // If we have a constant or non-constant insertion into the low element of
6595     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6596     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6597     // depending on what the source datatype is.
6598     if (Idx == 0) {
6599       if (NumZero == 0)
6600         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6601
6602       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6603           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6604         if (VT.is256BitVector() || VT.is512BitVector()) {
6605           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6606           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6607                              Item, DAG.getIntPtrConstant(0));
6608         }
6609         assert(VT.is128BitVector() && "Expected an SSE value type!");
6610         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6611         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6612         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6613       }
6614
6615       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6616         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6617         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6618         if (VT.is256BitVector()) {
6619           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6620           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6621         } else {
6622           assert(VT.is128BitVector() && "Expected an SSE value type!");
6623           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6624         }
6625         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6626       }
6627     }
6628
6629     // Is it a vector logical left shift?
6630     if (NumElems == 2 && Idx == 1 &&
6631         X86::isZeroNode(Op.getOperand(0)) &&
6632         !X86::isZeroNode(Op.getOperand(1))) {
6633       unsigned NumBits = VT.getSizeInBits();
6634       return getVShift(true, VT,
6635                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6636                                    VT, Op.getOperand(1)),
6637                        NumBits/2, DAG, *this, dl);
6638     }
6639
6640     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6641       return SDValue();
6642
6643     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6644     // is a non-constant being inserted into an element other than the low one,
6645     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6646     // movd/movss) to move this into the low element, then shuffle it into
6647     // place.
6648     if (EVTBits == 32) {
6649       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6650
6651       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6652       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6653       SmallVector<int, 8> MaskVec;
6654       for (unsigned i = 0; i != NumElems; ++i)
6655         MaskVec.push_back(i == Idx ? 0 : 1);
6656       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6657     }
6658   }
6659
6660   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6661   if (Values.size() == 1) {
6662     if (EVTBits == 32) {
6663       // Instead of a shuffle like this:
6664       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6665       // Check if it's possible to issue this instead.
6666       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6667       unsigned Idx = countTrailingZeros(NonZeros);
6668       SDValue Item = Op.getOperand(Idx);
6669       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6670         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6671     }
6672     return SDValue();
6673   }
6674
6675   // A vector full of immediates; various special cases are already
6676   // handled, so this is best done with a single constant-pool load.
6677   if (IsAllConstants)
6678     return SDValue();
6679
6680   // For AVX-length vectors, build the individual 128-bit pieces and use
6681   // shuffles to put them in place.
6682   if (VT.is256BitVector() || VT.is512BitVector()) {
6683     SmallVector<SDValue, 64> V;
6684     for (unsigned i = 0; i != NumElems; ++i)
6685       V.push_back(Op.getOperand(i));
6686
6687     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6688
6689     // Build both the lower and upper subvector.
6690     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6691                                 makeArrayRef(&V[0], NumElems/2));
6692     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6693                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6694
6695     // Recreate the wider vector with the lower and upper part.
6696     if (VT.is256BitVector())
6697       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6698     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6699   }
6700
6701   // Let legalizer expand 2-wide build_vectors.
6702   if (EVTBits == 64) {
6703     if (NumNonZero == 1) {
6704       // One half is zero or undef.
6705       unsigned Idx = countTrailingZeros(NonZeros);
6706       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6707                                  Op.getOperand(Idx));
6708       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6709     }
6710     return SDValue();
6711   }
6712
6713   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6714   if (EVTBits == 8 && NumElems == 16) {
6715     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6716                                         Subtarget, *this);
6717     if (V.getNode()) return V;
6718   }
6719
6720   if (EVTBits == 16 && NumElems == 8) {
6721     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6722                                       Subtarget, *this);
6723     if (V.getNode()) return V;
6724   }
6725
6726   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6727   if (EVTBits == 32 && NumElems == 4) {
6728     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6729                                       NumZero, DAG, Subtarget, *this);
6730     if (V.getNode())
6731       return V;
6732   }
6733
6734   // If element VT is == 32 bits, turn it into a number of shuffles.
6735   SmallVector<SDValue, 8> V(NumElems);
6736   if (NumElems == 4 && NumZero > 0) {
6737     for (unsigned i = 0; i < 4; ++i) {
6738       bool isZero = !(NonZeros & (1 << i));
6739       if (isZero)
6740         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6741       else
6742         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6743     }
6744
6745     for (unsigned i = 0; i < 2; ++i) {
6746       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6747         default: break;
6748         case 0:
6749           V[i] = V[i*2];  // Must be a zero vector.
6750           break;
6751         case 1:
6752           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6753           break;
6754         case 2:
6755           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6756           break;
6757         case 3:
6758           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6759           break;
6760       }
6761     }
6762
6763     bool Reverse1 = (NonZeros & 0x3) == 2;
6764     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6765     int MaskVec[] = {
6766       Reverse1 ? 1 : 0,
6767       Reverse1 ? 0 : 1,
6768       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6769       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6770     };
6771     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6772   }
6773
6774   if (Values.size() > 1 && VT.is128BitVector()) {
6775     // Check for a build vector of consecutive loads.
6776     for (unsigned i = 0; i < NumElems; ++i)
6777       V[i] = Op.getOperand(i);
6778
6779     // Check for elements which are consecutive loads.
6780     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6781     if (LD.getNode())
6782       return LD;
6783
6784     // Check for a build vector from mostly shuffle plus few inserting.
6785     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6786     if (Sh.getNode())
6787       return Sh;
6788
6789     // For SSE 4.1, use insertps to put the high elements into the low element.
6790     if (getSubtarget()->hasSSE41()) {
6791       SDValue Result;
6792       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6793         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6794       else
6795         Result = DAG.getUNDEF(VT);
6796
6797       for (unsigned i = 1; i < NumElems; ++i) {
6798         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6799         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6800                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6801       }
6802       return Result;
6803     }
6804
6805     // Otherwise, expand into a number of unpckl*, start by extending each of
6806     // our (non-undef) elements to the full vector width with the element in the
6807     // bottom slot of the vector (which generates no code for SSE).
6808     for (unsigned i = 0; i < NumElems; ++i) {
6809       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6810         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6811       else
6812         V[i] = DAG.getUNDEF(VT);
6813     }
6814
6815     // Next, we iteratively mix elements, e.g. for v4f32:
6816     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6817     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6818     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6819     unsigned EltStride = NumElems >> 1;
6820     while (EltStride != 0) {
6821       for (unsigned i = 0; i < EltStride; ++i) {
6822         // If V[i+EltStride] is undef and this is the first round of mixing,
6823         // then it is safe to just drop this shuffle: V[i] is already in the
6824         // right place, the one element (since it's the first round) being
6825         // inserted as undef can be dropped.  This isn't safe for successive
6826         // rounds because they will permute elements within both vectors.
6827         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6828             EltStride == NumElems/2)
6829           continue;
6830
6831         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6832       }
6833       EltStride >>= 1;
6834     }
6835     return V[0];
6836   }
6837   return SDValue();
6838 }
6839
6840 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6841 // to create 256-bit vectors from two other 128-bit ones.
6842 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6843   SDLoc dl(Op);
6844   MVT ResVT = Op.getSimpleValueType();
6845
6846   assert((ResVT.is256BitVector() ||
6847           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6848
6849   SDValue V1 = Op.getOperand(0);
6850   SDValue V2 = Op.getOperand(1);
6851   unsigned NumElems = ResVT.getVectorNumElements();
6852   if(ResVT.is256BitVector())
6853     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6854
6855   if (Op.getNumOperands() == 4) {
6856     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6857                                 ResVT.getVectorNumElements()/2);
6858     SDValue V3 = Op.getOperand(2);
6859     SDValue V4 = Op.getOperand(3);
6860     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6861       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6862   }
6863   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6864 }
6865
6866 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6867   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6868   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6869          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6870           Op.getNumOperands() == 4)));
6871
6872   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6873   // from two other 128-bit ones.
6874
6875   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6876   return LowerAVXCONCAT_VECTORS(Op, DAG);
6877 }
6878
6879
6880 //===----------------------------------------------------------------------===//
6881 // Vector shuffle lowering
6882 //
6883 // This is an experimental code path for lowering vector shuffles on x86. It is
6884 // designed to handle arbitrary vector shuffles and blends, gracefully
6885 // degrading performance as necessary. It works hard to recognize idiomatic
6886 // shuffles and lower them to optimal instruction patterns without leaving
6887 // a framework that allows reasonably efficient handling of all vector shuffle
6888 // patterns.
6889 //===----------------------------------------------------------------------===//
6890
6891 /// \brief Tiny helper function to identify a no-op mask.
6892 ///
6893 /// This is a somewhat boring predicate function. It checks whether the mask
6894 /// array input, which is assumed to be a single-input shuffle mask of the kind
6895 /// used by the X86 shuffle instructions (not a fully general
6896 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6897 /// in-place shuffle are 'no-op's.
6898 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6899   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6900     if (Mask[i] != -1 && Mask[i] != i)
6901       return false;
6902   return true;
6903 }
6904
6905 /// \brief Helper function to classify a mask as a single-input mask.
6906 ///
6907 /// This isn't a generic single-input test because in the vector shuffle
6908 /// lowering we canonicalize single inputs to be the first input operand. This
6909 /// means we can more quickly test for a single input by only checking whether
6910 /// an input from the second operand exists. We also assume that the size of
6911 /// mask corresponds to the size of the input vectors which isn't true in the
6912 /// fully general case.
6913 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6914   for (int M : Mask)
6915     if (M >= (int)Mask.size())
6916       return false;
6917   return true;
6918 }
6919
6920 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6921 ///
6922 /// This helper function produces an 8-bit shuffle immediate corresponding to
6923 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6924 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6925 /// example.
6926 ///
6927 /// NB: We rely heavily on "undef" masks preserving the input lane.
6928 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6929                                           SelectionDAG &DAG) {
6930   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6931   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6932   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6933   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6934   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6935
6936   unsigned Imm = 0;
6937   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6938   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6939   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6940   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6941   return DAG.getConstant(Imm, MVT::i8);
6942 }
6943
6944 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6945 ///
6946 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6947 /// support for floating point shuffles but not integer shuffles. These
6948 /// instructions will incur a domain crossing penalty on some chips though so
6949 /// it is better to avoid lowering through this for integer vectors where
6950 /// possible.
6951 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6952                                        const X86Subtarget *Subtarget,
6953                                        SelectionDAG &DAG) {
6954   SDLoc DL(Op);
6955   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6956   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6957   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6958   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6959   ArrayRef<int> Mask = SVOp->getMask();
6960   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6961
6962   if (isSingleInputShuffleMask(Mask)) {
6963     // Straight shuffle of a single input vector. Simulate this by using the
6964     // single input as both of the "inputs" to this instruction..
6965     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6966     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6967                        DAG.getConstant(SHUFPDMask, MVT::i8));
6968   }
6969   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6970   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6971
6972   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6973   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6974                      DAG.getConstant(SHUFPDMask, MVT::i8));
6975 }
6976
6977 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6978 ///
6979 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6980 /// the integer unit to minimize domain crossing penalties. However, for blends
6981 /// it falls back to the floating point shuffle operation with appropriate bit
6982 /// casting.
6983 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6984                                        const X86Subtarget *Subtarget,
6985                                        SelectionDAG &DAG) {
6986   SDLoc DL(Op);
6987   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
6988   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6989   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
6990   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6991   ArrayRef<int> Mask = SVOp->getMask();
6992   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6993
6994   if (isSingleInputShuffleMask(Mask)) {
6995     // Straight shuffle of a single input vector. For everything from SSE2
6996     // onward this has a single fast instruction with no scary immediates.
6997     // We have to map the mask as it is actually a v4i32 shuffle instruction.
6998     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
6999     int WidenedMask[4] = {
7000         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7001         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7002     return DAG.getNode(
7003         ISD::BITCAST, DL, MVT::v2i64,
7004         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7005                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7006   }
7007
7008   // We implement this with SHUFPD which is pretty lame because it will likely
7009   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7010   // However, all the alternatives are still more cycles and newer chips don't
7011   // have this problem. It would be really nice if x86 had better shuffles here.
7012   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7013   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7014   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7015                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7016 }
7017
7018 /// \brief Lower 4-lane 32-bit floating point shuffles.
7019 ///
7020 /// Uses instructions exclusively from the floating point unit to minimize
7021 /// domain crossing penalties, as these are sufficient to implement all v4f32
7022 /// shuffles.
7023 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7024                                        const X86Subtarget *Subtarget,
7025                                        SelectionDAG &DAG) {
7026   SDLoc DL(Op);
7027   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7028   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7029   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7030   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7031   ArrayRef<int> Mask = SVOp->getMask();
7032   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7033
7034   SDValue LowV = V1, HighV = V2;
7035   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7036
7037   int NumV2Elements =
7038       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7039
7040   if (NumV2Elements == 0)
7041     // Straight shuffle of a single input vector. We pass the input vector to
7042     // both operands to simulate this with a SHUFPS.
7043     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7044                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7045
7046   if (NumV2Elements == 1) {
7047     int V2Index =
7048         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7049         Mask.begin();
7050     // Compute the index adjacent to V2Index and in the same half by toggling
7051     // the low bit.
7052     int V2AdjIndex = V2Index ^ 1;
7053
7054     if (Mask[V2AdjIndex] == -1) {
7055       // Handles all the cases where we have a single V2 element and an undef.
7056       // This will only ever happen in the high lanes because we commute the
7057       // vector otherwise.
7058       if (V2Index < 2)
7059         std::swap(LowV, HighV);
7060       NewMask[V2Index] -= 4;
7061     } else {
7062       // Handle the case where the V2 element ends up adjacent to a V1 element.
7063       // To make this work, blend them together as the first step.
7064       int V1Index = V2AdjIndex;
7065       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7066       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7067                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7068
7069       // Now proceed to reconstruct the final blend as we have the necessary
7070       // high or low half formed.
7071       if (V2Index < 2) {
7072         LowV = V2;
7073         HighV = V1;
7074       } else {
7075         HighV = V2;
7076       }
7077       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7078       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7079     }
7080   } else if (NumV2Elements == 2) {
7081     if (Mask[0] < 4 && Mask[1] < 4) {
7082       // Handle the easy case where we have V1 in the low lanes and V2 in the
7083       // high lanes. We never see this reversed because we sort the shuffle.
7084       NewMask[2] -= 4;
7085       NewMask[3] -= 4;
7086     } else {
7087       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7088       // trying to place elements directly, just blend them and set up the final
7089       // shuffle to place them.
7090
7091       // The first two blend mask elements are for V1, the second two are for
7092       // V2.
7093       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7094                           Mask[2] < 4 ? Mask[2] : Mask[3],
7095                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7096                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7097       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7098                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7099
7100       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7101       // a blend.
7102       LowV = HighV = V1;
7103       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7104       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7105       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7106       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7107     }
7108   }
7109   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7110                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7111 }
7112
7113 /// \brief Lower 4-lane i32 vector shuffles.
7114 ///
7115 /// We try to handle these with integer-domain shuffles where we can, but for
7116 /// blends we use the floating point domain blend instructions.
7117 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7118                                        const X86Subtarget *Subtarget,
7119                                        SelectionDAG &DAG) {
7120   SDLoc DL(Op);
7121   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7122   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7123   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7124   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7125   ArrayRef<int> Mask = SVOp->getMask();
7126   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7127
7128   if (isSingleInputShuffleMask(Mask))
7129     // Straight shuffle of a single input vector. For everything from SSE2
7130     // onward this has a single fast instruction with no scary immediates.
7131     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7132                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7133
7134   // We implement this with SHUFPS because it can blend from two vectors.
7135   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7136   // up the inputs, bypassing domain shift penalties that we would encur if we
7137   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7138   // relevant.
7139   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7140                      DAG.getVectorShuffle(
7141                          MVT::v4f32, DL,
7142                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7143                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7144 }
7145
7146 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7147 /// shuffle lowering, and the most complex part.
7148 ///
7149 /// The lowering strategy is to try to form pairs of input lanes which are
7150 /// targeted at the same half of the final vector, and then use a dword shuffle
7151 /// to place them onto the right half, and finally unpack the paired lanes into
7152 /// their final position.
7153 ///
7154 /// The exact breakdown of how to form these dword pairs and align them on the
7155 /// correct sides is really tricky. See the comments within the function for
7156 /// more of the details.
7157 static SDValue lowerV8I16SingleInputVectorShuffle(
7158     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7159     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7160   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7161   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7162   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7163
7164   SmallVector<int, 4> LoInputs;
7165   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7166                [](int M) { return M >= 0; });
7167   std::sort(LoInputs.begin(), LoInputs.end());
7168   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7169   SmallVector<int, 4> HiInputs;
7170   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7171                [](int M) { return M >= 0; });
7172   std::sort(HiInputs.begin(), HiInputs.end());
7173   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7174   int NumLToL =
7175       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7176   int NumHToL = LoInputs.size() - NumLToL;
7177   int NumLToH =
7178       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7179   int NumHToH = HiInputs.size() - NumLToH;
7180   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7181   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7182   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7183   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7184
7185   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7186   // such inputs we can swap two of the dwords across the half mark and end up
7187   // with <=2 inputs to each half in each half. Once there, we can fall through
7188   // to the generic code below. For example:
7189   //
7190   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7191   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7192   //
7193   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7194   // and 2-2.
7195   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7196                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7197     // Compute the index of dword with only one word among the three inputs in
7198     // a half by taking the sum of the half with three inputs and subtracting
7199     // the sum of the actual three inputs. The difference is the remaining
7200     // slot.
7201     int DWordA = (ThreeInputHalfSum -
7202                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7203                  2;
7204     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7205
7206     int PSHUFDMask[] = {0, 1, 2, 3};
7207     PSHUFDMask[DWordA] = DWordB;
7208     PSHUFDMask[DWordB] = DWordA;
7209     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7210                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7211                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7212                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7213
7214     // Adjust the mask to match the new locations of A and B.
7215     for (int &M : Mask)
7216       if (M != -1 && M/2 == DWordA)
7217         M = 2 * DWordB + M % 2;
7218       else if (M != -1 && M/2 == DWordB)
7219         M = 2 * DWordA + M % 2;
7220
7221     // Recurse back into this routine to re-compute state now that this isn't
7222     // a 3 and 1 problem.
7223     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7224                                 Mask);
7225   };
7226   if (NumLToL == 3 && NumHToL == 1)
7227     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7228   else if (NumLToL == 1 && NumHToL == 3)
7229     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7230   else if (NumLToH == 1 && NumHToH == 3)
7231     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7232   else if (NumLToH == 3 && NumHToH == 1)
7233     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7234
7235   // At this point there are at most two inputs to the low and high halves from
7236   // each half. That means the inputs can always be grouped into dwords and
7237   // those dwords can then be moved to the correct half with a dword shuffle.
7238   // We use at most one low and one high word shuffle to collect these paired
7239   // inputs into dwords, and finally a dword shuffle to place them.
7240   int PSHUFLMask[4] = {-1, -1, -1, -1};
7241   int PSHUFHMask[4] = {-1, -1, -1, -1};
7242   int PSHUFDMask[4] = {-1, -1, -1, -1};
7243
7244   // First fix the masks for all the inputs that are staying in their
7245   // original halves. This will then dictate the targets of the cross-half
7246   // shuffles.
7247   auto fixInPlaceInputs = [&PSHUFDMask](
7248       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7249       MutableArrayRef<int> HalfMask, int HalfOffset) {
7250     if (InPlaceInputs.empty())
7251       return;
7252     if (InPlaceInputs.size() == 1) {
7253       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7254           InPlaceInputs[0] - HalfOffset;
7255       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7256       return;
7257     }
7258
7259     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7260     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7261         InPlaceInputs[0] - HalfOffset;
7262     // Put the second input next to the first so that they are packed into
7263     // a dword. We find the adjacent index by toggling the low bit.
7264     int AdjIndex = InPlaceInputs[0] ^ 1;
7265     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7266     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7267     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7268   };
7269   if (!HToLInputs.empty())
7270     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7271   if (!LToHInputs.empty())
7272     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7273
7274   // Now gather the cross-half inputs and place them into a free dword of
7275   // their target half.
7276   // FIXME: This operation could almost certainly be simplified dramatically to
7277   // look more like the 3-1 fixing operation.
7278   auto moveInputsToRightHalf = [&PSHUFDMask](
7279       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7280       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7281       int SourceOffset, int DestOffset) {
7282     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7283       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7284     };
7285     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7286                                                int Word) {
7287       int LowWord = Word & ~1;
7288       int HighWord = Word | 1;
7289       return isWordClobbered(SourceHalfMask, LowWord) ||
7290              isWordClobbered(SourceHalfMask, HighWord);
7291     };
7292
7293     if (IncomingInputs.empty())
7294       return;
7295
7296     if (ExistingInputs.empty()) {
7297       // Map any dwords with inputs from them into the right half.
7298       for (int Input : IncomingInputs) {
7299         // If the source half mask maps over the inputs, turn those into
7300         // swaps and use the swapped lane.
7301         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7302           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7303             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7304                 Input - SourceOffset;
7305             // We have to swap the uses in our half mask in one sweep.
7306             for (int &M : HalfMask)
7307               if (M == SourceHalfMask[Input - SourceOffset])
7308                 M = Input;
7309               else if (M == Input)
7310                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7311           } else {
7312             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7313                        Input - SourceOffset &&
7314                    "Previous placement doesn't match!");
7315           }
7316           // Note that this correctly re-maps both when we do a swap and when
7317           // we observe the other side of the swap above. We rely on that to
7318           // avoid swapping the members of the input list directly.
7319           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7320         }
7321
7322         // Map the input's dword into the correct half.
7323         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7324           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7325         else
7326           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7327                      Input / 2 &&
7328                  "Previous placement doesn't match!");
7329       }
7330
7331       // And just directly shift any other-half mask elements to be same-half
7332       // as we will have mirrored the dword containing the element into the
7333       // same position within that half.
7334       for (int &M : HalfMask)
7335         if (M >= SourceOffset && M < SourceOffset + 4) {
7336           M = M - SourceOffset + DestOffset;
7337           assert(M >= 0 && "This should never wrap below zero!");
7338         }
7339       return;
7340     }
7341
7342     // Ensure we have the input in a viable dword of its current half. This
7343     // is particularly tricky because the original position may be clobbered
7344     // by inputs being moved and *staying* in that half.
7345     if (IncomingInputs.size() == 1) {
7346       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7347         int InputFixed = std::find(std::begin(SourceHalfMask),
7348                                    std::end(SourceHalfMask), -1) -
7349                          std::begin(SourceHalfMask) + SourceOffset;
7350         SourceHalfMask[InputFixed - SourceOffset] =
7351             IncomingInputs[0] - SourceOffset;
7352         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7353                      InputFixed);
7354         IncomingInputs[0] = InputFixed;
7355       }
7356     } else if (IncomingInputs.size() == 2) {
7357       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7358           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7359         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7360         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7361                "Not all dwords can be clobbered!");
7362         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7363         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7364         for (int &M : HalfMask)
7365           if (M == IncomingInputs[0])
7366             M = SourceDWordBase + SourceOffset;
7367           else if (M == IncomingInputs[1])
7368             M = SourceDWordBase + 1 + SourceOffset;
7369         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7370         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7371       }
7372     } else {
7373       llvm_unreachable("Unhandled input size!");
7374     }
7375
7376     // Now hoist the DWord down to the right half.
7377     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7378     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7379     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7380     for (int Input : IncomingInputs)
7381       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7382                    FreeDWord * 2 + Input % 2);
7383   };
7384   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7385                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7386   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7387                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7388
7389   // Now enact all the shuffles we've computed to move the inputs into their
7390   // target half.
7391   if (!isNoopShuffleMask(PSHUFLMask))
7392     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7393                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7394   if (!isNoopShuffleMask(PSHUFHMask))
7395     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7396                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7397   if (!isNoopShuffleMask(PSHUFDMask))
7398     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7399                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7400                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7401                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7402
7403   // At this point, each half should contain all its inputs, and we can then
7404   // just shuffle them into their final position.
7405   assert(std::count_if(LoMask.begin(), LoMask.end(),
7406                        [](int M) { return M >= 4; }) == 0 &&
7407          "Failed to lift all the high half inputs to the low mask!");
7408   assert(std::count_if(HiMask.begin(), HiMask.end(),
7409                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7410          "Failed to lift all the low half inputs to the high mask!");
7411
7412   // Do a half shuffle for the low mask.
7413   if (!isNoopShuffleMask(LoMask))
7414     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7415                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7416
7417   // Do a half shuffle with the high mask after shifting its values down.
7418   for (int &M : HiMask)
7419     if (M >= 0)
7420       M -= 4;
7421   if (!isNoopShuffleMask(HiMask))
7422     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7423                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7424
7425   return V;
7426 }
7427
7428 /// \brief Detect whether the mask pattern should be lowered through
7429 /// interleaving.
7430 ///
7431 /// This essentially tests whether viewing the mask as an interleaving of two
7432 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7433 /// lowering it through interleaving is a significantly better strategy.
7434 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7435   int NumEvenInputs[2] = {0, 0};
7436   int NumOddInputs[2] = {0, 0};
7437   int NumLoInputs[2] = {0, 0};
7438   int NumHiInputs[2] = {0, 0};
7439   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7440     if (Mask[i] < 0)
7441       continue;
7442
7443     int InputIdx = Mask[i] >= Size;
7444
7445     if (i < Size / 2)
7446       ++NumLoInputs[InputIdx];
7447     else
7448       ++NumHiInputs[InputIdx];
7449
7450     if ((i % 2) == 0)
7451       ++NumEvenInputs[InputIdx];
7452     else
7453       ++NumOddInputs[InputIdx];
7454   }
7455
7456   // The minimum number of cross-input results for both the interleaved and
7457   // split cases. If interleaving results in fewer cross-input results, return
7458   // true.
7459   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7460                                     NumEvenInputs[0] + NumOddInputs[1]);
7461   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7462                               NumLoInputs[0] + NumHiInputs[1]);
7463   return InterleavedCrosses < SplitCrosses;
7464 }
7465
7466 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7467 ///
7468 /// This strategy only works when the inputs from each vector fit into a single
7469 /// half of that vector, and generally there are not so many inputs as to leave
7470 /// the in-place shuffles required highly constrained (and thus expensive). It
7471 /// shifts all the inputs into a single side of both input vectors and then
7472 /// uses an unpack to interleave these inputs in a single vector. At that
7473 /// point, we will fall back on the generic single input shuffle lowering.
7474 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7475                                                  SDValue V2,
7476                                                  MutableArrayRef<int> Mask,
7477                                                  const X86Subtarget *Subtarget,
7478                                                  SelectionDAG &DAG) {
7479   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7480   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7481   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7482   for (int i = 0; i < 8; ++i)
7483     if (Mask[i] >= 0 && Mask[i] < 4)
7484       LoV1Inputs.push_back(i);
7485     else if (Mask[i] >= 4 && Mask[i] < 8)
7486       HiV1Inputs.push_back(i);
7487     else if (Mask[i] >= 8 && Mask[i] < 12)
7488       LoV2Inputs.push_back(i);
7489     else if (Mask[i] >= 12)
7490       HiV2Inputs.push_back(i);
7491
7492   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7493   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7494   (void)NumV1Inputs;
7495   (void)NumV2Inputs;
7496   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7497   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7498   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7499
7500   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7501                      HiV1Inputs.size() + HiV2Inputs.size();
7502
7503   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7504                               ArrayRef<int> HiInputs, bool MoveToLo,
7505                               int MaskOffset) {
7506     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7507     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7508     if (BadInputs.empty())
7509       return V;
7510
7511     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7512     int MoveOffset = MoveToLo ? 0 : 4;
7513
7514     if (GoodInputs.empty()) {
7515       for (int BadInput : BadInputs) {
7516         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7517         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7518       }
7519     } else {
7520       if (GoodInputs.size() == 2) {
7521         // If the low inputs are spread across two dwords, pack them into
7522         // a single dword.
7523         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7524             Mask[GoodInputs[0]] - MaskOffset;
7525         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7526             Mask[GoodInputs[1]] - MaskOffset;
7527         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7528         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7529       } else {
7530         // Otherwise pin the low inputs.
7531         for (int GoodInput : GoodInputs)
7532           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7533       }
7534
7535       int MoveMaskIdx =
7536           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7537           std::begin(MoveMask);
7538       assert(MoveMaskIdx >= MoveOffset && "Established above");
7539
7540       if (BadInputs.size() == 2) {
7541         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7542         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7543         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7544             Mask[BadInputs[0]] - MaskOffset;
7545         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7546             Mask[BadInputs[1]] - MaskOffset;
7547         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7548         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7549       } else {
7550         assert(BadInputs.size() == 1 && "All sizes handled");
7551         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7552         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7553       }
7554     }
7555
7556     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7557                                 MoveMask);
7558   };
7559   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7560                         /*MaskOffset*/ 0);
7561   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7562                         /*MaskOffset*/ 8);
7563
7564   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7565   // cross-half traffic in the final shuffle.
7566
7567   // Munge the mask to be a single-input mask after the unpack merges the
7568   // results.
7569   for (int &M : Mask)
7570     if (M != -1)
7571       M = 2 * (M % 4) + (M / 8);
7572
7573   return DAG.getVectorShuffle(
7574       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7575                                   DL, MVT::v8i16, V1, V2),
7576       DAG.getUNDEF(MVT::v8i16), Mask);
7577 }
7578
7579 /// \brief Generic lowering of 8-lane i16 shuffles.
7580 ///
7581 /// This handles both single-input shuffles and combined shuffle/blends with
7582 /// two inputs. The single input shuffles are immediately delegated to
7583 /// a dedicated lowering routine.
7584 ///
7585 /// The blends are lowered in one of three fundamental ways. If there are few
7586 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7587 /// of the input is significantly cheaper when lowered as an interleaving of
7588 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7589 /// halves of the inputs separately (making them have relatively few inputs)
7590 /// and then concatenate them.
7591 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7592                                        const X86Subtarget *Subtarget,
7593                                        SelectionDAG &DAG) {
7594   SDLoc DL(Op);
7595   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7596   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7597   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7598   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7599   ArrayRef<int> OrigMask = SVOp->getMask();
7600   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7601                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7602   MutableArrayRef<int> Mask(MaskStorage);
7603
7604   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7605
7606   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7607   auto isV2 = [](int M) { return M >= 8; };
7608
7609   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7610   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7611
7612   if (NumV2Inputs == 0)
7613     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7614
7615   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7616                             "to be V1-input shuffles.");
7617
7618   if (NumV1Inputs + NumV2Inputs <= 4)
7619     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7620
7621   // Check whether an interleaving lowering is likely to be more efficient.
7622   // This isn't perfect but it is a strong heuristic that tends to work well on
7623   // the kinds of shuffles that show up in practice.
7624   //
7625   // FIXME: Handle 1x, 2x, and 4x interleaving.
7626   if (shouldLowerAsInterleaving(Mask)) {
7627     // FIXME: Figure out whether we should pack these into the low or high
7628     // halves.
7629
7630     int EMask[8], OMask[8];
7631     for (int i = 0; i < 4; ++i) {
7632       EMask[i] = Mask[2*i];
7633       OMask[i] = Mask[2*i + 1];
7634       EMask[i + 4] = -1;
7635       OMask[i + 4] = -1;
7636     }
7637
7638     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7639     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7640
7641     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7642   }
7643
7644   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7645   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7646
7647   for (int i = 0; i < 4; ++i) {
7648     LoBlendMask[i] = Mask[i];
7649     HiBlendMask[i] = Mask[i + 4];
7650   }
7651
7652   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7653   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7654   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7655   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7656
7657   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7658                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7659 }
7660
7661 /// \brief Generic lowering of v16i8 shuffles.
7662 ///
7663 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7664 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7665 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7666 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7667 /// back together.
7668 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7669                                        const X86Subtarget *Subtarget,
7670                                        SelectionDAG &DAG) {
7671   SDLoc DL(Op);
7672   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7673   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7674   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7675   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7676   ArrayRef<int> OrigMask = SVOp->getMask();
7677   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7678   int MaskStorage[16] = {
7679       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7680       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7681       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7682       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7683   MutableArrayRef<int> Mask(MaskStorage);
7684   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7685   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7686
7687   // For single-input shuffles, there are some nicer lowering tricks we can use.
7688   if (isSingleInputShuffleMask(Mask)) {
7689     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7690     // Notably, this handles splat and partial-splat shuffles more efficiently.
7691     // However, it only makes sense if the pre-duplication shuffle simplifies
7692     // things significantly. Currently, this means we need to be able to
7693     // express the pre-duplication shuffle as an i16 shuffle.
7694     //
7695     // FIXME: We should check for other patterns which can be widened into an
7696     // i16 shuffle as well.
7697     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7698       for (int i = 0; i < 16; i += 2) {
7699         if (Mask[i] != Mask[i + 1])
7700           return false;
7701       }
7702       return true;
7703     };
7704     auto tryToWidenViaDuplication = [&]() -> SDValue {
7705       if (!canWidenViaDuplication(Mask))
7706         return SDValue();
7707       SmallVector<int, 4> LoInputs;
7708       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7709                    [](int M) { return M >= 0 && M < 8; });
7710       std::sort(LoInputs.begin(), LoInputs.end());
7711       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7712                      LoInputs.end());
7713       SmallVector<int, 4> HiInputs;
7714       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7715                    [](int M) { return M >= 8; });
7716       std::sort(HiInputs.begin(), HiInputs.end());
7717       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7718                      HiInputs.end());
7719
7720       bool TargetLo = LoInputs.size() >= HiInputs.size();
7721       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7722       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7723
7724       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7725       SmallDenseMap<int, int, 8> LaneMap;
7726       for (int I : InPlaceInputs) {
7727         PreDupI16Shuffle[I/2] = I/2;
7728         LaneMap[I] = I;
7729       }
7730       int j = TargetLo ? 0 : 4, je = j + 4;
7731       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7732         // Check if j is already a shuffle of this input. This happens when
7733         // there are two adjacent bytes after we move the low one.
7734         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7735           // If we haven't yet mapped the input, search for a slot into which
7736           // we can map it.
7737           while (j < je && PreDupI16Shuffle[j] != -1)
7738             ++j;
7739
7740           if (j == je)
7741             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7742             return SDValue();
7743
7744           // Map this input with the i16 shuffle.
7745           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7746         }
7747
7748         // Update the lane map based on the mapping we ended up with.
7749         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7750       }
7751       V1 = DAG.getNode(
7752           ISD::BITCAST, DL, MVT::v16i8,
7753           DAG.getVectorShuffle(MVT::v8i16, DL,
7754                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7755                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
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 PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7762       for (int i = 0; i < 16; i += 2) {
7763         if (Mask[i] != -1)
7764           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7765         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7766       }
7767       return DAG.getNode(
7768           ISD::BITCAST, DL, MVT::v16i8,
7769           DAG.getVectorShuffle(MVT::v8i16, DL,
7770                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7771                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7772     };
7773     if (SDValue V = tryToWidenViaDuplication())
7774       return V;
7775   }
7776
7777   // Check whether an interleaving lowering is likely to be more efficient.
7778   // This isn't perfect but it is a strong heuristic that tends to work well on
7779   // the kinds of shuffles that show up in practice.
7780   //
7781   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7782   if (shouldLowerAsInterleaving(Mask)) {
7783     // FIXME: Figure out whether we should pack these into the low or high
7784     // halves.
7785
7786     int EMask[16], OMask[16];
7787     for (int i = 0; i < 8; ++i) {
7788       EMask[i] = Mask[2*i];
7789       OMask[i] = Mask[2*i + 1];
7790       EMask[i + 8] = -1;
7791       OMask[i + 8] = -1;
7792     }
7793
7794     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7795     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7796
7797     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7798   }
7799
7800   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7801   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7802   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7803   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7804
7805   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7806                             MutableArrayRef<int> V1HalfBlendMask,
7807                             MutableArrayRef<int> V2HalfBlendMask) {
7808     for (int i = 0; i < 8; ++i)
7809       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7810         V1HalfBlendMask[i] = HalfMask[i];
7811         HalfMask[i] = i;
7812       } else if (HalfMask[i] >= 16) {
7813         V2HalfBlendMask[i] = HalfMask[i] - 16;
7814         HalfMask[i] = i + 8;
7815       }
7816   };
7817   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7818   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7819
7820   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7821
7822   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
7823                              MutableArrayRef<int> HiBlendMask) {
7824     SDValue V1, V2;
7825     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
7826     // them out and avoid using UNPCK{L,H} to extract the elements of V as
7827     // i16s.
7828     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
7829                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
7830         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
7831                      [](int M) { return M >= 0 && M % 2 == 1; })) {
7832       // Use a mask to drop the high bytes.
7833       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
7834       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
7835                        DAG.getConstant(0x00FF, MVT::v8i16));
7836
7837       // This will be a single vector shuffle instead of a blend so nuke V2.
7838       V2 = DAG.getUNDEF(MVT::v8i16);
7839
7840       // Squash the masks to point directly into V1.
7841       for (int &M : LoBlendMask)
7842         if (M >= 0)
7843           M /= 2;
7844       for (int &M : HiBlendMask)
7845         if (M >= 0)
7846           M /= 2;
7847     } else {
7848       // Otherwise just unpack the low half of V into V1 and the high half into
7849       // V2 so that we can blend them as i16s.
7850       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7851                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
7852       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7853                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
7854     }
7855
7856     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7857     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7858     return std::make_pair(BlendedLo, BlendedHi);
7859   };
7860   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
7861   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
7862   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
7863
7864   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7865   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7866
7867   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7868 }
7869
7870 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7871 ///
7872 /// This routine breaks down the specific type of 128-bit shuffle and
7873 /// dispatches to the lowering routines accordingly.
7874 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7875                                         MVT VT, const X86Subtarget *Subtarget,
7876                                         SelectionDAG &DAG) {
7877   switch (VT.SimpleTy) {
7878   case MVT::v2i64:
7879     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7880   case MVT::v2f64:
7881     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7882   case MVT::v4i32:
7883     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7884   case MVT::v4f32:
7885     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7886   case MVT::v8i16:
7887     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7888   case MVT::v16i8:
7889     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7890
7891   default:
7892     llvm_unreachable("Unimplemented!");
7893   }
7894 }
7895
7896 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7897 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7898   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7899     if (Mask[i] + 1 != Mask[i+1])
7900       return false;
7901
7902   return true;
7903 }
7904
7905 /// \brief Top-level lowering for x86 vector shuffles.
7906 ///
7907 /// This handles decomposition, canonicalization, and lowering of all x86
7908 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7909 /// above in helper routines. The canonicalization attempts to widen shuffles
7910 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7911 /// s.t. only one of the two inputs needs to be tested, etc.
7912 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7913                                   SelectionDAG &DAG) {
7914   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7915   ArrayRef<int> Mask = SVOp->getMask();
7916   SDValue V1 = Op.getOperand(0);
7917   SDValue V2 = Op.getOperand(1);
7918   MVT VT = Op.getSimpleValueType();
7919   int NumElements = VT.getVectorNumElements();
7920   SDLoc dl(Op);
7921
7922   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7923
7924   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7925   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7926   if (V1IsUndef && V2IsUndef)
7927     return DAG.getUNDEF(VT);
7928
7929   // When we create a shuffle node we put the UNDEF node to second operand,
7930   // but in some cases the first operand may be transformed to UNDEF.
7931   // In this case we should just commute the node.
7932   if (V1IsUndef)
7933     return DAG.getCommutedVectorShuffle(*SVOp);
7934
7935   // Check for non-undef masks pointing at an undef vector and make the masks
7936   // undef as well. This makes it easier to match the shuffle based solely on
7937   // the mask.
7938   if (V2IsUndef)
7939     for (int M : Mask)
7940       if (M >= NumElements) {
7941         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7942         for (int &M : NewMask)
7943           if (M >= NumElements)
7944             M = -1;
7945         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7946       }
7947
7948   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7949   // lanes but wider integers. We cap this to not form integers larger than i64
7950   // but it might be interesting to form i128 integers to handle flipping the
7951   // low and high halves of AVX 256-bit vectors.
7952   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7953       areAdjacentMasksSequential(Mask)) {
7954     SmallVector<int, 8> NewMask;
7955     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7956       NewMask.push_back(Mask[i] / 2);
7957     MVT NewVT =
7958         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7959                          VT.getVectorNumElements() / 2);
7960     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7961     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7962     return DAG.getNode(ISD::BITCAST, dl, VT,
7963                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7964   }
7965
7966   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7967   for (int M : SVOp->getMask())
7968     if (M < 0)
7969       ++NumUndefElements;
7970     else if (M < NumElements)
7971       ++NumV1Elements;
7972     else
7973       ++NumV2Elements;
7974
7975   // Commute the shuffle as needed such that more elements come from V1 than
7976   // V2. This allows us to match the shuffle pattern strictly on how many
7977   // elements come from V1 without handling the symmetric cases.
7978   if (NumV2Elements > NumV1Elements)
7979     return DAG.getCommutedVectorShuffle(*SVOp);
7980
7981   // When the number of V1 and V2 elements are the same, try to minimize the
7982   // number of uses of V2 in the low half of the vector.
7983   if (NumV1Elements == NumV2Elements) {
7984     int LowV1Elements = 0, LowV2Elements = 0;
7985     for (int M : SVOp->getMask().slice(0, NumElements / 2))
7986       if (M >= NumElements)
7987         ++LowV2Elements;
7988       else if (M >= 0)
7989         ++LowV1Elements;
7990     if (LowV2Elements > LowV1Elements)
7991       return DAG.getCommutedVectorShuffle(*SVOp);
7992   }
7993
7994   // For each vector width, delegate to a specialized lowering routine.
7995   if (VT.getSizeInBits() == 128)
7996     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
7997
7998   llvm_unreachable("Unimplemented!");
7999 }
8000
8001
8002 //===----------------------------------------------------------------------===//
8003 // Legacy vector shuffle lowering
8004 //
8005 // This code is the legacy code handling vector shuffles until the above
8006 // replaces its functionality and performance.
8007 //===----------------------------------------------------------------------===//
8008
8009 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8010                         bool hasInt256, unsigned *MaskOut = nullptr) {
8011   MVT EltVT = VT.getVectorElementType();
8012
8013   // There is no blend with immediate in AVX-512.
8014   if (VT.is512BitVector())
8015     return false;
8016
8017   if (!hasSSE41 || EltVT == MVT::i8)
8018     return false;
8019   if (!hasInt256 && VT == MVT::v16i16)
8020     return false;
8021
8022   unsigned MaskValue = 0;
8023   unsigned NumElems = VT.getVectorNumElements();
8024   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8025   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8026   unsigned NumElemsInLane = NumElems / NumLanes;
8027
8028   // Blend for v16i16 should be symetric for the both lanes.
8029   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8030
8031     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8032     int EltIdx = MaskVals[i];
8033
8034     if ((EltIdx < 0 || EltIdx == (int)i) &&
8035         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8036       continue;
8037
8038     if (((unsigned)EltIdx == (i + NumElems)) &&
8039         (SndLaneEltIdx < 0 ||
8040          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8041       MaskValue |= (1 << i);
8042     else
8043       return false;
8044   }
8045
8046   if (MaskOut)
8047     *MaskOut = MaskValue;
8048   return true;
8049 }
8050
8051 // Try to lower a shuffle node into a simple blend instruction.
8052 // This function assumes isBlendMask returns true for this
8053 // SuffleVectorSDNode
8054 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8055                                           unsigned MaskValue,
8056                                           const X86Subtarget *Subtarget,
8057                                           SelectionDAG &DAG) {
8058   MVT VT = SVOp->getSimpleValueType(0);
8059   MVT EltVT = VT.getVectorElementType();
8060   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8061                      Subtarget->hasInt256() && "Trying to lower a "
8062                                                "VECTOR_SHUFFLE to a Blend but "
8063                                                "with the wrong mask"));
8064   SDValue V1 = SVOp->getOperand(0);
8065   SDValue V2 = SVOp->getOperand(1);
8066   SDLoc dl(SVOp);
8067   unsigned NumElems = VT.getVectorNumElements();
8068
8069   // Convert i32 vectors to floating point if it is not AVX2.
8070   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8071   MVT BlendVT = VT;
8072   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8073     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8074                                NumElems);
8075     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8076     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8077   }
8078
8079   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8080                             DAG.getConstant(MaskValue, MVT::i32));
8081   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8082 }
8083
8084 /// In vector type \p VT, return true if the element at index \p InputIdx
8085 /// falls on a different 128-bit lane than \p OutputIdx.
8086 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8087                                      unsigned OutputIdx) {
8088   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8089   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8090 }
8091
8092 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8093 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8094 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8095 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8096 /// zero.
8097 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8098                          SelectionDAG &DAG) {
8099   MVT VT = V1.getSimpleValueType();
8100   assert(VT.is128BitVector() || VT.is256BitVector());
8101
8102   MVT EltVT = VT.getVectorElementType();
8103   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8104   unsigned NumElts = VT.getVectorNumElements();
8105
8106   SmallVector<SDValue, 32> PshufbMask;
8107   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8108     int InputIdx = MaskVals[OutputIdx];
8109     unsigned InputByteIdx;
8110
8111     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8112       InputByteIdx = 0x80;
8113     else {
8114       // Cross lane is not allowed.
8115       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8116         return SDValue();
8117       InputByteIdx = InputIdx * EltSizeInBytes;
8118       // Index is an byte offset within the 128-bit lane.
8119       InputByteIdx &= 0xf;
8120     }
8121
8122     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8123       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8124       if (InputByteIdx != 0x80)
8125         ++InputByteIdx;
8126     }
8127   }
8128
8129   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8130   if (ShufVT != VT)
8131     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8132   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8133                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8134 }
8135
8136 // v8i16 shuffles - Prefer shuffles in the following order:
8137 // 1. [all]   pshuflw, pshufhw, optional move
8138 // 2. [ssse3] 1 x pshufb
8139 // 3. [ssse3] 2 x pshufb + 1 x por
8140 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8141 static SDValue
8142 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8143                          SelectionDAG &DAG) {
8144   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8145   SDValue V1 = SVOp->getOperand(0);
8146   SDValue V2 = SVOp->getOperand(1);
8147   SDLoc dl(SVOp);
8148   SmallVector<int, 8> MaskVals;
8149
8150   // Determine if more than 1 of the words in each of the low and high quadwords
8151   // of the result come from the same quadword of one of the two inputs.  Undef
8152   // mask values count as coming from any quadword, for better codegen.
8153   //
8154   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8155   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8156   unsigned LoQuad[] = { 0, 0, 0, 0 };
8157   unsigned HiQuad[] = { 0, 0, 0, 0 };
8158   // Indices of quads used.
8159   std::bitset<4> InputQuads;
8160   for (unsigned i = 0; i < 8; ++i) {
8161     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8162     int EltIdx = SVOp->getMaskElt(i);
8163     MaskVals.push_back(EltIdx);
8164     if (EltIdx < 0) {
8165       ++Quad[0];
8166       ++Quad[1];
8167       ++Quad[2];
8168       ++Quad[3];
8169       continue;
8170     }
8171     ++Quad[EltIdx / 4];
8172     InputQuads.set(EltIdx / 4);
8173   }
8174
8175   int BestLoQuad = -1;
8176   unsigned MaxQuad = 1;
8177   for (unsigned i = 0; i < 4; ++i) {
8178     if (LoQuad[i] > MaxQuad) {
8179       BestLoQuad = i;
8180       MaxQuad = LoQuad[i];
8181     }
8182   }
8183
8184   int BestHiQuad = -1;
8185   MaxQuad = 1;
8186   for (unsigned i = 0; i < 4; ++i) {
8187     if (HiQuad[i] > MaxQuad) {
8188       BestHiQuad = i;
8189       MaxQuad = HiQuad[i];
8190     }
8191   }
8192
8193   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8194   // of the two input vectors, shuffle them into one input vector so only a
8195   // single pshufb instruction is necessary. If there are more than 2 input
8196   // quads, disable the next transformation since it does not help SSSE3.
8197   bool V1Used = InputQuads[0] || InputQuads[1];
8198   bool V2Used = InputQuads[2] || InputQuads[3];
8199   if (Subtarget->hasSSSE3()) {
8200     if (InputQuads.count() == 2 && V1Used && V2Used) {
8201       BestLoQuad = InputQuads[0] ? 0 : 1;
8202       BestHiQuad = InputQuads[2] ? 2 : 3;
8203     }
8204     if (InputQuads.count() > 2) {
8205       BestLoQuad = -1;
8206       BestHiQuad = -1;
8207     }
8208   }
8209
8210   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8211   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8212   // words from all 4 input quadwords.
8213   SDValue NewV;
8214   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8215     int MaskV[] = {
8216       BestLoQuad < 0 ? 0 : BestLoQuad,
8217       BestHiQuad < 0 ? 1 : BestHiQuad
8218     };
8219     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8220                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8221                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8222     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8223
8224     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8225     // source words for the shuffle, to aid later transformations.
8226     bool AllWordsInNewV = true;
8227     bool InOrder[2] = { true, true };
8228     for (unsigned i = 0; i != 8; ++i) {
8229       int idx = MaskVals[i];
8230       if (idx != (int)i)
8231         InOrder[i/4] = false;
8232       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8233         continue;
8234       AllWordsInNewV = false;
8235       break;
8236     }
8237
8238     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8239     if (AllWordsInNewV) {
8240       for (int i = 0; i != 8; ++i) {
8241         int idx = MaskVals[i];
8242         if (idx < 0)
8243           continue;
8244         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8245         if ((idx != i) && idx < 4)
8246           pshufhw = false;
8247         if ((idx != i) && idx > 3)
8248           pshuflw = false;
8249       }
8250       V1 = NewV;
8251       V2Used = false;
8252       BestLoQuad = 0;
8253       BestHiQuad = 1;
8254     }
8255
8256     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8257     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8258     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8259       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8260       unsigned TargetMask = 0;
8261       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8262                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8263       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8264       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8265                              getShufflePSHUFLWImmediate(SVOp);
8266       V1 = NewV.getOperand(0);
8267       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8268     }
8269   }
8270
8271   // Promote splats to a larger type which usually leads to more efficient code.
8272   // FIXME: Is this true if pshufb is available?
8273   if (SVOp->isSplat())
8274     return PromoteSplat(SVOp, DAG);
8275
8276   // If we have SSSE3, and all words of the result are from 1 input vector,
8277   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8278   // is present, fall back to case 4.
8279   if (Subtarget->hasSSSE3()) {
8280     SmallVector<SDValue,16> pshufbMask;
8281
8282     // If we have elements from both input vectors, set the high bit of the
8283     // shuffle mask element to zero out elements that come from V2 in the V1
8284     // mask, and elements that come from V1 in the V2 mask, so that the two
8285     // results can be OR'd together.
8286     bool TwoInputs = V1Used && V2Used;
8287     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8288     if (!TwoInputs)
8289       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8290
8291     // Calculate the shuffle mask for the second input, shuffle it, and
8292     // OR it with the first shuffled input.
8293     CommuteVectorShuffleMask(MaskVals, 8);
8294     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8295     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8296     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8297   }
8298
8299   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8300   // and update MaskVals with new element order.
8301   std::bitset<8> InOrder;
8302   if (BestLoQuad >= 0) {
8303     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8304     for (int i = 0; i != 4; ++i) {
8305       int idx = MaskVals[i];
8306       if (idx < 0) {
8307         InOrder.set(i);
8308       } else if ((idx / 4) == BestLoQuad) {
8309         MaskV[i] = idx & 3;
8310         InOrder.set(i);
8311       }
8312     }
8313     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8314                                 &MaskV[0]);
8315
8316     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8317       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8318       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8319                                   NewV.getOperand(0),
8320                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8321     }
8322   }
8323
8324   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8325   // and update MaskVals with the new element order.
8326   if (BestHiQuad >= 0) {
8327     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8328     for (unsigned i = 4; i != 8; ++i) {
8329       int idx = MaskVals[i];
8330       if (idx < 0) {
8331         InOrder.set(i);
8332       } else if ((idx / 4) == BestHiQuad) {
8333         MaskV[i] = (idx & 3) + 4;
8334         InOrder.set(i);
8335       }
8336     }
8337     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8338                                 &MaskV[0]);
8339
8340     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8341       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8342       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8343                                   NewV.getOperand(0),
8344                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8345     }
8346   }
8347
8348   // In case BestHi & BestLo were both -1, which means each quadword has a word
8349   // from each of the four input quadwords, calculate the InOrder bitvector now
8350   // before falling through to the insert/extract cleanup.
8351   if (BestLoQuad == -1 && BestHiQuad == -1) {
8352     NewV = V1;
8353     for (int i = 0; i != 8; ++i)
8354       if (MaskVals[i] < 0 || MaskVals[i] == i)
8355         InOrder.set(i);
8356   }
8357
8358   // The other elements are put in the right place using pextrw and pinsrw.
8359   for (unsigned i = 0; i != 8; ++i) {
8360     if (InOrder[i])
8361       continue;
8362     int EltIdx = MaskVals[i];
8363     if (EltIdx < 0)
8364       continue;
8365     SDValue ExtOp = (EltIdx < 8) ?
8366       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8367                   DAG.getIntPtrConstant(EltIdx)) :
8368       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8369                   DAG.getIntPtrConstant(EltIdx - 8));
8370     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8371                        DAG.getIntPtrConstant(i));
8372   }
8373   return NewV;
8374 }
8375
8376 /// \brief v16i16 shuffles
8377 ///
8378 /// FIXME: We only support generation of a single pshufb currently.  We can
8379 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8380 /// well (e.g 2 x pshufb + 1 x por).
8381 static SDValue
8382 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8383   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8384   SDValue V1 = SVOp->getOperand(0);
8385   SDValue V2 = SVOp->getOperand(1);
8386   SDLoc dl(SVOp);
8387
8388   if (V2.getOpcode() != ISD::UNDEF)
8389     return SDValue();
8390
8391   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8392   return getPSHUFB(MaskVals, V1, dl, DAG);
8393 }
8394
8395 // v16i8 shuffles - Prefer shuffles in the following order:
8396 // 1. [ssse3] 1 x pshufb
8397 // 2. [ssse3] 2 x pshufb + 1 x por
8398 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8399 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8400                                         const X86Subtarget* Subtarget,
8401                                         SelectionDAG &DAG) {
8402   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8403   SDValue V1 = SVOp->getOperand(0);
8404   SDValue V2 = SVOp->getOperand(1);
8405   SDLoc dl(SVOp);
8406   ArrayRef<int> MaskVals = SVOp->getMask();
8407
8408   // Promote splats to a larger type which usually leads to more efficient code.
8409   // FIXME: Is this true if pshufb is available?
8410   if (SVOp->isSplat())
8411     return PromoteSplat(SVOp, DAG);
8412
8413   // If we have SSSE3, case 1 is generated when all result bytes come from
8414   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8415   // present, fall back to case 3.
8416
8417   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8418   if (Subtarget->hasSSSE3()) {
8419     SmallVector<SDValue,16> pshufbMask;
8420
8421     // If all result elements are from one input vector, then only translate
8422     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8423     //
8424     // Otherwise, we have elements from both input vectors, and must zero out
8425     // elements that come from V2 in the first mask, and V1 in the second mask
8426     // so that we can OR them together.
8427     for (unsigned i = 0; i != 16; ++i) {
8428       int EltIdx = MaskVals[i];
8429       if (EltIdx < 0 || EltIdx >= 16)
8430         EltIdx = 0x80;
8431       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8432     }
8433     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8434                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8435                                  MVT::v16i8, pshufbMask));
8436
8437     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8438     // the 2nd operand if it's undefined or zero.
8439     if (V2.getOpcode() == ISD::UNDEF ||
8440         ISD::isBuildVectorAllZeros(V2.getNode()))
8441       return V1;
8442
8443     // Calculate the shuffle mask for the second input, shuffle it, and
8444     // OR it with the first shuffled input.
8445     pshufbMask.clear();
8446     for (unsigned i = 0; i != 16; ++i) {
8447       int EltIdx = MaskVals[i];
8448       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8449       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8450     }
8451     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8452                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8453                                  MVT::v16i8, pshufbMask));
8454     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8455   }
8456
8457   // No SSSE3 - Calculate in place words and then fix all out of place words
8458   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8459   // the 16 different words that comprise the two doublequadword input vectors.
8460   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8461   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8462   SDValue NewV = V1;
8463   for (int i = 0; i != 8; ++i) {
8464     int Elt0 = MaskVals[i*2];
8465     int Elt1 = MaskVals[i*2+1];
8466
8467     // This word of the result is all undef, skip it.
8468     if (Elt0 < 0 && Elt1 < 0)
8469       continue;
8470
8471     // This word of the result is already in the correct place, skip it.
8472     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8473       continue;
8474
8475     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8476     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8477     SDValue InsElt;
8478
8479     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8480     // using a single extract together, load it and store it.
8481     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8482       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8483                            DAG.getIntPtrConstant(Elt1 / 2));
8484       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8485                         DAG.getIntPtrConstant(i));
8486       continue;
8487     }
8488
8489     // If Elt1 is defined, extract it from the appropriate source.  If the
8490     // source byte is not also odd, shift the extracted word left 8 bits
8491     // otherwise clear the bottom 8 bits if we need to do an or.
8492     if (Elt1 >= 0) {
8493       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8494                            DAG.getIntPtrConstant(Elt1 / 2));
8495       if ((Elt1 & 1) == 0)
8496         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8497                              DAG.getConstant(8,
8498                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8499       else if (Elt0 >= 0)
8500         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8501                              DAG.getConstant(0xFF00, MVT::i16));
8502     }
8503     // If Elt0 is defined, extract it from the appropriate source.  If the
8504     // source byte is not also even, shift the extracted word right 8 bits. If
8505     // Elt1 was also defined, OR the extracted values together before
8506     // inserting them in the result.
8507     if (Elt0 >= 0) {
8508       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8509                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8510       if ((Elt0 & 1) != 0)
8511         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8512                               DAG.getConstant(8,
8513                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8514       else if (Elt1 >= 0)
8515         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8516                              DAG.getConstant(0x00FF, MVT::i16));
8517       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8518                          : InsElt0;
8519     }
8520     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8521                        DAG.getIntPtrConstant(i));
8522   }
8523   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8524 }
8525
8526 // v32i8 shuffles - Translate to VPSHUFB if possible.
8527 static
8528 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8529                                  const X86Subtarget *Subtarget,
8530                                  SelectionDAG &DAG) {
8531   MVT VT = SVOp->getSimpleValueType(0);
8532   SDValue V1 = SVOp->getOperand(0);
8533   SDValue V2 = SVOp->getOperand(1);
8534   SDLoc dl(SVOp);
8535   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8536
8537   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8538   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8539   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8540
8541   // VPSHUFB may be generated if
8542   // (1) one of input vector is undefined or zeroinitializer.
8543   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8544   // And (2) the mask indexes don't cross the 128-bit lane.
8545   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8546       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8547     return SDValue();
8548
8549   if (V1IsAllZero && !V2IsAllZero) {
8550     CommuteVectorShuffleMask(MaskVals, 32);
8551     V1 = V2;
8552   }
8553   return getPSHUFB(MaskVals, V1, dl, DAG);
8554 }
8555
8556 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8557 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8558 /// done when every pair / quad of shuffle mask elements point to elements in
8559 /// the right sequence. e.g.
8560 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8561 static
8562 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8563                                  SelectionDAG &DAG) {
8564   MVT VT = SVOp->getSimpleValueType(0);
8565   SDLoc dl(SVOp);
8566   unsigned NumElems = VT.getVectorNumElements();
8567   MVT NewVT;
8568   unsigned Scale;
8569   switch (VT.SimpleTy) {
8570   default: llvm_unreachable("Unexpected!");
8571   case MVT::v2i64:
8572   case MVT::v2f64:
8573            return SDValue(SVOp, 0);
8574   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8575   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8576   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8577   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8578   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8579   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8580   }
8581
8582   SmallVector<int, 8> MaskVec;
8583   for (unsigned i = 0; i != NumElems; i += Scale) {
8584     int StartIdx = -1;
8585     for (unsigned j = 0; j != Scale; ++j) {
8586       int EltIdx = SVOp->getMaskElt(i+j);
8587       if (EltIdx < 0)
8588         continue;
8589       if (StartIdx < 0)
8590         StartIdx = (EltIdx / Scale);
8591       if (EltIdx != (int)(StartIdx*Scale + j))
8592         return SDValue();
8593     }
8594     MaskVec.push_back(StartIdx);
8595   }
8596
8597   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8598   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8599   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8600 }
8601
8602 /// getVZextMovL - Return a zero-extending vector move low node.
8603 ///
8604 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8605                             SDValue SrcOp, SelectionDAG &DAG,
8606                             const X86Subtarget *Subtarget, SDLoc dl) {
8607   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8608     LoadSDNode *LD = nullptr;
8609     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8610       LD = dyn_cast<LoadSDNode>(SrcOp);
8611     if (!LD) {
8612       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8613       // instead.
8614       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8615       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8616           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8617           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8618           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8619         // PR2108
8620         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8621         return DAG.getNode(ISD::BITCAST, dl, VT,
8622                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8623                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8624                                                    OpVT,
8625                                                    SrcOp.getOperand(0)
8626                                                           .getOperand(0))));
8627       }
8628     }
8629   }
8630
8631   return DAG.getNode(ISD::BITCAST, dl, VT,
8632                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8633                                  DAG.getNode(ISD::BITCAST, dl,
8634                                              OpVT, SrcOp)));
8635 }
8636
8637 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8638 /// which could not be matched by any known target speficic shuffle
8639 static SDValue
8640 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8641
8642   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8643   if (NewOp.getNode())
8644     return NewOp;
8645
8646   MVT VT = SVOp->getSimpleValueType(0);
8647
8648   unsigned NumElems = VT.getVectorNumElements();
8649   unsigned NumLaneElems = NumElems / 2;
8650
8651   SDLoc dl(SVOp);
8652   MVT EltVT = VT.getVectorElementType();
8653   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8654   SDValue Output[2];
8655
8656   SmallVector<int, 16> Mask;
8657   for (unsigned l = 0; l < 2; ++l) {
8658     // Build a shuffle mask for the output, discovering on the fly which
8659     // input vectors to use as shuffle operands (recorded in InputUsed).
8660     // If building a suitable shuffle vector proves too hard, then bail
8661     // out with UseBuildVector set.
8662     bool UseBuildVector = false;
8663     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8664     unsigned LaneStart = l * NumLaneElems;
8665     for (unsigned i = 0; i != NumLaneElems; ++i) {
8666       // The mask element.  This indexes into the input.
8667       int Idx = SVOp->getMaskElt(i+LaneStart);
8668       if (Idx < 0) {
8669         // the mask element does not index into any input vector.
8670         Mask.push_back(-1);
8671         continue;
8672       }
8673
8674       // The input vector this mask element indexes into.
8675       int Input = Idx / NumLaneElems;
8676
8677       // Turn the index into an offset from the start of the input vector.
8678       Idx -= Input * NumLaneElems;
8679
8680       // Find or create a shuffle vector operand to hold this input.
8681       unsigned OpNo;
8682       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8683         if (InputUsed[OpNo] == Input)
8684           // This input vector is already an operand.
8685           break;
8686         if (InputUsed[OpNo] < 0) {
8687           // Create a new operand for this input vector.
8688           InputUsed[OpNo] = Input;
8689           break;
8690         }
8691       }
8692
8693       if (OpNo >= array_lengthof(InputUsed)) {
8694         // More than two input vectors used!  Give up on trying to create a
8695         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8696         UseBuildVector = true;
8697         break;
8698       }
8699
8700       // Add the mask index for the new shuffle vector.
8701       Mask.push_back(Idx + OpNo * NumLaneElems);
8702     }
8703
8704     if (UseBuildVector) {
8705       SmallVector<SDValue, 16> SVOps;
8706       for (unsigned i = 0; i != NumLaneElems; ++i) {
8707         // The mask element.  This indexes into the input.
8708         int Idx = SVOp->getMaskElt(i+LaneStart);
8709         if (Idx < 0) {
8710           SVOps.push_back(DAG.getUNDEF(EltVT));
8711           continue;
8712         }
8713
8714         // The input vector this mask element indexes into.
8715         int Input = Idx / NumElems;
8716
8717         // Turn the index into an offset from the start of the input vector.
8718         Idx -= Input * NumElems;
8719
8720         // Extract the vector element by hand.
8721         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8722                                     SVOp->getOperand(Input),
8723                                     DAG.getIntPtrConstant(Idx)));
8724       }
8725
8726       // Construct the output using a BUILD_VECTOR.
8727       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8728     } else if (InputUsed[0] < 0) {
8729       // No input vectors were used! The result is undefined.
8730       Output[l] = DAG.getUNDEF(NVT);
8731     } else {
8732       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8733                                         (InputUsed[0] % 2) * NumLaneElems,
8734                                         DAG, dl);
8735       // If only one input was used, use an undefined vector for the other.
8736       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8737         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8738                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8739       // At least one input vector was used. Create a new shuffle vector.
8740       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8741     }
8742
8743     Mask.clear();
8744   }
8745
8746   // Concatenate the result back
8747   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8748 }
8749
8750 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8751 /// 4 elements, and match them with several different shuffle types.
8752 static SDValue
8753 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8754   SDValue V1 = SVOp->getOperand(0);
8755   SDValue V2 = SVOp->getOperand(1);
8756   SDLoc dl(SVOp);
8757   MVT VT = SVOp->getSimpleValueType(0);
8758
8759   assert(VT.is128BitVector() && "Unsupported vector size");
8760
8761   std::pair<int, int> Locs[4];
8762   int Mask1[] = { -1, -1, -1, -1 };
8763   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8764
8765   unsigned NumHi = 0;
8766   unsigned NumLo = 0;
8767   for (unsigned i = 0; i != 4; ++i) {
8768     int Idx = PermMask[i];
8769     if (Idx < 0) {
8770       Locs[i] = std::make_pair(-1, -1);
8771     } else {
8772       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8773       if (Idx < 4) {
8774         Locs[i] = std::make_pair(0, NumLo);
8775         Mask1[NumLo] = Idx;
8776         NumLo++;
8777       } else {
8778         Locs[i] = std::make_pair(1, NumHi);
8779         if (2+NumHi < 4)
8780           Mask1[2+NumHi] = Idx;
8781         NumHi++;
8782       }
8783     }
8784   }
8785
8786   if (NumLo <= 2 && NumHi <= 2) {
8787     // If no more than two elements come from either vector. This can be
8788     // implemented with two shuffles. First shuffle gather the elements.
8789     // The second shuffle, which takes the first shuffle as both of its
8790     // vector operands, put the elements into the right order.
8791     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8792
8793     int Mask2[] = { -1, -1, -1, -1 };
8794
8795     for (unsigned i = 0; i != 4; ++i)
8796       if (Locs[i].first != -1) {
8797         unsigned Idx = (i < 2) ? 0 : 4;
8798         Idx += Locs[i].first * 2 + Locs[i].second;
8799         Mask2[i] = Idx;
8800       }
8801
8802     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8803   }
8804
8805   if (NumLo == 3 || NumHi == 3) {
8806     // Otherwise, we must have three elements from one vector, call it X, and
8807     // one element from the other, call it Y.  First, use a shufps to build an
8808     // intermediate vector with the one element from Y and the element from X
8809     // that will be in the same half in the final destination (the indexes don't
8810     // matter). Then, use a shufps to build the final vector, taking the half
8811     // containing the element from Y from the intermediate, and the other half
8812     // from X.
8813     if (NumHi == 3) {
8814       // Normalize it so the 3 elements come from V1.
8815       CommuteVectorShuffleMask(PermMask, 4);
8816       std::swap(V1, V2);
8817     }
8818
8819     // Find the element from V2.
8820     unsigned HiIndex;
8821     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8822       int Val = PermMask[HiIndex];
8823       if (Val < 0)
8824         continue;
8825       if (Val >= 4)
8826         break;
8827     }
8828
8829     Mask1[0] = PermMask[HiIndex];
8830     Mask1[1] = -1;
8831     Mask1[2] = PermMask[HiIndex^1];
8832     Mask1[3] = -1;
8833     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8834
8835     if (HiIndex >= 2) {
8836       Mask1[0] = PermMask[0];
8837       Mask1[1] = PermMask[1];
8838       Mask1[2] = HiIndex & 1 ? 6 : 4;
8839       Mask1[3] = HiIndex & 1 ? 4 : 6;
8840       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8841     }
8842
8843     Mask1[0] = HiIndex & 1 ? 2 : 0;
8844     Mask1[1] = HiIndex & 1 ? 0 : 2;
8845     Mask1[2] = PermMask[2];
8846     Mask1[3] = PermMask[3];
8847     if (Mask1[2] >= 0)
8848       Mask1[2] += 4;
8849     if (Mask1[3] >= 0)
8850       Mask1[3] += 4;
8851     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8852   }
8853
8854   // Break it into (shuffle shuffle_hi, shuffle_lo).
8855   int LoMask[] = { -1, -1, -1, -1 };
8856   int HiMask[] = { -1, -1, -1, -1 };
8857
8858   int *MaskPtr = LoMask;
8859   unsigned MaskIdx = 0;
8860   unsigned LoIdx = 0;
8861   unsigned HiIdx = 2;
8862   for (unsigned i = 0; i != 4; ++i) {
8863     if (i == 2) {
8864       MaskPtr = HiMask;
8865       MaskIdx = 1;
8866       LoIdx = 0;
8867       HiIdx = 2;
8868     }
8869     int Idx = PermMask[i];
8870     if (Idx < 0) {
8871       Locs[i] = std::make_pair(-1, -1);
8872     } else if (Idx < 4) {
8873       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8874       MaskPtr[LoIdx] = Idx;
8875       LoIdx++;
8876     } else {
8877       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8878       MaskPtr[HiIdx] = Idx;
8879       HiIdx++;
8880     }
8881   }
8882
8883   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8884   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8885   int MaskOps[] = { -1, -1, -1, -1 };
8886   for (unsigned i = 0; i != 4; ++i)
8887     if (Locs[i].first != -1)
8888       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8889   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8890 }
8891
8892 static bool MayFoldVectorLoad(SDValue V) {
8893   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8894     V = V.getOperand(0);
8895
8896   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8897     V = V.getOperand(0);
8898   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8899       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8900     // BUILD_VECTOR (load), undef
8901     V = V.getOperand(0);
8902
8903   return MayFoldLoad(V);
8904 }
8905
8906 static
8907 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8908   MVT VT = Op.getSimpleValueType();
8909
8910   // Canonizalize to v2f64.
8911   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8912   return DAG.getNode(ISD::BITCAST, dl, VT,
8913                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8914                                           V1, DAG));
8915 }
8916
8917 static
8918 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8919                         bool HasSSE2) {
8920   SDValue V1 = Op.getOperand(0);
8921   SDValue V2 = Op.getOperand(1);
8922   MVT VT = Op.getSimpleValueType();
8923
8924   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8925
8926   if (HasSSE2 && VT == MVT::v2f64)
8927     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8928
8929   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8930   return DAG.getNode(ISD::BITCAST, dl, VT,
8931                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8932                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8933                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8934 }
8935
8936 static
8937 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8938   SDValue V1 = Op.getOperand(0);
8939   SDValue V2 = Op.getOperand(1);
8940   MVT VT = Op.getSimpleValueType();
8941
8942   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8943          "unsupported shuffle type");
8944
8945   if (V2.getOpcode() == ISD::UNDEF)
8946     V2 = V1;
8947
8948   // v4i32 or v4f32
8949   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8950 }
8951
8952 static
8953 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8954   SDValue V1 = Op.getOperand(0);
8955   SDValue V2 = Op.getOperand(1);
8956   MVT VT = Op.getSimpleValueType();
8957   unsigned NumElems = VT.getVectorNumElements();
8958
8959   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8960   // operand of these instructions is only memory, so check if there's a
8961   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8962   // same masks.
8963   bool CanFoldLoad = false;
8964
8965   // Trivial case, when V2 comes from a load.
8966   if (MayFoldVectorLoad(V2))
8967     CanFoldLoad = true;
8968
8969   // When V1 is a load, it can be folded later into a store in isel, example:
8970   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8971   //    turns into:
8972   //  (MOVLPSmr addr:$src1, VR128:$src2)
8973   // So, recognize this potential and also use MOVLPS or MOVLPD
8974   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8975     CanFoldLoad = true;
8976
8977   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8978   if (CanFoldLoad) {
8979     if (HasSSE2 && NumElems == 2)
8980       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
8981
8982     if (NumElems == 4)
8983       // If we don't care about the second element, proceed to use movss.
8984       if (SVOp->getMaskElt(1) != -1)
8985         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
8986   }
8987
8988   // movl and movlp will both match v2i64, but v2i64 is never matched by
8989   // movl earlier because we make it strict to avoid messing with the movlp load
8990   // folding logic (see the code above getMOVLP call). Match it here then,
8991   // this is horrible, but will stay like this until we move all shuffle
8992   // matching to x86 specific nodes. Note that for the 1st condition all
8993   // types are matched with movsd.
8994   if (HasSSE2) {
8995     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
8996     // as to remove this logic from here, as much as possible
8997     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
8998       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8999     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9000   }
9001
9002   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9003
9004   // Invert the operand order and use SHUFPS to match it.
9005   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9006                               getShuffleSHUFImmediate(SVOp), DAG);
9007 }
9008
9009 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9010                                          SelectionDAG &DAG) {
9011   SDLoc dl(Load);
9012   MVT VT = Load->getSimpleValueType(0);
9013   MVT EVT = VT.getVectorElementType();
9014   SDValue Addr = Load->getOperand(1);
9015   SDValue NewAddr = DAG.getNode(
9016       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9017       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9018
9019   SDValue NewLoad =
9020       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9021                   DAG.getMachineFunction().getMachineMemOperand(
9022                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9023   return NewLoad;
9024 }
9025
9026 // It is only safe to call this function if isINSERTPSMask is true for
9027 // this shufflevector mask.
9028 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9029                            SelectionDAG &DAG) {
9030   // Generate an insertps instruction when inserting an f32 from memory onto a
9031   // v4f32 or when copying a member from one v4f32 to another.
9032   // We also use it for transferring i32 from one register to another,
9033   // since it simply copies the same bits.
9034   // If we're transferring an i32 from memory to a specific element in a
9035   // register, we output a generic DAG that will match the PINSRD
9036   // instruction.
9037   MVT VT = SVOp->getSimpleValueType(0);
9038   MVT EVT = VT.getVectorElementType();
9039   SDValue V1 = SVOp->getOperand(0);
9040   SDValue V2 = SVOp->getOperand(1);
9041   auto Mask = SVOp->getMask();
9042   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9043          "unsupported vector type for insertps/pinsrd");
9044
9045   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9046   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9047   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9048
9049   SDValue From;
9050   SDValue To;
9051   unsigned DestIndex;
9052   if (FromV1 == 1) {
9053     From = V1;
9054     To = V2;
9055     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9056                 Mask.begin();
9057   } else {
9058     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9059            "More than one element from V1 and from V2, or no elements from one "
9060            "of the vectors. This case should not have returned true from "
9061            "isINSERTPSMask");
9062     From = V2;
9063     To = V1;
9064     DestIndex =
9065         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9066   }
9067
9068   unsigned SrcIndex = Mask[DestIndex] % 4;
9069   if (MayFoldLoad(From)) {
9070     // Trivial case, when From comes from a load and is only used by the
9071     // shuffle. Make it use insertps from the vector that we need from that
9072     // load.
9073     SDValue NewLoad =
9074         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9075     if (!NewLoad.getNode())
9076       return SDValue();
9077
9078     if (EVT == MVT::f32) {
9079       // Create this as a scalar to vector to match the instruction pattern.
9080       SDValue LoadScalarToVector =
9081           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9082       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9083       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9084                          InsertpsMask);
9085     } else { // EVT == MVT::i32
9086       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9087       // instruction, to match the PINSRD instruction, which loads an i32 to a
9088       // certain vector element.
9089       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9090                          DAG.getConstant(DestIndex, MVT::i32));
9091     }
9092   }
9093
9094   // Vector-element-to-vector
9095   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9096   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9097 }
9098
9099 // Reduce a vector shuffle to zext.
9100 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9101                                     SelectionDAG &DAG) {
9102   // PMOVZX is only available from SSE41.
9103   if (!Subtarget->hasSSE41())
9104     return SDValue();
9105
9106   MVT VT = Op.getSimpleValueType();
9107
9108   // Only AVX2 support 256-bit vector integer extending.
9109   if (!Subtarget->hasInt256() && VT.is256BitVector())
9110     return SDValue();
9111
9112   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9113   SDLoc DL(Op);
9114   SDValue V1 = Op.getOperand(0);
9115   SDValue V2 = Op.getOperand(1);
9116   unsigned NumElems = VT.getVectorNumElements();
9117
9118   // Extending is an unary operation and the element type of the source vector
9119   // won't be equal to or larger than i64.
9120   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9121       VT.getVectorElementType() == MVT::i64)
9122     return SDValue();
9123
9124   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9125   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9126   while ((1U << Shift) < NumElems) {
9127     if (SVOp->getMaskElt(1U << Shift) == 1)
9128       break;
9129     Shift += 1;
9130     // The maximal ratio is 8, i.e. from i8 to i64.
9131     if (Shift > 3)
9132       return SDValue();
9133   }
9134
9135   // Check the shuffle mask.
9136   unsigned Mask = (1U << Shift) - 1;
9137   for (unsigned i = 0; i != NumElems; ++i) {
9138     int EltIdx = SVOp->getMaskElt(i);
9139     if ((i & Mask) != 0 && EltIdx != -1)
9140       return SDValue();
9141     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9142       return SDValue();
9143   }
9144
9145   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9146   MVT NeVT = MVT::getIntegerVT(NBits);
9147   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9148
9149   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9150     return SDValue();
9151
9152   // Simplify the operand as it's prepared to be fed into shuffle.
9153   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9154   if (V1.getOpcode() == ISD::BITCAST &&
9155       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9156       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9157       V1.getOperand(0).getOperand(0)
9158         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9159     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9160     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9161     ConstantSDNode *CIdx =
9162       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9163     // If it's foldable, i.e. normal load with single use, we will let code
9164     // selection to fold it. Otherwise, we will short the conversion sequence.
9165     if (CIdx && CIdx->getZExtValue() == 0 &&
9166         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9167       MVT FullVT = V.getSimpleValueType();
9168       MVT V1VT = V1.getSimpleValueType();
9169       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9170         // The "ext_vec_elt" node is wider than the result node.
9171         // In this case we should extract subvector from V.
9172         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9173         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9174         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9175                                         FullVT.getVectorNumElements()/Ratio);
9176         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9177                         DAG.getIntPtrConstant(0));
9178       }
9179       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9180     }
9181   }
9182
9183   return DAG.getNode(ISD::BITCAST, DL, VT,
9184                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9185 }
9186
9187 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9188                                       SelectionDAG &DAG) {
9189   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9190   MVT VT = Op.getSimpleValueType();
9191   SDLoc dl(Op);
9192   SDValue V1 = Op.getOperand(0);
9193   SDValue V2 = Op.getOperand(1);
9194
9195   if (isZeroShuffle(SVOp))
9196     return getZeroVector(VT, Subtarget, DAG, dl);
9197
9198   // Handle splat operations
9199   if (SVOp->isSplat()) {
9200     // Use vbroadcast whenever the splat comes from a foldable load
9201     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9202     if (Broadcast.getNode())
9203       return Broadcast;
9204   }
9205
9206   // Check integer expanding shuffles.
9207   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9208   if (NewOp.getNode())
9209     return NewOp;
9210
9211   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9212   // do it!
9213   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9214       VT == MVT::v32i8) {
9215     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9216     if (NewOp.getNode())
9217       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9218   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9219     // FIXME: Figure out a cleaner way to do this.
9220     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9221       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9222       if (NewOp.getNode()) {
9223         MVT NewVT = NewOp.getSimpleValueType();
9224         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9225                                NewVT, true, false))
9226           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9227                               dl);
9228       }
9229     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9230       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9231       if (NewOp.getNode()) {
9232         MVT NewVT = NewOp.getSimpleValueType();
9233         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9234           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9235                               dl);
9236       }
9237     }
9238   }
9239   return SDValue();
9240 }
9241
9242 SDValue
9243 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9244   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9245   SDValue V1 = Op.getOperand(0);
9246   SDValue V2 = Op.getOperand(1);
9247   MVT VT = Op.getSimpleValueType();
9248   SDLoc dl(Op);
9249   unsigned NumElems = VT.getVectorNumElements();
9250   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9251   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9252   bool V1IsSplat = false;
9253   bool V2IsSplat = false;
9254   bool HasSSE2 = Subtarget->hasSSE2();
9255   bool HasFp256    = Subtarget->hasFp256();
9256   bool HasInt256   = Subtarget->hasInt256();
9257   MachineFunction &MF = DAG.getMachineFunction();
9258   bool OptForSize = MF.getFunction()->getAttributes().
9259     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9260
9261   // Check if we should use the experimental vector shuffle lowering. If so,
9262   // delegate completely to that code path.
9263   if (ExperimentalVectorShuffleLowering)
9264     return lowerVectorShuffle(Op, Subtarget, DAG);
9265
9266   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9267
9268   if (V1IsUndef && V2IsUndef)
9269     return DAG.getUNDEF(VT);
9270
9271   // When we create a shuffle node we put the UNDEF node to second operand,
9272   // but in some cases the first operand may be transformed to UNDEF.
9273   // In this case we should just commute the node.
9274   if (V1IsUndef)
9275     return DAG.getCommutedVectorShuffle(*SVOp);
9276
9277   // Vector shuffle lowering takes 3 steps:
9278   //
9279   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9280   //    narrowing and commutation of operands should be handled.
9281   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9282   //    shuffle nodes.
9283   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9284   //    so the shuffle can be broken into other shuffles and the legalizer can
9285   //    try the lowering again.
9286   //
9287   // The general idea is that no vector_shuffle operation should be left to
9288   // be matched during isel, all of them must be converted to a target specific
9289   // node here.
9290
9291   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9292   // narrowing and commutation of operands should be handled. The actual code
9293   // doesn't include all of those, work in progress...
9294   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9295   if (NewOp.getNode())
9296     return NewOp;
9297
9298   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9299
9300   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9301   // unpckh_undef). Only use pshufd if speed is more important than size.
9302   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9303     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9304   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9305     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9306
9307   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9308       V2IsUndef && MayFoldVectorLoad(V1))
9309     return getMOVDDup(Op, dl, V1, DAG);
9310
9311   if (isMOVHLPS_v_undef_Mask(M, VT))
9312     return getMOVHighToLow(Op, dl, DAG);
9313
9314   // Use to match splats
9315   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9316       (VT == MVT::v2f64 || VT == MVT::v2i64))
9317     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9318
9319   if (isPSHUFDMask(M, VT)) {
9320     // The actual implementation will match the mask in the if above and then
9321     // during isel it can match several different instructions, not only pshufd
9322     // as its name says, sad but true, emulate the behavior for now...
9323     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9324       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9325
9326     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9327
9328     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9329       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9330
9331     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9332       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9333                                   DAG);
9334
9335     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9336                                 TargetMask, DAG);
9337   }
9338
9339   if (isPALIGNRMask(M, VT, Subtarget))
9340     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9341                                 getShufflePALIGNRImmediate(SVOp),
9342                                 DAG);
9343
9344   // Check if this can be converted into a logical shift.
9345   bool isLeft = false;
9346   unsigned ShAmt = 0;
9347   SDValue ShVal;
9348   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9349   if (isShift && ShVal.hasOneUse()) {
9350     // If the shifted value has multiple uses, it may be cheaper to use
9351     // v_set0 + movlhps or movhlps, etc.
9352     MVT EltVT = VT.getVectorElementType();
9353     ShAmt *= EltVT.getSizeInBits();
9354     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9355   }
9356
9357   if (isMOVLMask(M, VT)) {
9358     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9359       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9360     if (!isMOVLPMask(M, VT)) {
9361       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9362         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9363
9364       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9365         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9366     }
9367   }
9368
9369   // FIXME: fold these into legal mask.
9370   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9371     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9372
9373   if (isMOVHLPSMask(M, VT))
9374     return getMOVHighToLow(Op, dl, DAG);
9375
9376   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9377     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9378
9379   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9380     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9381
9382   if (isMOVLPMask(M, VT))
9383     return getMOVLP(Op, dl, DAG, HasSSE2);
9384
9385   if (ShouldXformToMOVHLPS(M, VT) ||
9386       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9387     return DAG.getCommutedVectorShuffle(*SVOp);
9388
9389   if (isShift) {
9390     // No better options. Use a vshldq / vsrldq.
9391     MVT EltVT = VT.getVectorElementType();
9392     ShAmt *= EltVT.getSizeInBits();
9393     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9394   }
9395
9396   bool Commuted = false;
9397   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9398   // 1,1,1,1 -> v8i16 though.
9399   BitVector UndefElements;
9400   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9401     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9402       V1IsSplat = true;
9403   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9404     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9405       V2IsSplat = true;
9406
9407   // Canonicalize the splat or undef, if present, to be on the RHS.
9408   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9409     CommuteVectorShuffleMask(M, NumElems);
9410     std::swap(V1, V2);
9411     std::swap(V1IsSplat, V2IsSplat);
9412     Commuted = true;
9413   }
9414
9415   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9416     // Shuffling low element of v1 into undef, just return v1.
9417     if (V2IsUndef)
9418       return V1;
9419     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9420     // the instruction selector will not match, so get a canonical MOVL with
9421     // swapped operands to undo the commute.
9422     return getMOVL(DAG, dl, VT, V2, V1);
9423   }
9424
9425   if (isUNPCKLMask(M, VT, HasInt256))
9426     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9427
9428   if (isUNPCKHMask(M, VT, HasInt256))
9429     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9430
9431   if (V2IsSplat) {
9432     // Normalize mask so all entries that point to V2 points to its first
9433     // element then try to match unpck{h|l} again. If match, return a
9434     // new vector_shuffle with the corrected mask.p
9435     SmallVector<int, 8> NewMask(M.begin(), M.end());
9436     NormalizeMask(NewMask, NumElems);
9437     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9438       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9439     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9440       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9441   }
9442
9443   if (Commuted) {
9444     // Commute is back and try unpck* again.
9445     // FIXME: this seems wrong.
9446     CommuteVectorShuffleMask(M, NumElems);
9447     std::swap(V1, V2);
9448     std::swap(V1IsSplat, V2IsSplat);
9449
9450     if (isUNPCKLMask(M, VT, HasInt256))
9451       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9452
9453     if (isUNPCKHMask(M, VT, HasInt256))
9454       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9455   }
9456
9457   // Normalize the node to match x86 shuffle ops if needed
9458   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9459     return DAG.getCommutedVectorShuffle(*SVOp);
9460
9461   // The checks below are all present in isShuffleMaskLegal, but they are
9462   // inlined here right now to enable us to directly emit target specific
9463   // nodes, and remove one by one until they don't return Op anymore.
9464
9465   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9466       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9467     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9468       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9469   }
9470
9471   if (isPSHUFHWMask(M, VT, HasInt256))
9472     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9473                                 getShufflePSHUFHWImmediate(SVOp),
9474                                 DAG);
9475
9476   if (isPSHUFLWMask(M, VT, HasInt256))
9477     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9478                                 getShufflePSHUFLWImmediate(SVOp),
9479                                 DAG);
9480
9481   unsigned MaskValue;
9482   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9483                   &MaskValue))
9484     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9485
9486   if (isSHUFPMask(M, VT))
9487     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9488                                 getShuffleSHUFImmediate(SVOp), DAG);
9489
9490   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9491     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9492   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9493     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9494
9495   //===--------------------------------------------------------------------===//
9496   // Generate target specific nodes for 128 or 256-bit shuffles only
9497   // supported in the AVX instruction set.
9498   //
9499
9500   // Handle VMOVDDUPY permutations
9501   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9502     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9503
9504   // Handle VPERMILPS/D* permutations
9505   if (isVPERMILPMask(M, VT)) {
9506     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9507       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9508                                   getShuffleSHUFImmediate(SVOp), DAG);
9509     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9510                                 getShuffleSHUFImmediate(SVOp), DAG);
9511   }
9512
9513   unsigned Idx;
9514   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9515     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9516                               Idx*(NumElems/2), DAG, dl);
9517
9518   // Handle VPERM2F128/VPERM2I128 permutations
9519   if (isVPERM2X128Mask(M, VT, HasFp256))
9520     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9521                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9522
9523   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9524     return getINSERTPS(SVOp, dl, DAG);
9525
9526   unsigned Imm8;
9527   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9528     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9529
9530   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9531       VT.is512BitVector()) {
9532     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9533     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9534     SmallVector<SDValue, 16> permclMask;
9535     for (unsigned i = 0; i != NumElems; ++i) {
9536       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9537     }
9538
9539     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9540     if (V2IsUndef)
9541       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9542       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9543                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9544     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9545                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9546   }
9547
9548   //===--------------------------------------------------------------------===//
9549   // Since no target specific shuffle was selected for this generic one,
9550   // lower it into other known shuffles. FIXME: this isn't true yet, but
9551   // this is the plan.
9552   //
9553
9554   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9555   if (VT == MVT::v8i16) {
9556     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9557     if (NewOp.getNode())
9558       return NewOp;
9559   }
9560
9561   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9562     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9563     if (NewOp.getNode())
9564       return NewOp;
9565   }
9566
9567   if (VT == MVT::v16i8) {
9568     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9569     if (NewOp.getNode())
9570       return NewOp;
9571   }
9572
9573   if (VT == MVT::v32i8) {
9574     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9575     if (NewOp.getNode())
9576       return NewOp;
9577   }
9578
9579   // Handle all 128-bit wide vectors with 4 elements, and match them with
9580   // several different shuffle types.
9581   if (NumElems == 4 && VT.is128BitVector())
9582     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9583
9584   // Handle general 256-bit shuffles
9585   if (VT.is256BitVector())
9586     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9587
9588   return SDValue();
9589 }
9590
9591 // This function assumes its argument is a BUILD_VECTOR of constants or
9592 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9593 // true.
9594 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9595                                     unsigned &MaskValue) {
9596   MaskValue = 0;
9597   unsigned NumElems = BuildVector->getNumOperands();
9598   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9599   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9600   unsigned NumElemsInLane = NumElems / NumLanes;
9601
9602   // Blend for v16i16 should be symetric for the both lanes.
9603   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9604     SDValue EltCond = BuildVector->getOperand(i);
9605     SDValue SndLaneEltCond =
9606         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9607
9608     int Lane1Cond = -1, Lane2Cond = -1;
9609     if (isa<ConstantSDNode>(EltCond))
9610       Lane1Cond = !isZero(EltCond);
9611     if (isa<ConstantSDNode>(SndLaneEltCond))
9612       Lane2Cond = !isZero(SndLaneEltCond);
9613
9614     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9615       // Lane1Cond != 0, means we want the first argument.
9616       // Lane1Cond == 0, means we want the second argument.
9617       // The encoding of this argument is 0 for the first argument, 1
9618       // for the second. Therefore, invert the condition.
9619       MaskValue |= !Lane1Cond << i;
9620     else if (Lane1Cond < 0)
9621       MaskValue |= !Lane2Cond << i;
9622     else
9623       return false;
9624   }
9625   return true;
9626 }
9627
9628 // Try to lower a vselect node into a simple blend instruction.
9629 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9630                                    SelectionDAG &DAG) {
9631   SDValue Cond = Op.getOperand(0);
9632   SDValue LHS = Op.getOperand(1);
9633   SDValue RHS = Op.getOperand(2);
9634   SDLoc dl(Op);
9635   MVT VT = Op.getSimpleValueType();
9636   MVT EltVT = VT.getVectorElementType();
9637   unsigned NumElems = VT.getVectorNumElements();
9638
9639   // There is no blend with immediate in AVX-512.
9640   if (VT.is512BitVector())
9641     return SDValue();
9642
9643   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9644     return SDValue();
9645   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9646     return SDValue();
9647
9648   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9649     return SDValue();
9650
9651   // Check the mask for BLEND and build the value.
9652   unsigned MaskValue = 0;
9653   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9654     return SDValue();
9655
9656   // Convert i32 vectors to floating point if it is not AVX2.
9657   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9658   MVT BlendVT = VT;
9659   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9660     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9661                                NumElems);
9662     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9663     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9664   }
9665
9666   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9667                             DAG.getConstant(MaskValue, MVT::i32));
9668   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9669 }
9670
9671 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9672   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9673   if (BlendOp.getNode())
9674     return BlendOp;
9675
9676   // Some types for vselect were previously set to Expand, not Legal or
9677   // Custom. Return an empty SDValue so we fall-through to Expand, after
9678   // the Custom lowering phase.
9679   MVT VT = Op.getSimpleValueType();
9680   switch (VT.SimpleTy) {
9681   default:
9682     break;
9683   case MVT::v8i16:
9684   case MVT::v16i16:
9685     return SDValue();
9686   }
9687
9688   // We couldn't create a "Blend with immediate" node.
9689   // This node should still be legal, but we'll have to emit a blendv*
9690   // instruction.
9691   return Op;
9692 }
9693
9694 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9695   MVT VT = Op.getSimpleValueType();
9696   SDLoc dl(Op);
9697
9698   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9699     return SDValue();
9700
9701   if (VT.getSizeInBits() == 8) {
9702     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9703                                   Op.getOperand(0), Op.getOperand(1));
9704     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9705                                   DAG.getValueType(VT));
9706     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9707   }
9708
9709   if (VT.getSizeInBits() == 16) {
9710     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9711     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9712     if (Idx == 0)
9713       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9714                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9715                                      DAG.getNode(ISD::BITCAST, dl,
9716                                                  MVT::v4i32,
9717                                                  Op.getOperand(0)),
9718                                      Op.getOperand(1)));
9719     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9720                                   Op.getOperand(0), Op.getOperand(1));
9721     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9722                                   DAG.getValueType(VT));
9723     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9724   }
9725
9726   if (VT == MVT::f32) {
9727     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9728     // the result back to FR32 register. It's only worth matching if the
9729     // result has a single use which is a store or a bitcast to i32.  And in
9730     // the case of a store, it's not worth it if the index is a constant 0,
9731     // because a MOVSSmr can be used instead, which is smaller and faster.
9732     if (!Op.hasOneUse())
9733       return SDValue();
9734     SDNode *User = *Op.getNode()->use_begin();
9735     if ((User->getOpcode() != ISD::STORE ||
9736          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9737           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9738         (User->getOpcode() != ISD::BITCAST ||
9739          User->getValueType(0) != MVT::i32))
9740       return SDValue();
9741     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9742                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9743                                               Op.getOperand(0)),
9744                                               Op.getOperand(1));
9745     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9746   }
9747
9748   if (VT == MVT::i32 || VT == MVT::i64) {
9749     // ExtractPS/pextrq works with constant index.
9750     if (isa<ConstantSDNode>(Op.getOperand(1)))
9751       return Op;
9752   }
9753   return SDValue();
9754 }
9755
9756 /// Extract one bit from mask vector, like v16i1 or v8i1.
9757 /// AVX-512 feature.
9758 SDValue
9759 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9760   SDValue Vec = Op.getOperand(0);
9761   SDLoc dl(Vec);
9762   MVT VecVT = Vec.getSimpleValueType();
9763   SDValue Idx = Op.getOperand(1);
9764   MVT EltVT = Op.getSimpleValueType();
9765
9766   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9767
9768   // variable index can't be handled in mask registers,
9769   // extend vector to VR512
9770   if (!isa<ConstantSDNode>(Idx)) {
9771     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9772     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9773     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9774                               ExtVT.getVectorElementType(), Ext, Idx);
9775     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9776   }
9777
9778   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9779   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9780   unsigned MaxSift = rc->getSize()*8 - 1;
9781   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9782                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9783   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9784                     DAG.getConstant(MaxSift, MVT::i8));
9785   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9786                        DAG.getIntPtrConstant(0));
9787 }
9788
9789 SDValue
9790 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9791                                            SelectionDAG &DAG) const {
9792   SDLoc dl(Op);
9793   SDValue Vec = Op.getOperand(0);
9794   MVT VecVT = Vec.getSimpleValueType();
9795   SDValue Idx = Op.getOperand(1);
9796
9797   if (Op.getSimpleValueType() == MVT::i1)
9798     return ExtractBitFromMaskVector(Op, DAG);
9799
9800   if (!isa<ConstantSDNode>(Idx)) {
9801     if (VecVT.is512BitVector() ||
9802         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9803          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9804
9805       MVT MaskEltVT =
9806         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9807       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9808                                     MaskEltVT.getSizeInBits());
9809
9810       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9811       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9812                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9813                                 Idx, DAG.getConstant(0, getPointerTy()));
9814       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9815       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9816                         Perm, DAG.getConstant(0, getPointerTy()));
9817     }
9818     return SDValue();
9819   }
9820
9821   // If this is a 256-bit vector result, first extract the 128-bit vector and
9822   // then extract the element from the 128-bit vector.
9823   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9824
9825     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9826     // Get the 128-bit vector.
9827     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9828     MVT EltVT = VecVT.getVectorElementType();
9829
9830     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9831
9832     //if (IdxVal >= NumElems/2)
9833     //  IdxVal -= NumElems/2;
9834     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9835     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9836                        DAG.getConstant(IdxVal, MVT::i32));
9837   }
9838
9839   assert(VecVT.is128BitVector() && "Unexpected vector length");
9840
9841   if (Subtarget->hasSSE41()) {
9842     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9843     if (Res.getNode())
9844       return Res;
9845   }
9846
9847   MVT VT = Op.getSimpleValueType();
9848   // TODO: handle v16i8.
9849   if (VT.getSizeInBits() == 16) {
9850     SDValue Vec = Op.getOperand(0);
9851     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9852     if (Idx == 0)
9853       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9854                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9855                                      DAG.getNode(ISD::BITCAST, dl,
9856                                                  MVT::v4i32, Vec),
9857                                      Op.getOperand(1)));
9858     // Transform it so it match pextrw which produces a 32-bit result.
9859     MVT EltVT = MVT::i32;
9860     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9861                                   Op.getOperand(0), Op.getOperand(1));
9862     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9863                                   DAG.getValueType(VT));
9864     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9865   }
9866
9867   if (VT.getSizeInBits() == 32) {
9868     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9869     if (Idx == 0)
9870       return Op;
9871
9872     // SHUFPS the element to the lowest double word, then movss.
9873     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9874     MVT VVT = Op.getOperand(0).getSimpleValueType();
9875     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9876                                        DAG.getUNDEF(VVT), Mask);
9877     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9878                        DAG.getIntPtrConstant(0));
9879   }
9880
9881   if (VT.getSizeInBits() == 64) {
9882     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9883     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9884     //        to match extract_elt for f64.
9885     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9886     if (Idx == 0)
9887       return Op;
9888
9889     // UNPCKHPD the element to the lowest double word, then movsd.
9890     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9891     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9892     int Mask[2] = { 1, -1 };
9893     MVT VVT = Op.getOperand(0).getSimpleValueType();
9894     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9895                                        DAG.getUNDEF(VVT), Mask);
9896     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9897                        DAG.getIntPtrConstant(0));
9898   }
9899
9900   return SDValue();
9901 }
9902
9903 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9904   MVT VT = Op.getSimpleValueType();
9905   MVT EltVT = VT.getVectorElementType();
9906   SDLoc dl(Op);
9907
9908   SDValue N0 = Op.getOperand(0);
9909   SDValue N1 = Op.getOperand(1);
9910   SDValue N2 = Op.getOperand(2);
9911
9912   if (!VT.is128BitVector())
9913     return SDValue();
9914
9915   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9916       isa<ConstantSDNode>(N2)) {
9917     unsigned Opc;
9918     if (VT == MVT::v8i16)
9919       Opc = X86ISD::PINSRW;
9920     else if (VT == MVT::v16i8)
9921       Opc = X86ISD::PINSRB;
9922     else
9923       Opc = X86ISD::PINSRB;
9924
9925     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9926     // argument.
9927     if (N1.getValueType() != MVT::i32)
9928       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9929     if (N2.getValueType() != MVT::i32)
9930       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9931     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9932   }
9933
9934   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9935     // Bits [7:6] of the constant are the source select.  This will always be
9936     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9937     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9938     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9939     // Bits [5:4] of the constant are the destination select.  This is the
9940     //  value of the incoming immediate.
9941     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9942     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9943     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9944     // Create this as a scalar to vector..
9945     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9946     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9947   }
9948
9949   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9950     // PINSR* works with constant index.
9951     return Op;
9952   }
9953   return SDValue();
9954 }
9955
9956 /// Insert one bit to mask vector, like v16i1 or v8i1.
9957 /// AVX-512 feature.
9958 SDValue 
9959 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9960   SDLoc dl(Op);
9961   SDValue Vec = Op.getOperand(0);
9962   SDValue Elt = Op.getOperand(1);
9963   SDValue Idx = Op.getOperand(2);
9964   MVT VecVT = Vec.getSimpleValueType();
9965
9966   if (!isa<ConstantSDNode>(Idx)) {
9967     // Non constant index. Extend source and destination,
9968     // insert element and then truncate the result.
9969     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9970     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9971     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9972       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9973       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9974     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9975   }
9976
9977   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9978   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9979   if (Vec.getOpcode() == ISD::UNDEF)
9980     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9981                        DAG.getConstant(IdxVal, MVT::i8));
9982   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9983   unsigned MaxSift = rc->getSize()*8 - 1;
9984   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9985                     DAG.getConstant(MaxSift, MVT::i8));
9986   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
9987                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9988   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
9989 }
9990 SDValue
9991 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
9992   MVT VT = Op.getSimpleValueType();
9993   MVT EltVT = VT.getVectorElementType();
9994   
9995   if (EltVT == MVT::i1)
9996     return InsertBitToMaskVector(Op, DAG);
9997
9998   SDLoc dl(Op);
9999   SDValue N0 = Op.getOperand(0);
10000   SDValue N1 = Op.getOperand(1);
10001   SDValue N2 = Op.getOperand(2);
10002
10003   // If this is a 256-bit vector result, first extract the 128-bit vector,
10004   // insert the element into the extracted half and then place it back.
10005   if (VT.is256BitVector() || VT.is512BitVector()) {
10006     if (!isa<ConstantSDNode>(N2))
10007       return SDValue();
10008
10009     // Get the desired 128-bit vector half.
10010     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10011     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10012
10013     // Insert the element into the desired half.
10014     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10015     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10016
10017     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10018                     DAG.getConstant(IdxIn128, MVT::i32));
10019
10020     // Insert the changed part back to the 256-bit vector
10021     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10022   }
10023
10024   if (Subtarget->hasSSE41())
10025     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10026
10027   if (EltVT == MVT::i8)
10028     return SDValue();
10029
10030   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10031     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10032     // as its second argument.
10033     if (N1.getValueType() != MVT::i32)
10034       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10035     if (N2.getValueType() != MVT::i32)
10036       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10037     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10038   }
10039   return SDValue();
10040 }
10041
10042 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10043   SDLoc dl(Op);
10044   MVT OpVT = Op.getSimpleValueType();
10045
10046   // If this is a 256-bit vector result, first insert into a 128-bit
10047   // vector and then insert into the 256-bit vector.
10048   if (!OpVT.is128BitVector()) {
10049     // Insert into a 128-bit vector.
10050     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10051     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10052                                  OpVT.getVectorNumElements() / SizeFactor);
10053
10054     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10055
10056     // Insert the 128-bit vector.
10057     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10058   }
10059
10060   if (OpVT == MVT::v1i64 &&
10061       Op.getOperand(0).getValueType() == MVT::i64)
10062     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10063
10064   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10065   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10066   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10067                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10068 }
10069
10070 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10071 // a simple subregister reference or explicit instructions to grab
10072 // upper bits of a vector.
10073 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10074                                       SelectionDAG &DAG) {
10075   SDLoc dl(Op);
10076   SDValue In =  Op.getOperand(0);
10077   SDValue Idx = Op.getOperand(1);
10078   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10079   MVT ResVT   = Op.getSimpleValueType();
10080   MVT InVT    = In.getSimpleValueType();
10081
10082   if (Subtarget->hasFp256()) {
10083     if (ResVT.is128BitVector() &&
10084         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10085         isa<ConstantSDNode>(Idx)) {
10086       return Extract128BitVector(In, IdxVal, DAG, dl);
10087     }
10088     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10089         isa<ConstantSDNode>(Idx)) {
10090       return Extract256BitVector(In, IdxVal, DAG, dl);
10091     }
10092   }
10093   return SDValue();
10094 }
10095
10096 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10097 // simple superregister reference or explicit instructions to insert
10098 // the upper bits of a vector.
10099 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10100                                      SelectionDAG &DAG) {
10101   if (Subtarget->hasFp256()) {
10102     SDLoc dl(Op.getNode());
10103     SDValue Vec = Op.getNode()->getOperand(0);
10104     SDValue SubVec = Op.getNode()->getOperand(1);
10105     SDValue Idx = Op.getNode()->getOperand(2);
10106
10107     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10108          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10109         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10110         isa<ConstantSDNode>(Idx)) {
10111       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10112       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10113     }
10114
10115     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10116         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10117         isa<ConstantSDNode>(Idx)) {
10118       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10119       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10120     }
10121   }
10122   return SDValue();
10123 }
10124
10125 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10126 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10127 // one of the above mentioned nodes. It has to be wrapped because otherwise
10128 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10129 // be used to form addressing mode. These wrapped nodes will be selected
10130 // into MOV32ri.
10131 SDValue
10132 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10133   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10134
10135   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10136   // global base reg.
10137   unsigned char OpFlag = 0;
10138   unsigned WrapperKind = X86ISD::Wrapper;
10139   CodeModel::Model M = DAG.getTarget().getCodeModel();
10140
10141   if (Subtarget->isPICStyleRIPRel() &&
10142       (M == CodeModel::Small || M == CodeModel::Kernel))
10143     WrapperKind = X86ISD::WrapperRIP;
10144   else if (Subtarget->isPICStyleGOT())
10145     OpFlag = X86II::MO_GOTOFF;
10146   else if (Subtarget->isPICStyleStubPIC())
10147     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10148
10149   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10150                                              CP->getAlignment(),
10151                                              CP->getOffset(), OpFlag);
10152   SDLoc DL(CP);
10153   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10154   // With PIC, the address is actually $g + Offset.
10155   if (OpFlag) {
10156     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10157                          DAG.getNode(X86ISD::GlobalBaseReg,
10158                                      SDLoc(), getPointerTy()),
10159                          Result);
10160   }
10161
10162   return Result;
10163 }
10164
10165 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10166   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10167
10168   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10169   // global base reg.
10170   unsigned char OpFlag = 0;
10171   unsigned WrapperKind = X86ISD::Wrapper;
10172   CodeModel::Model M = DAG.getTarget().getCodeModel();
10173
10174   if (Subtarget->isPICStyleRIPRel() &&
10175       (M == CodeModel::Small || M == CodeModel::Kernel))
10176     WrapperKind = X86ISD::WrapperRIP;
10177   else if (Subtarget->isPICStyleGOT())
10178     OpFlag = X86II::MO_GOTOFF;
10179   else if (Subtarget->isPICStyleStubPIC())
10180     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10181
10182   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10183                                           OpFlag);
10184   SDLoc DL(JT);
10185   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10186
10187   // With PIC, the address is actually $g + Offset.
10188   if (OpFlag)
10189     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10190                          DAG.getNode(X86ISD::GlobalBaseReg,
10191                                      SDLoc(), getPointerTy()),
10192                          Result);
10193
10194   return Result;
10195 }
10196
10197 SDValue
10198 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10199   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10200
10201   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10202   // global base reg.
10203   unsigned char OpFlag = 0;
10204   unsigned WrapperKind = X86ISD::Wrapper;
10205   CodeModel::Model M = DAG.getTarget().getCodeModel();
10206
10207   if (Subtarget->isPICStyleRIPRel() &&
10208       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10209     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10210       OpFlag = X86II::MO_GOTPCREL;
10211     WrapperKind = X86ISD::WrapperRIP;
10212   } else if (Subtarget->isPICStyleGOT()) {
10213     OpFlag = X86II::MO_GOT;
10214   } else if (Subtarget->isPICStyleStubPIC()) {
10215     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10216   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10217     OpFlag = X86II::MO_DARWIN_NONLAZY;
10218   }
10219
10220   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10221
10222   SDLoc DL(Op);
10223   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10224
10225   // With PIC, the address is actually $g + Offset.
10226   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10227       !Subtarget->is64Bit()) {
10228     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10229                          DAG.getNode(X86ISD::GlobalBaseReg,
10230                                      SDLoc(), getPointerTy()),
10231                          Result);
10232   }
10233
10234   // For symbols that require a load from a stub to get the address, emit the
10235   // load.
10236   if (isGlobalStubReference(OpFlag))
10237     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10238                          MachinePointerInfo::getGOT(), false, false, false, 0);
10239
10240   return Result;
10241 }
10242
10243 SDValue
10244 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10245   // Create the TargetBlockAddressAddress node.
10246   unsigned char OpFlags =
10247     Subtarget->ClassifyBlockAddressReference();
10248   CodeModel::Model M = DAG.getTarget().getCodeModel();
10249   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10250   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10251   SDLoc dl(Op);
10252   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10253                                              OpFlags);
10254
10255   if (Subtarget->isPICStyleRIPRel() &&
10256       (M == CodeModel::Small || M == CodeModel::Kernel))
10257     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10258   else
10259     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10260
10261   // With PIC, the address is actually $g + Offset.
10262   if (isGlobalRelativeToPICBase(OpFlags)) {
10263     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10264                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10265                          Result);
10266   }
10267
10268   return Result;
10269 }
10270
10271 SDValue
10272 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10273                                       int64_t Offset, SelectionDAG &DAG) const {
10274   // Create the TargetGlobalAddress node, folding in the constant
10275   // offset if it is legal.
10276   unsigned char OpFlags =
10277       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10278   CodeModel::Model M = DAG.getTarget().getCodeModel();
10279   SDValue Result;
10280   if (OpFlags == X86II::MO_NO_FLAG &&
10281       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10282     // A direct static reference to a global.
10283     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10284     Offset = 0;
10285   } else {
10286     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10287   }
10288
10289   if (Subtarget->isPICStyleRIPRel() &&
10290       (M == CodeModel::Small || M == CodeModel::Kernel))
10291     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10292   else
10293     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10294
10295   // With PIC, the address is actually $g + Offset.
10296   if (isGlobalRelativeToPICBase(OpFlags)) {
10297     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10298                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10299                          Result);
10300   }
10301
10302   // For globals that require a load from a stub to get the address, emit the
10303   // load.
10304   if (isGlobalStubReference(OpFlags))
10305     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10306                          MachinePointerInfo::getGOT(), false, false, false, 0);
10307
10308   // If there was a non-zero offset that we didn't fold, create an explicit
10309   // addition for it.
10310   if (Offset != 0)
10311     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10312                          DAG.getConstant(Offset, getPointerTy()));
10313
10314   return Result;
10315 }
10316
10317 SDValue
10318 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10319   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10320   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10321   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10322 }
10323
10324 static SDValue
10325 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10326            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10327            unsigned char OperandFlags, bool LocalDynamic = false) {
10328   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10329   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10330   SDLoc dl(GA);
10331   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10332                                            GA->getValueType(0),
10333                                            GA->getOffset(),
10334                                            OperandFlags);
10335
10336   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10337                                            : X86ISD::TLSADDR;
10338
10339   if (InFlag) {
10340     SDValue Ops[] = { Chain,  TGA, *InFlag };
10341     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10342   } else {
10343     SDValue Ops[]  = { Chain, TGA };
10344     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10345   }
10346
10347   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10348   MFI->setAdjustsStack(true);
10349
10350   SDValue Flag = Chain.getValue(1);
10351   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10352 }
10353
10354 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10355 static SDValue
10356 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10357                                 const EVT PtrVT) {
10358   SDValue InFlag;
10359   SDLoc dl(GA);  // ? function entry point might be better
10360   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10361                                    DAG.getNode(X86ISD::GlobalBaseReg,
10362                                                SDLoc(), PtrVT), InFlag);
10363   InFlag = Chain.getValue(1);
10364
10365   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10366 }
10367
10368 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10369 static SDValue
10370 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10371                                 const EVT PtrVT) {
10372   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10373                     X86::RAX, X86II::MO_TLSGD);
10374 }
10375
10376 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10377                                            SelectionDAG &DAG,
10378                                            const EVT PtrVT,
10379                                            bool is64Bit) {
10380   SDLoc dl(GA);
10381
10382   // Get the start address of the TLS block for this module.
10383   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10384       .getInfo<X86MachineFunctionInfo>();
10385   MFI->incNumLocalDynamicTLSAccesses();
10386
10387   SDValue Base;
10388   if (is64Bit) {
10389     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10390                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10391   } else {
10392     SDValue InFlag;
10393     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10394         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10395     InFlag = Chain.getValue(1);
10396     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10397                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10398   }
10399
10400   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10401   // of Base.
10402
10403   // Build x@dtpoff.
10404   unsigned char OperandFlags = X86II::MO_DTPOFF;
10405   unsigned WrapperKind = X86ISD::Wrapper;
10406   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10407                                            GA->getValueType(0),
10408                                            GA->getOffset(), OperandFlags);
10409   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10410
10411   // Add x@dtpoff with the base.
10412   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10413 }
10414
10415 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10416 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10417                                    const EVT PtrVT, TLSModel::Model model,
10418                                    bool is64Bit, bool isPIC) {
10419   SDLoc dl(GA);
10420
10421   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10422   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10423                                                          is64Bit ? 257 : 256));
10424
10425   SDValue ThreadPointer =
10426       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10427                   MachinePointerInfo(Ptr), false, false, false, 0);
10428
10429   unsigned char OperandFlags = 0;
10430   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10431   // initialexec.
10432   unsigned WrapperKind = X86ISD::Wrapper;
10433   if (model == TLSModel::LocalExec) {
10434     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10435   } else if (model == TLSModel::InitialExec) {
10436     if (is64Bit) {
10437       OperandFlags = X86II::MO_GOTTPOFF;
10438       WrapperKind = X86ISD::WrapperRIP;
10439     } else {
10440       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10441     }
10442   } else {
10443     llvm_unreachable("Unexpected model");
10444   }
10445
10446   // emit "addl x@ntpoff,%eax" (local exec)
10447   // or "addl x@indntpoff,%eax" (initial exec)
10448   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10449   SDValue TGA =
10450       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10451                                  GA->getOffset(), OperandFlags);
10452   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10453
10454   if (model == TLSModel::InitialExec) {
10455     if (isPIC && !is64Bit) {
10456       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10457                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10458                            Offset);
10459     }
10460
10461     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10462                          MachinePointerInfo::getGOT(), false, false, false, 0);
10463   }
10464
10465   // The address of the thread local variable is the add of the thread
10466   // pointer with the offset of the variable.
10467   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10468 }
10469
10470 SDValue
10471 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10472
10473   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10474   const GlobalValue *GV = GA->getGlobal();
10475
10476   if (Subtarget->isTargetELF()) {
10477     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10478
10479     switch (model) {
10480       case TLSModel::GeneralDynamic:
10481         if (Subtarget->is64Bit())
10482           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10483         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10484       case TLSModel::LocalDynamic:
10485         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10486                                            Subtarget->is64Bit());
10487       case TLSModel::InitialExec:
10488       case TLSModel::LocalExec:
10489         return LowerToTLSExecModel(
10490             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10491             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10492     }
10493     llvm_unreachable("Unknown TLS model.");
10494   }
10495
10496   if (Subtarget->isTargetDarwin()) {
10497     // Darwin only has one model of TLS.  Lower to that.
10498     unsigned char OpFlag = 0;
10499     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10500                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10501
10502     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10503     // global base reg.
10504     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10505                  !Subtarget->is64Bit();
10506     if (PIC32)
10507       OpFlag = X86II::MO_TLVP_PIC_BASE;
10508     else
10509       OpFlag = X86II::MO_TLVP;
10510     SDLoc DL(Op);
10511     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10512                                                 GA->getValueType(0),
10513                                                 GA->getOffset(), OpFlag);
10514     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10515
10516     // With PIC32, the address is actually $g + Offset.
10517     if (PIC32)
10518       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10519                            DAG.getNode(X86ISD::GlobalBaseReg,
10520                                        SDLoc(), getPointerTy()),
10521                            Offset);
10522
10523     // Lowering the machine isd will make sure everything is in the right
10524     // location.
10525     SDValue Chain = DAG.getEntryNode();
10526     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10527     SDValue Args[] = { Chain, Offset };
10528     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10529
10530     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10531     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10532     MFI->setAdjustsStack(true);
10533
10534     // And our return value (tls address) is in the standard call return value
10535     // location.
10536     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10537     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10538                               Chain.getValue(1));
10539   }
10540
10541   if (Subtarget->isTargetKnownWindowsMSVC() ||
10542       Subtarget->isTargetWindowsGNU()) {
10543     // Just use the implicit TLS architecture
10544     // Need to generate someting similar to:
10545     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10546     //                                  ; from TEB
10547     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10548     //   mov     rcx, qword [rdx+rcx*8]
10549     //   mov     eax, .tls$:tlsvar
10550     //   [rax+rcx] contains the address
10551     // Windows 64bit: gs:0x58
10552     // Windows 32bit: fs:__tls_array
10553
10554     SDLoc dl(GA);
10555     SDValue Chain = DAG.getEntryNode();
10556
10557     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10558     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10559     // use its literal value of 0x2C.
10560     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10561                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10562                                                              256)
10563                                         : Type::getInt32PtrTy(*DAG.getContext(),
10564                                                               257));
10565
10566     SDValue TlsArray =
10567         Subtarget->is64Bit()
10568             ? DAG.getIntPtrConstant(0x58)
10569             : (Subtarget->isTargetWindowsGNU()
10570                    ? DAG.getIntPtrConstant(0x2C)
10571                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10572
10573     SDValue ThreadPointer =
10574         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10575                     MachinePointerInfo(Ptr), false, false, false, 0);
10576
10577     // Load the _tls_index variable
10578     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10579     if (Subtarget->is64Bit())
10580       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10581                            IDX, MachinePointerInfo(), MVT::i32,
10582                            false, false, 0);
10583     else
10584       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10585                         false, false, false, 0);
10586
10587     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10588                                     getPointerTy());
10589     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10590
10591     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10592     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10593                       false, false, false, 0);
10594
10595     // Get the offset of start of .tls section
10596     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10597                                              GA->getValueType(0),
10598                                              GA->getOffset(), X86II::MO_SECREL);
10599     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10600
10601     // The address of the thread local variable is the add of the thread
10602     // pointer with the offset of the variable.
10603     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10604   }
10605
10606   llvm_unreachable("TLS not implemented for this target.");
10607 }
10608
10609 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10610 /// and take a 2 x i32 value to shift plus a shift amount.
10611 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10612   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10613   MVT VT = Op.getSimpleValueType();
10614   unsigned VTBits = VT.getSizeInBits();
10615   SDLoc dl(Op);
10616   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10617   SDValue ShOpLo = Op.getOperand(0);
10618   SDValue ShOpHi = Op.getOperand(1);
10619   SDValue ShAmt  = Op.getOperand(2);
10620   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10621   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10622   // during isel.
10623   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10624                                   DAG.getConstant(VTBits - 1, MVT::i8));
10625   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10626                                      DAG.getConstant(VTBits - 1, MVT::i8))
10627                        : DAG.getConstant(0, VT);
10628
10629   SDValue Tmp2, Tmp3;
10630   if (Op.getOpcode() == ISD::SHL_PARTS) {
10631     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10632     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10633   } else {
10634     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10635     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10636   }
10637
10638   // If the shift amount is larger or equal than the width of a part we can't
10639   // rely on the results of shld/shrd. Insert a test and select the appropriate
10640   // values for large shift amounts.
10641   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10642                                 DAG.getConstant(VTBits, MVT::i8));
10643   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10644                              AndNode, DAG.getConstant(0, MVT::i8));
10645
10646   SDValue Hi, Lo;
10647   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10648   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10649   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10650
10651   if (Op.getOpcode() == ISD::SHL_PARTS) {
10652     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10653     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10654   } else {
10655     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10656     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10657   }
10658
10659   SDValue Ops[2] = { Lo, Hi };
10660   return DAG.getMergeValues(Ops, dl);
10661 }
10662
10663 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10664                                            SelectionDAG &DAG) const {
10665   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10666
10667   if (SrcVT.isVector())
10668     return SDValue();
10669
10670   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10671          "Unknown SINT_TO_FP to lower!");
10672
10673   // These are really Legal; return the operand so the caller accepts it as
10674   // Legal.
10675   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10676     return Op;
10677   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10678       Subtarget->is64Bit()) {
10679     return Op;
10680   }
10681
10682   SDLoc dl(Op);
10683   unsigned Size = SrcVT.getSizeInBits()/8;
10684   MachineFunction &MF = DAG.getMachineFunction();
10685   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10686   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10687   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10688                                StackSlot,
10689                                MachinePointerInfo::getFixedStack(SSFI),
10690                                false, false, 0);
10691   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10692 }
10693
10694 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10695                                      SDValue StackSlot,
10696                                      SelectionDAG &DAG) const {
10697   // Build the FILD
10698   SDLoc DL(Op);
10699   SDVTList Tys;
10700   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10701   if (useSSE)
10702     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10703   else
10704     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10705
10706   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10707
10708   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10709   MachineMemOperand *MMO;
10710   if (FI) {
10711     int SSFI = FI->getIndex();
10712     MMO =
10713       DAG.getMachineFunction()
10714       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10715                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10716   } else {
10717     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10718     StackSlot = StackSlot.getOperand(1);
10719   }
10720   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10721   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10722                                            X86ISD::FILD, DL,
10723                                            Tys, Ops, SrcVT, MMO);
10724
10725   if (useSSE) {
10726     Chain = Result.getValue(1);
10727     SDValue InFlag = Result.getValue(2);
10728
10729     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10730     // shouldn't be necessary except that RFP cannot be live across
10731     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10732     MachineFunction &MF = DAG.getMachineFunction();
10733     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10734     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10735     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10736     Tys = DAG.getVTList(MVT::Other);
10737     SDValue Ops[] = {
10738       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10739     };
10740     MachineMemOperand *MMO =
10741       DAG.getMachineFunction()
10742       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10743                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10744
10745     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10746                                     Ops, Op.getValueType(), MMO);
10747     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10748                          MachinePointerInfo::getFixedStack(SSFI),
10749                          false, false, false, 0);
10750   }
10751
10752   return Result;
10753 }
10754
10755 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10756 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10757                                                SelectionDAG &DAG) const {
10758   // This algorithm is not obvious. Here it is what we're trying to output:
10759   /*
10760      movq       %rax,  %xmm0
10761      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10762      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10763      #ifdef __SSE3__
10764        haddpd   %xmm0, %xmm0
10765      #else
10766        pshufd   $0x4e, %xmm0, %xmm1
10767        addpd    %xmm1, %xmm0
10768      #endif
10769   */
10770
10771   SDLoc dl(Op);
10772   LLVMContext *Context = DAG.getContext();
10773
10774   // Build some magic constants.
10775   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10776   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10777   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10778
10779   SmallVector<Constant*,2> CV1;
10780   CV1.push_back(
10781     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10782                                       APInt(64, 0x4330000000000000ULL))));
10783   CV1.push_back(
10784     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10785                                       APInt(64, 0x4530000000000000ULL))));
10786   Constant *C1 = ConstantVector::get(CV1);
10787   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10788
10789   // Load the 64-bit value into an XMM register.
10790   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10791                             Op.getOperand(0));
10792   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10793                               MachinePointerInfo::getConstantPool(),
10794                               false, false, false, 16);
10795   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10796                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10797                               CLod0);
10798
10799   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10800                               MachinePointerInfo::getConstantPool(),
10801                               false, false, false, 16);
10802   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10803   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10804   SDValue Result;
10805
10806   if (Subtarget->hasSSE3()) {
10807     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10808     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10809   } else {
10810     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10811     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10812                                            S2F, 0x4E, DAG);
10813     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10814                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10815                          Sub);
10816   }
10817
10818   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10819                      DAG.getIntPtrConstant(0));
10820 }
10821
10822 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10823 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10824                                                SelectionDAG &DAG) const {
10825   SDLoc dl(Op);
10826   // FP constant to bias correct the final result.
10827   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10828                                    MVT::f64);
10829
10830   // Load the 32-bit value into an XMM register.
10831   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10832                              Op.getOperand(0));
10833
10834   // Zero out the upper parts of the register.
10835   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10836
10837   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10838                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10839                      DAG.getIntPtrConstant(0));
10840
10841   // Or the load with the bias.
10842   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10843                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10844                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10845                                                    MVT::v2f64, Load)),
10846                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10847                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10848                                                    MVT::v2f64, Bias)));
10849   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10850                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10851                    DAG.getIntPtrConstant(0));
10852
10853   // Subtract the bias.
10854   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10855
10856   // Handle final rounding.
10857   EVT DestVT = Op.getValueType();
10858
10859   if (DestVT.bitsLT(MVT::f64))
10860     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10861                        DAG.getIntPtrConstant(0));
10862   if (DestVT.bitsGT(MVT::f64))
10863     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10864
10865   // Handle final rounding.
10866   return Sub;
10867 }
10868
10869 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10870                                                SelectionDAG &DAG) const {
10871   SDValue N0 = Op.getOperand(0);
10872   MVT SVT = N0.getSimpleValueType();
10873   SDLoc dl(Op);
10874
10875   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10876           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10877          "Custom UINT_TO_FP is not supported!");
10878
10879   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10880   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10881                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10882 }
10883
10884 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10885                                            SelectionDAG &DAG) const {
10886   SDValue N0 = Op.getOperand(0);
10887   SDLoc dl(Op);
10888
10889   if (Op.getValueType().isVector())
10890     return lowerUINT_TO_FP_vec(Op, DAG);
10891
10892   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10893   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10894   // the optimization here.
10895   if (DAG.SignBitIsZero(N0))
10896     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10897
10898   MVT SrcVT = N0.getSimpleValueType();
10899   MVT DstVT = Op.getSimpleValueType();
10900   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10901     return LowerUINT_TO_FP_i64(Op, DAG);
10902   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10903     return LowerUINT_TO_FP_i32(Op, DAG);
10904   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10905     return SDValue();
10906
10907   // Make a 64-bit buffer, and use it to build an FILD.
10908   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10909   if (SrcVT == MVT::i32) {
10910     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10911     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10912                                      getPointerTy(), StackSlot, WordOff);
10913     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10914                                   StackSlot, MachinePointerInfo(),
10915                                   false, false, 0);
10916     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10917                                   OffsetSlot, MachinePointerInfo(),
10918                                   false, false, 0);
10919     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10920     return Fild;
10921   }
10922
10923   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10924   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10925                                StackSlot, MachinePointerInfo(),
10926                                false, false, 0);
10927   // For i64 source, we need to add the appropriate power of 2 if the input
10928   // was negative.  This is the same as the optimization in
10929   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10930   // we must be careful to do the computation in x87 extended precision, not
10931   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10932   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10933   MachineMemOperand *MMO =
10934     DAG.getMachineFunction()
10935     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10936                           MachineMemOperand::MOLoad, 8, 8);
10937
10938   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10939   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10940   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10941                                          MVT::i64, MMO);
10942
10943   APInt FF(32, 0x5F800000ULL);
10944
10945   // Check whether the sign bit is set.
10946   SDValue SignSet = DAG.getSetCC(dl,
10947                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10948                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10949                                  ISD::SETLT);
10950
10951   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10952   SDValue FudgePtr = DAG.getConstantPool(
10953                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10954                                          getPointerTy());
10955
10956   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10957   SDValue Zero = DAG.getIntPtrConstant(0);
10958   SDValue Four = DAG.getIntPtrConstant(4);
10959   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10960                                Zero, Four);
10961   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10962
10963   // Load the value out, extending it from f32 to f80.
10964   // FIXME: Avoid the extend by constructing the right constant pool?
10965   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10966                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10967                                  MVT::f32, false, false, 4);
10968   // Extend everything to 80 bits to force it to be done on x87.
10969   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10970   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10971 }
10972
10973 std::pair<SDValue,SDValue>
10974 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10975                                     bool IsSigned, bool IsReplace) const {
10976   SDLoc DL(Op);
10977
10978   EVT DstTy = Op.getValueType();
10979
10980   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10981     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10982     DstTy = MVT::i64;
10983   }
10984
10985   assert(DstTy.getSimpleVT() <= MVT::i64 &&
10986          DstTy.getSimpleVT() >= MVT::i16 &&
10987          "Unknown FP_TO_INT to lower!");
10988
10989   // These are really Legal.
10990   if (DstTy == MVT::i32 &&
10991       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10992     return std::make_pair(SDValue(), SDValue());
10993   if (Subtarget->is64Bit() &&
10994       DstTy == MVT::i64 &&
10995       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
10996     return std::make_pair(SDValue(), SDValue());
10997
10998   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
10999   // stack slot, or into the FTOL runtime function.
11000   MachineFunction &MF = DAG.getMachineFunction();
11001   unsigned MemSize = DstTy.getSizeInBits()/8;
11002   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11003   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11004
11005   unsigned Opc;
11006   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11007     Opc = X86ISD::WIN_FTOL;
11008   else
11009     switch (DstTy.getSimpleVT().SimpleTy) {
11010     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11011     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11012     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11013     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11014     }
11015
11016   SDValue Chain = DAG.getEntryNode();
11017   SDValue Value = Op.getOperand(0);
11018   EVT TheVT = Op.getOperand(0).getValueType();
11019   // FIXME This causes a redundant load/store if the SSE-class value is already
11020   // in memory, such as if it is on the callstack.
11021   if (isScalarFPTypeInSSEReg(TheVT)) {
11022     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11023     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11024                          MachinePointerInfo::getFixedStack(SSFI),
11025                          false, false, 0);
11026     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11027     SDValue Ops[] = {
11028       Chain, StackSlot, DAG.getValueType(TheVT)
11029     };
11030
11031     MachineMemOperand *MMO =
11032       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11033                               MachineMemOperand::MOLoad, MemSize, MemSize);
11034     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11035     Chain = Value.getValue(1);
11036     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11037     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11038   }
11039
11040   MachineMemOperand *MMO =
11041     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11042                             MachineMemOperand::MOStore, MemSize, MemSize);
11043
11044   if (Opc != X86ISD::WIN_FTOL) {
11045     // Build the FP_TO_INT*_IN_MEM
11046     SDValue Ops[] = { Chain, Value, StackSlot };
11047     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11048                                            Ops, DstTy, MMO);
11049     return std::make_pair(FIST, StackSlot);
11050   } else {
11051     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11052       DAG.getVTList(MVT::Other, MVT::Glue),
11053       Chain, Value);
11054     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11055       MVT::i32, ftol.getValue(1));
11056     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11057       MVT::i32, eax.getValue(2));
11058     SDValue Ops[] = { eax, edx };
11059     SDValue pair = IsReplace
11060       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11061       : DAG.getMergeValues(Ops, DL);
11062     return std::make_pair(pair, SDValue());
11063   }
11064 }
11065
11066 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11067                               const X86Subtarget *Subtarget) {
11068   MVT VT = Op->getSimpleValueType(0);
11069   SDValue In = Op->getOperand(0);
11070   MVT InVT = In.getSimpleValueType();
11071   SDLoc dl(Op);
11072
11073   // Optimize vectors in AVX mode:
11074   //
11075   //   v8i16 -> v8i32
11076   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11077   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11078   //   Concat upper and lower parts.
11079   //
11080   //   v4i32 -> v4i64
11081   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11082   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11083   //   Concat upper and lower parts.
11084   //
11085
11086   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11087       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11088       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11089     return SDValue();
11090
11091   if (Subtarget->hasInt256())
11092     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11093
11094   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11095   SDValue Undef = DAG.getUNDEF(InVT);
11096   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11097   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11098   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11099
11100   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11101                              VT.getVectorNumElements()/2);
11102
11103   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11104   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11105
11106   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11107 }
11108
11109 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11110                                         SelectionDAG &DAG) {
11111   MVT VT = Op->getSimpleValueType(0);
11112   SDValue In = Op->getOperand(0);
11113   MVT InVT = In.getSimpleValueType();
11114   SDLoc DL(Op);
11115   unsigned int NumElts = VT.getVectorNumElements();
11116   if (NumElts != 8 && NumElts != 16)
11117     return SDValue();
11118
11119   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11120     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11121
11122   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11123   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11124   // Now we have only mask extension
11125   assert(InVT.getVectorElementType() == MVT::i1);
11126   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11127   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11128   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11129   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11130   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11131                            MachinePointerInfo::getConstantPool(),
11132                            false, false, false, Alignment);
11133
11134   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11135   if (VT.is512BitVector())
11136     return Brcst;
11137   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11138 }
11139
11140 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11141                                SelectionDAG &DAG) {
11142   if (Subtarget->hasFp256()) {
11143     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11144     if (Res.getNode())
11145       return Res;
11146   }
11147
11148   return SDValue();
11149 }
11150
11151 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11152                                 SelectionDAG &DAG) {
11153   SDLoc DL(Op);
11154   MVT VT = Op.getSimpleValueType();
11155   SDValue In = Op.getOperand(0);
11156   MVT SVT = In.getSimpleValueType();
11157
11158   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11159     return LowerZERO_EXTEND_AVX512(Op, DAG);
11160
11161   if (Subtarget->hasFp256()) {
11162     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11163     if (Res.getNode())
11164       return Res;
11165   }
11166
11167   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11168          VT.getVectorNumElements() != SVT.getVectorNumElements());
11169   return SDValue();
11170 }
11171
11172 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11173   SDLoc DL(Op);
11174   MVT VT = Op.getSimpleValueType();
11175   SDValue In = Op.getOperand(0);
11176   MVT InVT = In.getSimpleValueType();
11177
11178   if (VT == MVT::i1) {
11179     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11180            "Invalid scalar TRUNCATE operation");
11181     if (InVT == MVT::i32)
11182       return SDValue();
11183     if (InVT.getSizeInBits() == 64)
11184       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11185     else if (InVT.getSizeInBits() < 32)
11186       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11187     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11188   }
11189   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11190          "Invalid TRUNCATE operation");
11191
11192   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11193     if (VT.getVectorElementType().getSizeInBits() >=8)
11194       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11195
11196     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11197     unsigned NumElts = InVT.getVectorNumElements();
11198     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11199     if (InVT.getSizeInBits() < 512) {
11200       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11201       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11202       InVT = ExtVT;
11203     }
11204     
11205     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11206     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11207     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11208     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11209     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11210                            MachinePointerInfo::getConstantPool(),
11211                            false, false, false, Alignment);
11212     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11213     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11214     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11215   }
11216
11217   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11218     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11219     if (Subtarget->hasInt256()) {
11220       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11221       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11222       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11223                                 ShufMask);
11224       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11225                          DAG.getIntPtrConstant(0));
11226     }
11227
11228     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11229                                DAG.getIntPtrConstant(0));
11230     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11231                                DAG.getIntPtrConstant(2));
11232     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11233     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11234     static const int ShufMask[] = {0, 2, 4, 6};
11235     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11236   }
11237
11238   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11239     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11240     if (Subtarget->hasInt256()) {
11241       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11242
11243       SmallVector<SDValue,32> pshufbMask;
11244       for (unsigned i = 0; i < 2; ++i) {
11245         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11246         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11247         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11248         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11249         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11250         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11251         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11252         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11253         for (unsigned j = 0; j < 8; ++j)
11254           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11255       }
11256       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11257       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11258       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11259
11260       static const int ShufMask[] = {0,  2,  -1,  -1};
11261       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11262                                 &ShufMask[0]);
11263       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11264                        DAG.getIntPtrConstant(0));
11265       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11266     }
11267
11268     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11269                                DAG.getIntPtrConstant(0));
11270
11271     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11272                                DAG.getIntPtrConstant(4));
11273
11274     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11275     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11276
11277     // The PSHUFB mask:
11278     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11279                                    -1, -1, -1, -1, -1, -1, -1, -1};
11280
11281     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11282     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11283     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11284
11285     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11286     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11287
11288     // The MOVLHPS Mask:
11289     static const int ShufMask2[] = {0, 1, 4, 5};
11290     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11291     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11292   }
11293
11294   // Handle truncation of V256 to V128 using shuffles.
11295   if (!VT.is128BitVector() || !InVT.is256BitVector())
11296     return SDValue();
11297
11298   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11299
11300   unsigned NumElems = VT.getVectorNumElements();
11301   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11302
11303   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11304   // Prepare truncation shuffle mask
11305   for (unsigned i = 0; i != NumElems; ++i)
11306     MaskVec[i] = i * 2;
11307   SDValue V = DAG.getVectorShuffle(NVT, DL,
11308                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11309                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11310   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11311                      DAG.getIntPtrConstant(0));
11312 }
11313
11314 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11315                                            SelectionDAG &DAG) const {
11316   assert(!Op.getSimpleValueType().isVector());
11317
11318   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11319     /*IsSigned=*/ true, /*IsReplace=*/ false);
11320   SDValue FIST = Vals.first, StackSlot = Vals.second;
11321   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11322   if (!FIST.getNode()) return Op;
11323
11324   if (StackSlot.getNode())
11325     // Load the result.
11326     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11327                        FIST, StackSlot, MachinePointerInfo(),
11328                        false, false, false, 0);
11329
11330   // The node is the result.
11331   return FIST;
11332 }
11333
11334 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11335                                            SelectionDAG &DAG) const {
11336   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11337     /*IsSigned=*/ false, /*IsReplace=*/ false);
11338   SDValue FIST = Vals.first, StackSlot = Vals.second;
11339   assert(FIST.getNode() && "Unexpected failure");
11340
11341   if (StackSlot.getNode())
11342     // Load the result.
11343     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11344                        FIST, StackSlot, MachinePointerInfo(),
11345                        false, false, false, 0);
11346
11347   // The node is the result.
11348   return FIST;
11349 }
11350
11351 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11352   SDLoc DL(Op);
11353   MVT VT = Op.getSimpleValueType();
11354   SDValue In = Op.getOperand(0);
11355   MVT SVT = In.getSimpleValueType();
11356
11357   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11358
11359   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11360                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11361                                  In, DAG.getUNDEF(SVT)));
11362 }
11363
11364 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11365   LLVMContext *Context = DAG.getContext();
11366   SDLoc dl(Op);
11367   MVT VT = Op.getSimpleValueType();
11368   MVT EltVT = VT;
11369   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11370   if (VT.isVector()) {
11371     EltVT = VT.getVectorElementType();
11372     NumElts = VT.getVectorNumElements();
11373   }
11374   Constant *C;
11375   if (EltVT == MVT::f64)
11376     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11377                                           APInt(64, ~(1ULL << 63))));
11378   else
11379     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11380                                           APInt(32, ~(1U << 31))));
11381   C = ConstantVector::getSplat(NumElts, C);
11382   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11383   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11384   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11385   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11386                              MachinePointerInfo::getConstantPool(),
11387                              false, false, false, Alignment);
11388   if (VT.isVector()) {
11389     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11390     return DAG.getNode(ISD::BITCAST, dl, VT,
11391                        DAG.getNode(ISD::AND, dl, ANDVT,
11392                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11393                                                Op.getOperand(0)),
11394                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11395   }
11396   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11397 }
11398
11399 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11400   LLVMContext *Context = DAG.getContext();
11401   SDLoc dl(Op);
11402   MVT VT = Op.getSimpleValueType();
11403   MVT EltVT = VT;
11404   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11405   if (VT.isVector()) {
11406     EltVT = VT.getVectorElementType();
11407     NumElts = VT.getVectorNumElements();
11408   }
11409   Constant *C;
11410   if (EltVT == MVT::f64)
11411     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11412                                           APInt(64, 1ULL << 63)));
11413   else
11414     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11415                                           APInt(32, 1U << 31)));
11416   C = ConstantVector::getSplat(NumElts, C);
11417   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11418   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11419   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11420   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11421                              MachinePointerInfo::getConstantPool(),
11422                              false, false, false, Alignment);
11423   if (VT.isVector()) {
11424     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11425     return DAG.getNode(ISD::BITCAST, dl, VT,
11426                        DAG.getNode(ISD::XOR, dl, XORVT,
11427                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11428                                                Op.getOperand(0)),
11429                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11430   }
11431
11432   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11433 }
11434
11435 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11437   LLVMContext *Context = DAG.getContext();
11438   SDValue Op0 = Op.getOperand(0);
11439   SDValue Op1 = Op.getOperand(1);
11440   SDLoc dl(Op);
11441   MVT VT = Op.getSimpleValueType();
11442   MVT SrcVT = Op1.getSimpleValueType();
11443
11444   // If second operand is smaller, extend it first.
11445   if (SrcVT.bitsLT(VT)) {
11446     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11447     SrcVT = VT;
11448   }
11449   // And if it is bigger, shrink it first.
11450   if (SrcVT.bitsGT(VT)) {
11451     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11452     SrcVT = VT;
11453   }
11454
11455   // At this point the operands and the result should have the same
11456   // type, and that won't be f80 since that is not custom lowered.
11457
11458   // First get the sign bit of second operand.
11459   SmallVector<Constant*,4> CV;
11460   if (SrcVT == MVT::f64) {
11461     const fltSemantics &Sem = APFloat::IEEEdouble;
11462     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11463     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11464   } else {
11465     const fltSemantics &Sem = APFloat::IEEEsingle;
11466     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11467     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11468     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11469     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11470   }
11471   Constant *C = ConstantVector::get(CV);
11472   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11473   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11474                               MachinePointerInfo::getConstantPool(),
11475                               false, false, false, 16);
11476   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11477
11478   // Shift sign bit right or left if the two operands have different types.
11479   if (SrcVT.bitsGT(VT)) {
11480     // Op0 is MVT::f32, Op1 is MVT::f64.
11481     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11482     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11483                           DAG.getConstant(32, MVT::i32));
11484     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11485     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11486                           DAG.getIntPtrConstant(0));
11487   }
11488
11489   // Clear first operand sign bit.
11490   CV.clear();
11491   if (VT == MVT::f64) {
11492     const fltSemantics &Sem = APFloat::IEEEdouble;
11493     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11494                                                    APInt(64, ~(1ULL << 63)))));
11495     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11496   } else {
11497     const fltSemantics &Sem = APFloat::IEEEsingle;
11498     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11499                                                    APInt(32, ~(1U << 31)))));
11500     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11501     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11502     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11503   }
11504   C = ConstantVector::get(CV);
11505   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11506   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11507                               MachinePointerInfo::getConstantPool(),
11508                               false, false, false, 16);
11509   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11510
11511   // Or the value with the sign bit.
11512   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11513 }
11514
11515 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11516   SDValue N0 = Op.getOperand(0);
11517   SDLoc dl(Op);
11518   MVT VT = Op.getSimpleValueType();
11519
11520   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11521   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11522                                   DAG.getConstant(1, VT));
11523   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11524 }
11525
11526 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11527 //
11528 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11529                                       SelectionDAG &DAG) {
11530   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11531
11532   if (!Subtarget->hasSSE41())
11533     return SDValue();
11534
11535   if (!Op->hasOneUse())
11536     return SDValue();
11537
11538   SDNode *N = Op.getNode();
11539   SDLoc DL(N);
11540
11541   SmallVector<SDValue, 8> Opnds;
11542   DenseMap<SDValue, unsigned> VecInMap;
11543   SmallVector<SDValue, 8> VecIns;
11544   EVT VT = MVT::Other;
11545
11546   // Recognize a special case where a vector is casted into wide integer to
11547   // test all 0s.
11548   Opnds.push_back(N->getOperand(0));
11549   Opnds.push_back(N->getOperand(1));
11550
11551   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11552     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11553     // BFS traverse all OR'd operands.
11554     if (I->getOpcode() == ISD::OR) {
11555       Opnds.push_back(I->getOperand(0));
11556       Opnds.push_back(I->getOperand(1));
11557       // Re-evaluate the number of nodes to be traversed.
11558       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11559       continue;
11560     }
11561
11562     // Quit if a non-EXTRACT_VECTOR_ELT
11563     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11564       return SDValue();
11565
11566     // Quit if without a constant index.
11567     SDValue Idx = I->getOperand(1);
11568     if (!isa<ConstantSDNode>(Idx))
11569       return SDValue();
11570
11571     SDValue ExtractedFromVec = I->getOperand(0);
11572     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11573     if (M == VecInMap.end()) {
11574       VT = ExtractedFromVec.getValueType();
11575       // Quit if not 128/256-bit vector.
11576       if (!VT.is128BitVector() && !VT.is256BitVector())
11577         return SDValue();
11578       // Quit if not the same type.
11579       if (VecInMap.begin() != VecInMap.end() &&
11580           VT != VecInMap.begin()->first.getValueType())
11581         return SDValue();
11582       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11583       VecIns.push_back(ExtractedFromVec);
11584     }
11585     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11586   }
11587
11588   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11589          "Not extracted from 128-/256-bit vector.");
11590
11591   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11592
11593   for (DenseMap<SDValue, unsigned>::const_iterator
11594         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11595     // Quit if not all elements are used.
11596     if (I->second != FullMask)
11597       return SDValue();
11598   }
11599
11600   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11601
11602   // Cast all vectors into TestVT for PTEST.
11603   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11604     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11605
11606   // If more than one full vectors are evaluated, OR them first before PTEST.
11607   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11608     // Each iteration will OR 2 nodes and append the result until there is only
11609     // 1 node left, i.e. the final OR'd value of all vectors.
11610     SDValue LHS = VecIns[Slot];
11611     SDValue RHS = VecIns[Slot + 1];
11612     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11613   }
11614
11615   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11616                      VecIns.back(), VecIns.back());
11617 }
11618
11619 /// \brief return true if \c Op has a use that doesn't just read flags.
11620 static bool hasNonFlagsUse(SDValue Op) {
11621   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11622        ++UI) {
11623     SDNode *User = *UI;
11624     unsigned UOpNo = UI.getOperandNo();
11625     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11626       // Look pass truncate.
11627       UOpNo = User->use_begin().getOperandNo();
11628       User = *User->use_begin();
11629     }
11630
11631     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11632         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11633       return true;
11634   }
11635   return false;
11636 }
11637
11638 /// Emit nodes that will be selected as "test Op0,Op0", or something
11639 /// equivalent.
11640 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11641                                     SelectionDAG &DAG) const {
11642   if (Op.getValueType() == MVT::i1)
11643     // KORTEST instruction should be selected
11644     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11645                        DAG.getConstant(0, Op.getValueType()));
11646
11647   // CF and OF aren't always set the way we want. Determine which
11648   // of these we need.
11649   bool NeedCF = false;
11650   bool NeedOF = false;
11651   switch (X86CC) {
11652   default: break;
11653   case X86::COND_A: case X86::COND_AE:
11654   case X86::COND_B: case X86::COND_BE:
11655     NeedCF = true;
11656     break;
11657   case X86::COND_G: case X86::COND_GE:
11658   case X86::COND_L: case X86::COND_LE:
11659   case X86::COND_O: case X86::COND_NO: {
11660     // Check if we really need to set the
11661     // Overflow flag. If NoSignedWrap is present
11662     // that is not actually needed.
11663     switch (Op->getOpcode()) {
11664     case ISD::ADD:
11665     case ISD::SUB:
11666     case ISD::MUL:
11667     case ISD::SHL: {
11668       const BinaryWithFlagsSDNode *BinNode =
11669           cast<BinaryWithFlagsSDNode>(Op.getNode());
11670       if (BinNode->hasNoSignedWrap())
11671         break;
11672     }
11673     default:
11674       NeedOF = true;
11675       break;
11676     }
11677     break;
11678   }
11679   }
11680   // See if we can use the EFLAGS value from the operand instead of
11681   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11682   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11683   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11684     // Emit a CMP with 0, which is the TEST pattern.
11685     //if (Op.getValueType() == MVT::i1)
11686     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11687     //                     DAG.getConstant(0, MVT::i1));
11688     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11689                        DAG.getConstant(0, Op.getValueType()));
11690   }
11691   unsigned Opcode = 0;
11692   unsigned NumOperands = 0;
11693
11694   // Truncate operations may prevent the merge of the SETCC instruction
11695   // and the arithmetic instruction before it. Attempt to truncate the operands
11696   // of the arithmetic instruction and use a reduced bit-width instruction.
11697   bool NeedTruncation = false;
11698   SDValue ArithOp = Op;
11699   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11700     SDValue Arith = Op->getOperand(0);
11701     // Both the trunc and the arithmetic op need to have one user each.
11702     if (Arith->hasOneUse())
11703       switch (Arith.getOpcode()) {
11704         default: break;
11705         case ISD::ADD:
11706         case ISD::SUB:
11707         case ISD::AND:
11708         case ISD::OR:
11709         case ISD::XOR: {
11710           NeedTruncation = true;
11711           ArithOp = Arith;
11712         }
11713       }
11714   }
11715
11716   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11717   // which may be the result of a CAST.  We use the variable 'Op', which is the
11718   // non-casted variable when we check for possible users.
11719   switch (ArithOp.getOpcode()) {
11720   case ISD::ADD:
11721     // Due to an isel shortcoming, be conservative if this add is likely to be
11722     // selected as part of a load-modify-store instruction. When the root node
11723     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11724     // uses of other nodes in the match, such as the ADD in this case. This
11725     // leads to the ADD being left around and reselected, with the result being
11726     // two adds in the output.  Alas, even if none our users are stores, that
11727     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11728     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11729     // climbing the DAG back to the root, and it doesn't seem to be worth the
11730     // effort.
11731     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11732          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11733       if (UI->getOpcode() != ISD::CopyToReg &&
11734           UI->getOpcode() != ISD::SETCC &&
11735           UI->getOpcode() != ISD::STORE)
11736         goto default_case;
11737
11738     if (ConstantSDNode *C =
11739         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11740       // An add of one will be selected as an INC.
11741       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11742         Opcode = X86ISD::INC;
11743         NumOperands = 1;
11744         break;
11745       }
11746
11747       // An add of negative one (subtract of one) will be selected as a DEC.
11748       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11749         Opcode = X86ISD::DEC;
11750         NumOperands = 1;
11751         break;
11752       }
11753     }
11754
11755     // Otherwise use a regular EFLAGS-setting add.
11756     Opcode = X86ISD::ADD;
11757     NumOperands = 2;
11758     break;
11759   case ISD::SHL:
11760   case ISD::SRL:
11761     // If we have a constant logical shift that's only used in a comparison
11762     // against zero turn it into an equivalent AND. This allows turning it into
11763     // a TEST instruction later.
11764     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11765         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11766       EVT VT = Op.getValueType();
11767       unsigned BitWidth = VT.getSizeInBits();
11768       unsigned ShAmt = Op->getConstantOperandVal(1);
11769       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11770         break;
11771       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11772                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11773                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11774       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11775         break;
11776       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11777                                 DAG.getConstant(Mask, VT));
11778       DAG.ReplaceAllUsesWith(Op, New);
11779       Op = New;
11780     }
11781     break;
11782
11783   case ISD::AND:
11784     // If the primary and result isn't used, don't bother using X86ISD::AND,
11785     // because a TEST instruction will be better.
11786     if (!hasNonFlagsUse(Op))
11787       break;
11788     // FALL THROUGH
11789   case ISD::SUB:
11790   case ISD::OR:
11791   case ISD::XOR:
11792     // Due to the ISEL shortcoming noted above, be conservative if this op is
11793     // likely to be selected as part of a load-modify-store instruction.
11794     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11795            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11796       if (UI->getOpcode() == ISD::STORE)
11797         goto default_case;
11798
11799     // Otherwise use a regular EFLAGS-setting instruction.
11800     switch (ArithOp.getOpcode()) {
11801     default: llvm_unreachable("unexpected operator!");
11802     case ISD::SUB: Opcode = X86ISD::SUB; break;
11803     case ISD::XOR: Opcode = X86ISD::XOR; break;
11804     case ISD::AND: Opcode = X86ISD::AND; break;
11805     case ISD::OR: {
11806       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11807         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11808         if (EFLAGS.getNode())
11809           return EFLAGS;
11810       }
11811       Opcode = X86ISD::OR;
11812       break;
11813     }
11814     }
11815
11816     NumOperands = 2;
11817     break;
11818   case X86ISD::ADD:
11819   case X86ISD::SUB:
11820   case X86ISD::INC:
11821   case X86ISD::DEC:
11822   case X86ISD::OR:
11823   case X86ISD::XOR:
11824   case X86ISD::AND:
11825     return SDValue(Op.getNode(), 1);
11826   default:
11827   default_case:
11828     break;
11829   }
11830
11831   // If we found that truncation is beneficial, perform the truncation and
11832   // update 'Op'.
11833   if (NeedTruncation) {
11834     EVT VT = Op.getValueType();
11835     SDValue WideVal = Op->getOperand(0);
11836     EVT WideVT = WideVal.getValueType();
11837     unsigned ConvertedOp = 0;
11838     // Use a target machine opcode to prevent further DAGCombine
11839     // optimizations that may separate the arithmetic operations
11840     // from the setcc node.
11841     switch (WideVal.getOpcode()) {
11842       default: break;
11843       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11844       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11845       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11846       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11847       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11848     }
11849
11850     if (ConvertedOp) {
11851       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11852       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11853         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11854         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11855         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11856       }
11857     }
11858   }
11859
11860   if (Opcode == 0)
11861     // Emit a CMP with 0, which is the TEST pattern.
11862     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11863                        DAG.getConstant(0, Op.getValueType()));
11864
11865   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11866   SmallVector<SDValue, 4> Ops;
11867   for (unsigned i = 0; i != NumOperands; ++i)
11868     Ops.push_back(Op.getOperand(i));
11869
11870   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11871   DAG.ReplaceAllUsesWith(Op, New);
11872   return SDValue(New.getNode(), 1);
11873 }
11874
11875 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11876 /// equivalent.
11877 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11878                                    SDLoc dl, SelectionDAG &DAG) const {
11879   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11880     if (C->getAPIntValue() == 0)
11881       return EmitTest(Op0, X86CC, dl, DAG);
11882
11883      if (Op0.getValueType() == MVT::i1)
11884        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11885   }
11886  
11887   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11888        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11889     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11890     // This avoids subregister aliasing issues. Keep the smaller reference 
11891     // if we're optimizing for size, however, as that'll allow better folding 
11892     // of memory operations.
11893     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11894         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11895              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11896         !Subtarget->isAtom()) {
11897       unsigned ExtendOp =
11898           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11899       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11900       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11901     }
11902     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11903     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11904     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11905                               Op0, Op1);
11906     return SDValue(Sub.getNode(), 1);
11907   }
11908   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11909 }
11910
11911 /// Convert a comparison if required by the subtarget.
11912 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11913                                                  SelectionDAG &DAG) const {
11914   // If the subtarget does not support the FUCOMI instruction, floating-point
11915   // comparisons have to be converted.
11916   if (Subtarget->hasCMov() ||
11917       Cmp.getOpcode() != X86ISD::CMP ||
11918       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11919       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11920     return Cmp;
11921
11922   // The instruction selector will select an FUCOM instruction instead of
11923   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11924   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11925   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11926   SDLoc dl(Cmp);
11927   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11928   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11929   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11930                             DAG.getConstant(8, MVT::i8));
11931   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11932   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11933 }
11934
11935 static bool isAllOnes(SDValue V) {
11936   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11937   return C && C->isAllOnesValue();
11938 }
11939
11940 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11941 /// if it's possible.
11942 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11943                                      SDLoc dl, SelectionDAG &DAG) const {
11944   SDValue Op0 = And.getOperand(0);
11945   SDValue Op1 = And.getOperand(1);
11946   if (Op0.getOpcode() == ISD::TRUNCATE)
11947     Op0 = Op0.getOperand(0);
11948   if (Op1.getOpcode() == ISD::TRUNCATE)
11949     Op1 = Op1.getOperand(0);
11950
11951   SDValue LHS, RHS;
11952   if (Op1.getOpcode() == ISD::SHL)
11953     std::swap(Op0, Op1);
11954   if (Op0.getOpcode() == ISD::SHL) {
11955     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11956       if (And00C->getZExtValue() == 1) {
11957         // If we looked past a truncate, check that it's only truncating away
11958         // known zeros.
11959         unsigned BitWidth = Op0.getValueSizeInBits();
11960         unsigned AndBitWidth = And.getValueSizeInBits();
11961         if (BitWidth > AndBitWidth) {
11962           APInt Zeros, Ones;
11963           DAG.computeKnownBits(Op0, Zeros, Ones);
11964           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11965             return SDValue();
11966         }
11967         LHS = Op1;
11968         RHS = Op0.getOperand(1);
11969       }
11970   } else if (Op1.getOpcode() == ISD::Constant) {
11971     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11972     uint64_t AndRHSVal = AndRHS->getZExtValue();
11973     SDValue AndLHS = Op0;
11974
11975     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11976       LHS = AndLHS.getOperand(0);
11977       RHS = AndLHS.getOperand(1);
11978     }
11979
11980     // Use BT if the immediate can't be encoded in a TEST instruction.
11981     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11982       LHS = AndLHS;
11983       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11984     }
11985   }
11986
11987   if (LHS.getNode()) {
11988     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
11989     // instruction.  Since the shift amount is in-range-or-undefined, we know
11990     // that doing a bittest on the i32 value is ok.  We extend to i32 because
11991     // the encoding for the i16 version is larger than the i32 version.
11992     // Also promote i16 to i32 for performance / code size reason.
11993     if (LHS.getValueType() == MVT::i8 ||
11994         LHS.getValueType() == MVT::i16)
11995       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
11996
11997     // If the operand types disagree, extend the shift amount to match.  Since
11998     // BT ignores high bits (like shifts) we can use anyextend.
11999     if (LHS.getValueType() != RHS.getValueType())
12000       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12001
12002     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12003     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12004     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12005                        DAG.getConstant(Cond, MVT::i8), BT);
12006   }
12007
12008   return SDValue();
12009 }
12010
12011 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12012 /// mask CMPs.
12013 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12014                               SDValue &Op1) {
12015   unsigned SSECC;
12016   bool Swap = false;
12017
12018   // SSE Condition code mapping:
12019   //  0 - EQ
12020   //  1 - LT
12021   //  2 - LE
12022   //  3 - UNORD
12023   //  4 - NEQ
12024   //  5 - NLT
12025   //  6 - NLE
12026   //  7 - ORD
12027   switch (SetCCOpcode) {
12028   default: llvm_unreachable("Unexpected SETCC condition");
12029   case ISD::SETOEQ:
12030   case ISD::SETEQ:  SSECC = 0; break;
12031   case ISD::SETOGT:
12032   case ISD::SETGT:  Swap = true; // Fallthrough
12033   case ISD::SETLT:
12034   case ISD::SETOLT: SSECC = 1; break;
12035   case ISD::SETOGE:
12036   case ISD::SETGE:  Swap = true; // Fallthrough
12037   case ISD::SETLE:
12038   case ISD::SETOLE: SSECC = 2; break;
12039   case ISD::SETUO:  SSECC = 3; break;
12040   case ISD::SETUNE:
12041   case ISD::SETNE:  SSECC = 4; break;
12042   case ISD::SETULE: Swap = true; // Fallthrough
12043   case ISD::SETUGE: SSECC = 5; break;
12044   case ISD::SETULT: Swap = true; // Fallthrough
12045   case ISD::SETUGT: SSECC = 6; break;
12046   case ISD::SETO:   SSECC = 7; break;
12047   case ISD::SETUEQ:
12048   case ISD::SETONE: SSECC = 8; break;
12049   }
12050   if (Swap)
12051     std::swap(Op0, Op1);
12052
12053   return SSECC;
12054 }
12055
12056 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12057 // ones, and then concatenate the result back.
12058 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12059   MVT VT = Op.getSimpleValueType();
12060
12061   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12062          "Unsupported value type for operation");
12063
12064   unsigned NumElems = VT.getVectorNumElements();
12065   SDLoc dl(Op);
12066   SDValue CC = Op.getOperand(2);
12067
12068   // Extract the LHS vectors
12069   SDValue LHS = Op.getOperand(0);
12070   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12071   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12072
12073   // Extract the RHS vectors
12074   SDValue RHS = Op.getOperand(1);
12075   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12076   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12077
12078   // Issue the operation on the smaller types and concatenate the result back
12079   MVT EltVT = VT.getVectorElementType();
12080   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12081   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12082                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12083                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12084 }
12085
12086 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12087                                      const X86Subtarget *Subtarget) {
12088   SDValue Op0 = Op.getOperand(0);
12089   SDValue Op1 = Op.getOperand(1);
12090   SDValue CC = Op.getOperand(2);
12091   MVT VT = Op.getSimpleValueType();
12092   SDLoc dl(Op);
12093
12094   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12095          Op.getValueType().getScalarType() == MVT::i1 &&
12096          "Cannot set masked compare for this operation");
12097
12098   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12099   unsigned  Opc = 0;
12100   bool Unsigned = false;
12101   bool Swap = false;
12102   unsigned SSECC;
12103   switch (SetCCOpcode) {
12104   default: llvm_unreachable("Unexpected SETCC condition");
12105   case ISD::SETNE:  SSECC = 4; break;
12106   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12107   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12108   case ISD::SETLT:  Swap = true; //fall-through
12109   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12110   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12111   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12112   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12113   case ISD::SETULE: Unsigned = true; //fall-through
12114   case ISD::SETLE:  SSECC = 2; break;
12115   }
12116
12117   if (Swap)
12118     std::swap(Op0, Op1);
12119   if (Opc)
12120     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12121   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12122   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12123                      DAG.getConstant(SSECC, MVT::i8));
12124 }
12125
12126 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12127 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12128 /// return an empty value.
12129 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12130 {
12131   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12132   if (!BV)
12133     return SDValue();
12134
12135   MVT VT = Op1.getSimpleValueType();
12136   MVT EVT = VT.getVectorElementType();
12137   unsigned n = VT.getVectorNumElements();
12138   SmallVector<SDValue, 8> ULTOp1;
12139
12140   for (unsigned i = 0; i < n; ++i) {
12141     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12142     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12143       return SDValue();
12144
12145     // Avoid underflow.
12146     APInt Val = Elt->getAPIntValue();
12147     if (Val == 0)
12148       return SDValue();
12149
12150     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12151   }
12152
12153   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12154 }
12155
12156 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12157                            SelectionDAG &DAG) {
12158   SDValue Op0 = Op.getOperand(0);
12159   SDValue Op1 = Op.getOperand(1);
12160   SDValue CC = Op.getOperand(2);
12161   MVT VT = Op.getSimpleValueType();
12162   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12163   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12164   SDLoc dl(Op);
12165
12166   if (isFP) {
12167 #ifndef NDEBUG
12168     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12169     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12170 #endif
12171
12172     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12173     unsigned Opc = X86ISD::CMPP;
12174     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12175       assert(VT.getVectorNumElements() <= 16);
12176       Opc = X86ISD::CMPM;
12177     }
12178     // In the two special cases we can't handle, emit two comparisons.
12179     if (SSECC == 8) {
12180       unsigned CC0, CC1;
12181       unsigned CombineOpc;
12182       if (SetCCOpcode == ISD::SETUEQ) {
12183         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12184       } else {
12185         assert(SetCCOpcode == ISD::SETONE);
12186         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12187       }
12188
12189       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12190                                  DAG.getConstant(CC0, MVT::i8));
12191       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12192                                  DAG.getConstant(CC1, MVT::i8));
12193       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12194     }
12195     // Handle all other FP comparisons here.
12196     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12197                        DAG.getConstant(SSECC, MVT::i8));
12198   }
12199
12200   // Break 256-bit integer vector compare into smaller ones.
12201   if (VT.is256BitVector() && !Subtarget->hasInt256())
12202     return Lower256IntVSETCC(Op, DAG);
12203
12204   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12205   EVT OpVT = Op1.getValueType();
12206   if (Subtarget->hasAVX512()) {
12207     if (Op1.getValueType().is512BitVector() ||
12208         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12209       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12210
12211     // In AVX-512 architecture setcc returns mask with i1 elements,
12212     // But there is no compare instruction for i8 and i16 elements.
12213     // We are not talking about 512-bit operands in this case, these
12214     // types are illegal.
12215     if (MaskResult &&
12216         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12217          OpVT.getVectorElementType().getSizeInBits() >= 8))
12218       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12219                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12220   }
12221
12222   // We are handling one of the integer comparisons here.  Since SSE only has
12223   // GT and EQ comparisons for integer, swapping operands and multiple
12224   // operations may be required for some comparisons.
12225   unsigned Opc;
12226   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12227   bool Subus = false;
12228
12229   switch (SetCCOpcode) {
12230   default: llvm_unreachable("Unexpected SETCC condition");
12231   case ISD::SETNE:  Invert = true;
12232   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12233   case ISD::SETLT:  Swap = true;
12234   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12235   case ISD::SETGE:  Swap = true;
12236   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12237                     Invert = true; break;
12238   case ISD::SETULT: Swap = true;
12239   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12240                     FlipSigns = true; break;
12241   case ISD::SETUGE: Swap = true;
12242   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12243                     FlipSigns = true; Invert = true; break;
12244   }
12245
12246   // Special case: Use min/max operations for SETULE/SETUGE
12247   MVT VET = VT.getVectorElementType();
12248   bool hasMinMax =
12249        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12250     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12251
12252   if (hasMinMax) {
12253     switch (SetCCOpcode) {
12254     default: break;
12255     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12256     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12257     }
12258
12259     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12260   }
12261
12262   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12263   if (!MinMax && hasSubus) {
12264     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12265     // Op0 u<= Op1:
12266     //   t = psubus Op0, Op1
12267     //   pcmpeq t, <0..0>
12268     switch (SetCCOpcode) {
12269     default: break;
12270     case ISD::SETULT: {
12271       // If the comparison is against a constant we can turn this into a
12272       // setule.  With psubus, setule does not require a swap.  This is
12273       // beneficial because the constant in the register is no longer
12274       // destructed as the destination so it can be hoisted out of a loop.
12275       // Only do this pre-AVX since vpcmp* is no longer destructive.
12276       if (Subtarget->hasAVX())
12277         break;
12278       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12279       if (ULEOp1.getNode()) {
12280         Op1 = ULEOp1;
12281         Subus = true; Invert = false; Swap = false;
12282       }
12283       break;
12284     }
12285     // Psubus is better than flip-sign because it requires no inversion.
12286     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12287     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12288     }
12289
12290     if (Subus) {
12291       Opc = X86ISD::SUBUS;
12292       FlipSigns = false;
12293     }
12294   }
12295
12296   if (Swap)
12297     std::swap(Op0, Op1);
12298
12299   // Check that the operation in question is available (most are plain SSE2,
12300   // but PCMPGTQ and PCMPEQQ have different requirements).
12301   if (VT == MVT::v2i64) {
12302     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12303       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12304
12305       // First cast everything to the right type.
12306       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12307       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12308
12309       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12310       // bits of the inputs before performing those operations. The lower
12311       // compare is always unsigned.
12312       SDValue SB;
12313       if (FlipSigns) {
12314         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12315       } else {
12316         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12317         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12318         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12319                          Sign, Zero, Sign, Zero);
12320       }
12321       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12322       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12323
12324       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12325       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12326       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12327
12328       // Create masks for only the low parts/high parts of the 64 bit integers.
12329       static const int MaskHi[] = { 1, 1, 3, 3 };
12330       static const int MaskLo[] = { 0, 0, 2, 2 };
12331       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12332       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12333       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12334
12335       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12336       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12337
12338       if (Invert)
12339         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12340
12341       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12342     }
12343
12344     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12345       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12346       // pcmpeqd + pshufd + pand.
12347       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12348
12349       // First cast everything to the right type.
12350       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12351       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12352
12353       // Do the compare.
12354       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12355
12356       // Make sure the lower and upper halves are both all-ones.
12357       static const int Mask[] = { 1, 0, 3, 2 };
12358       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12359       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12360
12361       if (Invert)
12362         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12363
12364       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12365     }
12366   }
12367
12368   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12369   // bits of the inputs before performing those operations.
12370   if (FlipSigns) {
12371     EVT EltVT = VT.getVectorElementType();
12372     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12373     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12374     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12375   }
12376
12377   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12378
12379   // If the logical-not of the result is required, perform that now.
12380   if (Invert)
12381     Result = DAG.getNOT(dl, Result, VT);
12382
12383   if (MinMax)
12384     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12385
12386   if (Subus)
12387     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12388                          getZeroVector(VT, Subtarget, DAG, dl));
12389
12390   return Result;
12391 }
12392
12393 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12394
12395   MVT VT = Op.getSimpleValueType();
12396
12397   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12398
12399   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12400          && "SetCC type must be 8-bit or 1-bit integer");
12401   SDValue Op0 = Op.getOperand(0);
12402   SDValue Op1 = Op.getOperand(1);
12403   SDLoc dl(Op);
12404   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12405
12406   // Optimize to BT if possible.
12407   // Lower (X & (1 << N)) == 0 to BT(X, N).
12408   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12409   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12410   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12411       Op1.getOpcode() == ISD::Constant &&
12412       cast<ConstantSDNode>(Op1)->isNullValue() &&
12413       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12414     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12415     if (NewSetCC.getNode())
12416       return NewSetCC;
12417   }
12418
12419   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12420   // these.
12421   if (Op1.getOpcode() == ISD::Constant &&
12422       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12423        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12424       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12425
12426     // If the input is a setcc, then reuse the input setcc or use a new one with
12427     // the inverted condition.
12428     if (Op0.getOpcode() == X86ISD::SETCC) {
12429       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12430       bool Invert = (CC == ISD::SETNE) ^
12431         cast<ConstantSDNode>(Op1)->isNullValue();
12432       if (!Invert)
12433         return Op0;
12434
12435       CCode = X86::GetOppositeBranchCondition(CCode);
12436       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12437                                   DAG.getConstant(CCode, MVT::i8),
12438                                   Op0.getOperand(1));
12439       if (VT == MVT::i1)
12440         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12441       return SetCC;
12442     }
12443   }
12444   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12445       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12446       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12447
12448     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12449     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12450   }
12451
12452   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12453   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12454   if (X86CC == X86::COND_INVALID)
12455     return SDValue();
12456
12457   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12458   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12459   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12460                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12461   if (VT == MVT::i1)
12462     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12463   return SetCC;
12464 }
12465
12466 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12467 static bool isX86LogicalCmp(SDValue Op) {
12468   unsigned Opc = Op.getNode()->getOpcode();
12469   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12470       Opc == X86ISD::SAHF)
12471     return true;
12472   if (Op.getResNo() == 1 &&
12473       (Opc == X86ISD::ADD ||
12474        Opc == X86ISD::SUB ||
12475        Opc == X86ISD::ADC ||
12476        Opc == X86ISD::SBB ||
12477        Opc == X86ISD::SMUL ||
12478        Opc == X86ISD::UMUL ||
12479        Opc == X86ISD::INC ||
12480        Opc == X86ISD::DEC ||
12481        Opc == X86ISD::OR ||
12482        Opc == X86ISD::XOR ||
12483        Opc == X86ISD::AND))
12484     return true;
12485
12486   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12487     return true;
12488
12489   return false;
12490 }
12491
12492 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12493   if (V.getOpcode() != ISD::TRUNCATE)
12494     return false;
12495
12496   SDValue VOp0 = V.getOperand(0);
12497   unsigned InBits = VOp0.getValueSizeInBits();
12498   unsigned Bits = V.getValueSizeInBits();
12499   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12500 }
12501
12502 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12503   bool addTest = true;
12504   SDValue Cond  = Op.getOperand(0);
12505   SDValue Op1 = Op.getOperand(1);
12506   SDValue Op2 = Op.getOperand(2);
12507   SDLoc DL(Op);
12508   EVT VT = Op1.getValueType();
12509   SDValue CC;
12510
12511   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12512   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12513   // sequence later on.
12514   if (Cond.getOpcode() == ISD::SETCC &&
12515       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12516        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12517       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12518     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12519     int SSECC = translateX86FSETCC(
12520         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12521
12522     if (SSECC != 8) {
12523       if (Subtarget->hasAVX512()) {
12524         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12525                                   DAG.getConstant(SSECC, MVT::i8));
12526         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12527       }
12528       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12529                                 DAG.getConstant(SSECC, MVT::i8));
12530       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12531       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12532       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12533     }
12534   }
12535
12536   if (Cond.getOpcode() == ISD::SETCC) {
12537     SDValue NewCond = LowerSETCC(Cond, DAG);
12538     if (NewCond.getNode())
12539       Cond = NewCond;
12540   }
12541
12542   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12543   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12544   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12545   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12546   if (Cond.getOpcode() == X86ISD::SETCC &&
12547       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12548       isZero(Cond.getOperand(1).getOperand(1))) {
12549     SDValue Cmp = Cond.getOperand(1);
12550
12551     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12552
12553     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12554         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12555       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12556
12557       SDValue CmpOp0 = Cmp.getOperand(0);
12558       // Apply further optimizations for special cases
12559       // (select (x != 0), -1, 0) -> neg & sbb
12560       // (select (x == 0), 0, -1) -> neg & sbb
12561       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12562         if (YC->isNullValue() &&
12563             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12564           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12565           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12566                                     DAG.getConstant(0, CmpOp0.getValueType()),
12567                                     CmpOp0);
12568           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12569                                     DAG.getConstant(X86::COND_B, MVT::i8),
12570                                     SDValue(Neg.getNode(), 1));
12571           return Res;
12572         }
12573
12574       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12575                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12576       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12577
12578       SDValue Res =   // Res = 0 or -1.
12579         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12580                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12581
12582       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12583         Res = DAG.getNOT(DL, Res, Res.getValueType());
12584
12585       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12586       if (!N2C || !N2C->isNullValue())
12587         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12588       return Res;
12589     }
12590   }
12591
12592   // Look past (and (setcc_carry (cmp ...)), 1).
12593   if (Cond.getOpcode() == ISD::AND &&
12594       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12595     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12596     if (C && C->getAPIntValue() == 1)
12597       Cond = Cond.getOperand(0);
12598   }
12599
12600   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12601   // setting operand in place of the X86ISD::SETCC.
12602   unsigned CondOpcode = Cond.getOpcode();
12603   if (CondOpcode == X86ISD::SETCC ||
12604       CondOpcode == X86ISD::SETCC_CARRY) {
12605     CC = Cond.getOperand(0);
12606
12607     SDValue Cmp = Cond.getOperand(1);
12608     unsigned Opc = Cmp.getOpcode();
12609     MVT VT = Op.getSimpleValueType();
12610
12611     bool IllegalFPCMov = false;
12612     if (VT.isFloatingPoint() && !VT.isVector() &&
12613         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12614       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12615
12616     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12617         Opc == X86ISD::BT) { // FIXME
12618       Cond = Cmp;
12619       addTest = false;
12620     }
12621   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12622              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12623              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12624               Cond.getOperand(0).getValueType() != MVT::i8)) {
12625     SDValue LHS = Cond.getOperand(0);
12626     SDValue RHS = Cond.getOperand(1);
12627     unsigned X86Opcode;
12628     unsigned X86Cond;
12629     SDVTList VTs;
12630     switch (CondOpcode) {
12631     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12632     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12633     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12634     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12635     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12636     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12637     default: llvm_unreachable("unexpected overflowing operator");
12638     }
12639     if (CondOpcode == ISD::UMULO)
12640       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12641                           MVT::i32);
12642     else
12643       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12644
12645     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12646
12647     if (CondOpcode == ISD::UMULO)
12648       Cond = X86Op.getValue(2);
12649     else
12650       Cond = X86Op.getValue(1);
12651
12652     CC = DAG.getConstant(X86Cond, MVT::i8);
12653     addTest = false;
12654   }
12655
12656   if (addTest) {
12657     // Look pass the truncate if the high bits are known zero.
12658     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12659         Cond = Cond.getOperand(0);
12660
12661     // We know the result of AND is compared against zero. Try to match
12662     // it to BT.
12663     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12664       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12665       if (NewSetCC.getNode()) {
12666         CC = NewSetCC.getOperand(0);
12667         Cond = NewSetCC.getOperand(1);
12668         addTest = false;
12669       }
12670     }
12671   }
12672
12673   if (addTest) {
12674     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12675     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12676   }
12677
12678   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12679   // a <  b ?  0 : -1 -> RES = setcc_carry
12680   // a >= b ? -1 :  0 -> RES = setcc_carry
12681   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12682   if (Cond.getOpcode() == X86ISD::SUB) {
12683     Cond = ConvertCmpIfNecessary(Cond, DAG);
12684     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12685
12686     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12687         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12688       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12689                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12690       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12691         return DAG.getNOT(DL, Res, Res.getValueType());
12692       return Res;
12693     }
12694   }
12695
12696   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12697   // widen the cmov and push the truncate through. This avoids introducing a new
12698   // branch during isel and doesn't add any extensions.
12699   if (Op.getValueType() == MVT::i8 &&
12700       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12701     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12702     if (T1.getValueType() == T2.getValueType() &&
12703         // Blacklist CopyFromReg to avoid partial register stalls.
12704         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12705       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12706       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12707       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12708     }
12709   }
12710
12711   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12712   // condition is true.
12713   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12714   SDValue Ops[] = { Op2, Op1, CC, Cond };
12715   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12716 }
12717
12718 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12719   MVT VT = Op->getSimpleValueType(0);
12720   SDValue In = Op->getOperand(0);
12721   MVT InVT = In.getSimpleValueType();
12722   SDLoc dl(Op);
12723
12724   unsigned int NumElts = VT.getVectorNumElements();
12725   if (NumElts != 8 && NumElts != 16)
12726     return SDValue();
12727
12728   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12729     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12730
12731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12732   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12733
12734   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12735   Constant *C = ConstantInt::get(*DAG.getContext(),
12736     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12737
12738   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12739   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12740   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12741                           MachinePointerInfo::getConstantPool(),
12742                           false, false, false, Alignment);
12743   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12744   if (VT.is512BitVector())
12745     return Brcst;
12746   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12747 }
12748
12749 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12750                                 SelectionDAG &DAG) {
12751   MVT VT = Op->getSimpleValueType(0);
12752   SDValue In = Op->getOperand(0);
12753   MVT InVT = In.getSimpleValueType();
12754   SDLoc dl(Op);
12755
12756   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12757     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12758
12759   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12760       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12761       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12762     return SDValue();
12763
12764   if (Subtarget->hasInt256())
12765     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12766
12767   // Optimize vectors in AVX mode
12768   // Sign extend  v8i16 to v8i32 and
12769   //              v4i32 to v4i64
12770   //
12771   // Divide input vector into two parts
12772   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12773   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12774   // concat the vectors to original VT
12775
12776   unsigned NumElems = InVT.getVectorNumElements();
12777   SDValue Undef = DAG.getUNDEF(InVT);
12778
12779   SmallVector<int,8> ShufMask1(NumElems, -1);
12780   for (unsigned i = 0; i != NumElems/2; ++i)
12781     ShufMask1[i] = i;
12782
12783   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12784
12785   SmallVector<int,8> ShufMask2(NumElems, -1);
12786   for (unsigned i = 0; i != NumElems/2; ++i)
12787     ShufMask2[i] = i + NumElems/2;
12788
12789   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12790
12791   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12792                                 VT.getVectorNumElements()/2);
12793
12794   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12795   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12796
12797   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12798 }
12799
12800 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12801 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12802 // from the AND / OR.
12803 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12804   Opc = Op.getOpcode();
12805   if (Opc != ISD::OR && Opc != ISD::AND)
12806     return false;
12807   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12808           Op.getOperand(0).hasOneUse() &&
12809           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12810           Op.getOperand(1).hasOneUse());
12811 }
12812
12813 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12814 // 1 and that the SETCC node has a single use.
12815 static bool isXor1OfSetCC(SDValue Op) {
12816   if (Op.getOpcode() != ISD::XOR)
12817     return false;
12818   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12819   if (N1C && N1C->getAPIntValue() == 1) {
12820     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12821       Op.getOperand(0).hasOneUse();
12822   }
12823   return false;
12824 }
12825
12826 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12827   bool addTest = true;
12828   SDValue Chain = Op.getOperand(0);
12829   SDValue Cond  = Op.getOperand(1);
12830   SDValue Dest  = Op.getOperand(2);
12831   SDLoc dl(Op);
12832   SDValue CC;
12833   bool Inverted = false;
12834
12835   if (Cond.getOpcode() == ISD::SETCC) {
12836     // Check for setcc([su]{add,sub,mul}o == 0).
12837     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12838         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12839         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12840         Cond.getOperand(0).getResNo() == 1 &&
12841         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12842          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12843          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12844          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12845          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12846          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12847       Inverted = true;
12848       Cond = Cond.getOperand(0);
12849     } else {
12850       SDValue NewCond = LowerSETCC(Cond, DAG);
12851       if (NewCond.getNode())
12852         Cond = NewCond;
12853     }
12854   }
12855 #if 0
12856   // FIXME: LowerXALUO doesn't handle these!!
12857   else if (Cond.getOpcode() == X86ISD::ADD  ||
12858            Cond.getOpcode() == X86ISD::SUB  ||
12859            Cond.getOpcode() == X86ISD::SMUL ||
12860            Cond.getOpcode() == X86ISD::UMUL)
12861     Cond = LowerXALUO(Cond, DAG);
12862 #endif
12863
12864   // Look pass (and (setcc_carry (cmp ...)), 1).
12865   if (Cond.getOpcode() == ISD::AND &&
12866       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12867     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12868     if (C && C->getAPIntValue() == 1)
12869       Cond = Cond.getOperand(0);
12870   }
12871
12872   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12873   // setting operand in place of the X86ISD::SETCC.
12874   unsigned CondOpcode = Cond.getOpcode();
12875   if (CondOpcode == X86ISD::SETCC ||
12876       CondOpcode == X86ISD::SETCC_CARRY) {
12877     CC = Cond.getOperand(0);
12878
12879     SDValue Cmp = Cond.getOperand(1);
12880     unsigned Opc = Cmp.getOpcode();
12881     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12882     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12883       Cond = Cmp;
12884       addTest = false;
12885     } else {
12886       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12887       default: break;
12888       case X86::COND_O:
12889       case X86::COND_B:
12890         // These can only come from an arithmetic instruction with overflow,
12891         // e.g. SADDO, UADDO.
12892         Cond = Cond.getNode()->getOperand(1);
12893         addTest = false;
12894         break;
12895       }
12896     }
12897   }
12898   CondOpcode = Cond.getOpcode();
12899   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12900       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12901       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12902        Cond.getOperand(0).getValueType() != MVT::i8)) {
12903     SDValue LHS = Cond.getOperand(0);
12904     SDValue RHS = Cond.getOperand(1);
12905     unsigned X86Opcode;
12906     unsigned X86Cond;
12907     SDVTList VTs;
12908     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12909     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12910     // X86ISD::INC).
12911     switch (CondOpcode) {
12912     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12913     case ISD::SADDO:
12914       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12915         if (C->isOne()) {
12916           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12917           break;
12918         }
12919       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12920     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12921     case ISD::SSUBO:
12922       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12923         if (C->isOne()) {
12924           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12925           break;
12926         }
12927       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12928     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12929     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12930     default: llvm_unreachable("unexpected overflowing operator");
12931     }
12932     if (Inverted)
12933       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12934     if (CondOpcode == ISD::UMULO)
12935       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12936                           MVT::i32);
12937     else
12938       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12939
12940     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12941
12942     if (CondOpcode == ISD::UMULO)
12943       Cond = X86Op.getValue(2);
12944     else
12945       Cond = X86Op.getValue(1);
12946
12947     CC = DAG.getConstant(X86Cond, MVT::i8);
12948     addTest = false;
12949   } else {
12950     unsigned CondOpc;
12951     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12952       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12953       if (CondOpc == ISD::OR) {
12954         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12955         // two branches instead of an explicit OR instruction with a
12956         // separate test.
12957         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12958             isX86LogicalCmp(Cmp)) {
12959           CC = Cond.getOperand(0).getOperand(0);
12960           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12961                               Chain, Dest, CC, Cmp);
12962           CC = Cond.getOperand(1).getOperand(0);
12963           Cond = Cmp;
12964           addTest = false;
12965         }
12966       } else { // ISD::AND
12967         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12968         // two branches instead of an explicit AND instruction with a
12969         // separate test. However, we only do this if this block doesn't
12970         // have a fall-through edge, because this requires an explicit
12971         // jmp when the condition is false.
12972         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12973             isX86LogicalCmp(Cmp) &&
12974             Op.getNode()->hasOneUse()) {
12975           X86::CondCode CCode =
12976             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12977           CCode = X86::GetOppositeBranchCondition(CCode);
12978           CC = DAG.getConstant(CCode, MVT::i8);
12979           SDNode *User = *Op.getNode()->use_begin();
12980           // Look for an unconditional branch following this conditional branch.
12981           // We need this because we need to reverse the successors in order
12982           // to implement FCMP_OEQ.
12983           if (User->getOpcode() == ISD::BR) {
12984             SDValue FalseBB = User->getOperand(1);
12985             SDNode *NewBR =
12986               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
12987             assert(NewBR == User);
12988             (void)NewBR;
12989             Dest = FalseBB;
12990
12991             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12992                                 Chain, Dest, CC, Cmp);
12993             X86::CondCode CCode =
12994               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
12995             CCode = X86::GetOppositeBranchCondition(CCode);
12996             CC = DAG.getConstant(CCode, MVT::i8);
12997             Cond = Cmp;
12998             addTest = false;
12999           }
13000         }
13001       }
13002     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13003       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13004       // It should be transformed during dag combiner except when the condition
13005       // is set by a arithmetics with overflow node.
13006       X86::CondCode CCode =
13007         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13008       CCode = X86::GetOppositeBranchCondition(CCode);
13009       CC = DAG.getConstant(CCode, MVT::i8);
13010       Cond = Cond.getOperand(0).getOperand(1);
13011       addTest = false;
13012     } else if (Cond.getOpcode() == ISD::SETCC &&
13013                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13014       // For FCMP_OEQ, we can emit
13015       // two branches instead of an explicit AND instruction with a
13016       // separate test. However, we only do this if this block doesn't
13017       // have a fall-through edge, because this requires an explicit
13018       // jmp when the condition is false.
13019       if (Op.getNode()->hasOneUse()) {
13020         SDNode *User = *Op.getNode()->use_begin();
13021         // Look for an unconditional branch following this conditional branch.
13022         // We need this because we need to reverse the successors in order
13023         // to implement FCMP_OEQ.
13024         if (User->getOpcode() == ISD::BR) {
13025           SDValue FalseBB = User->getOperand(1);
13026           SDNode *NewBR =
13027             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13028           assert(NewBR == User);
13029           (void)NewBR;
13030           Dest = FalseBB;
13031
13032           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13033                                     Cond.getOperand(0), Cond.getOperand(1));
13034           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13035           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13036           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13037                               Chain, Dest, CC, Cmp);
13038           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13039           Cond = Cmp;
13040           addTest = false;
13041         }
13042       }
13043     } else if (Cond.getOpcode() == ISD::SETCC &&
13044                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13045       // For FCMP_UNE, we can emit
13046       // two branches instead of an explicit AND instruction with a
13047       // separate test. However, we only do this if this block doesn't
13048       // have a fall-through edge, because this requires an explicit
13049       // jmp when the condition is false.
13050       if (Op.getNode()->hasOneUse()) {
13051         SDNode *User = *Op.getNode()->use_begin();
13052         // Look for an unconditional branch following this conditional branch.
13053         // We need this because we need to reverse the successors in order
13054         // to implement FCMP_UNE.
13055         if (User->getOpcode() == ISD::BR) {
13056           SDValue FalseBB = User->getOperand(1);
13057           SDNode *NewBR =
13058             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13059           assert(NewBR == User);
13060           (void)NewBR;
13061
13062           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13063                                     Cond.getOperand(0), Cond.getOperand(1));
13064           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13065           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13066           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13067                               Chain, Dest, CC, Cmp);
13068           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13069           Cond = Cmp;
13070           addTest = false;
13071           Dest = FalseBB;
13072         }
13073       }
13074     }
13075   }
13076
13077   if (addTest) {
13078     // Look pass the truncate if the high bits are known zero.
13079     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13080         Cond = Cond.getOperand(0);
13081
13082     // We know the result of AND is compared against zero. Try to match
13083     // it to BT.
13084     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13085       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13086       if (NewSetCC.getNode()) {
13087         CC = NewSetCC.getOperand(0);
13088         Cond = NewSetCC.getOperand(1);
13089         addTest = false;
13090       }
13091     }
13092   }
13093
13094   if (addTest) {
13095     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13096     CC = DAG.getConstant(X86Cond, MVT::i8);
13097     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13098   }
13099   Cond = ConvertCmpIfNecessary(Cond, DAG);
13100   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13101                      Chain, Dest, CC, Cond);
13102 }
13103
13104 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13105 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13106 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13107 // that the guard pages used by the OS virtual memory manager are allocated in
13108 // correct sequence.
13109 SDValue
13110 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13111                                            SelectionDAG &DAG) const {
13112   MachineFunction &MF = DAG.getMachineFunction();
13113   bool SplitStack = MF.shouldSplitStack();
13114   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13115                SplitStack;
13116   SDLoc dl(Op);
13117
13118   if (!Lower) {
13119     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13120     SDNode* Node = Op.getNode();
13121
13122     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13123     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13124         " not tell us which reg is the stack pointer!");
13125     EVT VT = Node->getValueType(0);
13126     SDValue Tmp1 = SDValue(Node, 0);
13127     SDValue Tmp2 = SDValue(Node, 1);
13128     SDValue Tmp3 = Node->getOperand(2);
13129     SDValue Chain = Tmp1.getOperand(0);
13130
13131     // Chain the dynamic stack allocation so that it doesn't modify the stack
13132     // pointer when other instructions are using the stack.
13133     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13134         SDLoc(Node));
13135
13136     SDValue Size = Tmp2.getOperand(1);
13137     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13138     Chain = SP.getValue(1);
13139     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13140     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13141     unsigned StackAlign = TFI.getStackAlignment();
13142     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13143     if (Align > StackAlign)
13144       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13145           DAG.getConstant(-(uint64_t)Align, VT));
13146     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13147
13148     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13149         DAG.getIntPtrConstant(0, true), SDValue(),
13150         SDLoc(Node));
13151
13152     SDValue Ops[2] = { Tmp1, Tmp2 };
13153     return DAG.getMergeValues(Ops, dl);
13154   }
13155
13156   // Get the inputs.
13157   SDValue Chain = Op.getOperand(0);
13158   SDValue Size  = Op.getOperand(1);
13159   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13160   EVT VT = Op.getNode()->getValueType(0);
13161
13162   bool Is64Bit = Subtarget->is64Bit();
13163   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13164
13165   if (SplitStack) {
13166     MachineRegisterInfo &MRI = MF.getRegInfo();
13167
13168     if (Is64Bit) {
13169       // The 64 bit implementation of segmented stacks needs to clobber both r10
13170       // r11. This makes it impossible to use it along with nested parameters.
13171       const Function *F = MF.getFunction();
13172
13173       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13174            I != E; ++I)
13175         if (I->hasNestAttr())
13176           report_fatal_error("Cannot use segmented stacks with functions that "
13177                              "have nested arguments.");
13178     }
13179
13180     const TargetRegisterClass *AddrRegClass =
13181       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13182     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13183     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13184     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13185                                 DAG.getRegister(Vreg, SPTy));
13186     SDValue Ops1[2] = { Value, Chain };
13187     return DAG.getMergeValues(Ops1, dl);
13188   } else {
13189     SDValue Flag;
13190     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13191
13192     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13193     Flag = Chain.getValue(1);
13194     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13195
13196     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13197
13198     const X86RegisterInfo *RegInfo =
13199       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13200     unsigned SPReg = RegInfo->getStackRegister();
13201     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13202     Chain = SP.getValue(1);
13203
13204     if (Align) {
13205       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13206                        DAG.getConstant(-(uint64_t)Align, VT));
13207       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13208     }
13209
13210     SDValue Ops1[2] = { SP, Chain };
13211     return DAG.getMergeValues(Ops1, dl);
13212   }
13213 }
13214
13215 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13216   MachineFunction &MF = DAG.getMachineFunction();
13217   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13218
13219   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13220   SDLoc DL(Op);
13221
13222   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13223     // vastart just stores the address of the VarArgsFrameIndex slot into the
13224     // memory location argument.
13225     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13226                                    getPointerTy());
13227     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13228                         MachinePointerInfo(SV), false, false, 0);
13229   }
13230
13231   // __va_list_tag:
13232   //   gp_offset         (0 - 6 * 8)
13233   //   fp_offset         (48 - 48 + 8 * 16)
13234   //   overflow_arg_area (point to parameters coming in memory).
13235   //   reg_save_area
13236   SmallVector<SDValue, 8> MemOps;
13237   SDValue FIN = Op.getOperand(1);
13238   // Store gp_offset
13239   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13240                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13241                                                MVT::i32),
13242                                FIN, MachinePointerInfo(SV), false, false, 0);
13243   MemOps.push_back(Store);
13244
13245   // Store fp_offset
13246   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13247                     FIN, DAG.getIntPtrConstant(4));
13248   Store = DAG.getStore(Op.getOperand(0), DL,
13249                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13250                                        MVT::i32),
13251                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13252   MemOps.push_back(Store);
13253
13254   // Store ptr to overflow_arg_area
13255   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13256                     FIN, DAG.getIntPtrConstant(4));
13257   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13258                                     getPointerTy());
13259   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13260                        MachinePointerInfo(SV, 8),
13261                        false, false, 0);
13262   MemOps.push_back(Store);
13263
13264   // Store ptr to reg_save_area.
13265   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13266                     FIN, DAG.getIntPtrConstant(8));
13267   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13268                                     getPointerTy());
13269   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13270                        MachinePointerInfo(SV, 16), false, false, 0);
13271   MemOps.push_back(Store);
13272   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13273 }
13274
13275 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13276   assert(Subtarget->is64Bit() &&
13277          "LowerVAARG only handles 64-bit va_arg!");
13278   assert((Subtarget->isTargetLinux() ||
13279           Subtarget->isTargetDarwin()) &&
13280           "Unhandled target in LowerVAARG");
13281   assert(Op.getNode()->getNumOperands() == 4);
13282   SDValue Chain = Op.getOperand(0);
13283   SDValue SrcPtr = Op.getOperand(1);
13284   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13285   unsigned Align = Op.getConstantOperandVal(3);
13286   SDLoc dl(Op);
13287
13288   EVT ArgVT = Op.getNode()->getValueType(0);
13289   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13290   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13291   uint8_t ArgMode;
13292
13293   // Decide which area this value should be read from.
13294   // TODO: Implement the AMD64 ABI in its entirety. This simple
13295   // selection mechanism works only for the basic types.
13296   if (ArgVT == MVT::f80) {
13297     llvm_unreachable("va_arg for f80 not yet implemented");
13298   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13299     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13300   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13301     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13302   } else {
13303     llvm_unreachable("Unhandled argument type in LowerVAARG");
13304   }
13305
13306   if (ArgMode == 2) {
13307     // Sanity Check: Make sure using fp_offset makes sense.
13308     assert(!DAG.getTarget().Options.UseSoftFloat &&
13309            !(DAG.getMachineFunction()
13310                 .getFunction()->getAttributes()
13311                 .hasAttribute(AttributeSet::FunctionIndex,
13312                               Attribute::NoImplicitFloat)) &&
13313            Subtarget->hasSSE1());
13314   }
13315
13316   // Insert VAARG_64 node into the DAG
13317   // VAARG_64 returns two values: Variable Argument Address, Chain
13318   SmallVector<SDValue, 11> InstOps;
13319   InstOps.push_back(Chain);
13320   InstOps.push_back(SrcPtr);
13321   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13322   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13323   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13324   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13325   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13326                                           VTs, InstOps, MVT::i64,
13327                                           MachinePointerInfo(SV),
13328                                           /*Align=*/0,
13329                                           /*Volatile=*/false,
13330                                           /*ReadMem=*/true,
13331                                           /*WriteMem=*/true);
13332   Chain = VAARG.getValue(1);
13333
13334   // Load the next argument and return it
13335   return DAG.getLoad(ArgVT, dl,
13336                      Chain,
13337                      VAARG,
13338                      MachinePointerInfo(),
13339                      false, false, false, 0);
13340 }
13341
13342 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13343                            SelectionDAG &DAG) {
13344   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13345   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13346   SDValue Chain = Op.getOperand(0);
13347   SDValue DstPtr = Op.getOperand(1);
13348   SDValue SrcPtr = Op.getOperand(2);
13349   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13350   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13351   SDLoc DL(Op);
13352
13353   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13354                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13355                        false,
13356                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13357 }
13358
13359 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13360 // amount is a constant. Takes immediate version of shift as input.
13361 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13362                                           SDValue SrcOp, uint64_t ShiftAmt,
13363                                           SelectionDAG &DAG) {
13364   MVT ElementType = VT.getVectorElementType();
13365
13366   // Fold this packed shift into its first operand if ShiftAmt is 0.
13367   if (ShiftAmt == 0)
13368     return SrcOp;
13369
13370   // Check for ShiftAmt >= element width
13371   if (ShiftAmt >= ElementType.getSizeInBits()) {
13372     if (Opc == X86ISD::VSRAI)
13373       ShiftAmt = ElementType.getSizeInBits() - 1;
13374     else
13375       return DAG.getConstant(0, VT);
13376   }
13377
13378   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13379          && "Unknown target vector shift-by-constant node");
13380
13381   // Fold this packed vector shift into a build vector if SrcOp is a
13382   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13383   if (VT == SrcOp.getSimpleValueType() &&
13384       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13385     SmallVector<SDValue, 8> Elts;
13386     unsigned NumElts = SrcOp->getNumOperands();
13387     ConstantSDNode *ND;
13388
13389     switch(Opc) {
13390     default: llvm_unreachable(nullptr);
13391     case X86ISD::VSHLI:
13392       for (unsigned i=0; i!=NumElts; ++i) {
13393         SDValue CurrentOp = SrcOp->getOperand(i);
13394         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13395           Elts.push_back(CurrentOp);
13396           continue;
13397         }
13398         ND = cast<ConstantSDNode>(CurrentOp);
13399         const APInt &C = ND->getAPIntValue();
13400         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13401       }
13402       break;
13403     case X86ISD::VSRLI:
13404       for (unsigned i=0; i!=NumElts; ++i) {
13405         SDValue CurrentOp = SrcOp->getOperand(i);
13406         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13407           Elts.push_back(CurrentOp);
13408           continue;
13409         }
13410         ND = cast<ConstantSDNode>(CurrentOp);
13411         const APInt &C = ND->getAPIntValue();
13412         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13413       }
13414       break;
13415     case X86ISD::VSRAI:
13416       for (unsigned i=0; i!=NumElts; ++i) {
13417         SDValue CurrentOp = SrcOp->getOperand(i);
13418         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13419           Elts.push_back(CurrentOp);
13420           continue;
13421         }
13422         ND = cast<ConstantSDNode>(CurrentOp);
13423         const APInt &C = ND->getAPIntValue();
13424         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13425       }
13426       break;
13427     }
13428
13429     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13430   }
13431
13432   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13433 }
13434
13435 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13436 // may or may not be a constant. Takes immediate version of shift as input.
13437 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13438                                    SDValue SrcOp, SDValue ShAmt,
13439                                    SelectionDAG &DAG) {
13440   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13441
13442   // Catch shift-by-constant.
13443   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13444     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13445                                       CShAmt->getZExtValue(), DAG);
13446
13447   // Change opcode to non-immediate version
13448   switch (Opc) {
13449     default: llvm_unreachable("Unknown target vector shift node");
13450     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13451     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13452     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13453   }
13454
13455   // Need to build a vector containing shift amount
13456   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13457   SDValue ShOps[4];
13458   ShOps[0] = ShAmt;
13459   ShOps[1] = DAG.getConstant(0, MVT::i32);
13460   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13461   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13462
13463   // The return type has to be a 128-bit type with the same element
13464   // type as the input type.
13465   MVT EltVT = VT.getVectorElementType();
13466   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13467
13468   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13469   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13470 }
13471
13472 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13473   SDLoc dl(Op);
13474   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13475   switch (IntNo) {
13476   default: return SDValue();    // Don't custom lower most intrinsics.
13477   // Comparison intrinsics.
13478   case Intrinsic::x86_sse_comieq_ss:
13479   case Intrinsic::x86_sse_comilt_ss:
13480   case Intrinsic::x86_sse_comile_ss:
13481   case Intrinsic::x86_sse_comigt_ss:
13482   case Intrinsic::x86_sse_comige_ss:
13483   case Intrinsic::x86_sse_comineq_ss:
13484   case Intrinsic::x86_sse_ucomieq_ss:
13485   case Intrinsic::x86_sse_ucomilt_ss:
13486   case Intrinsic::x86_sse_ucomile_ss:
13487   case Intrinsic::x86_sse_ucomigt_ss:
13488   case Intrinsic::x86_sse_ucomige_ss:
13489   case Intrinsic::x86_sse_ucomineq_ss:
13490   case Intrinsic::x86_sse2_comieq_sd:
13491   case Intrinsic::x86_sse2_comilt_sd:
13492   case Intrinsic::x86_sse2_comile_sd:
13493   case Intrinsic::x86_sse2_comigt_sd:
13494   case Intrinsic::x86_sse2_comige_sd:
13495   case Intrinsic::x86_sse2_comineq_sd:
13496   case Intrinsic::x86_sse2_ucomieq_sd:
13497   case Intrinsic::x86_sse2_ucomilt_sd:
13498   case Intrinsic::x86_sse2_ucomile_sd:
13499   case Intrinsic::x86_sse2_ucomigt_sd:
13500   case Intrinsic::x86_sse2_ucomige_sd:
13501   case Intrinsic::x86_sse2_ucomineq_sd: {
13502     unsigned Opc;
13503     ISD::CondCode CC;
13504     switch (IntNo) {
13505     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13506     case Intrinsic::x86_sse_comieq_ss:
13507     case Intrinsic::x86_sse2_comieq_sd:
13508       Opc = X86ISD::COMI;
13509       CC = ISD::SETEQ;
13510       break;
13511     case Intrinsic::x86_sse_comilt_ss:
13512     case Intrinsic::x86_sse2_comilt_sd:
13513       Opc = X86ISD::COMI;
13514       CC = ISD::SETLT;
13515       break;
13516     case Intrinsic::x86_sse_comile_ss:
13517     case Intrinsic::x86_sse2_comile_sd:
13518       Opc = X86ISD::COMI;
13519       CC = ISD::SETLE;
13520       break;
13521     case Intrinsic::x86_sse_comigt_ss:
13522     case Intrinsic::x86_sse2_comigt_sd:
13523       Opc = X86ISD::COMI;
13524       CC = ISD::SETGT;
13525       break;
13526     case Intrinsic::x86_sse_comige_ss:
13527     case Intrinsic::x86_sse2_comige_sd:
13528       Opc = X86ISD::COMI;
13529       CC = ISD::SETGE;
13530       break;
13531     case Intrinsic::x86_sse_comineq_ss:
13532     case Intrinsic::x86_sse2_comineq_sd:
13533       Opc = X86ISD::COMI;
13534       CC = ISD::SETNE;
13535       break;
13536     case Intrinsic::x86_sse_ucomieq_ss:
13537     case Intrinsic::x86_sse2_ucomieq_sd:
13538       Opc = X86ISD::UCOMI;
13539       CC = ISD::SETEQ;
13540       break;
13541     case Intrinsic::x86_sse_ucomilt_ss:
13542     case Intrinsic::x86_sse2_ucomilt_sd:
13543       Opc = X86ISD::UCOMI;
13544       CC = ISD::SETLT;
13545       break;
13546     case Intrinsic::x86_sse_ucomile_ss:
13547     case Intrinsic::x86_sse2_ucomile_sd:
13548       Opc = X86ISD::UCOMI;
13549       CC = ISD::SETLE;
13550       break;
13551     case Intrinsic::x86_sse_ucomigt_ss:
13552     case Intrinsic::x86_sse2_ucomigt_sd:
13553       Opc = X86ISD::UCOMI;
13554       CC = ISD::SETGT;
13555       break;
13556     case Intrinsic::x86_sse_ucomige_ss:
13557     case Intrinsic::x86_sse2_ucomige_sd:
13558       Opc = X86ISD::UCOMI;
13559       CC = ISD::SETGE;
13560       break;
13561     case Intrinsic::x86_sse_ucomineq_ss:
13562     case Intrinsic::x86_sse2_ucomineq_sd:
13563       Opc = X86ISD::UCOMI;
13564       CC = ISD::SETNE;
13565       break;
13566     }
13567
13568     SDValue LHS = Op.getOperand(1);
13569     SDValue RHS = Op.getOperand(2);
13570     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13571     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13572     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13573     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13574                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13575     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13576   }
13577
13578   // Arithmetic intrinsics.
13579   case Intrinsic::x86_sse2_pmulu_dq:
13580   case Intrinsic::x86_avx2_pmulu_dq:
13581     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13582                        Op.getOperand(1), Op.getOperand(2));
13583
13584   case Intrinsic::x86_sse41_pmuldq:
13585   case Intrinsic::x86_avx2_pmul_dq:
13586     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13587                        Op.getOperand(1), Op.getOperand(2));
13588
13589   case Intrinsic::x86_sse2_pmulhu_w:
13590   case Intrinsic::x86_avx2_pmulhu_w:
13591     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13592                        Op.getOperand(1), Op.getOperand(2));
13593
13594   case Intrinsic::x86_sse2_pmulh_w:
13595   case Intrinsic::x86_avx2_pmulh_w:
13596     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13597                        Op.getOperand(1), Op.getOperand(2));
13598
13599   // SSE2/AVX2 sub with unsigned saturation intrinsics
13600   case Intrinsic::x86_sse2_psubus_b:
13601   case Intrinsic::x86_sse2_psubus_w:
13602   case Intrinsic::x86_avx2_psubus_b:
13603   case Intrinsic::x86_avx2_psubus_w:
13604     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13605                        Op.getOperand(1), Op.getOperand(2));
13606
13607   // SSE3/AVX horizontal add/sub intrinsics
13608   case Intrinsic::x86_sse3_hadd_ps:
13609   case Intrinsic::x86_sse3_hadd_pd:
13610   case Intrinsic::x86_avx_hadd_ps_256:
13611   case Intrinsic::x86_avx_hadd_pd_256:
13612   case Intrinsic::x86_sse3_hsub_ps:
13613   case Intrinsic::x86_sse3_hsub_pd:
13614   case Intrinsic::x86_avx_hsub_ps_256:
13615   case Intrinsic::x86_avx_hsub_pd_256:
13616   case Intrinsic::x86_ssse3_phadd_w_128:
13617   case Intrinsic::x86_ssse3_phadd_d_128:
13618   case Intrinsic::x86_avx2_phadd_w:
13619   case Intrinsic::x86_avx2_phadd_d:
13620   case Intrinsic::x86_ssse3_phsub_w_128:
13621   case Intrinsic::x86_ssse3_phsub_d_128:
13622   case Intrinsic::x86_avx2_phsub_w:
13623   case Intrinsic::x86_avx2_phsub_d: {
13624     unsigned Opcode;
13625     switch (IntNo) {
13626     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13627     case Intrinsic::x86_sse3_hadd_ps:
13628     case Intrinsic::x86_sse3_hadd_pd:
13629     case Intrinsic::x86_avx_hadd_ps_256:
13630     case Intrinsic::x86_avx_hadd_pd_256:
13631       Opcode = X86ISD::FHADD;
13632       break;
13633     case Intrinsic::x86_sse3_hsub_ps:
13634     case Intrinsic::x86_sse3_hsub_pd:
13635     case Intrinsic::x86_avx_hsub_ps_256:
13636     case Intrinsic::x86_avx_hsub_pd_256:
13637       Opcode = X86ISD::FHSUB;
13638       break;
13639     case Intrinsic::x86_ssse3_phadd_w_128:
13640     case Intrinsic::x86_ssse3_phadd_d_128:
13641     case Intrinsic::x86_avx2_phadd_w:
13642     case Intrinsic::x86_avx2_phadd_d:
13643       Opcode = X86ISD::HADD;
13644       break;
13645     case Intrinsic::x86_ssse3_phsub_w_128:
13646     case Intrinsic::x86_ssse3_phsub_d_128:
13647     case Intrinsic::x86_avx2_phsub_w:
13648     case Intrinsic::x86_avx2_phsub_d:
13649       Opcode = X86ISD::HSUB;
13650       break;
13651     }
13652     return DAG.getNode(Opcode, dl, Op.getValueType(),
13653                        Op.getOperand(1), Op.getOperand(2));
13654   }
13655
13656   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13657   case Intrinsic::x86_sse2_pmaxu_b:
13658   case Intrinsic::x86_sse41_pmaxuw:
13659   case Intrinsic::x86_sse41_pmaxud:
13660   case Intrinsic::x86_avx2_pmaxu_b:
13661   case Intrinsic::x86_avx2_pmaxu_w:
13662   case Intrinsic::x86_avx2_pmaxu_d:
13663   case Intrinsic::x86_sse2_pminu_b:
13664   case Intrinsic::x86_sse41_pminuw:
13665   case Intrinsic::x86_sse41_pminud:
13666   case Intrinsic::x86_avx2_pminu_b:
13667   case Intrinsic::x86_avx2_pminu_w:
13668   case Intrinsic::x86_avx2_pminu_d:
13669   case Intrinsic::x86_sse41_pmaxsb:
13670   case Intrinsic::x86_sse2_pmaxs_w:
13671   case Intrinsic::x86_sse41_pmaxsd:
13672   case Intrinsic::x86_avx2_pmaxs_b:
13673   case Intrinsic::x86_avx2_pmaxs_w:
13674   case Intrinsic::x86_avx2_pmaxs_d:
13675   case Intrinsic::x86_sse41_pminsb:
13676   case Intrinsic::x86_sse2_pmins_w:
13677   case Intrinsic::x86_sse41_pminsd:
13678   case Intrinsic::x86_avx2_pmins_b:
13679   case Intrinsic::x86_avx2_pmins_w:
13680   case Intrinsic::x86_avx2_pmins_d: {
13681     unsigned Opcode;
13682     switch (IntNo) {
13683     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13684     case Intrinsic::x86_sse2_pmaxu_b:
13685     case Intrinsic::x86_sse41_pmaxuw:
13686     case Intrinsic::x86_sse41_pmaxud:
13687     case Intrinsic::x86_avx2_pmaxu_b:
13688     case Intrinsic::x86_avx2_pmaxu_w:
13689     case Intrinsic::x86_avx2_pmaxu_d:
13690       Opcode = X86ISD::UMAX;
13691       break;
13692     case Intrinsic::x86_sse2_pminu_b:
13693     case Intrinsic::x86_sse41_pminuw:
13694     case Intrinsic::x86_sse41_pminud:
13695     case Intrinsic::x86_avx2_pminu_b:
13696     case Intrinsic::x86_avx2_pminu_w:
13697     case Intrinsic::x86_avx2_pminu_d:
13698       Opcode = X86ISD::UMIN;
13699       break;
13700     case Intrinsic::x86_sse41_pmaxsb:
13701     case Intrinsic::x86_sse2_pmaxs_w:
13702     case Intrinsic::x86_sse41_pmaxsd:
13703     case Intrinsic::x86_avx2_pmaxs_b:
13704     case Intrinsic::x86_avx2_pmaxs_w:
13705     case Intrinsic::x86_avx2_pmaxs_d:
13706       Opcode = X86ISD::SMAX;
13707       break;
13708     case Intrinsic::x86_sse41_pminsb:
13709     case Intrinsic::x86_sse2_pmins_w:
13710     case Intrinsic::x86_sse41_pminsd:
13711     case Intrinsic::x86_avx2_pmins_b:
13712     case Intrinsic::x86_avx2_pmins_w:
13713     case Intrinsic::x86_avx2_pmins_d:
13714       Opcode = X86ISD::SMIN;
13715       break;
13716     }
13717     return DAG.getNode(Opcode, dl, Op.getValueType(),
13718                        Op.getOperand(1), Op.getOperand(2));
13719   }
13720
13721   // SSE/SSE2/AVX floating point max/min intrinsics.
13722   case Intrinsic::x86_sse_max_ps:
13723   case Intrinsic::x86_sse2_max_pd:
13724   case Intrinsic::x86_avx_max_ps_256:
13725   case Intrinsic::x86_avx_max_pd_256:
13726   case Intrinsic::x86_sse_min_ps:
13727   case Intrinsic::x86_sse2_min_pd:
13728   case Intrinsic::x86_avx_min_ps_256:
13729   case Intrinsic::x86_avx_min_pd_256: {
13730     unsigned Opcode;
13731     switch (IntNo) {
13732     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13733     case Intrinsic::x86_sse_max_ps:
13734     case Intrinsic::x86_sse2_max_pd:
13735     case Intrinsic::x86_avx_max_ps_256:
13736     case Intrinsic::x86_avx_max_pd_256:
13737       Opcode = X86ISD::FMAX;
13738       break;
13739     case Intrinsic::x86_sse_min_ps:
13740     case Intrinsic::x86_sse2_min_pd:
13741     case Intrinsic::x86_avx_min_ps_256:
13742     case Intrinsic::x86_avx_min_pd_256:
13743       Opcode = X86ISD::FMIN;
13744       break;
13745     }
13746     return DAG.getNode(Opcode, dl, Op.getValueType(),
13747                        Op.getOperand(1), Op.getOperand(2));
13748   }
13749
13750   // AVX2 variable shift intrinsics
13751   case Intrinsic::x86_avx2_psllv_d:
13752   case Intrinsic::x86_avx2_psllv_q:
13753   case Intrinsic::x86_avx2_psllv_d_256:
13754   case Intrinsic::x86_avx2_psllv_q_256:
13755   case Intrinsic::x86_avx2_psrlv_d:
13756   case Intrinsic::x86_avx2_psrlv_q:
13757   case Intrinsic::x86_avx2_psrlv_d_256:
13758   case Intrinsic::x86_avx2_psrlv_q_256:
13759   case Intrinsic::x86_avx2_psrav_d:
13760   case Intrinsic::x86_avx2_psrav_d_256: {
13761     unsigned Opcode;
13762     switch (IntNo) {
13763     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13764     case Intrinsic::x86_avx2_psllv_d:
13765     case Intrinsic::x86_avx2_psllv_q:
13766     case Intrinsic::x86_avx2_psllv_d_256:
13767     case Intrinsic::x86_avx2_psllv_q_256:
13768       Opcode = ISD::SHL;
13769       break;
13770     case Intrinsic::x86_avx2_psrlv_d:
13771     case Intrinsic::x86_avx2_psrlv_q:
13772     case Intrinsic::x86_avx2_psrlv_d_256:
13773     case Intrinsic::x86_avx2_psrlv_q_256:
13774       Opcode = ISD::SRL;
13775       break;
13776     case Intrinsic::x86_avx2_psrav_d:
13777     case Intrinsic::x86_avx2_psrav_d_256:
13778       Opcode = ISD::SRA;
13779       break;
13780     }
13781     return DAG.getNode(Opcode, dl, Op.getValueType(),
13782                        Op.getOperand(1), Op.getOperand(2));
13783   }
13784
13785   case Intrinsic::x86_sse2_packssdw_128:
13786   case Intrinsic::x86_sse2_packsswb_128:
13787   case Intrinsic::x86_avx2_packssdw:
13788   case Intrinsic::x86_avx2_packsswb:
13789     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13790                        Op.getOperand(1), Op.getOperand(2));
13791
13792   case Intrinsic::x86_sse2_packuswb_128:
13793   case Intrinsic::x86_sse41_packusdw:
13794   case Intrinsic::x86_avx2_packuswb:
13795   case Intrinsic::x86_avx2_packusdw:
13796     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13797                        Op.getOperand(1), Op.getOperand(2));
13798
13799   case Intrinsic::x86_ssse3_pshuf_b_128:
13800   case Intrinsic::x86_avx2_pshuf_b:
13801     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13802                        Op.getOperand(1), Op.getOperand(2));
13803
13804   case Intrinsic::x86_sse2_pshuf_d:
13805     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13806                        Op.getOperand(1), Op.getOperand(2));
13807
13808   case Intrinsic::x86_sse2_pshufl_w:
13809     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13810                        Op.getOperand(1), Op.getOperand(2));
13811
13812   case Intrinsic::x86_sse2_pshufh_w:
13813     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13814                        Op.getOperand(1), Op.getOperand(2));
13815
13816   case Intrinsic::x86_ssse3_psign_b_128:
13817   case Intrinsic::x86_ssse3_psign_w_128:
13818   case Intrinsic::x86_ssse3_psign_d_128:
13819   case Intrinsic::x86_avx2_psign_b:
13820   case Intrinsic::x86_avx2_psign_w:
13821   case Intrinsic::x86_avx2_psign_d:
13822     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13823                        Op.getOperand(1), Op.getOperand(2));
13824
13825   case Intrinsic::x86_sse41_insertps:
13826     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13827                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13828
13829   case Intrinsic::x86_avx_vperm2f128_ps_256:
13830   case Intrinsic::x86_avx_vperm2f128_pd_256:
13831   case Intrinsic::x86_avx_vperm2f128_si_256:
13832   case Intrinsic::x86_avx2_vperm2i128:
13833     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13834                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13835
13836   case Intrinsic::x86_avx2_permd:
13837   case Intrinsic::x86_avx2_permps:
13838     // Operands intentionally swapped. Mask is last operand to intrinsic,
13839     // but second operand for node/instruction.
13840     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13841                        Op.getOperand(2), Op.getOperand(1));
13842
13843   case Intrinsic::x86_sse_sqrt_ps:
13844   case Intrinsic::x86_sse2_sqrt_pd:
13845   case Intrinsic::x86_avx_sqrt_ps_256:
13846   case Intrinsic::x86_avx_sqrt_pd_256:
13847     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13848
13849   // ptest and testp intrinsics. The intrinsic these come from are designed to
13850   // return an integer value, not just an instruction so lower it to the ptest
13851   // or testp pattern and a setcc for the result.
13852   case Intrinsic::x86_sse41_ptestz:
13853   case Intrinsic::x86_sse41_ptestc:
13854   case Intrinsic::x86_sse41_ptestnzc:
13855   case Intrinsic::x86_avx_ptestz_256:
13856   case Intrinsic::x86_avx_ptestc_256:
13857   case Intrinsic::x86_avx_ptestnzc_256:
13858   case Intrinsic::x86_avx_vtestz_ps:
13859   case Intrinsic::x86_avx_vtestc_ps:
13860   case Intrinsic::x86_avx_vtestnzc_ps:
13861   case Intrinsic::x86_avx_vtestz_pd:
13862   case Intrinsic::x86_avx_vtestc_pd:
13863   case Intrinsic::x86_avx_vtestnzc_pd:
13864   case Intrinsic::x86_avx_vtestz_ps_256:
13865   case Intrinsic::x86_avx_vtestc_ps_256:
13866   case Intrinsic::x86_avx_vtestnzc_ps_256:
13867   case Intrinsic::x86_avx_vtestz_pd_256:
13868   case Intrinsic::x86_avx_vtestc_pd_256:
13869   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13870     bool IsTestPacked = false;
13871     unsigned X86CC;
13872     switch (IntNo) {
13873     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13874     case Intrinsic::x86_avx_vtestz_ps:
13875     case Intrinsic::x86_avx_vtestz_pd:
13876     case Intrinsic::x86_avx_vtestz_ps_256:
13877     case Intrinsic::x86_avx_vtestz_pd_256:
13878       IsTestPacked = true; // Fallthrough
13879     case Intrinsic::x86_sse41_ptestz:
13880     case Intrinsic::x86_avx_ptestz_256:
13881       // ZF = 1
13882       X86CC = X86::COND_E;
13883       break;
13884     case Intrinsic::x86_avx_vtestc_ps:
13885     case Intrinsic::x86_avx_vtestc_pd:
13886     case Intrinsic::x86_avx_vtestc_ps_256:
13887     case Intrinsic::x86_avx_vtestc_pd_256:
13888       IsTestPacked = true; // Fallthrough
13889     case Intrinsic::x86_sse41_ptestc:
13890     case Intrinsic::x86_avx_ptestc_256:
13891       // CF = 1
13892       X86CC = X86::COND_B;
13893       break;
13894     case Intrinsic::x86_avx_vtestnzc_ps:
13895     case Intrinsic::x86_avx_vtestnzc_pd:
13896     case Intrinsic::x86_avx_vtestnzc_ps_256:
13897     case Intrinsic::x86_avx_vtestnzc_pd_256:
13898       IsTestPacked = true; // Fallthrough
13899     case Intrinsic::x86_sse41_ptestnzc:
13900     case Intrinsic::x86_avx_ptestnzc_256:
13901       // ZF and CF = 0
13902       X86CC = X86::COND_A;
13903       break;
13904     }
13905
13906     SDValue LHS = Op.getOperand(1);
13907     SDValue RHS = Op.getOperand(2);
13908     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13909     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13910     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13911     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13912     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13913   }
13914   case Intrinsic::x86_avx512_kortestz_w:
13915   case Intrinsic::x86_avx512_kortestc_w: {
13916     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13917     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13918     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13919     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13920     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13921     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13922     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13923   }
13924
13925   // SSE/AVX shift intrinsics
13926   case Intrinsic::x86_sse2_psll_w:
13927   case Intrinsic::x86_sse2_psll_d:
13928   case Intrinsic::x86_sse2_psll_q:
13929   case Intrinsic::x86_avx2_psll_w:
13930   case Intrinsic::x86_avx2_psll_d:
13931   case Intrinsic::x86_avx2_psll_q:
13932   case Intrinsic::x86_sse2_psrl_w:
13933   case Intrinsic::x86_sse2_psrl_d:
13934   case Intrinsic::x86_sse2_psrl_q:
13935   case Intrinsic::x86_avx2_psrl_w:
13936   case Intrinsic::x86_avx2_psrl_d:
13937   case Intrinsic::x86_avx2_psrl_q:
13938   case Intrinsic::x86_sse2_psra_w:
13939   case Intrinsic::x86_sse2_psra_d:
13940   case Intrinsic::x86_avx2_psra_w:
13941   case Intrinsic::x86_avx2_psra_d: {
13942     unsigned Opcode;
13943     switch (IntNo) {
13944     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13945     case Intrinsic::x86_sse2_psll_w:
13946     case Intrinsic::x86_sse2_psll_d:
13947     case Intrinsic::x86_sse2_psll_q:
13948     case Intrinsic::x86_avx2_psll_w:
13949     case Intrinsic::x86_avx2_psll_d:
13950     case Intrinsic::x86_avx2_psll_q:
13951       Opcode = X86ISD::VSHL;
13952       break;
13953     case Intrinsic::x86_sse2_psrl_w:
13954     case Intrinsic::x86_sse2_psrl_d:
13955     case Intrinsic::x86_sse2_psrl_q:
13956     case Intrinsic::x86_avx2_psrl_w:
13957     case Intrinsic::x86_avx2_psrl_d:
13958     case Intrinsic::x86_avx2_psrl_q:
13959       Opcode = X86ISD::VSRL;
13960       break;
13961     case Intrinsic::x86_sse2_psra_w:
13962     case Intrinsic::x86_sse2_psra_d:
13963     case Intrinsic::x86_avx2_psra_w:
13964     case Intrinsic::x86_avx2_psra_d:
13965       Opcode = X86ISD::VSRA;
13966       break;
13967     }
13968     return DAG.getNode(Opcode, dl, Op.getValueType(),
13969                        Op.getOperand(1), Op.getOperand(2));
13970   }
13971
13972   // SSE/AVX immediate shift intrinsics
13973   case Intrinsic::x86_sse2_pslli_w:
13974   case Intrinsic::x86_sse2_pslli_d:
13975   case Intrinsic::x86_sse2_pslli_q:
13976   case Intrinsic::x86_avx2_pslli_w:
13977   case Intrinsic::x86_avx2_pslli_d:
13978   case Intrinsic::x86_avx2_pslli_q:
13979   case Intrinsic::x86_sse2_psrli_w:
13980   case Intrinsic::x86_sse2_psrli_d:
13981   case Intrinsic::x86_sse2_psrli_q:
13982   case Intrinsic::x86_avx2_psrli_w:
13983   case Intrinsic::x86_avx2_psrli_d:
13984   case Intrinsic::x86_avx2_psrli_q:
13985   case Intrinsic::x86_sse2_psrai_w:
13986   case Intrinsic::x86_sse2_psrai_d:
13987   case Intrinsic::x86_avx2_psrai_w:
13988   case Intrinsic::x86_avx2_psrai_d: {
13989     unsigned Opcode;
13990     switch (IntNo) {
13991     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13992     case Intrinsic::x86_sse2_pslli_w:
13993     case Intrinsic::x86_sse2_pslli_d:
13994     case Intrinsic::x86_sse2_pslli_q:
13995     case Intrinsic::x86_avx2_pslli_w:
13996     case Intrinsic::x86_avx2_pslli_d:
13997     case Intrinsic::x86_avx2_pslli_q:
13998       Opcode = X86ISD::VSHLI;
13999       break;
14000     case Intrinsic::x86_sse2_psrli_w:
14001     case Intrinsic::x86_sse2_psrli_d:
14002     case Intrinsic::x86_sse2_psrli_q:
14003     case Intrinsic::x86_avx2_psrli_w:
14004     case Intrinsic::x86_avx2_psrli_d:
14005     case Intrinsic::x86_avx2_psrli_q:
14006       Opcode = X86ISD::VSRLI;
14007       break;
14008     case Intrinsic::x86_sse2_psrai_w:
14009     case Intrinsic::x86_sse2_psrai_d:
14010     case Intrinsic::x86_avx2_psrai_w:
14011     case Intrinsic::x86_avx2_psrai_d:
14012       Opcode = X86ISD::VSRAI;
14013       break;
14014     }
14015     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14016                                Op.getOperand(1), Op.getOperand(2), DAG);
14017   }
14018
14019   case Intrinsic::x86_sse42_pcmpistria128:
14020   case Intrinsic::x86_sse42_pcmpestria128:
14021   case Intrinsic::x86_sse42_pcmpistric128:
14022   case Intrinsic::x86_sse42_pcmpestric128:
14023   case Intrinsic::x86_sse42_pcmpistrio128:
14024   case Intrinsic::x86_sse42_pcmpestrio128:
14025   case Intrinsic::x86_sse42_pcmpistris128:
14026   case Intrinsic::x86_sse42_pcmpestris128:
14027   case Intrinsic::x86_sse42_pcmpistriz128:
14028   case Intrinsic::x86_sse42_pcmpestriz128: {
14029     unsigned Opcode;
14030     unsigned X86CC;
14031     switch (IntNo) {
14032     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14033     case Intrinsic::x86_sse42_pcmpistria128:
14034       Opcode = X86ISD::PCMPISTRI;
14035       X86CC = X86::COND_A;
14036       break;
14037     case Intrinsic::x86_sse42_pcmpestria128:
14038       Opcode = X86ISD::PCMPESTRI;
14039       X86CC = X86::COND_A;
14040       break;
14041     case Intrinsic::x86_sse42_pcmpistric128:
14042       Opcode = X86ISD::PCMPISTRI;
14043       X86CC = X86::COND_B;
14044       break;
14045     case Intrinsic::x86_sse42_pcmpestric128:
14046       Opcode = X86ISD::PCMPESTRI;
14047       X86CC = X86::COND_B;
14048       break;
14049     case Intrinsic::x86_sse42_pcmpistrio128:
14050       Opcode = X86ISD::PCMPISTRI;
14051       X86CC = X86::COND_O;
14052       break;
14053     case Intrinsic::x86_sse42_pcmpestrio128:
14054       Opcode = X86ISD::PCMPESTRI;
14055       X86CC = X86::COND_O;
14056       break;
14057     case Intrinsic::x86_sse42_pcmpistris128:
14058       Opcode = X86ISD::PCMPISTRI;
14059       X86CC = X86::COND_S;
14060       break;
14061     case Intrinsic::x86_sse42_pcmpestris128:
14062       Opcode = X86ISD::PCMPESTRI;
14063       X86CC = X86::COND_S;
14064       break;
14065     case Intrinsic::x86_sse42_pcmpistriz128:
14066       Opcode = X86ISD::PCMPISTRI;
14067       X86CC = X86::COND_E;
14068       break;
14069     case Intrinsic::x86_sse42_pcmpestriz128:
14070       Opcode = X86ISD::PCMPESTRI;
14071       X86CC = X86::COND_E;
14072       break;
14073     }
14074     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14075     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14076     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14077     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14078                                 DAG.getConstant(X86CC, MVT::i8),
14079                                 SDValue(PCMP.getNode(), 1));
14080     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14081   }
14082
14083   case Intrinsic::x86_sse42_pcmpistri128:
14084   case Intrinsic::x86_sse42_pcmpestri128: {
14085     unsigned Opcode;
14086     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14087       Opcode = X86ISD::PCMPISTRI;
14088     else
14089       Opcode = X86ISD::PCMPESTRI;
14090
14091     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14092     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14093     return DAG.getNode(Opcode, dl, VTs, NewOps);
14094   }
14095   case Intrinsic::x86_fma_vfmadd_ps:
14096   case Intrinsic::x86_fma_vfmadd_pd:
14097   case Intrinsic::x86_fma_vfmsub_ps:
14098   case Intrinsic::x86_fma_vfmsub_pd:
14099   case Intrinsic::x86_fma_vfnmadd_ps:
14100   case Intrinsic::x86_fma_vfnmadd_pd:
14101   case Intrinsic::x86_fma_vfnmsub_ps:
14102   case Intrinsic::x86_fma_vfnmsub_pd:
14103   case Intrinsic::x86_fma_vfmaddsub_ps:
14104   case Intrinsic::x86_fma_vfmaddsub_pd:
14105   case Intrinsic::x86_fma_vfmsubadd_ps:
14106   case Intrinsic::x86_fma_vfmsubadd_pd:
14107   case Intrinsic::x86_fma_vfmadd_ps_256:
14108   case Intrinsic::x86_fma_vfmadd_pd_256:
14109   case Intrinsic::x86_fma_vfmsub_ps_256:
14110   case Intrinsic::x86_fma_vfmsub_pd_256:
14111   case Intrinsic::x86_fma_vfnmadd_ps_256:
14112   case Intrinsic::x86_fma_vfnmadd_pd_256:
14113   case Intrinsic::x86_fma_vfnmsub_ps_256:
14114   case Intrinsic::x86_fma_vfnmsub_pd_256:
14115   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14116   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14117   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14118   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14119   case Intrinsic::x86_fma_vfmadd_ps_512:
14120   case Intrinsic::x86_fma_vfmadd_pd_512:
14121   case Intrinsic::x86_fma_vfmsub_ps_512:
14122   case Intrinsic::x86_fma_vfmsub_pd_512:
14123   case Intrinsic::x86_fma_vfnmadd_ps_512:
14124   case Intrinsic::x86_fma_vfnmadd_pd_512:
14125   case Intrinsic::x86_fma_vfnmsub_ps_512:
14126   case Intrinsic::x86_fma_vfnmsub_pd_512:
14127   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14128   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14129   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14130   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14131     unsigned Opc;
14132     switch (IntNo) {
14133     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14134     case Intrinsic::x86_fma_vfmadd_ps:
14135     case Intrinsic::x86_fma_vfmadd_pd:
14136     case Intrinsic::x86_fma_vfmadd_ps_256:
14137     case Intrinsic::x86_fma_vfmadd_pd_256:
14138     case Intrinsic::x86_fma_vfmadd_ps_512:
14139     case Intrinsic::x86_fma_vfmadd_pd_512:
14140       Opc = X86ISD::FMADD;
14141       break;
14142     case Intrinsic::x86_fma_vfmsub_ps:
14143     case Intrinsic::x86_fma_vfmsub_pd:
14144     case Intrinsic::x86_fma_vfmsub_ps_256:
14145     case Intrinsic::x86_fma_vfmsub_pd_256:
14146     case Intrinsic::x86_fma_vfmsub_ps_512:
14147     case Intrinsic::x86_fma_vfmsub_pd_512:
14148       Opc = X86ISD::FMSUB;
14149       break;
14150     case Intrinsic::x86_fma_vfnmadd_ps:
14151     case Intrinsic::x86_fma_vfnmadd_pd:
14152     case Intrinsic::x86_fma_vfnmadd_ps_256:
14153     case Intrinsic::x86_fma_vfnmadd_pd_256:
14154     case Intrinsic::x86_fma_vfnmadd_ps_512:
14155     case Intrinsic::x86_fma_vfnmadd_pd_512:
14156       Opc = X86ISD::FNMADD;
14157       break;
14158     case Intrinsic::x86_fma_vfnmsub_ps:
14159     case Intrinsic::x86_fma_vfnmsub_pd:
14160     case Intrinsic::x86_fma_vfnmsub_ps_256:
14161     case Intrinsic::x86_fma_vfnmsub_pd_256:
14162     case Intrinsic::x86_fma_vfnmsub_ps_512:
14163     case Intrinsic::x86_fma_vfnmsub_pd_512:
14164       Opc = X86ISD::FNMSUB;
14165       break;
14166     case Intrinsic::x86_fma_vfmaddsub_ps:
14167     case Intrinsic::x86_fma_vfmaddsub_pd:
14168     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14169     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14170     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14171     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14172       Opc = X86ISD::FMADDSUB;
14173       break;
14174     case Intrinsic::x86_fma_vfmsubadd_ps:
14175     case Intrinsic::x86_fma_vfmsubadd_pd:
14176     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14177     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14178     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14179     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14180       Opc = X86ISD::FMSUBADD;
14181       break;
14182     }
14183
14184     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14185                        Op.getOperand(2), Op.getOperand(3));
14186   }
14187   }
14188 }
14189
14190 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14191                               SDValue Src, SDValue Mask, SDValue Base,
14192                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14193                               const X86Subtarget * Subtarget) {
14194   SDLoc dl(Op);
14195   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14196   assert(C && "Invalid scale type");
14197   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14198   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14199                              Index.getSimpleValueType().getVectorNumElements());
14200   SDValue MaskInReg;
14201   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14202   if (MaskC)
14203     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14204   else
14205     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14206   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14207   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14208   SDValue Segment = DAG.getRegister(0, MVT::i32);
14209   if (Src.getOpcode() == ISD::UNDEF)
14210     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14211   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14212   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14213   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14214   return DAG.getMergeValues(RetOps, dl);
14215 }
14216
14217 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14218                                SDValue Src, SDValue Mask, SDValue Base,
14219                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14220   SDLoc dl(Op);
14221   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14222   assert(C && "Invalid scale type");
14223   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14224   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14225   SDValue Segment = DAG.getRegister(0, MVT::i32);
14226   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14227                              Index.getSimpleValueType().getVectorNumElements());
14228   SDValue MaskInReg;
14229   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14230   if (MaskC)
14231     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14232   else
14233     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14234   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14235   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14236   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14237   return SDValue(Res, 1);
14238 }
14239
14240 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14241                                SDValue Mask, SDValue Base, SDValue Index,
14242                                SDValue ScaleOp, SDValue Chain) {
14243   SDLoc dl(Op);
14244   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14245   assert(C && "Invalid scale type");
14246   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14247   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14248   SDValue Segment = DAG.getRegister(0, MVT::i32);
14249   EVT MaskVT =
14250     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14251   SDValue MaskInReg;
14252   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14253   if (MaskC)
14254     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14255   else
14256     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14257   //SDVTList VTs = DAG.getVTList(MVT::Other);
14258   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14259   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14260   return SDValue(Res, 0);
14261 }
14262
14263 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14264 // read performance monitor counters (x86_rdpmc).
14265 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14266                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14267                               SmallVectorImpl<SDValue> &Results) {
14268   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14269   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14270   SDValue LO, HI;
14271
14272   // The ECX register is used to select the index of the performance counter
14273   // to read.
14274   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14275                                    N->getOperand(2));
14276   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14277
14278   // Reads the content of a 64-bit performance counter and returns it in the
14279   // registers EDX:EAX.
14280   if (Subtarget->is64Bit()) {
14281     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14282     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14283                             LO.getValue(2));
14284   } else {
14285     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14286     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14287                             LO.getValue(2));
14288   }
14289   Chain = HI.getValue(1);
14290
14291   if (Subtarget->is64Bit()) {
14292     // The EAX register is loaded with the low-order 32 bits. The EDX register
14293     // is loaded with the supported high-order bits of the counter.
14294     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14295                               DAG.getConstant(32, MVT::i8));
14296     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14297     Results.push_back(Chain);
14298     return;
14299   }
14300
14301   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14302   SDValue Ops[] = { LO, HI };
14303   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14304   Results.push_back(Pair);
14305   Results.push_back(Chain);
14306 }
14307
14308 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14309 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14310 // also used to custom lower READCYCLECOUNTER nodes.
14311 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14312                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14313                               SmallVectorImpl<SDValue> &Results) {
14314   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14315   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14316   SDValue LO, HI;
14317
14318   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14319   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14320   // and the EAX register is loaded with the low-order 32 bits.
14321   if (Subtarget->is64Bit()) {
14322     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14323     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14324                             LO.getValue(2));
14325   } else {
14326     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14327     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14328                             LO.getValue(2));
14329   }
14330   SDValue Chain = HI.getValue(1);
14331
14332   if (Opcode == X86ISD::RDTSCP_DAG) {
14333     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14334
14335     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14336     // the ECX register. Add 'ecx' explicitly to the chain.
14337     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14338                                      HI.getValue(2));
14339     // Explicitly store the content of ECX at the location passed in input
14340     // to the 'rdtscp' intrinsic.
14341     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14342                          MachinePointerInfo(), false, false, 0);
14343   }
14344
14345   if (Subtarget->is64Bit()) {
14346     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14347     // the EAX register is loaded with the low-order 32 bits.
14348     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14349                               DAG.getConstant(32, MVT::i8));
14350     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14351     Results.push_back(Chain);
14352     return;
14353   }
14354
14355   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14356   SDValue Ops[] = { LO, HI };
14357   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14358   Results.push_back(Pair);
14359   Results.push_back(Chain);
14360 }
14361
14362 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14363                                      SelectionDAG &DAG) {
14364   SmallVector<SDValue, 2> Results;
14365   SDLoc DL(Op);
14366   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14367                           Results);
14368   return DAG.getMergeValues(Results, DL);
14369 }
14370
14371 enum IntrinsicType {
14372   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14373 };
14374
14375 struct IntrinsicData {
14376   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14377     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14378   IntrinsicType Type;
14379   unsigned      Opc0;
14380   unsigned      Opc1;
14381 };
14382
14383 std::map < unsigned, IntrinsicData> IntrMap;
14384 static void InitIntinsicsMap() {
14385   static bool Initialized = false;
14386   if (Initialized) 
14387     return;
14388   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14389                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14390   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14391                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14392   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14393                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14394   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14395                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14396   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14397                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14398   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14399                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14400   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14401                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14402   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14403                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14404   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14405                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14406
14407   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14408                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14409   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14410                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14411   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14412                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14413   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14414                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14415   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14416                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14417   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14418                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14419   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14420                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14421   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14422                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14423    
14424   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14425                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14426                                                         X86::VGATHERPF1QPSm)));
14427   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14428                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14429                                                         X86::VGATHERPF1QPDm)));
14430   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14431                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14432                                                         X86::VGATHERPF1DPDm)));
14433   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14434                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14435                                                         X86::VGATHERPF1DPSm)));
14436   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14437                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14438                                                         X86::VSCATTERPF1QPSm)));
14439   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14440                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14441                                                         X86::VSCATTERPF1QPDm)));
14442   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14443                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14444                                                         X86::VSCATTERPF1DPDm)));
14445   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14446                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14447                                                         X86::VSCATTERPF1DPSm)));
14448   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14449                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14450   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14451                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14452   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14453                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14454   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14455                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14456   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14457                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14458   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14459                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14460   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14461                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14462   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14463                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14464   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14465                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14466   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14467                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14468   Initialized = true;
14469 }
14470
14471 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14472                                       SelectionDAG &DAG) {
14473   InitIntinsicsMap();
14474   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14475   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14476   if (itr == IntrMap.end())
14477     return SDValue();
14478
14479   SDLoc dl(Op);
14480   IntrinsicData Intr = itr->second;
14481   switch(Intr.Type) {
14482   case RDSEED:
14483   case RDRAND: {
14484     // Emit the node with the right value type.
14485     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14486     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14487
14488     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14489     // Otherwise return the value from Rand, which is always 0, casted to i32.
14490     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14491                       DAG.getConstant(1, Op->getValueType(1)),
14492                       DAG.getConstant(X86::COND_B, MVT::i32),
14493                       SDValue(Result.getNode(), 1) };
14494     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14495                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14496                                   Ops);
14497
14498     // Return { result, isValid, chain }.
14499     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14500                        SDValue(Result.getNode(), 2));
14501   }
14502   case GATHER: {
14503   //gather(v1, mask, index, base, scale);
14504     SDValue Chain = Op.getOperand(0);
14505     SDValue Src   = Op.getOperand(2);
14506     SDValue Base  = Op.getOperand(3);
14507     SDValue Index = Op.getOperand(4);
14508     SDValue Mask  = Op.getOperand(5);
14509     SDValue Scale = Op.getOperand(6);
14510     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14511                           Subtarget);
14512   }
14513   case SCATTER: {
14514   //scatter(base, mask, index, v1, scale);
14515     SDValue Chain = Op.getOperand(0);
14516     SDValue Base  = Op.getOperand(2);
14517     SDValue Mask  = Op.getOperand(3);
14518     SDValue Index = Op.getOperand(4);
14519     SDValue Src   = Op.getOperand(5);
14520     SDValue Scale = Op.getOperand(6);
14521     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14522   }
14523   case PREFETCH: {
14524     SDValue Hint = Op.getOperand(6);
14525     unsigned HintVal;
14526     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14527         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14528       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14529     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14530     SDValue Chain = Op.getOperand(0);
14531     SDValue Mask  = Op.getOperand(2);
14532     SDValue Index = Op.getOperand(3);
14533     SDValue Base  = Op.getOperand(4);
14534     SDValue Scale = Op.getOperand(5);
14535     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14536   }
14537   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14538   case RDTSC: {
14539     SmallVector<SDValue, 2> Results;
14540     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14541     return DAG.getMergeValues(Results, dl);
14542   }
14543   // Read Performance Monitoring Counters.
14544   case RDPMC: {
14545     SmallVector<SDValue, 2> Results;
14546     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14547     return DAG.getMergeValues(Results, dl);
14548   }
14549   // XTEST intrinsics.
14550   case XTEST: {
14551     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14552     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14553     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14554                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14555                                 InTrans);
14556     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14557     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14558                        Ret, SDValue(InTrans.getNode(), 1));
14559   }
14560   }
14561   llvm_unreachable("Unknown Intrinsic Type");
14562 }
14563
14564 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14565                                            SelectionDAG &DAG) const {
14566   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14567   MFI->setReturnAddressIsTaken(true);
14568
14569   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14570     return SDValue();
14571
14572   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14573   SDLoc dl(Op);
14574   EVT PtrVT = getPointerTy();
14575
14576   if (Depth > 0) {
14577     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14578     const X86RegisterInfo *RegInfo =
14579       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14580     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14581     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14582                        DAG.getNode(ISD::ADD, dl, PtrVT,
14583                                    FrameAddr, Offset),
14584                        MachinePointerInfo(), false, false, false, 0);
14585   }
14586
14587   // Just load the return address.
14588   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14589   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14590                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14591 }
14592
14593 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14594   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14595   MFI->setFrameAddressIsTaken(true);
14596
14597   EVT VT = Op.getValueType();
14598   SDLoc dl(Op);  // FIXME probably not meaningful
14599   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14600   const X86RegisterInfo *RegInfo =
14601     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14602   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14603   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14604           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14605          "Invalid Frame Register!");
14606   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14607   while (Depth--)
14608     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14609                             MachinePointerInfo(),
14610                             false, false, false, 0);
14611   return FrameAddr;
14612 }
14613
14614 // FIXME? Maybe this could be a TableGen attribute on some registers and
14615 // this table could be generated automatically from RegInfo.
14616 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14617                                               EVT VT) const {
14618   unsigned Reg = StringSwitch<unsigned>(RegName)
14619                        .Case("esp", X86::ESP)
14620                        .Case("rsp", X86::RSP)
14621                        .Default(0);
14622   if (Reg)
14623     return Reg;
14624   report_fatal_error("Invalid register name global variable");
14625 }
14626
14627 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14628                                                      SelectionDAG &DAG) const {
14629   const X86RegisterInfo *RegInfo =
14630     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14631   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14632 }
14633
14634 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14635   SDValue Chain     = Op.getOperand(0);
14636   SDValue Offset    = Op.getOperand(1);
14637   SDValue Handler   = Op.getOperand(2);
14638   SDLoc dl      (Op);
14639
14640   EVT PtrVT = getPointerTy();
14641   const X86RegisterInfo *RegInfo =
14642     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14643   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14644   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14645           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14646          "Invalid Frame Register!");
14647   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14648   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14649
14650   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14651                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14652   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14653   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14654                        false, false, 0);
14655   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14656
14657   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14658                      DAG.getRegister(StoreAddrReg, PtrVT));
14659 }
14660
14661 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14662                                                SelectionDAG &DAG) const {
14663   SDLoc DL(Op);
14664   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14665                      DAG.getVTList(MVT::i32, MVT::Other),
14666                      Op.getOperand(0), Op.getOperand(1));
14667 }
14668
14669 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14670                                                 SelectionDAG &DAG) const {
14671   SDLoc DL(Op);
14672   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14673                      Op.getOperand(0), Op.getOperand(1));
14674 }
14675
14676 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14677   return Op.getOperand(0);
14678 }
14679
14680 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14681                                                 SelectionDAG &DAG) const {
14682   SDValue Root = Op.getOperand(0);
14683   SDValue Trmp = Op.getOperand(1); // trampoline
14684   SDValue FPtr = Op.getOperand(2); // nested function
14685   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14686   SDLoc dl (Op);
14687
14688   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14689   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14690
14691   if (Subtarget->is64Bit()) {
14692     SDValue OutChains[6];
14693
14694     // Large code-model.
14695     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14696     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14697
14698     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14699     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14700
14701     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14702
14703     // Load the pointer to the nested function into R11.
14704     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14705     SDValue Addr = Trmp;
14706     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14707                                 Addr, MachinePointerInfo(TrmpAddr),
14708                                 false, false, 0);
14709
14710     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14711                        DAG.getConstant(2, MVT::i64));
14712     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14713                                 MachinePointerInfo(TrmpAddr, 2),
14714                                 false, false, 2);
14715
14716     // Load the 'nest' parameter value into R10.
14717     // R10 is specified in X86CallingConv.td
14718     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14719     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14720                        DAG.getConstant(10, MVT::i64));
14721     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14722                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14723                                 false, false, 0);
14724
14725     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14726                        DAG.getConstant(12, MVT::i64));
14727     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14728                                 MachinePointerInfo(TrmpAddr, 12),
14729                                 false, false, 2);
14730
14731     // Jump to the nested function.
14732     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14733     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14734                        DAG.getConstant(20, MVT::i64));
14735     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14736                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14737                                 false, false, 0);
14738
14739     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14740     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14741                        DAG.getConstant(22, MVT::i64));
14742     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14743                                 MachinePointerInfo(TrmpAddr, 22),
14744                                 false, false, 0);
14745
14746     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14747   } else {
14748     const Function *Func =
14749       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14750     CallingConv::ID CC = Func->getCallingConv();
14751     unsigned NestReg;
14752
14753     switch (CC) {
14754     default:
14755       llvm_unreachable("Unsupported calling convention");
14756     case CallingConv::C:
14757     case CallingConv::X86_StdCall: {
14758       // Pass 'nest' parameter in ECX.
14759       // Must be kept in sync with X86CallingConv.td
14760       NestReg = X86::ECX;
14761
14762       // Check that ECX wasn't needed by an 'inreg' parameter.
14763       FunctionType *FTy = Func->getFunctionType();
14764       const AttributeSet &Attrs = Func->getAttributes();
14765
14766       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14767         unsigned InRegCount = 0;
14768         unsigned Idx = 1;
14769
14770         for (FunctionType::param_iterator I = FTy->param_begin(),
14771              E = FTy->param_end(); I != E; ++I, ++Idx)
14772           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14773             // FIXME: should only count parameters that are lowered to integers.
14774             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14775
14776         if (InRegCount > 2) {
14777           report_fatal_error("Nest register in use - reduce number of inreg"
14778                              " parameters!");
14779         }
14780       }
14781       break;
14782     }
14783     case CallingConv::X86_FastCall:
14784     case CallingConv::X86_ThisCall:
14785     case CallingConv::Fast:
14786       // Pass 'nest' parameter in EAX.
14787       // Must be kept in sync with X86CallingConv.td
14788       NestReg = X86::EAX;
14789       break;
14790     }
14791
14792     SDValue OutChains[4];
14793     SDValue Addr, Disp;
14794
14795     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14796                        DAG.getConstant(10, MVT::i32));
14797     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14798
14799     // This is storing the opcode for MOV32ri.
14800     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14801     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14802     OutChains[0] = DAG.getStore(Root, dl,
14803                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14804                                 Trmp, MachinePointerInfo(TrmpAddr),
14805                                 false, false, 0);
14806
14807     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14808                        DAG.getConstant(1, MVT::i32));
14809     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14810                                 MachinePointerInfo(TrmpAddr, 1),
14811                                 false, false, 1);
14812
14813     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14814     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14815                        DAG.getConstant(5, MVT::i32));
14816     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14817                                 MachinePointerInfo(TrmpAddr, 5),
14818                                 false, false, 1);
14819
14820     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14821                        DAG.getConstant(6, MVT::i32));
14822     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14823                                 MachinePointerInfo(TrmpAddr, 6),
14824                                 false, false, 1);
14825
14826     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14827   }
14828 }
14829
14830 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14831                                             SelectionDAG &DAG) const {
14832   /*
14833    The rounding mode is in bits 11:10 of FPSR, and has the following
14834    settings:
14835      00 Round to nearest
14836      01 Round to -inf
14837      10 Round to +inf
14838      11 Round to 0
14839
14840   FLT_ROUNDS, on the other hand, expects the following:
14841     -1 Undefined
14842      0 Round to 0
14843      1 Round to nearest
14844      2 Round to +inf
14845      3 Round to -inf
14846
14847   To perform the conversion, we do:
14848     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14849   */
14850
14851   MachineFunction &MF = DAG.getMachineFunction();
14852   const TargetMachine &TM = MF.getTarget();
14853   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14854   unsigned StackAlignment = TFI.getStackAlignment();
14855   MVT VT = Op.getSimpleValueType();
14856   SDLoc DL(Op);
14857
14858   // Save FP Control Word to stack slot
14859   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14860   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14861
14862   MachineMemOperand *MMO =
14863    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14864                            MachineMemOperand::MOStore, 2, 2);
14865
14866   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14867   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14868                                           DAG.getVTList(MVT::Other),
14869                                           Ops, MVT::i16, MMO);
14870
14871   // Load FP Control Word from stack slot
14872   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14873                             MachinePointerInfo(), false, false, false, 0);
14874
14875   // Transform as necessary
14876   SDValue CWD1 =
14877     DAG.getNode(ISD::SRL, DL, MVT::i16,
14878                 DAG.getNode(ISD::AND, DL, MVT::i16,
14879                             CWD, DAG.getConstant(0x800, MVT::i16)),
14880                 DAG.getConstant(11, MVT::i8));
14881   SDValue CWD2 =
14882     DAG.getNode(ISD::SRL, DL, MVT::i16,
14883                 DAG.getNode(ISD::AND, DL, MVT::i16,
14884                             CWD, DAG.getConstant(0x400, MVT::i16)),
14885                 DAG.getConstant(9, MVT::i8));
14886
14887   SDValue RetVal =
14888     DAG.getNode(ISD::AND, DL, MVT::i16,
14889                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14890                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14891                             DAG.getConstant(1, MVT::i16)),
14892                 DAG.getConstant(3, MVT::i16));
14893
14894   return DAG.getNode((VT.getSizeInBits() < 16 ?
14895                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14896 }
14897
14898 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14899   MVT VT = Op.getSimpleValueType();
14900   EVT OpVT = VT;
14901   unsigned NumBits = VT.getSizeInBits();
14902   SDLoc dl(Op);
14903
14904   Op = Op.getOperand(0);
14905   if (VT == MVT::i8) {
14906     // Zero extend to i32 since there is not an i8 bsr.
14907     OpVT = MVT::i32;
14908     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14909   }
14910
14911   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14912   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14913   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14914
14915   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14916   SDValue Ops[] = {
14917     Op,
14918     DAG.getConstant(NumBits+NumBits-1, OpVT),
14919     DAG.getConstant(X86::COND_E, MVT::i8),
14920     Op.getValue(1)
14921   };
14922   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14923
14924   // Finally xor with NumBits-1.
14925   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14926
14927   if (VT == MVT::i8)
14928     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14929   return Op;
14930 }
14931
14932 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14933   MVT VT = Op.getSimpleValueType();
14934   EVT OpVT = VT;
14935   unsigned NumBits = VT.getSizeInBits();
14936   SDLoc dl(Op);
14937
14938   Op = Op.getOperand(0);
14939   if (VT == MVT::i8) {
14940     // Zero extend to i32 since there is not an i8 bsr.
14941     OpVT = MVT::i32;
14942     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14943   }
14944
14945   // Issue a bsr (scan bits in reverse).
14946   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14947   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14948
14949   // And xor with NumBits-1.
14950   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14951
14952   if (VT == MVT::i8)
14953     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14954   return Op;
14955 }
14956
14957 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14958   MVT VT = Op.getSimpleValueType();
14959   unsigned NumBits = VT.getSizeInBits();
14960   SDLoc dl(Op);
14961   Op = Op.getOperand(0);
14962
14963   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14964   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14965   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14966
14967   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14968   SDValue Ops[] = {
14969     Op,
14970     DAG.getConstant(NumBits, VT),
14971     DAG.getConstant(X86::COND_E, MVT::i8),
14972     Op.getValue(1)
14973   };
14974   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14975 }
14976
14977 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14978 // ones, and then concatenate the result back.
14979 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14980   MVT VT = Op.getSimpleValueType();
14981
14982   assert(VT.is256BitVector() && VT.isInteger() &&
14983          "Unsupported value type for operation");
14984
14985   unsigned NumElems = VT.getVectorNumElements();
14986   SDLoc dl(Op);
14987
14988   // Extract the LHS vectors
14989   SDValue LHS = Op.getOperand(0);
14990   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14991   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14992
14993   // Extract the RHS vectors
14994   SDValue RHS = Op.getOperand(1);
14995   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
14996   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
14997
14998   MVT EltVT = VT.getVectorElementType();
14999   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15000
15001   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15002                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15003                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15004 }
15005
15006 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15007   assert(Op.getSimpleValueType().is256BitVector() &&
15008          Op.getSimpleValueType().isInteger() &&
15009          "Only handle AVX 256-bit vector integer operation");
15010   return Lower256IntArith(Op, DAG);
15011 }
15012
15013 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15014   assert(Op.getSimpleValueType().is256BitVector() &&
15015          Op.getSimpleValueType().isInteger() &&
15016          "Only handle AVX 256-bit vector integer operation");
15017   return Lower256IntArith(Op, DAG);
15018 }
15019
15020 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15021                         SelectionDAG &DAG) {
15022   SDLoc dl(Op);
15023   MVT VT = Op.getSimpleValueType();
15024
15025   // Decompose 256-bit ops into smaller 128-bit ops.
15026   if (VT.is256BitVector() && !Subtarget->hasInt256())
15027     return Lower256IntArith(Op, DAG);
15028
15029   SDValue A = Op.getOperand(0);
15030   SDValue B = Op.getOperand(1);
15031
15032   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15033   if (VT == MVT::v4i32) {
15034     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15035            "Should not custom lower when pmuldq is available!");
15036
15037     // Extract the odd parts.
15038     static const int UnpackMask[] = { 1, -1, 3, -1 };
15039     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15040     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15041
15042     // Multiply the even parts.
15043     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15044     // Now multiply odd parts.
15045     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15046
15047     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15048     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15049
15050     // Merge the two vectors back together with a shuffle. This expands into 2
15051     // shuffles.
15052     static const int ShufMask[] = { 0, 4, 2, 6 };
15053     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15054   }
15055
15056   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15057          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15058
15059   //  Ahi = psrlqi(a, 32);
15060   //  Bhi = psrlqi(b, 32);
15061   //
15062   //  AloBlo = pmuludq(a, b);
15063   //  AloBhi = pmuludq(a, Bhi);
15064   //  AhiBlo = pmuludq(Ahi, b);
15065
15066   //  AloBhi = psllqi(AloBhi, 32);
15067   //  AhiBlo = psllqi(AhiBlo, 32);
15068   //  return AloBlo + AloBhi + AhiBlo;
15069
15070   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15071   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15072
15073   // Bit cast to 32-bit vectors for MULUDQ
15074   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15075                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15076   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15077   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15078   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15079   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15080
15081   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15082   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15083   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15084
15085   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15086   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15087
15088   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15089   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15090 }
15091
15092 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15093   assert(Subtarget->isTargetWin64() && "Unexpected target");
15094   EVT VT = Op.getValueType();
15095   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15096          "Unexpected return type for lowering");
15097
15098   RTLIB::Libcall LC;
15099   bool isSigned;
15100   switch (Op->getOpcode()) {
15101   default: llvm_unreachable("Unexpected request for libcall!");
15102   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15103   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15104   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15105   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15106   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15107   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15108   }
15109
15110   SDLoc dl(Op);
15111   SDValue InChain = DAG.getEntryNode();
15112
15113   TargetLowering::ArgListTy Args;
15114   TargetLowering::ArgListEntry Entry;
15115   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15116     EVT ArgVT = Op->getOperand(i).getValueType();
15117     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15118            "Unexpected argument type for lowering");
15119     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15120     Entry.Node = StackPtr;
15121     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15122                            false, false, 16);
15123     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15124     Entry.Ty = PointerType::get(ArgTy,0);
15125     Entry.isSExt = false;
15126     Entry.isZExt = false;
15127     Args.push_back(Entry);
15128   }
15129
15130   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15131                                          getPointerTy());
15132
15133   TargetLowering::CallLoweringInfo CLI(DAG);
15134   CLI.setDebugLoc(dl).setChain(InChain)
15135     .setCallee(getLibcallCallingConv(LC),
15136                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15137                Callee, std::move(Args), 0)
15138     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15139
15140   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15141   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15142 }
15143
15144 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15145                              SelectionDAG &DAG) {
15146   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15147   EVT VT = Op0.getValueType();
15148   SDLoc dl(Op);
15149
15150   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15151          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15152
15153   // PMULxD operations multiply each even value (starting at 0) of LHS with
15154   // the related value of RHS and produce a widen result.
15155   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15156   // => <2 x i64> <ae|cg>
15157   //
15158   // In other word, to have all the results, we need to perform two PMULxD:
15159   // 1. one with the even values.
15160   // 2. one with the odd values.
15161   // To achieve #2, with need to place the odd values at an even position.
15162   //
15163   // Place the odd value at an even position (basically, shift all values 1
15164   // step to the left):
15165   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15166   // <a|b|c|d> => <b|undef|d|undef>
15167   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15168   // <e|f|g|h> => <f|undef|h|undef>
15169   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15170
15171   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15172   // ints.
15173   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15174   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15175   unsigned Opcode =
15176       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15177   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15178   // => <2 x i64> <ae|cg>
15179   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15180                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15181   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15182   // => <2 x i64> <bf|dh>
15183   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15184                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15185
15186   // Shuffle it back into the right order.
15187   // The internal representation is big endian.
15188   // In other words, a i64 bitcasted to 2 x i32 has its high part at index 0
15189   // and its low part at index 1.
15190   // Moreover, we have: Mul1 = <ae|cg> ; Mul2 = <bf|dh>
15191   // Vector index                0 1   ;          2 3
15192   // We want      <ae|bf|cg|dh>
15193   // Vector index   0  2  1  3
15194   // Since each element is seen as 2 x i32, we get:
15195   // high_mask[i] = 2 x vector_index[i]
15196   // low_mask[i] = 2 x vector_index[i] + 1
15197   // where vector_index = {0, Size/2, 1, Size/2 + 1, ...,
15198   //                       Size/2 - 1, Size/2 + Size/2 - 1}
15199   // where Size is the number of element of the final vector.
15200   SDValue Highs, Lows;
15201   if (VT == MVT::v8i32) {
15202     const int HighMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15203     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15204     const int LowMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15205     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15206   } else {
15207     const int HighMask[] = {0, 4, 2, 6};
15208     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15209     const int LowMask[] = {1, 5, 3, 7};
15210     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15211   }
15212
15213   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15214   // unsigned multiply.
15215   if (IsSigned && !Subtarget->hasSSE41()) {
15216     SDValue ShAmt =
15217         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15218     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15219                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15220     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15221                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15222
15223     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15224     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15225   }
15226
15227   // The low part of a MUL_LOHI is supposed to be the first value and the
15228   // high part the second value.
15229   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Lows, Highs);
15230 }
15231
15232 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15233                                          const X86Subtarget *Subtarget) {
15234   MVT VT = Op.getSimpleValueType();
15235   SDLoc dl(Op);
15236   SDValue R = Op.getOperand(0);
15237   SDValue Amt = Op.getOperand(1);
15238
15239   // Optimize shl/srl/sra with constant shift amount.
15240   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15241     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15242       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15243
15244       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15245           (Subtarget->hasInt256() &&
15246            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15247           (Subtarget->hasAVX512() &&
15248            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15249         if (Op.getOpcode() == ISD::SHL)
15250           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15251                                             DAG);
15252         if (Op.getOpcode() == ISD::SRL)
15253           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15254                                             DAG);
15255         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15256           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15257                                             DAG);
15258       }
15259
15260       if (VT == MVT::v16i8) {
15261         if (Op.getOpcode() == ISD::SHL) {
15262           // Make a large shift.
15263           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15264                                                    MVT::v8i16, R, ShiftAmt,
15265                                                    DAG);
15266           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15267           // Zero out the rightmost bits.
15268           SmallVector<SDValue, 16> V(16,
15269                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15270                                                      MVT::i8));
15271           return DAG.getNode(ISD::AND, dl, VT, SHL,
15272                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15273         }
15274         if (Op.getOpcode() == ISD::SRL) {
15275           // Make a large shift.
15276           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15277                                                    MVT::v8i16, R, ShiftAmt,
15278                                                    DAG);
15279           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15280           // Zero out the leftmost bits.
15281           SmallVector<SDValue, 16> V(16,
15282                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15283                                                      MVT::i8));
15284           return DAG.getNode(ISD::AND, dl, VT, SRL,
15285                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15286         }
15287         if (Op.getOpcode() == ISD::SRA) {
15288           if (ShiftAmt == 7) {
15289             // R s>> 7  ===  R s< 0
15290             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15291             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15292           }
15293
15294           // R s>> a === ((R u>> a) ^ m) - m
15295           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15296           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15297                                                          MVT::i8));
15298           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15299           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15300           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15301           return Res;
15302         }
15303         llvm_unreachable("Unknown shift opcode.");
15304       }
15305
15306       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15307         if (Op.getOpcode() == ISD::SHL) {
15308           // Make a large shift.
15309           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15310                                                    MVT::v16i16, R, ShiftAmt,
15311                                                    DAG);
15312           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15313           // Zero out the rightmost bits.
15314           SmallVector<SDValue, 32> V(32,
15315                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15316                                                      MVT::i8));
15317           return DAG.getNode(ISD::AND, dl, VT, SHL,
15318                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15319         }
15320         if (Op.getOpcode() == ISD::SRL) {
15321           // Make a large shift.
15322           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15323                                                    MVT::v16i16, R, ShiftAmt,
15324                                                    DAG);
15325           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15326           // Zero out the leftmost bits.
15327           SmallVector<SDValue, 32> V(32,
15328                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15329                                                      MVT::i8));
15330           return DAG.getNode(ISD::AND, dl, VT, SRL,
15331                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15332         }
15333         if (Op.getOpcode() == ISD::SRA) {
15334           if (ShiftAmt == 7) {
15335             // R s>> 7  ===  R s< 0
15336             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15337             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15338           }
15339
15340           // R s>> a === ((R u>> a) ^ m) - m
15341           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15342           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15343                                                          MVT::i8));
15344           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15345           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15346           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15347           return Res;
15348         }
15349         llvm_unreachable("Unknown shift opcode.");
15350       }
15351     }
15352   }
15353
15354   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15355   if (!Subtarget->is64Bit() &&
15356       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15357       Amt.getOpcode() == ISD::BITCAST &&
15358       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15359     Amt = Amt.getOperand(0);
15360     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15361                      VT.getVectorNumElements();
15362     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15363     uint64_t ShiftAmt = 0;
15364     for (unsigned i = 0; i != Ratio; ++i) {
15365       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15366       if (!C)
15367         return SDValue();
15368       // 6 == Log2(64)
15369       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15370     }
15371     // Check remaining shift amounts.
15372     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15373       uint64_t ShAmt = 0;
15374       for (unsigned j = 0; j != Ratio; ++j) {
15375         ConstantSDNode *C =
15376           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15377         if (!C)
15378           return SDValue();
15379         // 6 == Log2(64)
15380         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15381       }
15382       if (ShAmt != ShiftAmt)
15383         return SDValue();
15384     }
15385     switch (Op.getOpcode()) {
15386     default:
15387       llvm_unreachable("Unknown shift opcode!");
15388     case ISD::SHL:
15389       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15390                                         DAG);
15391     case ISD::SRL:
15392       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15393                                         DAG);
15394     case ISD::SRA:
15395       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15396                                         DAG);
15397     }
15398   }
15399
15400   return SDValue();
15401 }
15402
15403 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15404                                         const X86Subtarget* Subtarget) {
15405   MVT VT = Op.getSimpleValueType();
15406   SDLoc dl(Op);
15407   SDValue R = Op.getOperand(0);
15408   SDValue Amt = Op.getOperand(1);
15409
15410   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15411       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15412       (Subtarget->hasInt256() &&
15413        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15414         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15415        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15416     SDValue BaseShAmt;
15417     EVT EltVT = VT.getVectorElementType();
15418
15419     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15420       unsigned NumElts = VT.getVectorNumElements();
15421       unsigned i, j;
15422       for (i = 0; i != NumElts; ++i) {
15423         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15424           continue;
15425         break;
15426       }
15427       for (j = i; j != NumElts; ++j) {
15428         SDValue Arg = Amt.getOperand(j);
15429         if (Arg.getOpcode() == ISD::UNDEF) continue;
15430         if (Arg != Amt.getOperand(i))
15431           break;
15432       }
15433       if (i != NumElts && j == NumElts)
15434         BaseShAmt = Amt.getOperand(i);
15435     } else {
15436       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15437         Amt = Amt.getOperand(0);
15438       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15439                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15440         SDValue InVec = Amt.getOperand(0);
15441         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15442           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15443           unsigned i = 0;
15444           for (; i != NumElts; ++i) {
15445             SDValue Arg = InVec.getOperand(i);
15446             if (Arg.getOpcode() == ISD::UNDEF) continue;
15447             BaseShAmt = Arg;
15448             break;
15449           }
15450         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15451            if (ConstantSDNode *C =
15452                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15453              unsigned SplatIdx =
15454                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15455              if (C->getZExtValue() == SplatIdx)
15456                BaseShAmt = InVec.getOperand(1);
15457            }
15458         }
15459         if (!BaseShAmt.getNode())
15460           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15461                                   DAG.getIntPtrConstant(0));
15462       }
15463     }
15464
15465     if (BaseShAmt.getNode()) {
15466       if (EltVT.bitsGT(MVT::i32))
15467         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15468       else if (EltVT.bitsLT(MVT::i32))
15469         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15470
15471       switch (Op.getOpcode()) {
15472       default:
15473         llvm_unreachable("Unknown shift opcode!");
15474       case ISD::SHL:
15475         switch (VT.SimpleTy) {
15476         default: return SDValue();
15477         case MVT::v2i64:
15478         case MVT::v4i32:
15479         case MVT::v8i16:
15480         case MVT::v4i64:
15481         case MVT::v8i32:
15482         case MVT::v16i16:
15483         case MVT::v16i32:
15484         case MVT::v8i64:
15485           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15486         }
15487       case ISD::SRA:
15488         switch (VT.SimpleTy) {
15489         default: return SDValue();
15490         case MVT::v4i32:
15491         case MVT::v8i16:
15492         case MVT::v8i32:
15493         case MVT::v16i16:
15494         case MVT::v16i32:
15495         case MVT::v8i64:
15496           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15497         }
15498       case ISD::SRL:
15499         switch (VT.SimpleTy) {
15500         default: return SDValue();
15501         case MVT::v2i64:
15502         case MVT::v4i32:
15503         case MVT::v8i16:
15504         case MVT::v4i64:
15505         case MVT::v8i32:
15506         case MVT::v16i16:
15507         case MVT::v16i32:
15508         case MVT::v8i64:
15509           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15510         }
15511       }
15512     }
15513   }
15514
15515   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15516   if (!Subtarget->is64Bit() &&
15517       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15518       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15519       Amt.getOpcode() == ISD::BITCAST &&
15520       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15521     Amt = Amt.getOperand(0);
15522     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15523                      VT.getVectorNumElements();
15524     std::vector<SDValue> Vals(Ratio);
15525     for (unsigned i = 0; i != Ratio; ++i)
15526       Vals[i] = Amt.getOperand(i);
15527     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15528       for (unsigned j = 0; j != Ratio; ++j)
15529         if (Vals[j] != Amt.getOperand(i + j))
15530           return SDValue();
15531     }
15532     switch (Op.getOpcode()) {
15533     default:
15534       llvm_unreachable("Unknown shift opcode!");
15535     case ISD::SHL:
15536       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15537     case ISD::SRL:
15538       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15539     case ISD::SRA:
15540       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15541     }
15542   }
15543
15544   return SDValue();
15545 }
15546
15547 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15548                           SelectionDAG &DAG) {
15549   MVT VT = Op.getSimpleValueType();
15550   SDLoc dl(Op);
15551   SDValue R = Op.getOperand(0);
15552   SDValue Amt = Op.getOperand(1);
15553   SDValue V;
15554
15555   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15556   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15557
15558   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15559   if (V.getNode())
15560     return V;
15561
15562   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15563   if (V.getNode())
15564       return V;
15565
15566   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15567     return Op;
15568   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15569   if (Subtarget->hasInt256()) {
15570     if (Op.getOpcode() == ISD::SRL &&
15571         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15572          VT == MVT::v4i64 || VT == MVT::v8i32))
15573       return Op;
15574     if (Op.getOpcode() == ISD::SHL &&
15575         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15576          VT == MVT::v4i64 || VT == MVT::v8i32))
15577       return Op;
15578     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15579       return Op;
15580   }
15581
15582   // If possible, lower this packed shift into a vector multiply instead of
15583   // expanding it into a sequence of scalar shifts.
15584   // Do this only if the vector shift count is a constant build_vector.
15585   if (Op.getOpcode() == ISD::SHL && 
15586       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15587        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15588       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15589     SmallVector<SDValue, 8> Elts;
15590     EVT SVT = VT.getScalarType();
15591     unsigned SVTBits = SVT.getSizeInBits();
15592     const APInt &One = APInt(SVTBits, 1);
15593     unsigned NumElems = VT.getVectorNumElements();
15594
15595     for (unsigned i=0; i !=NumElems; ++i) {
15596       SDValue Op = Amt->getOperand(i);
15597       if (Op->getOpcode() == ISD::UNDEF) {
15598         Elts.push_back(Op);
15599         continue;
15600       }
15601
15602       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15603       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15604       uint64_t ShAmt = C.getZExtValue();
15605       if (ShAmt >= SVTBits) {
15606         Elts.push_back(DAG.getUNDEF(SVT));
15607         continue;
15608       }
15609       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15610     }
15611     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15612     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15613   }
15614
15615   // Lower SHL with variable shift amount.
15616   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15617     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15618
15619     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15620     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15621     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15622     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15623   }
15624
15625   // If possible, lower this shift as a sequence of two shifts by
15626   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15627   // Example:
15628   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15629   //
15630   // Could be rewritten as:
15631   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15632   //
15633   // The advantage is that the two shifts from the example would be
15634   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15635   // the vector shift into four scalar shifts plus four pairs of vector
15636   // insert/extract.
15637   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15638       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15639     unsigned TargetOpcode = X86ISD::MOVSS;
15640     bool CanBeSimplified;
15641     // The splat value for the first packed shift (the 'X' from the example).
15642     SDValue Amt1 = Amt->getOperand(0);
15643     // The splat value for the second packed shift (the 'Y' from the example).
15644     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15645                                         Amt->getOperand(2);
15646
15647     // See if it is possible to replace this node with a sequence of
15648     // two shifts followed by a MOVSS/MOVSD
15649     if (VT == MVT::v4i32) {
15650       // Check if it is legal to use a MOVSS.
15651       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15652                         Amt2 == Amt->getOperand(3);
15653       if (!CanBeSimplified) {
15654         // Otherwise, check if we can still simplify this node using a MOVSD.
15655         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15656                           Amt->getOperand(2) == Amt->getOperand(3);
15657         TargetOpcode = X86ISD::MOVSD;
15658         Amt2 = Amt->getOperand(2);
15659       }
15660     } else {
15661       // Do similar checks for the case where the machine value type
15662       // is MVT::v8i16.
15663       CanBeSimplified = Amt1 == Amt->getOperand(1);
15664       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15665         CanBeSimplified = Amt2 == Amt->getOperand(i);
15666
15667       if (!CanBeSimplified) {
15668         TargetOpcode = X86ISD::MOVSD;
15669         CanBeSimplified = true;
15670         Amt2 = Amt->getOperand(4);
15671         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15672           CanBeSimplified = Amt1 == Amt->getOperand(i);
15673         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15674           CanBeSimplified = Amt2 == Amt->getOperand(j);
15675       }
15676     }
15677     
15678     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15679         isa<ConstantSDNode>(Amt2)) {
15680       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15681       EVT CastVT = MVT::v4i32;
15682       SDValue Splat1 = 
15683         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15684       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15685       SDValue Splat2 = 
15686         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15687       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15688       if (TargetOpcode == X86ISD::MOVSD)
15689         CastVT = MVT::v2i64;
15690       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15691       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15692       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15693                                             BitCast1, DAG);
15694       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15695     }
15696   }
15697
15698   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15699     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15700
15701     // a = a << 5;
15702     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15703     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15704
15705     // Turn 'a' into a mask suitable for VSELECT
15706     SDValue VSelM = DAG.getConstant(0x80, VT);
15707     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15708     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15709
15710     SDValue CM1 = DAG.getConstant(0x0f, VT);
15711     SDValue CM2 = DAG.getConstant(0x3f, VT);
15712
15713     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15714     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15715     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15716     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15717     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15718
15719     // a += a
15720     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15721     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15722     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15723
15724     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15725     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15726     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15727     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15728     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15729
15730     // a += a
15731     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15732     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15733     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15734
15735     // return VSELECT(r, r+r, a);
15736     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15737                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15738     return R;
15739   }
15740
15741   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15742   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15743   // solution better.
15744   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15745     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15746     unsigned ExtOpc =
15747         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15748     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15749     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15750     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15751                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15752     }
15753
15754   // Decompose 256-bit shifts into smaller 128-bit shifts.
15755   if (VT.is256BitVector()) {
15756     unsigned NumElems = VT.getVectorNumElements();
15757     MVT EltVT = VT.getVectorElementType();
15758     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15759
15760     // Extract the two vectors
15761     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15762     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15763
15764     // Recreate the shift amount vectors
15765     SDValue Amt1, Amt2;
15766     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15767       // Constant shift amount
15768       SmallVector<SDValue, 4> Amt1Csts;
15769       SmallVector<SDValue, 4> Amt2Csts;
15770       for (unsigned i = 0; i != NumElems/2; ++i)
15771         Amt1Csts.push_back(Amt->getOperand(i));
15772       for (unsigned i = NumElems/2; i != NumElems; ++i)
15773         Amt2Csts.push_back(Amt->getOperand(i));
15774
15775       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15776       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15777     } else {
15778       // Variable shift amount
15779       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15780       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15781     }
15782
15783     // Issue new vector shifts for the smaller types
15784     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15785     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15786
15787     // Concatenate the result back
15788     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15789   }
15790
15791   return SDValue();
15792 }
15793
15794 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15795   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15796   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15797   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15798   // has only one use.
15799   SDNode *N = Op.getNode();
15800   SDValue LHS = N->getOperand(0);
15801   SDValue RHS = N->getOperand(1);
15802   unsigned BaseOp = 0;
15803   unsigned Cond = 0;
15804   SDLoc DL(Op);
15805   switch (Op.getOpcode()) {
15806   default: llvm_unreachable("Unknown ovf instruction!");
15807   case ISD::SADDO:
15808     // A subtract of one will be selected as a INC. Note that INC doesn't
15809     // set CF, so we can't do this for UADDO.
15810     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15811       if (C->isOne()) {
15812         BaseOp = X86ISD::INC;
15813         Cond = X86::COND_O;
15814         break;
15815       }
15816     BaseOp = X86ISD::ADD;
15817     Cond = X86::COND_O;
15818     break;
15819   case ISD::UADDO:
15820     BaseOp = X86ISD::ADD;
15821     Cond = X86::COND_B;
15822     break;
15823   case ISD::SSUBO:
15824     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15825     // set CF, so we can't do this for USUBO.
15826     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15827       if (C->isOne()) {
15828         BaseOp = X86ISD::DEC;
15829         Cond = X86::COND_O;
15830         break;
15831       }
15832     BaseOp = X86ISD::SUB;
15833     Cond = X86::COND_O;
15834     break;
15835   case ISD::USUBO:
15836     BaseOp = X86ISD::SUB;
15837     Cond = X86::COND_B;
15838     break;
15839   case ISD::SMULO:
15840     BaseOp = X86ISD::SMUL;
15841     Cond = X86::COND_O;
15842     break;
15843   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15844     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15845                                  MVT::i32);
15846     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15847
15848     SDValue SetCC =
15849       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15850                   DAG.getConstant(X86::COND_O, MVT::i32),
15851                   SDValue(Sum.getNode(), 2));
15852
15853     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15854   }
15855   }
15856
15857   // Also sets EFLAGS.
15858   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15859   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15860
15861   SDValue SetCC =
15862     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15863                 DAG.getConstant(Cond, MVT::i32),
15864                 SDValue(Sum.getNode(), 1));
15865
15866   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15867 }
15868
15869 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15870                                                   SelectionDAG &DAG) const {
15871   SDLoc dl(Op);
15872   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15873   MVT VT = Op.getSimpleValueType();
15874
15875   if (!Subtarget->hasSSE2() || !VT.isVector())
15876     return SDValue();
15877
15878   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15879                       ExtraVT.getScalarType().getSizeInBits();
15880
15881   switch (VT.SimpleTy) {
15882     default: return SDValue();
15883     case MVT::v8i32:
15884     case MVT::v16i16:
15885       if (!Subtarget->hasFp256())
15886         return SDValue();
15887       if (!Subtarget->hasInt256()) {
15888         // needs to be split
15889         unsigned NumElems = VT.getVectorNumElements();
15890
15891         // Extract the LHS vectors
15892         SDValue LHS = Op.getOperand(0);
15893         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15894         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15895
15896         MVT EltVT = VT.getVectorElementType();
15897         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15898
15899         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15900         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15901         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15902                                    ExtraNumElems/2);
15903         SDValue Extra = DAG.getValueType(ExtraVT);
15904
15905         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15906         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15907
15908         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15909       }
15910       // fall through
15911     case MVT::v4i32:
15912     case MVT::v8i16: {
15913       SDValue Op0 = Op.getOperand(0);
15914       SDValue Op00 = Op0.getOperand(0);
15915       SDValue Tmp1;
15916       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15917       if (Op0.getOpcode() == ISD::BITCAST &&
15918           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15919         // (sext (vzext x)) -> (vsext x)
15920         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15921         if (Tmp1.getNode()) {
15922           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15923           // This folding is only valid when the in-reg type is a vector of i8,
15924           // i16, or i32.
15925           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15926               ExtraEltVT == MVT::i32) {
15927             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15928             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15929                    "This optimization is invalid without a VZEXT.");
15930             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15931           }
15932           Op0 = Tmp1;
15933         }
15934       }
15935
15936       // If the above didn't work, then just use Shift-Left + Shift-Right.
15937       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15938                                         DAG);
15939       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15940                                         DAG);
15941     }
15942   }
15943 }
15944
15945 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15946                                  SelectionDAG &DAG) {
15947   SDLoc dl(Op);
15948   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15949     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15950   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15951     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15952
15953   // The only fence that needs an instruction is a sequentially-consistent
15954   // cross-thread fence.
15955   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15956     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15957     // no-sse2). There isn't any reason to disable it if the target processor
15958     // supports it.
15959     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15960       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15961
15962     SDValue Chain = Op.getOperand(0);
15963     SDValue Zero = DAG.getConstant(0, MVT::i32);
15964     SDValue Ops[] = {
15965       DAG.getRegister(X86::ESP, MVT::i32), // Base
15966       DAG.getTargetConstant(1, MVT::i8),   // Scale
15967       DAG.getRegister(0, MVT::i32),        // Index
15968       DAG.getTargetConstant(0, MVT::i32),  // Disp
15969       DAG.getRegister(0, MVT::i32),        // Segment.
15970       Zero,
15971       Chain
15972     };
15973     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15974     return SDValue(Res, 0);
15975   }
15976
15977   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15978   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15979 }
15980
15981 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15982                              SelectionDAG &DAG) {
15983   MVT T = Op.getSimpleValueType();
15984   SDLoc DL(Op);
15985   unsigned Reg = 0;
15986   unsigned size = 0;
15987   switch(T.SimpleTy) {
15988   default: llvm_unreachable("Invalid value type!");
15989   case MVT::i8:  Reg = X86::AL;  size = 1; break;
15990   case MVT::i16: Reg = X86::AX;  size = 2; break;
15991   case MVT::i32: Reg = X86::EAX; size = 4; break;
15992   case MVT::i64:
15993     assert(Subtarget->is64Bit() && "Node not type legal!");
15994     Reg = X86::RAX; size = 8;
15995     break;
15996   }
15997   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15998                                   Op.getOperand(2), SDValue());
15999   SDValue Ops[] = { cpIn.getValue(0),
16000                     Op.getOperand(1),
16001                     Op.getOperand(3),
16002                     DAG.getTargetConstant(size, MVT::i8),
16003                     cpIn.getValue(1) };
16004   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16005   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16006   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16007                                            Ops, T, MMO);
16008
16009   SDValue cpOut =
16010     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16011   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16012                                       MVT::i32, cpOut.getValue(2));
16013   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16014                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16015
16016   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16017   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16018   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16019   return SDValue();
16020 }
16021
16022 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16023                             SelectionDAG &DAG) {
16024   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16025   MVT DstVT = Op.getSimpleValueType();
16026
16027   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16028     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16029     if (DstVT != MVT::f64)
16030       // This conversion needs to be expanded.
16031       return SDValue();
16032
16033     SDValue InVec = Op->getOperand(0);
16034     SDLoc dl(Op);
16035     unsigned NumElts = SrcVT.getVectorNumElements();
16036     EVT SVT = SrcVT.getVectorElementType();
16037
16038     // Widen the vector in input in the case of MVT::v2i32.
16039     // Example: from MVT::v2i32 to MVT::v4i32.
16040     SmallVector<SDValue, 16> Elts;
16041     for (unsigned i = 0, e = NumElts; i != e; ++i)
16042       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16043                                  DAG.getIntPtrConstant(i)));
16044
16045     // Explicitly mark the extra elements as Undef.
16046     SDValue Undef = DAG.getUNDEF(SVT);
16047     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16048       Elts.push_back(Undef);
16049
16050     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16051     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16052     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16053     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16054                        DAG.getIntPtrConstant(0));
16055   }
16056
16057   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16058          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16059   assert((DstVT == MVT::i64 ||
16060           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16061          "Unexpected custom BITCAST");
16062   // i64 <=> MMX conversions are Legal.
16063   if (SrcVT==MVT::i64 && DstVT.isVector())
16064     return Op;
16065   if (DstVT==MVT::i64 && SrcVT.isVector())
16066     return Op;
16067   // MMX <=> MMX conversions are Legal.
16068   if (SrcVT.isVector() && DstVT.isVector())
16069     return Op;
16070   // All other conversions need to be expanded.
16071   return SDValue();
16072 }
16073
16074 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16075   SDNode *Node = Op.getNode();
16076   SDLoc dl(Node);
16077   EVT T = Node->getValueType(0);
16078   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16079                               DAG.getConstant(0, T), Node->getOperand(2));
16080   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16081                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16082                        Node->getOperand(0),
16083                        Node->getOperand(1), negOp,
16084                        cast<AtomicSDNode>(Node)->getMemOperand(),
16085                        cast<AtomicSDNode>(Node)->getOrdering(),
16086                        cast<AtomicSDNode>(Node)->getSynchScope());
16087 }
16088
16089 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16090   SDNode *Node = Op.getNode();
16091   SDLoc dl(Node);
16092   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16093
16094   // Convert seq_cst store -> xchg
16095   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16096   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16097   //        (The only way to get a 16-byte store is cmpxchg16b)
16098   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16099   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16100       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16101     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16102                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16103                                  Node->getOperand(0),
16104                                  Node->getOperand(1), Node->getOperand(2),
16105                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16106                                  cast<AtomicSDNode>(Node)->getOrdering(),
16107                                  cast<AtomicSDNode>(Node)->getSynchScope());
16108     return Swap.getValue(1);
16109   }
16110   // Other atomic stores have a simple pattern.
16111   return Op;
16112 }
16113
16114 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16115   EVT VT = Op.getNode()->getSimpleValueType(0);
16116
16117   // Let legalize expand this if it isn't a legal type yet.
16118   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16119     return SDValue();
16120
16121   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16122
16123   unsigned Opc;
16124   bool ExtraOp = false;
16125   switch (Op.getOpcode()) {
16126   default: llvm_unreachable("Invalid code");
16127   case ISD::ADDC: Opc = X86ISD::ADD; break;
16128   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16129   case ISD::SUBC: Opc = X86ISD::SUB; break;
16130   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16131   }
16132
16133   if (!ExtraOp)
16134     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16135                        Op.getOperand(1));
16136   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16137                      Op.getOperand(1), Op.getOperand(2));
16138 }
16139
16140 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16141                             SelectionDAG &DAG) {
16142   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16143
16144   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16145   // which returns the values as { float, float } (in XMM0) or
16146   // { double, double } (which is returned in XMM0, XMM1).
16147   SDLoc dl(Op);
16148   SDValue Arg = Op.getOperand(0);
16149   EVT ArgVT = Arg.getValueType();
16150   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16151
16152   TargetLowering::ArgListTy Args;
16153   TargetLowering::ArgListEntry Entry;
16154
16155   Entry.Node = Arg;
16156   Entry.Ty = ArgTy;
16157   Entry.isSExt = false;
16158   Entry.isZExt = false;
16159   Args.push_back(Entry);
16160
16161   bool isF64 = ArgVT == MVT::f64;
16162   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16163   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16164   // the results are returned via SRet in memory.
16165   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16167   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16168
16169   Type *RetTy = isF64
16170     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16171     : (Type*)VectorType::get(ArgTy, 4);
16172
16173   TargetLowering::CallLoweringInfo CLI(DAG);
16174   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16175     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16176
16177   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16178
16179   if (isF64)
16180     // Returned in xmm0 and xmm1.
16181     return CallResult.first;
16182
16183   // Returned in bits 0:31 and 32:64 xmm0.
16184   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16185                                CallResult.first, DAG.getIntPtrConstant(0));
16186   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16187                                CallResult.first, DAG.getIntPtrConstant(1));
16188   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16189   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16190 }
16191
16192 /// LowerOperation - Provide custom lowering hooks for some operations.
16193 ///
16194 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16195   switch (Op.getOpcode()) {
16196   default: llvm_unreachable("Should not custom lower this!");
16197   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16198   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16199   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16200     return LowerCMP_SWAP(Op, Subtarget, DAG);
16201   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16202   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16203   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16204   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16205   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16206   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16207   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16208   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16209   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16210   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16211   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16212   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16213   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16214   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16215   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16216   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16217   case ISD::SHL_PARTS:
16218   case ISD::SRA_PARTS:
16219   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16220   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16221   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16222   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16223   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16224   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16225   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16226   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16227   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16228   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16229   case ISD::FABS:               return LowerFABS(Op, DAG);
16230   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16231   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16232   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16233   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16234   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16235   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16236   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16237   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16238   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16239   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16240   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16241   case ISD::INTRINSIC_VOID:
16242   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16243   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16244   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16245   case ISD::FRAME_TO_ARGS_OFFSET:
16246                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16247   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16248   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16249   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16250   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16251   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16252   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16253   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16254   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16255   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16256   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16257   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16258   case ISD::UMUL_LOHI:
16259   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16260   case ISD::SRA:
16261   case ISD::SRL:
16262   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16263   case ISD::SADDO:
16264   case ISD::UADDO:
16265   case ISD::SSUBO:
16266   case ISD::USUBO:
16267   case ISD::SMULO:
16268   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16269   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16270   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16271   case ISD::ADDC:
16272   case ISD::ADDE:
16273   case ISD::SUBC:
16274   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16275   case ISD::ADD:                return LowerADD(Op, DAG);
16276   case ISD::SUB:                return LowerSUB(Op, DAG);
16277   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16278   }
16279 }
16280
16281 static void ReplaceATOMIC_LOAD(SDNode *Node,
16282                                SmallVectorImpl<SDValue> &Results,
16283                                SelectionDAG &DAG) {
16284   SDLoc dl(Node);
16285   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16286
16287   // Convert wide load -> cmpxchg8b/cmpxchg16b
16288   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16289   //        (The only way to get a 16-byte load is cmpxchg16b)
16290   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16291   SDValue Zero = DAG.getConstant(0, VT);
16292   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16293   SDValue Swap =
16294       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16295                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16296                            cast<AtomicSDNode>(Node)->getMemOperand(),
16297                            cast<AtomicSDNode>(Node)->getOrdering(),
16298                            cast<AtomicSDNode>(Node)->getOrdering(),
16299                            cast<AtomicSDNode>(Node)->getSynchScope());
16300   Results.push_back(Swap.getValue(0));
16301   Results.push_back(Swap.getValue(2));
16302 }
16303
16304 /// ReplaceNodeResults - Replace a node with an illegal result type
16305 /// with a new node built out of custom code.
16306 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16307                                            SmallVectorImpl<SDValue>&Results,
16308                                            SelectionDAG &DAG) const {
16309   SDLoc dl(N);
16310   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16311   switch (N->getOpcode()) {
16312   default:
16313     llvm_unreachable("Do not know how to custom type legalize this operation!");
16314   case ISD::SIGN_EXTEND_INREG:
16315   case ISD::ADDC:
16316   case ISD::ADDE:
16317   case ISD::SUBC:
16318   case ISD::SUBE:
16319     // We don't want to expand or promote these.
16320     return;
16321   case ISD::SDIV:
16322   case ISD::UDIV:
16323   case ISD::SREM:
16324   case ISD::UREM:
16325   case ISD::SDIVREM:
16326   case ISD::UDIVREM: {
16327     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16328     Results.push_back(V);
16329     return;
16330   }
16331   case ISD::FP_TO_SINT:
16332   case ISD::FP_TO_UINT: {
16333     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16334
16335     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16336       return;
16337
16338     std::pair<SDValue,SDValue> Vals =
16339         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16340     SDValue FIST = Vals.first, StackSlot = Vals.second;
16341     if (FIST.getNode()) {
16342       EVT VT = N->getValueType(0);
16343       // Return a load from the stack slot.
16344       if (StackSlot.getNode())
16345         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16346                                       MachinePointerInfo(),
16347                                       false, false, false, 0));
16348       else
16349         Results.push_back(FIST);
16350     }
16351     return;
16352   }
16353   case ISD::UINT_TO_FP: {
16354     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16355     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16356         N->getValueType(0) != MVT::v2f32)
16357       return;
16358     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16359                                  N->getOperand(0));
16360     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16361                                      MVT::f64);
16362     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16363     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16364                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16365     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16366     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16367     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16368     return;
16369   }
16370   case ISD::FP_ROUND: {
16371     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16372         return;
16373     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16374     Results.push_back(V);
16375     return;
16376   }
16377   case ISD::INTRINSIC_W_CHAIN: {
16378     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16379     switch (IntNo) {
16380     default : llvm_unreachable("Do not know how to custom type "
16381                                "legalize this intrinsic operation!");
16382     case Intrinsic::x86_rdtsc:
16383       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16384                                      Results);
16385     case Intrinsic::x86_rdtscp:
16386       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16387                                      Results);
16388     case Intrinsic::x86_rdpmc:
16389       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16390     }
16391   }
16392   case ISD::READCYCLECOUNTER: {
16393     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16394                                    Results);
16395   }
16396   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16397     EVT T = N->getValueType(0);
16398     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16399     bool Regs64bit = T == MVT::i128;
16400     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16401     SDValue cpInL, cpInH;
16402     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16403                         DAG.getConstant(0, HalfT));
16404     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16405                         DAG.getConstant(1, HalfT));
16406     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16407                              Regs64bit ? X86::RAX : X86::EAX,
16408                              cpInL, SDValue());
16409     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16410                              Regs64bit ? X86::RDX : X86::EDX,
16411                              cpInH, cpInL.getValue(1));
16412     SDValue swapInL, swapInH;
16413     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16414                           DAG.getConstant(0, HalfT));
16415     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16416                           DAG.getConstant(1, HalfT));
16417     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16418                                Regs64bit ? X86::RBX : X86::EBX,
16419                                swapInL, cpInH.getValue(1));
16420     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16421                                Regs64bit ? X86::RCX : X86::ECX,
16422                                swapInH, swapInL.getValue(1));
16423     SDValue Ops[] = { swapInH.getValue(0),
16424                       N->getOperand(1),
16425                       swapInH.getValue(1) };
16426     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16427     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16428     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16429                                   X86ISD::LCMPXCHG8_DAG;
16430     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16431     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16432                                         Regs64bit ? X86::RAX : X86::EAX,
16433                                         HalfT, Result.getValue(1));
16434     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16435                                         Regs64bit ? X86::RDX : X86::EDX,
16436                                         HalfT, cpOutL.getValue(2));
16437     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16438
16439     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16440                                         MVT::i32, cpOutH.getValue(2));
16441     SDValue Success =
16442         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16443                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16444     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16445
16446     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16447     Results.push_back(Success);
16448     Results.push_back(EFLAGS.getValue(1));
16449     return;
16450   }
16451   case ISD::ATOMIC_SWAP:
16452   case ISD::ATOMIC_LOAD_ADD:
16453   case ISD::ATOMIC_LOAD_SUB:
16454   case ISD::ATOMIC_LOAD_AND:
16455   case ISD::ATOMIC_LOAD_OR:
16456   case ISD::ATOMIC_LOAD_XOR:
16457   case ISD::ATOMIC_LOAD_NAND:
16458   case ISD::ATOMIC_LOAD_MIN:
16459   case ISD::ATOMIC_LOAD_MAX:
16460   case ISD::ATOMIC_LOAD_UMIN:
16461   case ISD::ATOMIC_LOAD_UMAX:
16462     // Delegate to generic TypeLegalization. Situations we can really handle
16463     // should have already been dealt with by X86AtomicExpand.cpp.
16464     break;
16465   case ISD::ATOMIC_LOAD: {
16466     ReplaceATOMIC_LOAD(N, Results, DAG);
16467     return;
16468   }
16469   case ISD::BITCAST: {
16470     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16471     EVT DstVT = N->getValueType(0);
16472     EVT SrcVT = N->getOperand(0)->getValueType(0);
16473
16474     if (SrcVT != MVT::f64 ||
16475         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16476       return;
16477
16478     unsigned NumElts = DstVT.getVectorNumElements();
16479     EVT SVT = DstVT.getVectorElementType();
16480     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16481     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16482                                    MVT::v2f64, N->getOperand(0));
16483     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16484
16485     if (ExperimentalVectorWideningLegalization) {
16486       // If we are legalizing vectors by widening, we already have the desired
16487       // legal vector type, just return it.
16488       Results.push_back(ToVecInt);
16489       return;
16490     }
16491
16492     SmallVector<SDValue, 8> Elts;
16493     for (unsigned i = 0, e = NumElts; i != e; ++i)
16494       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16495                                    ToVecInt, DAG.getIntPtrConstant(i)));
16496
16497     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16498   }
16499   }
16500 }
16501
16502 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16503   switch (Opcode) {
16504   default: return nullptr;
16505   case X86ISD::BSF:                return "X86ISD::BSF";
16506   case X86ISD::BSR:                return "X86ISD::BSR";
16507   case X86ISD::SHLD:               return "X86ISD::SHLD";
16508   case X86ISD::SHRD:               return "X86ISD::SHRD";
16509   case X86ISD::FAND:               return "X86ISD::FAND";
16510   case X86ISD::FANDN:              return "X86ISD::FANDN";
16511   case X86ISD::FOR:                return "X86ISD::FOR";
16512   case X86ISD::FXOR:               return "X86ISD::FXOR";
16513   case X86ISD::FSRL:               return "X86ISD::FSRL";
16514   case X86ISD::FILD:               return "X86ISD::FILD";
16515   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16516   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16517   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16518   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16519   case X86ISD::FLD:                return "X86ISD::FLD";
16520   case X86ISD::FST:                return "X86ISD::FST";
16521   case X86ISD::CALL:               return "X86ISD::CALL";
16522   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16523   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16524   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16525   case X86ISD::BT:                 return "X86ISD::BT";
16526   case X86ISD::CMP:                return "X86ISD::CMP";
16527   case X86ISD::COMI:               return "X86ISD::COMI";
16528   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16529   case X86ISD::CMPM:               return "X86ISD::CMPM";
16530   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16531   case X86ISD::SETCC:              return "X86ISD::SETCC";
16532   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16533   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16534   case X86ISD::CMOV:               return "X86ISD::CMOV";
16535   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16536   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16537   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16538   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16539   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16540   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16541   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16542   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16543   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16544   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16545   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16546   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16547   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16548   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16549   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16550   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16551   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16552   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16553   case X86ISD::HADD:               return "X86ISD::HADD";
16554   case X86ISD::HSUB:               return "X86ISD::HSUB";
16555   case X86ISD::FHADD:              return "X86ISD::FHADD";
16556   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16557   case X86ISD::UMAX:               return "X86ISD::UMAX";
16558   case X86ISD::UMIN:               return "X86ISD::UMIN";
16559   case X86ISD::SMAX:               return "X86ISD::SMAX";
16560   case X86ISD::SMIN:               return "X86ISD::SMIN";
16561   case X86ISD::FMAX:               return "X86ISD::FMAX";
16562   case X86ISD::FMIN:               return "X86ISD::FMIN";
16563   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16564   case X86ISD::FMINC:              return "X86ISD::FMINC";
16565   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16566   case X86ISD::FRCP:               return "X86ISD::FRCP";
16567   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16568   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16569   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16570   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16571   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16572   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16573   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16574   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16575   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16576   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16577   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16578   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16579   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16580   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16581   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16582   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16583   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16584   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16585   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16586   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16587   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16588   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16589   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16590   case X86ISD::VSHL:               return "X86ISD::VSHL";
16591   case X86ISD::VSRL:               return "X86ISD::VSRL";
16592   case X86ISD::VSRA:               return "X86ISD::VSRA";
16593   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16594   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16595   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16596   case X86ISD::CMPP:               return "X86ISD::CMPP";
16597   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16598   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16599   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16600   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16601   case X86ISD::ADD:                return "X86ISD::ADD";
16602   case X86ISD::SUB:                return "X86ISD::SUB";
16603   case X86ISD::ADC:                return "X86ISD::ADC";
16604   case X86ISD::SBB:                return "X86ISD::SBB";
16605   case X86ISD::SMUL:               return "X86ISD::SMUL";
16606   case X86ISD::UMUL:               return "X86ISD::UMUL";
16607   case X86ISD::INC:                return "X86ISD::INC";
16608   case X86ISD::DEC:                return "X86ISD::DEC";
16609   case X86ISD::OR:                 return "X86ISD::OR";
16610   case X86ISD::XOR:                return "X86ISD::XOR";
16611   case X86ISD::AND:                return "X86ISD::AND";
16612   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16613   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16614   case X86ISD::PTEST:              return "X86ISD::PTEST";
16615   case X86ISD::TESTP:              return "X86ISD::TESTP";
16616   case X86ISD::TESTM:              return "X86ISD::TESTM";
16617   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16618   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16619   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16620   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16621   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16622   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16623   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16624   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16625   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16626   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16627   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16628   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16629   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16630   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16631   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16632   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16633   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16634   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16635   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16636   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16637   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16638   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16639   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16640   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16641   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16642   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16643   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16644   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16645   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16646   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16647   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16648   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16649   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16650   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16651   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16652   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16653   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16654   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16655   case X86ISD::SAHF:               return "X86ISD::SAHF";
16656   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16657   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16658   case X86ISD::FMADD:              return "X86ISD::FMADD";
16659   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16660   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16661   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16662   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16663   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16664   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16665   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16666   case X86ISD::XTEST:              return "X86ISD::XTEST";
16667   }
16668 }
16669
16670 // isLegalAddressingMode - Return true if the addressing mode represented
16671 // by AM is legal for this target, for a load/store of the specified type.
16672 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16673                                               Type *Ty) const {
16674   // X86 supports extremely general addressing modes.
16675   CodeModel::Model M = getTargetMachine().getCodeModel();
16676   Reloc::Model R = getTargetMachine().getRelocationModel();
16677
16678   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16679   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16680     return false;
16681
16682   if (AM.BaseGV) {
16683     unsigned GVFlags =
16684       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16685
16686     // If a reference to this global requires an extra load, we can't fold it.
16687     if (isGlobalStubReference(GVFlags))
16688       return false;
16689
16690     // If BaseGV requires a register for the PIC base, we cannot also have a
16691     // BaseReg specified.
16692     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16693       return false;
16694
16695     // If lower 4G is not available, then we must use rip-relative addressing.
16696     if ((M != CodeModel::Small || R != Reloc::Static) &&
16697         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16698       return false;
16699   }
16700
16701   switch (AM.Scale) {
16702   case 0:
16703   case 1:
16704   case 2:
16705   case 4:
16706   case 8:
16707     // These scales always work.
16708     break;
16709   case 3:
16710   case 5:
16711   case 9:
16712     // These scales are formed with basereg+scalereg.  Only accept if there is
16713     // no basereg yet.
16714     if (AM.HasBaseReg)
16715       return false;
16716     break;
16717   default:  // Other stuff never works.
16718     return false;
16719   }
16720
16721   return true;
16722 }
16723
16724 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16725   unsigned Bits = Ty->getScalarSizeInBits();
16726
16727   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16728   // particularly cheaper than those without.
16729   if (Bits == 8)
16730     return false;
16731
16732   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16733   // variable shifts just as cheap as scalar ones.
16734   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16735     return false;
16736
16737   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16738   // fully general vector.
16739   return true;
16740 }
16741
16742 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16743   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16744     return false;
16745   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16746   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16747   return NumBits1 > NumBits2;
16748 }
16749
16750 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16751   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16752     return false;
16753
16754   if (!isTypeLegal(EVT::getEVT(Ty1)))
16755     return false;
16756
16757   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16758
16759   // Assuming the caller doesn't have a zeroext or signext return parameter,
16760   // truncation all the way down to i1 is valid.
16761   return true;
16762 }
16763
16764 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16765   return isInt<32>(Imm);
16766 }
16767
16768 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16769   // Can also use sub to handle negated immediates.
16770   return isInt<32>(Imm);
16771 }
16772
16773 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16774   if (!VT1.isInteger() || !VT2.isInteger())
16775     return false;
16776   unsigned NumBits1 = VT1.getSizeInBits();
16777   unsigned NumBits2 = VT2.getSizeInBits();
16778   return NumBits1 > NumBits2;
16779 }
16780
16781 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16782   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16783   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16784 }
16785
16786 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16787   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16788   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16789 }
16790
16791 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16792   EVT VT1 = Val.getValueType();
16793   if (isZExtFree(VT1, VT2))
16794     return true;
16795
16796   if (Val.getOpcode() != ISD::LOAD)
16797     return false;
16798
16799   if (!VT1.isSimple() || !VT1.isInteger() ||
16800       !VT2.isSimple() || !VT2.isInteger())
16801     return false;
16802
16803   switch (VT1.getSimpleVT().SimpleTy) {
16804   default: break;
16805   case MVT::i8:
16806   case MVT::i16:
16807   case MVT::i32:
16808     // X86 has 8, 16, and 32-bit zero-extending loads.
16809     return true;
16810   }
16811
16812   return false;
16813 }
16814
16815 bool
16816 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16817   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16818     return false;
16819
16820   VT = VT.getScalarType();
16821
16822   if (!VT.isSimple())
16823     return false;
16824
16825   switch (VT.getSimpleVT().SimpleTy) {
16826   case MVT::f32:
16827   case MVT::f64:
16828     return true;
16829   default:
16830     break;
16831   }
16832
16833   return false;
16834 }
16835
16836 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16837   // i16 instructions are longer (0x66 prefix) and potentially slower.
16838   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16839 }
16840
16841 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16842 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16843 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16844 /// are assumed to be legal.
16845 bool
16846 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16847                                       EVT VT) const {
16848   if (!VT.isSimple())
16849     return false;
16850
16851   MVT SVT = VT.getSimpleVT();
16852
16853   // Very little shuffling can be done for 64-bit vectors right now.
16854   if (VT.getSizeInBits() == 64)
16855     return false;
16856
16857   // If this is a single-input shuffle with no 128 bit lane crossings we can
16858   // lower it into pshufb.
16859   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16860       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16861     bool isLegal = true;
16862     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16863       if (M[I] >= (int)SVT.getVectorNumElements() ||
16864           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16865         isLegal = false;
16866         break;
16867       }
16868     }
16869     if (isLegal)
16870       return true;
16871   }
16872
16873   // FIXME: blends, shifts.
16874   return (SVT.getVectorNumElements() == 2 ||
16875           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16876           isMOVLMask(M, SVT) ||
16877           isMOVHLPSMask(M, SVT) ||
16878           isSHUFPMask(M, SVT) ||
16879           isPSHUFDMask(M, SVT) ||
16880           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16881           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16882           isPALIGNRMask(M, SVT, Subtarget) ||
16883           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16884           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16885           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16886           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16887           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16888 }
16889
16890 bool
16891 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16892                                           EVT VT) const {
16893   if (!VT.isSimple())
16894     return false;
16895
16896   MVT SVT = VT.getSimpleVT();
16897   unsigned NumElts = SVT.getVectorNumElements();
16898   // FIXME: This collection of masks seems suspect.
16899   if (NumElts == 2)
16900     return true;
16901   if (NumElts == 4 && SVT.is128BitVector()) {
16902     return (isMOVLMask(Mask, SVT)  ||
16903             isCommutedMOVLMask(Mask, SVT, true) ||
16904             isSHUFPMask(Mask, SVT) ||
16905             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16906   }
16907   return false;
16908 }
16909
16910 //===----------------------------------------------------------------------===//
16911 //                           X86 Scheduler Hooks
16912 //===----------------------------------------------------------------------===//
16913
16914 /// Utility function to emit xbegin specifying the start of an RTM region.
16915 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16916                                      const TargetInstrInfo *TII) {
16917   DebugLoc DL = MI->getDebugLoc();
16918
16919   const BasicBlock *BB = MBB->getBasicBlock();
16920   MachineFunction::iterator I = MBB;
16921   ++I;
16922
16923   // For the v = xbegin(), we generate
16924   //
16925   // thisMBB:
16926   //  xbegin sinkMBB
16927   //
16928   // mainMBB:
16929   //  eax = -1
16930   //
16931   // sinkMBB:
16932   //  v = eax
16933
16934   MachineBasicBlock *thisMBB = MBB;
16935   MachineFunction *MF = MBB->getParent();
16936   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16937   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16938   MF->insert(I, mainMBB);
16939   MF->insert(I, sinkMBB);
16940
16941   // Transfer the remainder of BB and its successor edges to sinkMBB.
16942   sinkMBB->splice(sinkMBB->begin(), MBB,
16943                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16944   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16945
16946   // thisMBB:
16947   //  xbegin sinkMBB
16948   //  # fallthrough to mainMBB
16949   //  # abortion to sinkMBB
16950   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16951   thisMBB->addSuccessor(mainMBB);
16952   thisMBB->addSuccessor(sinkMBB);
16953
16954   // mainMBB:
16955   //  EAX = -1
16956   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16957   mainMBB->addSuccessor(sinkMBB);
16958
16959   // sinkMBB:
16960   // EAX is live into the sinkMBB
16961   sinkMBB->addLiveIn(X86::EAX);
16962   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16963           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16964     .addReg(X86::EAX);
16965
16966   MI->eraseFromParent();
16967   return sinkMBB;
16968 }
16969
16970 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16971 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16972 // in the .td file.
16973 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16974                                        const TargetInstrInfo *TII) {
16975   unsigned Opc;
16976   switch (MI->getOpcode()) {
16977   default: llvm_unreachable("illegal opcode!");
16978   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16979   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16980   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16981   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16982   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16983   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16984   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16985   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16986   }
16987
16988   DebugLoc dl = MI->getDebugLoc();
16989   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16990
16991   unsigned NumArgs = MI->getNumOperands();
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::XMM0);
17003
17004   MI->eraseFromParent();
17005   return BB;
17006 }
17007
17008 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17009 // defs in an instruction pattern
17010 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17011                                        const TargetInstrInfo *TII) {
17012   unsigned Opc;
17013   switch (MI->getOpcode()) {
17014   default: llvm_unreachable("illegal opcode!");
17015   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17016   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17017   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17018   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17019   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17020   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17021   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17022   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17023   }
17024
17025   DebugLoc dl = MI->getDebugLoc();
17026   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17027
17028   unsigned NumArgs = MI->getNumOperands(); // remove the results
17029   for (unsigned i = 1; i < NumArgs; ++i) {
17030     MachineOperand &Op = MI->getOperand(i);
17031     if (!(Op.isReg() && Op.isImplicit()))
17032       MIB.addOperand(Op);
17033   }
17034   if (MI->hasOneMemOperand())
17035     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17036
17037   BuildMI(*BB, MI, dl,
17038     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17039     .addReg(X86::ECX);
17040
17041   MI->eraseFromParent();
17042   return BB;
17043 }
17044
17045 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17046                                        const TargetInstrInfo *TII,
17047                                        const X86Subtarget* Subtarget) {
17048   DebugLoc dl = MI->getDebugLoc();
17049
17050   // Address into RAX/EAX, other two args into ECX, EDX.
17051   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17052   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17053   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17054   for (int i = 0; i < X86::AddrNumOperands; ++i)
17055     MIB.addOperand(MI->getOperand(i));
17056
17057   unsigned ValOps = X86::AddrNumOperands;
17058   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17059     .addReg(MI->getOperand(ValOps).getReg());
17060   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17061     .addReg(MI->getOperand(ValOps+1).getReg());
17062
17063   // The instruction doesn't actually take any operands though.
17064   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17065
17066   MI->eraseFromParent(); // The pseudo is gone now.
17067   return BB;
17068 }
17069
17070 MachineBasicBlock *
17071 X86TargetLowering::EmitVAARG64WithCustomInserter(
17072                    MachineInstr *MI,
17073                    MachineBasicBlock *MBB) const {
17074   // Emit va_arg instruction on X86-64.
17075
17076   // Operands to this pseudo-instruction:
17077   // 0  ) Output        : destination address (reg)
17078   // 1-5) Input         : va_list address (addr, i64mem)
17079   // 6  ) ArgSize       : Size (in bytes) of vararg type
17080   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17081   // 8  ) Align         : Alignment of type
17082   // 9  ) EFLAGS (implicit-def)
17083
17084   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17085   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17086
17087   unsigned DestReg = MI->getOperand(0).getReg();
17088   MachineOperand &Base = MI->getOperand(1);
17089   MachineOperand &Scale = MI->getOperand(2);
17090   MachineOperand &Index = MI->getOperand(3);
17091   MachineOperand &Disp = MI->getOperand(4);
17092   MachineOperand &Segment = MI->getOperand(5);
17093   unsigned ArgSize = MI->getOperand(6).getImm();
17094   unsigned ArgMode = MI->getOperand(7).getImm();
17095   unsigned Align = MI->getOperand(8).getImm();
17096
17097   // Memory Reference
17098   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17099   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17100   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17101
17102   // Machine Information
17103   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17104   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17105   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17106   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17107   DebugLoc DL = MI->getDebugLoc();
17108
17109   // struct va_list {
17110   //   i32   gp_offset
17111   //   i32   fp_offset
17112   //   i64   overflow_area (address)
17113   //   i64   reg_save_area (address)
17114   // }
17115   // sizeof(va_list) = 24
17116   // alignment(va_list) = 8
17117
17118   unsigned TotalNumIntRegs = 6;
17119   unsigned TotalNumXMMRegs = 8;
17120   bool UseGPOffset = (ArgMode == 1);
17121   bool UseFPOffset = (ArgMode == 2);
17122   unsigned MaxOffset = TotalNumIntRegs * 8 +
17123                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17124
17125   /* Align ArgSize to a multiple of 8 */
17126   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17127   bool NeedsAlign = (Align > 8);
17128
17129   MachineBasicBlock *thisMBB = MBB;
17130   MachineBasicBlock *overflowMBB;
17131   MachineBasicBlock *offsetMBB;
17132   MachineBasicBlock *endMBB;
17133
17134   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17135   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17136   unsigned OffsetReg = 0;
17137
17138   if (!UseGPOffset && !UseFPOffset) {
17139     // If we only pull from the overflow region, we don't create a branch.
17140     // We don't need to alter control flow.
17141     OffsetDestReg = 0; // unused
17142     OverflowDestReg = DestReg;
17143
17144     offsetMBB = nullptr;
17145     overflowMBB = thisMBB;
17146     endMBB = thisMBB;
17147   } else {
17148     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17149     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17150     // If not, pull from overflow_area. (branch to overflowMBB)
17151     //
17152     //       thisMBB
17153     //         |     .
17154     //         |        .
17155     //     offsetMBB   overflowMBB
17156     //         |        .
17157     //         |     .
17158     //        endMBB
17159
17160     // Registers for the PHI in endMBB
17161     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17162     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17163
17164     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17165     MachineFunction *MF = MBB->getParent();
17166     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17167     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17168     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17169
17170     MachineFunction::iterator MBBIter = MBB;
17171     ++MBBIter;
17172
17173     // Insert the new basic blocks
17174     MF->insert(MBBIter, offsetMBB);
17175     MF->insert(MBBIter, overflowMBB);
17176     MF->insert(MBBIter, endMBB);
17177
17178     // Transfer the remainder of MBB and its successor edges to endMBB.
17179     endMBB->splice(endMBB->begin(), thisMBB,
17180                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17181     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17182
17183     // Make offsetMBB and overflowMBB successors of thisMBB
17184     thisMBB->addSuccessor(offsetMBB);
17185     thisMBB->addSuccessor(overflowMBB);
17186
17187     // endMBB is a successor of both offsetMBB and overflowMBB
17188     offsetMBB->addSuccessor(endMBB);
17189     overflowMBB->addSuccessor(endMBB);
17190
17191     // Load the offset value into a register
17192     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17193     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17194       .addOperand(Base)
17195       .addOperand(Scale)
17196       .addOperand(Index)
17197       .addDisp(Disp, UseFPOffset ? 4 : 0)
17198       .addOperand(Segment)
17199       .setMemRefs(MMOBegin, MMOEnd);
17200
17201     // Check if there is enough room left to pull this argument.
17202     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17203       .addReg(OffsetReg)
17204       .addImm(MaxOffset + 8 - ArgSizeA8);
17205
17206     // Branch to "overflowMBB" if offset >= max
17207     // Fall through to "offsetMBB" otherwise
17208     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17209       .addMBB(overflowMBB);
17210   }
17211
17212   // In offsetMBB, emit code to use the reg_save_area.
17213   if (offsetMBB) {
17214     assert(OffsetReg != 0);
17215
17216     // Read the reg_save_area address.
17217     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17218     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17219       .addOperand(Base)
17220       .addOperand(Scale)
17221       .addOperand(Index)
17222       .addDisp(Disp, 16)
17223       .addOperand(Segment)
17224       .setMemRefs(MMOBegin, MMOEnd);
17225
17226     // Zero-extend the offset
17227     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17228       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17229         .addImm(0)
17230         .addReg(OffsetReg)
17231         .addImm(X86::sub_32bit);
17232
17233     // Add the offset to the reg_save_area to get the final address.
17234     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17235       .addReg(OffsetReg64)
17236       .addReg(RegSaveReg);
17237
17238     // Compute the offset for the next argument
17239     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17240     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17241       .addReg(OffsetReg)
17242       .addImm(UseFPOffset ? 16 : 8);
17243
17244     // Store it back into the va_list.
17245     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17246       .addOperand(Base)
17247       .addOperand(Scale)
17248       .addOperand(Index)
17249       .addDisp(Disp, UseFPOffset ? 4 : 0)
17250       .addOperand(Segment)
17251       .addReg(NextOffsetReg)
17252       .setMemRefs(MMOBegin, MMOEnd);
17253
17254     // Jump to endMBB
17255     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17256       .addMBB(endMBB);
17257   }
17258
17259   //
17260   // Emit code to use overflow area
17261   //
17262
17263   // Load the overflow_area address into a register.
17264   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17265   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17266     .addOperand(Base)
17267     .addOperand(Scale)
17268     .addOperand(Index)
17269     .addDisp(Disp, 8)
17270     .addOperand(Segment)
17271     .setMemRefs(MMOBegin, MMOEnd);
17272
17273   // If we need to align it, do so. Otherwise, just copy the address
17274   // to OverflowDestReg.
17275   if (NeedsAlign) {
17276     // Align the overflow address
17277     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17278     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17279
17280     // aligned_addr = (addr + (align-1)) & ~(align-1)
17281     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17282       .addReg(OverflowAddrReg)
17283       .addImm(Align-1);
17284
17285     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17286       .addReg(TmpReg)
17287       .addImm(~(uint64_t)(Align-1));
17288   } else {
17289     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17290       .addReg(OverflowAddrReg);
17291   }
17292
17293   // Compute the next overflow address after this argument.
17294   // (the overflow address should be kept 8-byte aligned)
17295   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17296   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17297     .addReg(OverflowDestReg)
17298     .addImm(ArgSizeA8);
17299
17300   // Store the new overflow address.
17301   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17302     .addOperand(Base)
17303     .addOperand(Scale)
17304     .addOperand(Index)
17305     .addDisp(Disp, 8)
17306     .addOperand(Segment)
17307     .addReg(NextAddrReg)
17308     .setMemRefs(MMOBegin, MMOEnd);
17309
17310   // If we branched, emit the PHI to the front of endMBB.
17311   if (offsetMBB) {
17312     BuildMI(*endMBB, endMBB->begin(), DL,
17313             TII->get(X86::PHI), DestReg)
17314       .addReg(OffsetDestReg).addMBB(offsetMBB)
17315       .addReg(OverflowDestReg).addMBB(overflowMBB);
17316   }
17317
17318   // Erase the pseudo instruction
17319   MI->eraseFromParent();
17320
17321   return endMBB;
17322 }
17323
17324 MachineBasicBlock *
17325 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17326                                                  MachineInstr *MI,
17327                                                  MachineBasicBlock *MBB) const {
17328   // Emit code to save XMM registers to the stack. The ABI says that the
17329   // number of registers to save is given in %al, so it's theoretically
17330   // possible to do an indirect jump trick to avoid saving all of them,
17331   // however this code takes a simpler approach and just executes all
17332   // of the stores if %al is non-zero. It's less code, and it's probably
17333   // easier on the hardware branch predictor, and stores aren't all that
17334   // expensive anyway.
17335
17336   // Create the new basic blocks. One block contains all the XMM stores,
17337   // and one block is the final destination regardless of whether any
17338   // stores were performed.
17339   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17340   MachineFunction *F = MBB->getParent();
17341   MachineFunction::iterator MBBIter = MBB;
17342   ++MBBIter;
17343   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17344   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17345   F->insert(MBBIter, XMMSaveMBB);
17346   F->insert(MBBIter, EndMBB);
17347
17348   // Transfer the remainder of MBB and its successor edges to EndMBB.
17349   EndMBB->splice(EndMBB->begin(), MBB,
17350                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17351   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17352
17353   // The original block will now fall through to the XMM save block.
17354   MBB->addSuccessor(XMMSaveMBB);
17355   // The XMMSaveMBB will fall through to the end block.
17356   XMMSaveMBB->addSuccessor(EndMBB);
17357
17358   // Now add the instructions.
17359   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17360   DebugLoc DL = MI->getDebugLoc();
17361
17362   unsigned CountReg = MI->getOperand(0).getReg();
17363   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17364   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17365
17366   if (!Subtarget->isTargetWin64()) {
17367     // If %al is 0, branch around the XMM save block.
17368     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17369     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17370     MBB->addSuccessor(EndMBB);
17371   }
17372
17373   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17374   // that was just emitted, but clearly shouldn't be "saved".
17375   assert((MI->getNumOperands() <= 3 ||
17376           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17377           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17378          && "Expected last argument to be EFLAGS");
17379   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17380   // In the XMM save block, save all the XMM argument registers.
17381   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17382     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17383     MachineMemOperand *MMO =
17384       F->getMachineMemOperand(
17385           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17386         MachineMemOperand::MOStore,
17387         /*Size=*/16, /*Align=*/16);
17388     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17389       .addFrameIndex(RegSaveFrameIndex)
17390       .addImm(/*Scale=*/1)
17391       .addReg(/*IndexReg=*/0)
17392       .addImm(/*Disp=*/Offset)
17393       .addReg(/*Segment=*/0)
17394       .addReg(MI->getOperand(i).getReg())
17395       .addMemOperand(MMO);
17396   }
17397
17398   MI->eraseFromParent();   // The pseudo instruction is gone now.
17399
17400   return EndMBB;
17401 }
17402
17403 // The EFLAGS operand of SelectItr might be missing a kill marker
17404 // because there were multiple uses of EFLAGS, and ISel didn't know
17405 // which to mark. Figure out whether SelectItr should have had a
17406 // kill marker, and set it if it should. Returns the correct kill
17407 // marker value.
17408 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17409                                      MachineBasicBlock* BB,
17410                                      const TargetRegisterInfo* TRI) {
17411   // Scan forward through BB for a use/def of EFLAGS.
17412   MachineBasicBlock::iterator miI(std::next(SelectItr));
17413   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17414     const MachineInstr& mi = *miI;
17415     if (mi.readsRegister(X86::EFLAGS))
17416       return false;
17417     if (mi.definesRegister(X86::EFLAGS))
17418       break; // Should have kill-flag - update below.
17419   }
17420
17421   // If we hit the end of the block, check whether EFLAGS is live into a
17422   // successor.
17423   if (miI == BB->end()) {
17424     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17425                                           sEnd = BB->succ_end();
17426          sItr != sEnd; ++sItr) {
17427       MachineBasicBlock* succ = *sItr;
17428       if (succ->isLiveIn(X86::EFLAGS))
17429         return false;
17430     }
17431   }
17432
17433   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17434   // out. SelectMI should have a kill flag on EFLAGS.
17435   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17436   return true;
17437 }
17438
17439 MachineBasicBlock *
17440 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17441                                      MachineBasicBlock *BB) const {
17442   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17443   DebugLoc DL = MI->getDebugLoc();
17444
17445   // To "insert" a SELECT_CC instruction, we actually have to insert the
17446   // diamond control-flow pattern.  The incoming instruction knows the
17447   // destination vreg to set, the condition code register to branch on, the
17448   // true/false values to select between, and a branch opcode to use.
17449   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17450   MachineFunction::iterator It = BB;
17451   ++It;
17452
17453   //  thisMBB:
17454   //  ...
17455   //   TrueVal = ...
17456   //   cmpTY ccX, r1, r2
17457   //   bCC copy1MBB
17458   //   fallthrough --> copy0MBB
17459   MachineBasicBlock *thisMBB = BB;
17460   MachineFunction *F = BB->getParent();
17461   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17462   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17463   F->insert(It, copy0MBB);
17464   F->insert(It, sinkMBB);
17465
17466   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17467   // live into the sink and copy blocks.
17468   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17469   if (!MI->killsRegister(X86::EFLAGS) &&
17470       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17471     copy0MBB->addLiveIn(X86::EFLAGS);
17472     sinkMBB->addLiveIn(X86::EFLAGS);
17473   }
17474
17475   // Transfer the remainder of BB and its successor edges to sinkMBB.
17476   sinkMBB->splice(sinkMBB->begin(), BB,
17477                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17478   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17479
17480   // Add the true and fallthrough blocks as its successors.
17481   BB->addSuccessor(copy0MBB);
17482   BB->addSuccessor(sinkMBB);
17483
17484   // Create the conditional branch instruction.
17485   unsigned Opc =
17486     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17487   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17488
17489   //  copy0MBB:
17490   //   %FalseValue = ...
17491   //   # fallthrough to sinkMBB
17492   copy0MBB->addSuccessor(sinkMBB);
17493
17494   //  sinkMBB:
17495   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17496   //  ...
17497   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17498           TII->get(X86::PHI), MI->getOperand(0).getReg())
17499     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17500     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17501
17502   MI->eraseFromParent();   // The pseudo instruction is gone now.
17503   return sinkMBB;
17504 }
17505
17506 MachineBasicBlock *
17507 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17508                                         bool Is64Bit) const {
17509   MachineFunction *MF = BB->getParent();
17510   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17511   DebugLoc DL = MI->getDebugLoc();
17512   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17513
17514   assert(MF->shouldSplitStack());
17515
17516   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17517   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17518
17519   // BB:
17520   //  ... [Till the alloca]
17521   // If stacklet is not large enough, jump to mallocMBB
17522   //
17523   // bumpMBB:
17524   //  Allocate by subtracting from RSP
17525   //  Jump to continueMBB
17526   //
17527   // mallocMBB:
17528   //  Allocate by call to runtime
17529   //
17530   // continueMBB:
17531   //  ...
17532   //  [rest of original BB]
17533   //
17534
17535   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17536   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17537   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17538
17539   MachineRegisterInfo &MRI = MF->getRegInfo();
17540   const TargetRegisterClass *AddrRegClass =
17541     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17542
17543   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17544     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17545     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17546     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17547     sizeVReg = MI->getOperand(1).getReg(),
17548     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17549
17550   MachineFunction::iterator MBBIter = BB;
17551   ++MBBIter;
17552
17553   MF->insert(MBBIter, bumpMBB);
17554   MF->insert(MBBIter, mallocMBB);
17555   MF->insert(MBBIter, continueMBB);
17556
17557   continueMBB->splice(continueMBB->begin(), BB,
17558                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17559   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17560
17561   // Add code to the main basic block to check if the stack limit has been hit,
17562   // and if so, jump to mallocMBB otherwise to bumpMBB.
17563   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17564   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17565     .addReg(tmpSPVReg).addReg(sizeVReg);
17566   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17567     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17568     .addReg(SPLimitVReg);
17569   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17570
17571   // bumpMBB simply decreases the stack pointer, since we know the current
17572   // stacklet has enough space.
17573   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17574     .addReg(SPLimitVReg);
17575   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17576     .addReg(SPLimitVReg);
17577   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17578
17579   // Calls into a routine in libgcc to allocate more space from the heap.
17580   const uint32_t *RegMask =
17581     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17582   if (Is64Bit) {
17583     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17584       .addReg(sizeVReg);
17585     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17586       .addExternalSymbol("__morestack_allocate_stack_space")
17587       .addRegMask(RegMask)
17588       .addReg(X86::RDI, RegState::Implicit)
17589       .addReg(X86::RAX, RegState::ImplicitDefine);
17590   } else {
17591     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17592       .addImm(12);
17593     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17594     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17595       .addExternalSymbol("__morestack_allocate_stack_space")
17596       .addRegMask(RegMask)
17597       .addReg(X86::EAX, RegState::ImplicitDefine);
17598   }
17599
17600   if (!Is64Bit)
17601     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17602       .addImm(16);
17603
17604   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17605     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17606   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17607
17608   // Set up the CFG correctly.
17609   BB->addSuccessor(bumpMBB);
17610   BB->addSuccessor(mallocMBB);
17611   mallocMBB->addSuccessor(continueMBB);
17612   bumpMBB->addSuccessor(continueMBB);
17613
17614   // Take care of the PHI nodes.
17615   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17616           MI->getOperand(0).getReg())
17617     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17618     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17619
17620   // Delete the original pseudo instruction.
17621   MI->eraseFromParent();
17622
17623   // And we're done.
17624   return continueMBB;
17625 }
17626
17627 MachineBasicBlock *
17628 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17629                                         MachineBasicBlock *BB) const {
17630   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17631   DebugLoc DL = MI->getDebugLoc();
17632
17633   assert(!Subtarget->isTargetMacho());
17634
17635   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17636   // non-trivial part is impdef of ESP.
17637
17638   if (Subtarget->isTargetWin64()) {
17639     if (Subtarget->isTargetCygMing()) {
17640       // ___chkstk(Mingw64):
17641       // Clobbers R10, R11, RAX and EFLAGS.
17642       // Updates RSP.
17643       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17644         .addExternalSymbol("___chkstk")
17645         .addReg(X86::RAX, RegState::Implicit)
17646         .addReg(X86::RSP, RegState::Implicit)
17647         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17648         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17649         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17650     } else {
17651       // __chkstk(MSVCRT): does not update stack pointer.
17652       // Clobbers R10, R11 and EFLAGS.
17653       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17654         .addExternalSymbol("__chkstk")
17655         .addReg(X86::RAX, RegState::Implicit)
17656         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17657       // RAX has the offset to be subtracted from RSP.
17658       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17659         .addReg(X86::RSP)
17660         .addReg(X86::RAX);
17661     }
17662   } else {
17663     const char *StackProbeSymbol =
17664       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17665
17666     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17667       .addExternalSymbol(StackProbeSymbol)
17668       .addReg(X86::EAX, RegState::Implicit)
17669       .addReg(X86::ESP, RegState::Implicit)
17670       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17671       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17672       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17673   }
17674
17675   MI->eraseFromParent();   // The pseudo instruction is gone now.
17676   return BB;
17677 }
17678
17679 MachineBasicBlock *
17680 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17681                                       MachineBasicBlock *BB) const {
17682   // This is pretty easy.  We're taking the value that we received from
17683   // our load from the relocation, sticking it in either RDI (x86-64)
17684   // or EAX and doing an indirect call.  The return value will then
17685   // be in the normal return register.
17686   MachineFunction *F = BB->getParent();
17687   const X86InstrInfo *TII
17688     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17689   DebugLoc DL = MI->getDebugLoc();
17690
17691   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17692   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17693
17694   // Get a register mask for the lowered call.
17695   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17696   // proper register mask.
17697   const uint32_t *RegMask =
17698     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17699   if (Subtarget->is64Bit()) {
17700     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17701                                       TII->get(X86::MOV64rm), X86::RDI)
17702     .addReg(X86::RIP)
17703     .addImm(0).addReg(0)
17704     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17705                       MI->getOperand(3).getTargetFlags())
17706     .addReg(0);
17707     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17708     addDirectMem(MIB, X86::RDI);
17709     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17710   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17711     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17712                                       TII->get(X86::MOV32rm), X86::EAX)
17713     .addReg(0)
17714     .addImm(0).addReg(0)
17715     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17716                       MI->getOperand(3).getTargetFlags())
17717     .addReg(0);
17718     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17719     addDirectMem(MIB, X86::EAX);
17720     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17721   } else {
17722     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17723                                       TII->get(X86::MOV32rm), X86::EAX)
17724     .addReg(TII->getGlobalBaseReg(F))
17725     .addImm(0).addReg(0)
17726     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17727                       MI->getOperand(3).getTargetFlags())
17728     .addReg(0);
17729     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17730     addDirectMem(MIB, X86::EAX);
17731     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17732   }
17733
17734   MI->eraseFromParent(); // The pseudo instruction is gone now.
17735   return BB;
17736 }
17737
17738 MachineBasicBlock *
17739 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17740                                     MachineBasicBlock *MBB) const {
17741   DebugLoc DL = MI->getDebugLoc();
17742   MachineFunction *MF = MBB->getParent();
17743   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17744   MachineRegisterInfo &MRI = MF->getRegInfo();
17745
17746   const BasicBlock *BB = MBB->getBasicBlock();
17747   MachineFunction::iterator I = MBB;
17748   ++I;
17749
17750   // Memory Reference
17751   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17752   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17753
17754   unsigned DstReg;
17755   unsigned MemOpndSlot = 0;
17756
17757   unsigned CurOp = 0;
17758
17759   DstReg = MI->getOperand(CurOp++).getReg();
17760   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17761   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17762   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17763   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17764
17765   MemOpndSlot = CurOp;
17766
17767   MVT PVT = getPointerTy();
17768   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17769          "Invalid Pointer Size!");
17770
17771   // For v = setjmp(buf), we generate
17772   //
17773   // thisMBB:
17774   //  buf[LabelOffset] = restoreMBB
17775   //  SjLjSetup restoreMBB
17776   //
17777   // mainMBB:
17778   //  v_main = 0
17779   //
17780   // sinkMBB:
17781   //  v = phi(main, restore)
17782   //
17783   // restoreMBB:
17784   //  v_restore = 1
17785
17786   MachineBasicBlock *thisMBB = MBB;
17787   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17788   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17789   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17790   MF->insert(I, mainMBB);
17791   MF->insert(I, sinkMBB);
17792   MF->push_back(restoreMBB);
17793
17794   MachineInstrBuilder MIB;
17795
17796   // Transfer the remainder of BB and its successor edges to sinkMBB.
17797   sinkMBB->splice(sinkMBB->begin(), MBB,
17798                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17799   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17800
17801   // thisMBB:
17802   unsigned PtrStoreOpc = 0;
17803   unsigned LabelReg = 0;
17804   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17805   Reloc::Model RM = MF->getTarget().getRelocationModel();
17806   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17807                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17808
17809   // Prepare IP either in reg or imm.
17810   if (!UseImmLabel) {
17811     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17812     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17813     LabelReg = MRI.createVirtualRegister(PtrRC);
17814     if (Subtarget->is64Bit()) {
17815       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17816               .addReg(X86::RIP)
17817               .addImm(0)
17818               .addReg(0)
17819               .addMBB(restoreMBB)
17820               .addReg(0);
17821     } else {
17822       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17823       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17824               .addReg(XII->getGlobalBaseReg(MF))
17825               .addImm(0)
17826               .addReg(0)
17827               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17828               .addReg(0);
17829     }
17830   } else
17831     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17832   // Store IP
17833   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17834   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17835     if (i == X86::AddrDisp)
17836       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17837     else
17838       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17839   }
17840   if (!UseImmLabel)
17841     MIB.addReg(LabelReg);
17842   else
17843     MIB.addMBB(restoreMBB);
17844   MIB.setMemRefs(MMOBegin, MMOEnd);
17845   // Setup
17846   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17847           .addMBB(restoreMBB);
17848
17849   const X86RegisterInfo *RegInfo =
17850     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17851   MIB.addRegMask(RegInfo->getNoPreservedMask());
17852   thisMBB->addSuccessor(mainMBB);
17853   thisMBB->addSuccessor(restoreMBB);
17854
17855   // mainMBB:
17856   //  EAX = 0
17857   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17858   mainMBB->addSuccessor(sinkMBB);
17859
17860   // sinkMBB:
17861   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17862           TII->get(X86::PHI), DstReg)
17863     .addReg(mainDstReg).addMBB(mainMBB)
17864     .addReg(restoreDstReg).addMBB(restoreMBB);
17865
17866   // restoreMBB:
17867   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17868   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17869   restoreMBB->addSuccessor(sinkMBB);
17870
17871   MI->eraseFromParent();
17872   return sinkMBB;
17873 }
17874
17875 MachineBasicBlock *
17876 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17877                                      MachineBasicBlock *MBB) const {
17878   DebugLoc DL = MI->getDebugLoc();
17879   MachineFunction *MF = MBB->getParent();
17880   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17881   MachineRegisterInfo &MRI = MF->getRegInfo();
17882
17883   // Memory Reference
17884   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17885   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17886
17887   MVT PVT = getPointerTy();
17888   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17889          "Invalid Pointer Size!");
17890
17891   const TargetRegisterClass *RC =
17892     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17893   unsigned Tmp = MRI.createVirtualRegister(RC);
17894   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17895   const X86RegisterInfo *RegInfo =
17896     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17897   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17898   unsigned SP = RegInfo->getStackRegister();
17899
17900   MachineInstrBuilder MIB;
17901
17902   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17903   const int64_t SPOffset = 2 * PVT.getStoreSize();
17904
17905   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17906   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17907
17908   // Reload FP
17909   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17910   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17911     MIB.addOperand(MI->getOperand(i));
17912   MIB.setMemRefs(MMOBegin, MMOEnd);
17913   // Reload IP
17914   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17915   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17916     if (i == X86::AddrDisp)
17917       MIB.addDisp(MI->getOperand(i), LabelOffset);
17918     else
17919       MIB.addOperand(MI->getOperand(i));
17920   }
17921   MIB.setMemRefs(MMOBegin, MMOEnd);
17922   // Reload SP
17923   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17924   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17925     if (i == X86::AddrDisp)
17926       MIB.addDisp(MI->getOperand(i), SPOffset);
17927     else
17928       MIB.addOperand(MI->getOperand(i));
17929   }
17930   MIB.setMemRefs(MMOBegin, MMOEnd);
17931   // Jump
17932   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17933
17934   MI->eraseFromParent();
17935   return MBB;
17936 }
17937
17938 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17939 // accumulator loops. Writing back to the accumulator allows the coalescer
17940 // to remove extra copies in the loop.   
17941 MachineBasicBlock *
17942 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17943                                  MachineBasicBlock *MBB) const {
17944   MachineOperand &AddendOp = MI->getOperand(3);
17945
17946   // Bail out early if the addend isn't a register - we can't switch these.
17947   if (!AddendOp.isReg())
17948     return MBB;
17949
17950   MachineFunction &MF = *MBB->getParent();
17951   MachineRegisterInfo &MRI = MF.getRegInfo();
17952
17953   // Check whether the addend is defined by a PHI:
17954   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17955   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17956   if (!AddendDef.isPHI())
17957     return MBB;
17958
17959   // Look for the following pattern:
17960   // loop:
17961   //   %addend = phi [%entry, 0], [%loop, %result]
17962   //   ...
17963   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17964
17965   // Replace with:
17966   //   loop:
17967   //   %addend = phi [%entry, 0], [%loop, %result]
17968   //   ...
17969   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17970
17971   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17972     assert(AddendDef.getOperand(i).isReg());
17973     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17974     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17975     if (&PHISrcInst == MI) {
17976       // Found a matching instruction.
17977       unsigned NewFMAOpc = 0;
17978       switch (MI->getOpcode()) {
17979         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17980         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17981         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17982         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17983         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17984         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17985         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17986         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17987         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17988         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17989         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17990         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17991         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17992         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17993         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17994         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17995         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17996         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17997         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17998         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17999         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18000         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18001         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18002         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18003         default: llvm_unreachable("Unrecognized FMA variant.");
18004       }
18005
18006       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
18007       MachineInstrBuilder MIB =
18008         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18009         .addOperand(MI->getOperand(0))
18010         .addOperand(MI->getOperand(3))
18011         .addOperand(MI->getOperand(2))
18012         .addOperand(MI->getOperand(1));
18013       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18014       MI->eraseFromParent();
18015     }
18016   }
18017
18018   return MBB;
18019 }
18020
18021 MachineBasicBlock *
18022 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18023                                                MachineBasicBlock *BB) const {
18024   switch (MI->getOpcode()) {
18025   default: llvm_unreachable("Unexpected instr type to insert");
18026   case X86::TAILJMPd64:
18027   case X86::TAILJMPr64:
18028   case X86::TAILJMPm64:
18029     llvm_unreachable("TAILJMP64 would not be touched here.");
18030   case X86::TCRETURNdi64:
18031   case X86::TCRETURNri64:
18032   case X86::TCRETURNmi64:
18033     return BB;
18034   case X86::WIN_ALLOCA:
18035     return EmitLoweredWinAlloca(MI, BB);
18036   case X86::SEG_ALLOCA_32:
18037     return EmitLoweredSegAlloca(MI, BB, false);
18038   case X86::SEG_ALLOCA_64:
18039     return EmitLoweredSegAlloca(MI, BB, true);
18040   case X86::TLSCall_32:
18041   case X86::TLSCall_64:
18042     return EmitLoweredTLSCall(MI, BB);
18043   case X86::CMOV_GR8:
18044   case X86::CMOV_FR32:
18045   case X86::CMOV_FR64:
18046   case X86::CMOV_V4F32:
18047   case X86::CMOV_V2F64:
18048   case X86::CMOV_V2I64:
18049   case X86::CMOV_V8F32:
18050   case X86::CMOV_V4F64:
18051   case X86::CMOV_V4I64:
18052   case X86::CMOV_V16F32:
18053   case X86::CMOV_V8F64:
18054   case X86::CMOV_V8I64:
18055   case X86::CMOV_GR16:
18056   case X86::CMOV_GR32:
18057   case X86::CMOV_RFP32:
18058   case X86::CMOV_RFP64:
18059   case X86::CMOV_RFP80:
18060     return EmitLoweredSelect(MI, BB);
18061
18062   case X86::FP32_TO_INT16_IN_MEM:
18063   case X86::FP32_TO_INT32_IN_MEM:
18064   case X86::FP32_TO_INT64_IN_MEM:
18065   case X86::FP64_TO_INT16_IN_MEM:
18066   case X86::FP64_TO_INT32_IN_MEM:
18067   case X86::FP64_TO_INT64_IN_MEM:
18068   case X86::FP80_TO_INT16_IN_MEM:
18069   case X86::FP80_TO_INT32_IN_MEM:
18070   case X86::FP80_TO_INT64_IN_MEM: {
18071     MachineFunction *F = BB->getParent();
18072     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18073     DebugLoc DL = MI->getDebugLoc();
18074
18075     // Change the floating point control register to use "round towards zero"
18076     // mode when truncating to an integer value.
18077     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18078     addFrameReference(BuildMI(*BB, MI, DL,
18079                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18080
18081     // Load the old value of the high byte of the control word...
18082     unsigned OldCW =
18083       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18084     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18085                       CWFrameIdx);
18086
18087     // Set the high part to be round to zero...
18088     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18089       .addImm(0xC7F);
18090
18091     // Reload the modified control word now...
18092     addFrameReference(BuildMI(*BB, MI, DL,
18093                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18094
18095     // Restore the memory image of control word to original value
18096     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18097       .addReg(OldCW);
18098
18099     // Get the X86 opcode to use.
18100     unsigned Opc;
18101     switch (MI->getOpcode()) {
18102     default: llvm_unreachable("illegal opcode!");
18103     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18104     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18105     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18106     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18107     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18108     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18109     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18110     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18111     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18112     }
18113
18114     X86AddressMode AM;
18115     MachineOperand &Op = MI->getOperand(0);
18116     if (Op.isReg()) {
18117       AM.BaseType = X86AddressMode::RegBase;
18118       AM.Base.Reg = Op.getReg();
18119     } else {
18120       AM.BaseType = X86AddressMode::FrameIndexBase;
18121       AM.Base.FrameIndex = Op.getIndex();
18122     }
18123     Op = MI->getOperand(1);
18124     if (Op.isImm())
18125       AM.Scale = Op.getImm();
18126     Op = MI->getOperand(2);
18127     if (Op.isImm())
18128       AM.IndexReg = Op.getImm();
18129     Op = MI->getOperand(3);
18130     if (Op.isGlobal()) {
18131       AM.GV = Op.getGlobal();
18132     } else {
18133       AM.Disp = Op.getImm();
18134     }
18135     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18136                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18137
18138     // Reload the original control word now.
18139     addFrameReference(BuildMI(*BB, MI, DL,
18140                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18141
18142     MI->eraseFromParent();   // The pseudo instruction is gone now.
18143     return BB;
18144   }
18145     // String/text processing lowering.
18146   case X86::PCMPISTRM128REG:
18147   case X86::VPCMPISTRM128REG:
18148   case X86::PCMPISTRM128MEM:
18149   case X86::VPCMPISTRM128MEM:
18150   case X86::PCMPESTRM128REG:
18151   case X86::VPCMPESTRM128REG:
18152   case X86::PCMPESTRM128MEM:
18153   case X86::VPCMPESTRM128MEM:
18154     assert(Subtarget->hasSSE42() &&
18155            "Target must have SSE4.2 or AVX features enabled");
18156     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18157
18158   // String/text processing lowering.
18159   case X86::PCMPISTRIREG:
18160   case X86::VPCMPISTRIREG:
18161   case X86::PCMPISTRIMEM:
18162   case X86::VPCMPISTRIMEM:
18163   case X86::PCMPESTRIREG:
18164   case X86::VPCMPESTRIREG:
18165   case X86::PCMPESTRIMEM:
18166   case X86::VPCMPESTRIMEM:
18167     assert(Subtarget->hasSSE42() &&
18168            "Target must have SSE4.2 or AVX features enabled");
18169     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18170
18171   // Thread synchronization.
18172   case X86::MONITOR:
18173     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18174
18175   // xbegin
18176   case X86::XBEGIN:
18177     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18178
18179   case X86::VASTART_SAVE_XMM_REGS:
18180     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18181
18182   case X86::VAARG_64:
18183     return EmitVAARG64WithCustomInserter(MI, BB);
18184
18185   case X86::EH_SjLj_SetJmp32:
18186   case X86::EH_SjLj_SetJmp64:
18187     return emitEHSjLjSetJmp(MI, BB);
18188
18189   case X86::EH_SjLj_LongJmp32:
18190   case X86::EH_SjLj_LongJmp64:
18191     return emitEHSjLjLongJmp(MI, BB);
18192
18193   case TargetOpcode::STACKMAP:
18194   case TargetOpcode::PATCHPOINT:
18195     return emitPatchPoint(MI, BB);
18196
18197   case X86::VFMADDPDr213r:
18198   case X86::VFMADDPSr213r:
18199   case X86::VFMADDSDr213r:
18200   case X86::VFMADDSSr213r:
18201   case X86::VFMSUBPDr213r:
18202   case X86::VFMSUBPSr213r:
18203   case X86::VFMSUBSDr213r:
18204   case X86::VFMSUBSSr213r:
18205   case X86::VFNMADDPDr213r:
18206   case X86::VFNMADDPSr213r:
18207   case X86::VFNMADDSDr213r:
18208   case X86::VFNMADDSSr213r:
18209   case X86::VFNMSUBPDr213r:
18210   case X86::VFNMSUBPSr213r:
18211   case X86::VFNMSUBSDr213r:
18212   case X86::VFNMSUBSSr213r:
18213   case X86::VFMADDPDr213rY:
18214   case X86::VFMADDPSr213rY:
18215   case X86::VFMSUBPDr213rY:
18216   case X86::VFMSUBPSr213rY:
18217   case X86::VFNMADDPDr213rY:
18218   case X86::VFNMADDPSr213rY:
18219   case X86::VFNMSUBPDr213rY:
18220   case X86::VFNMSUBPSr213rY:
18221     return emitFMA3Instr(MI, BB);
18222   }
18223 }
18224
18225 //===----------------------------------------------------------------------===//
18226 //                           X86 Optimization Hooks
18227 //===----------------------------------------------------------------------===//
18228
18229 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18230                                                       APInt &KnownZero,
18231                                                       APInt &KnownOne,
18232                                                       const SelectionDAG &DAG,
18233                                                       unsigned Depth) const {
18234   unsigned BitWidth = KnownZero.getBitWidth();
18235   unsigned Opc = Op.getOpcode();
18236   assert((Opc >= ISD::BUILTIN_OP_END ||
18237           Opc == ISD::INTRINSIC_WO_CHAIN ||
18238           Opc == ISD::INTRINSIC_W_CHAIN ||
18239           Opc == ISD::INTRINSIC_VOID) &&
18240          "Should use MaskedValueIsZero if you don't know whether Op"
18241          " is a target node!");
18242
18243   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18244   switch (Opc) {
18245   default: break;
18246   case X86ISD::ADD:
18247   case X86ISD::SUB:
18248   case X86ISD::ADC:
18249   case X86ISD::SBB:
18250   case X86ISD::SMUL:
18251   case X86ISD::UMUL:
18252   case X86ISD::INC:
18253   case X86ISD::DEC:
18254   case X86ISD::OR:
18255   case X86ISD::XOR:
18256   case X86ISD::AND:
18257     // These nodes' second result is a boolean.
18258     if (Op.getResNo() == 0)
18259       break;
18260     // Fallthrough
18261   case X86ISD::SETCC:
18262     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18263     break;
18264   case ISD::INTRINSIC_WO_CHAIN: {
18265     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18266     unsigned NumLoBits = 0;
18267     switch (IntId) {
18268     default: break;
18269     case Intrinsic::x86_sse_movmsk_ps:
18270     case Intrinsic::x86_avx_movmsk_ps_256:
18271     case Intrinsic::x86_sse2_movmsk_pd:
18272     case Intrinsic::x86_avx_movmsk_pd_256:
18273     case Intrinsic::x86_mmx_pmovmskb:
18274     case Intrinsic::x86_sse2_pmovmskb_128:
18275     case Intrinsic::x86_avx2_pmovmskb: {
18276       // High bits of movmskp{s|d}, pmovmskb are known zero.
18277       switch (IntId) {
18278         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18279         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18280         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18281         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18282         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18283         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18284         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18285         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18286       }
18287       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18288       break;
18289     }
18290     }
18291     break;
18292   }
18293   }
18294 }
18295
18296 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18297   SDValue Op,
18298   const SelectionDAG &,
18299   unsigned Depth) const {
18300   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18301   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18302     return Op.getValueType().getScalarType().getSizeInBits();
18303
18304   // Fallback case.
18305   return 1;
18306 }
18307
18308 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18309 /// node is a GlobalAddress + offset.
18310 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18311                                        const GlobalValue* &GA,
18312                                        int64_t &Offset) const {
18313   if (N->getOpcode() == X86ISD::Wrapper) {
18314     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18315       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18316       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18317       return true;
18318     }
18319   }
18320   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18321 }
18322
18323 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18324 /// same as extracting the high 128-bit part of 256-bit vector and then
18325 /// inserting the result into the low part of a new 256-bit vector
18326 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18327   EVT VT = SVOp->getValueType(0);
18328   unsigned NumElems = VT.getVectorNumElements();
18329
18330   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18331   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18332     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18333         SVOp->getMaskElt(j) >= 0)
18334       return false;
18335
18336   return true;
18337 }
18338
18339 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18340 /// same as extracting the low 128-bit part of 256-bit vector and then
18341 /// inserting the result into the high part of a new 256-bit vector
18342 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18343   EVT VT = SVOp->getValueType(0);
18344   unsigned NumElems = VT.getVectorNumElements();
18345
18346   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18347   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18348     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18349         SVOp->getMaskElt(j) >= 0)
18350       return false;
18351
18352   return true;
18353 }
18354
18355 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18356 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18357                                         TargetLowering::DAGCombinerInfo &DCI,
18358                                         const X86Subtarget* Subtarget) {
18359   SDLoc dl(N);
18360   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18361   SDValue V1 = SVOp->getOperand(0);
18362   SDValue V2 = SVOp->getOperand(1);
18363   EVT VT = SVOp->getValueType(0);
18364   unsigned NumElems = VT.getVectorNumElements();
18365
18366   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18367       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18368     //
18369     //                   0,0,0,...
18370     //                      |
18371     //    V      UNDEF    BUILD_VECTOR    UNDEF
18372     //     \      /           \           /
18373     //  CONCAT_VECTOR         CONCAT_VECTOR
18374     //         \                  /
18375     //          \                /
18376     //          RESULT: V + zero extended
18377     //
18378     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18379         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18380         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18381       return SDValue();
18382
18383     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18384       return SDValue();
18385
18386     // To match the shuffle mask, the first half of the mask should
18387     // be exactly the first vector, and all the rest a splat with the
18388     // first element of the second one.
18389     for (unsigned i = 0; i != NumElems/2; ++i)
18390       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18391           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18392         return SDValue();
18393
18394     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18395     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18396       if (Ld->hasNUsesOfValue(1, 0)) {
18397         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18398         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18399         SDValue ResNode =
18400           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18401                                   Ld->getMemoryVT(),
18402                                   Ld->getPointerInfo(),
18403                                   Ld->getAlignment(),
18404                                   false/*isVolatile*/, true/*ReadMem*/,
18405                                   false/*WriteMem*/);
18406
18407         // Make sure the newly-created LOAD is in the same position as Ld in
18408         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18409         // and update uses of Ld's output chain to use the TokenFactor.
18410         if (Ld->hasAnyUseOfValue(1)) {
18411           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18412                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18413           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18414           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18415                                  SDValue(ResNode.getNode(), 1));
18416         }
18417
18418         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18419       }
18420     }
18421
18422     // Emit a zeroed vector and insert the desired subvector on its
18423     // first half.
18424     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18425     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18426     return DCI.CombineTo(N, InsV);
18427   }
18428
18429   //===--------------------------------------------------------------------===//
18430   // Combine some shuffles into subvector extracts and inserts:
18431   //
18432
18433   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18434   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18435     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18436     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18437     return DCI.CombineTo(N, InsV);
18438   }
18439
18440   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18441   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18442     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18443     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18444     return DCI.CombineTo(N, InsV);
18445   }
18446
18447   return SDValue();
18448 }
18449
18450 /// \brief Get the PSHUF-style mask from PSHUF node.
18451 ///
18452 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18453 /// PSHUF-style masks that can be reused with such instructions.
18454 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18455   SmallVector<int, 4> Mask;
18456   bool IsUnary;
18457   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18458   (void)HaveMask;
18459   assert(HaveMask);
18460
18461   switch (N.getOpcode()) {
18462   case X86ISD::PSHUFD:
18463     return Mask;
18464   case X86ISD::PSHUFLW:
18465     Mask.resize(4);
18466     return Mask;
18467   case X86ISD::PSHUFHW:
18468     Mask.erase(Mask.begin(), Mask.begin() + 4);
18469     for (int &M : Mask)
18470       M -= 4;
18471     return Mask;
18472   default:
18473     llvm_unreachable("No valid shuffle instruction found!");
18474   }
18475 }
18476
18477 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18478 ///
18479 /// We walk up the chain and look for a combinable shuffle, skipping over
18480 /// shuffles that we could hoist this shuffle's transformation past without
18481 /// altering anything.
18482 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18483                                          SelectionDAG &DAG,
18484                                          TargetLowering::DAGCombinerInfo &DCI) {
18485   assert(N.getOpcode() == X86ISD::PSHUFD &&
18486          "Called with something other than an x86 128-bit half shuffle!");
18487   SDLoc DL(N);
18488
18489   // Walk up a single-use chain looking for a combinable shuffle.
18490   SDValue V = N.getOperand(0);
18491   for (; V.hasOneUse(); V = V.getOperand(0)) {
18492     switch (V.getOpcode()) {
18493     default:
18494       return false; // Nothing combined!
18495
18496     case ISD::BITCAST:
18497       // Skip bitcasts as we always know the type for the target specific
18498       // instructions.
18499       continue;
18500
18501     case X86ISD::PSHUFD:
18502       // Found another dword shuffle.
18503       break;
18504
18505     case X86ISD::PSHUFLW:
18506       // Check that the low words (being shuffled) are the identity in the
18507       // dword shuffle, and the high words are self-contained.
18508       if (Mask[0] != 0 || Mask[1] != 1 ||
18509           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18510         return false;
18511
18512       continue;
18513
18514     case X86ISD::PSHUFHW:
18515       // Check that the high words (being shuffled) are the identity in the
18516       // dword shuffle, and the low words are self-contained.
18517       if (Mask[2] != 2 || Mask[3] != 3 ||
18518           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18519         return false;
18520
18521       continue;
18522
18523     case X86ISD::UNPCKL:
18524     case X86ISD::UNPCKH:
18525       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
18526       // shuffle into a preceding word shuffle.
18527       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
18528         return false;
18529
18530       // Search for a half-shuffle which we can combine with.
18531       unsigned CombineOp =
18532           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18533       if (V.getOperand(0) != V.getOperand(1) ||
18534           !V->isOnlyUserOf(V.getOperand(0).getNode()))
18535         return false;
18536       V = V.getOperand(0);
18537       do {
18538         switch (V.getOpcode()) {
18539         default:
18540           return false; // Nothing to combine.
18541
18542         case X86ISD::PSHUFLW:
18543         case X86ISD::PSHUFHW:
18544           if (V.getOpcode() == CombineOp)
18545             break;
18546
18547           // Fallthrough!
18548         case ISD::BITCAST:
18549           V = V.getOperand(0);
18550           continue;
18551         }
18552         break;
18553       } while (V.hasOneUse());
18554       break;
18555     }
18556     // Break out of the loop if we break out of the switch.
18557     break;
18558   }
18559
18560   if (!V.hasOneUse())
18561     // We fell out of the loop without finding a viable combining instruction.
18562     return false;
18563
18564   // Record the old value to use in RAUW-ing.
18565   SDValue Old = V;
18566
18567   // Merge this node's mask and our incoming mask.
18568   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18569   for (int &M : Mask)
18570     M = VMask[M];
18571   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
18572                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18573
18574   // It is possible that one of the combinable shuffles was completely absorbed
18575   // by the other, just replace it and revisit all users in that case.
18576   if (Old.getNode() == V.getNode()) {
18577     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18578     return true;
18579   }
18580
18581   // Replace N with its operand as we're going to combine that shuffle away.
18582   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18583
18584   // Replace the combinable shuffle with the combined one, updating all users
18585   // so that we re-evaluate the chain here.
18586   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18587   return true;
18588 }
18589
18590 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18591 ///
18592 /// We walk up the chain, skipping shuffles of the other half and looking
18593 /// through shuffles which switch halves trying to find a shuffle of the same
18594 /// pair of dwords.
18595 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18596                                         SelectionDAG &DAG,
18597                                         TargetLowering::DAGCombinerInfo &DCI) {
18598   assert(
18599       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18600       "Called with something other than an x86 128-bit half shuffle!");
18601   SDLoc DL(N);
18602   unsigned CombineOpcode = N.getOpcode();
18603
18604   // Walk up a single-use chain looking for a combinable shuffle.
18605   SDValue V = N.getOperand(0);
18606   for (; V.hasOneUse(); V = V.getOperand(0)) {
18607     switch (V.getOpcode()) {
18608     default:
18609       return false; // Nothing combined!
18610
18611     case ISD::BITCAST:
18612       // Skip bitcasts as we always know the type for the target specific
18613       // instructions.
18614       continue;
18615
18616     case X86ISD::PSHUFLW:
18617     case X86ISD::PSHUFHW:
18618       if (V.getOpcode() == CombineOpcode)
18619         break;
18620
18621       // Other-half shuffles are no-ops.
18622       continue;
18623
18624     case X86ISD::PSHUFD: {
18625       // We can only handle pshufd if the half we are combining either stays in
18626       // its half, or switches to the other half. Bail if one of these isn't
18627       // true.
18628       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18629       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18630       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18631             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18632         return false;
18633
18634       // Map the mask through the pshufd and keep walking up the chain.
18635       for (int i = 0; i < 4; ++i)
18636         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18637
18638       // Switch halves if the pshufd does.
18639       CombineOpcode =
18640           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18641       continue;
18642     }
18643     }
18644     // Break out of the loop if we break out of the switch.
18645     break;
18646   }
18647
18648   if (!V.hasOneUse())
18649     // We fell out of the loop without finding a viable combining instruction.
18650     return false;
18651
18652   // Record the old value to use in RAUW-ing.
18653   SDValue Old = V;
18654
18655   // Merge this node's mask and our incoming mask (adjusted to account for all
18656   // the pshufd instructions encountered).
18657   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18658   for (int &M : Mask)
18659     M = VMask[M];
18660   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18661                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18662
18663   // Replace N with its operand as we're going to combine that shuffle away.
18664   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18665
18666   // Replace the combinable shuffle with the combined one, updating all users
18667   // so that we re-evaluate the chain here.
18668   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18669   return true;
18670 }
18671
18672 /// \brief Try to combine x86 target specific shuffles.
18673 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18674                                            TargetLowering::DAGCombinerInfo &DCI,
18675                                            const X86Subtarget *Subtarget) {
18676   SDLoc DL(N);
18677   MVT VT = N.getSimpleValueType();
18678   SmallVector<int, 4> Mask;
18679
18680   switch (N.getOpcode()) {
18681   case X86ISD::PSHUFD:
18682   case X86ISD::PSHUFLW:
18683   case X86ISD::PSHUFHW:
18684     Mask = getPSHUFShuffleMask(N);
18685     assert(Mask.size() == 4);
18686     break;
18687   default:
18688     return SDValue();
18689   }
18690
18691   // Nuke no-op shuffles that show up after combining.
18692   if (isNoopShuffleMask(Mask))
18693     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18694
18695   // Look for simplifications involving one or two shuffle instructions.
18696   SDValue V = N.getOperand(0);
18697   switch (N.getOpcode()) {
18698   default:
18699     break;
18700   case X86ISD::PSHUFLW:
18701   case X86ISD::PSHUFHW:
18702     assert(VT == MVT::v8i16);
18703     (void)VT;
18704
18705     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18706       return SDValue(); // We combined away this shuffle, so we're done.
18707
18708     // See if this reduces to a PSHUFD which is no more expensive and can
18709     // combine with more operations.
18710     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18711         areAdjacentMasksSequential(Mask)) {
18712       int DMask[] = {-1, -1, -1, -1};
18713       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18714       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18715       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18716       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18717       DCI.AddToWorklist(V.getNode());
18718       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18719                       getV4X86ShuffleImm8ForMask(DMask, DAG));
18720       DCI.AddToWorklist(V.getNode());
18721       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18722     }
18723
18724     // Look for shuffle patterns which can be implemented as a single unpack.
18725     // FIXME: This doesn't handle the location of the PSHUFD generically, and
18726     // only works when we have a PSHUFD followed by two half-shuffles.
18727     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
18728         (V.getOpcode() == X86ISD::PSHUFLW ||
18729          V.getOpcode() == X86ISD::PSHUFHW) &&
18730         V.getOpcode() != N.getOpcode() &&
18731         V.hasOneUse()) {
18732       SDValue D = V.getOperand(0);
18733       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
18734         D = D.getOperand(0);
18735       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
18736         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18737         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
18738         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18739         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
18740         int WordMask[8];
18741         for (int i = 0; i < 4; ++i) {
18742           WordMask[i + NOffset] = Mask[i] + NOffset;
18743           WordMask[i + VOffset] = VMask[i] + VOffset;
18744         }
18745         // Map the word mask through the DWord mask.
18746         int MappedMask[8];
18747         for (int i = 0; i < 8; ++i)
18748           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
18749         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
18750         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
18751         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
18752                        std::begin(UnpackLoMask)) ||
18753             std::equal(std::begin(MappedMask), std::end(MappedMask),
18754                        std::begin(UnpackHiMask))) {
18755           // We can replace all three shuffles with an unpack.
18756           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
18757           DCI.AddToWorklist(V.getNode());
18758           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
18759                                                 : X86ISD::UNPCKH,
18760                              DL, MVT::v8i16, V, V);
18761         }
18762       }
18763     }
18764
18765     break;
18766
18767   case X86ISD::PSHUFD:
18768     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18769       return SDValue(); // We combined away this shuffle.
18770
18771     break;
18772   }
18773
18774   return SDValue();
18775 }
18776
18777 /// PerformShuffleCombine - Performs several different shuffle combines.
18778 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18779                                      TargetLowering::DAGCombinerInfo &DCI,
18780                                      const X86Subtarget *Subtarget) {
18781   SDLoc dl(N);
18782   SDValue N0 = N->getOperand(0);
18783   SDValue N1 = N->getOperand(1);
18784   EVT VT = N->getValueType(0);
18785
18786   // Don't create instructions with illegal types after legalize types has run.
18787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18788   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18789     return SDValue();
18790
18791   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18792   if (Subtarget->hasFp256() && VT.is256BitVector() &&
18793       N->getOpcode() == ISD::VECTOR_SHUFFLE)
18794     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18795
18796   // During Type Legalization, when promoting illegal vector types,
18797   // the backend might introduce new shuffle dag nodes and bitcasts.
18798   //
18799   // This code performs the following transformation:
18800   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18801   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18802   //
18803   // We do this only if both the bitcast and the BINOP dag nodes have
18804   // one use. Also, perform this transformation only if the new binary
18805   // operation is legal. This is to avoid introducing dag nodes that
18806   // potentially need to be further expanded (or custom lowered) into a
18807   // less optimal sequence of dag nodes.
18808   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18809       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18810       N0.getOpcode() == ISD::BITCAST) {
18811     SDValue BC0 = N0.getOperand(0);
18812     EVT SVT = BC0.getValueType();
18813     unsigned Opcode = BC0.getOpcode();
18814     unsigned NumElts = VT.getVectorNumElements();
18815     
18816     if (BC0.hasOneUse() && SVT.isVector() &&
18817         SVT.getVectorNumElements() * 2 == NumElts &&
18818         TLI.isOperationLegal(Opcode, VT)) {
18819       bool CanFold = false;
18820       switch (Opcode) {
18821       default : break;
18822       case ISD::ADD :
18823       case ISD::FADD :
18824       case ISD::SUB :
18825       case ISD::FSUB :
18826       case ISD::MUL :
18827       case ISD::FMUL :
18828         CanFold = true;
18829       }
18830
18831       unsigned SVTNumElts = SVT.getVectorNumElements();
18832       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18833       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18834         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18835       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18836         CanFold = SVOp->getMaskElt(i) < 0;
18837
18838       if (CanFold) {
18839         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18840         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18841         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18842         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18843       }
18844     }
18845   }
18846
18847   // Only handle 128 wide vector from here on.
18848   if (!VT.is128BitVector())
18849     return SDValue();
18850
18851   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18852   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18853   // consecutive, non-overlapping, and in the right order.
18854   SmallVector<SDValue, 16> Elts;
18855   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18856     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18857
18858   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18859   if (LD.getNode())
18860     return LD;
18861
18862   if (isTargetShuffle(N->getOpcode())) {
18863     SDValue Shuffle =
18864         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18865     if (Shuffle.getNode())
18866       return Shuffle;
18867   }
18868
18869   return SDValue();
18870 }
18871
18872 /// PerformTruncateCombine - Converts truncate operation to
18873 /// a sequence of vector shuffle operations.
18874 /// It is possible when we truncate 256-bit vector to 128-bit vector
18875 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18876                                       TargetLowering::DAGCombinerInfo &DCI,
18877                                       const X86Subtarget *Subtarget)  {
18878   return SDValue();
18879 }
18880
18881 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18882 /// specific shuffle of a load can be folded into a single element load.
18883 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18884 /// shuffles have been customed lowered so we need to handle those here.
18885 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18886                                          TargetLowering::DAGCombinerInfo &DCI) {
18887   if (DCI.isBeforeLegalizeOps())
18888     return SDValue();
18889
18890   SDValue InVec = N->getOperand(0);
18891   SDValue EltNo = N->getOperand(1);
18892
18893   if (!isa<ConstantSDNode>(EltNo))
18894     return SDValue();
18895
18896   EVT VT = InVec.getValueType();
18897
18898   bool HasShuffleIntoBitcast = false;
18899   if (InVec.getOpcode() == ISD::BITCAST) {
18900     // Don't duplicate a load with other uses.
18901     if (!InVec.hasOneUse())
18902       return SDValue();
18903     EVT BCVT = InVec.getOperand(0).getValueType();
18904     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18905       return SDValue();
18906     InVec = InVec.getOperand(0);
18907     HasShuffleIntoBitcast = true;
18908   }
18909
18910   if (!isTargetShuffle(InVec.getOpcode()))
18911     return SDValue();
18912
18913   // Don't duplicate a load with other uses.
18914   if (!InVec.hasOneUse())
18915     return SDValue();
18916
18917   SmallVector<int, 16> ShuffleMask;
18918   bool UnaryShuffle;
18919   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18920                             UnaryShuffle))
18921     return SDValue();
18922
18923   // Select the input vector, guarding against out of range extract vector.
18924   unsigned NumElems = VT.getVectorNumElements();
18925   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18926   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18927   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18928                                          : InVec.getOperand(1);
18929
18930   // If inputs to shuffle are the same for both ops, then allow 2 uses
18931   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18932
18933   if (LdNode.getOpcode() == ISD::BITCAST) {
18934     // Don't duplicate a load with other uses.
18935     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18936       return SDValue();
18937
18938     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18939     LdNode = LdNode.getOperand(0);
18940   }
18941
18942   if (!ISD::isNormalLoad(LdNode.getNode()))
18943     return SDValue();
18944
18945   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18946
18947   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18948     return SDValue();
18949
18950   if (HasShuffleIntoBitcast) {
18951     // If there's a bitcast before the shuffle, check if the load type and
18952     // alignment is valid.
18953     unsigned Align = LN0->getAlignment();
18954     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18955     unsigned NewAlign = TLI.getDataLayout()->
18956       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18957
18958     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18959       return SDValue();
18960   }
18961
18962   // All checks match so transform back to vector_shuffle so that DAG combiner
18963   // can finish the job
18964   SDLoc dl(N);
18965
18966   // Create shuffle node taking into account the case that its a unary shuffle
18967   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18968   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18969                                  InVec.getOperand(0), Shuffle,
18970                                  &ShuffleMask[0]);
18971   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18972   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18973                      EltNo);
18974 }
18975
18976 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18977 /// generation and convert it from being a bunch of shuffles and extracts
18978 /// to a simple store and scalar loads to extract the elements.
18979 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18980                                          TargetLowering::DAGCombinerInfo &DCI) {
18981   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18982   if (NewOp.getNode())
18983     return NewOp;
18984
18985   SDValue InputVector = N->getOperand(0);
18986
18987   // Detect whether we are trying to convert from mmx to i32 and the bitcast
18988   // from mmx to v2i32 has a single usage.
18989   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18990       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18991       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18992     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18993                        N->getValueType(0),
18994                        InputVector.getNode()->getOperand(0));
18995
18996   // Only operate on vectors of 4 elements, where the alternative shuffling
18997   // gets to be more expensive.
18998   if (InputVector.getValueType() != MVT::v4i32)
18999     return SDValue();
19000
19001   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19002   // single use which is a sign-extend or zero-extend, and all elements are
19003   // used.
19004   SmallVector<SDNode *, 4> Uses;
19005   unsigned ExtractedElements = 0;
19006   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19007        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19008     if (UI.getUse().getResNo() != InputVector.getResNo())
19009       return SDValue();
19010
19011     SDNode *Extract = *UI;
19012     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19013       return SDValue();
19014
19015     if (Extract->getValueType(0) != MVT::i32)
19016       return SDValue();
19017     if (!Extract->hasOneUse())
19018       return SDValue();
19019     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19020         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19021       return SDValue();
19022     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19023       return SDValue();
19024
19025     // Record which element was extracted.
19026     ExtractedElements |=
19027       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19028
19029     Uses.push_back(Extract);
19030   }
19031
19032   // If not all the elements were used, this may not be worthwhile.
19033   if (ExtractedElements != 15)
19034     return SDValue();
19035
19036   // Ok, we've now decided to do the transformation.
19037   SDLoc dl(InputVector);
19038
19039   // Store the value to a temporary stack slot.
19040   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19041   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19042                             MachinePointerInfo(), false, false, 0);
19043
19044   // Replace each use (extract) with a load of the appropriate element.
19045   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19046        UE = Uses.end(); UI != UE; ++UI) {
19047     SDNode *Extract = *UI;
19048
19049     // cOMpute the element's address.
19050     SDValue Idx = Extract->getOperand(1);
19051     unsigned EltSize =
19052         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19053     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19054     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19055     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19056
19057     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19058                                      StackPtr, OffsetVal);
19059
19060     // Load the scalar.
19061     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19062                                      ScalarAddr, MachinePointerInfo(),
19063                                      false, false, false, 0);
19064
19065     // Replace the exact with the load.
19066     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19067   }
19068
19069   // The replacement was made in place; don't return anything.
19070   return SDValue();
19071 }
19072
19073 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19074 static std::pair<unsigned, bool>
19075 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19076                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19077   if (!VT.isVector())
19078     return std::make_pair(0, false);
19079
19080   bool NeedSplit = false;
19081   switch (VT.getSimpleVT().SimpleTy) {
19082   default: return std::make_pair(0, false);
19083   case MVT::v32i8:
19084   case MVT::v16i16:
19085   case MVT::v8i32:
19086     if (!Subtarget->hasAVX2())
19087       NeedSplit = true;
19088     if (!Subtarget->hasAVX())
19089       return std::make_pair(0, false);
19090     break;
19091   case MVT::v16i8:
19092   case MVT::v8i16:
19093   case MVT::v4i32:
19094     if (!Subtarget->hasSSE2())
19095       return std::make_pair(0, false);
19096   }
19097
19098   // SSE2 has only a small subset of the operations.
19099   bool hasUnsigned = Subtarget->hasSSE41() ||
19100                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19101   bool hasSigned = Subtarget->hasSSE41() ||
19102                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19103
19104   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19105
19106   unsigned Opc = 0;
19107   // Check for x CC y ? x : y.
19108   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19109       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19110     switch (CC) {
19111     default: break;
19112     case ISD::SETULT:
19113     case ISD::SETULE:
19114       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19115     case ISD::SETUGT:
19116     case ISD::SETUGE:
19117       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19118     case ISD::SETLT:
19119     case ISD::SETLE:
19120       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19121     case ISD::SETGT:
19122     case ISD::SETGE:
19123       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19124     }
19125   // Check for x CC y ? y : x -- a min/max with reversed arms.
19126   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19127              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19128     switch (CC) {
19129     default: break;
19130     case ISD::SETULT:
19131     case ISD::SETULE:
19132       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19133     case ISD::SETUGT:
19134     case ISD::SETUGE:
19135       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19136     case ISD::SETLT:
19137     case ISD::SETLE:
19138       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19139     case ISD::SETGT:
19140     case ISD::SETGE:
19141       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19142     }
19143   }
19144
19145   return std::make_pair(Opc, NeedSplit);
19146 }
19147
19148 static SDValue
19149 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19150                                       const X86Subtarget *Subtarget) {
19151   SDLoc dl(N);
19152   SDValue Cond = N->getOperand(0);
19153   SDValue LHS = N->getOperand(1);
19154   SDValue RHS = N->getOperand(2);
19155
19156   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19157     SDValue CondSrc = Cond->getOperand(0);
19158     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19159       Cond = CondSrc->getOperand(0);
19160   }
19161
19162   MVT VT = N->getSimpleValueType(0);
19163   MVT EltVT = VT.getVectorElementType();
19164   unsigned NumElems = VT.getVectorNumElements();
19165   // There is no blend with immediate in AVX-512.
19166   if (VT.is512BitVector())
19167     return SDValue();
19168
19169   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19170     return SDValue();
19171   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19172     return SDValue();
19173
19174   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19175     return SDValue();
19176
19177   unsigned MaskValue = 0;
19178   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19179     return SDValue();
19180
19181   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19182   for (unsigned i = 0; i < NumElems; ++i) {
19183     // Be sure we emit undef where we can.
19184     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19185       ShuffleMask[i] = -1;
19186     else
19187       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19188   }
19189
19190   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19191 }
19192
19193 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19194 /// nodes.
19195 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19196                                     TargetLowering::DAGCombinerInfo &DCI,
19197                                     const X86Subtarget *Subtarget) {
19198   SDLoc DL(N);
19199   SDValue Cond = N->getOperand(0);
19200   // Get the LHS/RHS of the select.
19201   SDValue LHS = N->getOperand(1);
19202   SDValue RHS = N->getOperand(2);
19203   EVT VT = LHS.getValueType();
19204   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19205
19206   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19207   // instructions match the semantics of the common C idiom x<y?x:y but not
19208   // x<=y?x:y, because of how they handle negative zero (which can be
19209   // ignored in unsafe-math mode).
19210   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19211       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19212       (Subtarget->hasSSE2() ||
19213        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19214     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19215
19216     unsigned Opcode = 0;
19217     // Check for x CC y ? x : y.
19218     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19219         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19220       switch (CC) {
19221       default: break;
19222       case ISD::SETULT:
19223         // Converting this to a min would handle NaNs incorrectly, and swapping
19224         // the operands would cause it to handle comparisons between positive
19225         // and negative zero incorrectly.
19226         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19227           if (!DAG.getTarget().Options.UnsafeFPMath &&
19228               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19229             break;
19230           std::swap(LHS, RHS);
19231         }
19232         Opcode = X86ISD::FMIN;
19233         break;
19234       case ISD::SETOLE:
19235         // Converting this to a min would handle comparisons between positive
19236         // and negative zero incorrectly.
19237         if (!DAG.getTarget().Options.UnsafeFPMath &&
19238             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19239           break;
19240         Opcode = X86ISD::FMIN;
19241         break;
19242       case ISD::SETULE:
19243         // Converting this to a min would handle both negative zeros and NaNs
19244         // incorrectly, but we can swap the operands to fix both.
19245         std::swap(LHS, RHS);
19246       case ISD::SETOLT:
19247       case ISD::SETLT:
19248       case ISD::SETLE:
19249         Opcode = X86ISD::FMIN;
19250         break;
19251
19252       case ISD::SETOGE:
19253         // Converting this to a max would handle comparisons between positive
19254         // and negative zero incorrectly.
19255         if (!DAG.getTarget().Options.UnsafeFPMath &&
19256             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19257           break;
19258         Opcode = X86ISD::FMAX;
19259         break;
19260       case ISD::SETUGT:
19261         // Converting this to a max would handle NaNs incorrectly, and swapping
19262         // the operands would cause it to handle comparisons between positive
19263         // and negative zero incorrectly.
19264         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19265           if (!DAG.getTarget().Options.UnsafeFPMath &&
19266               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19267             break;
19268           std::swap(LHS, RHS);
19269         }
19270         Opcode = X86ISD::FMAX;
19271         break;
19272       case ISD::SETUGE:
19273         // Converting this to a max would handle both negative zeros and NaNs
19274         // incorrectly, but we can swap the operands to fix both.
19275         std::swap(LHS, RHS);
19276       case ISD::SETOGT:
19277       case ISD::SETGT:
19278       case ISD::SETGE:
19279         Opcode = X86ISD::FMAX;
19280         break;
19281       }
19282     // Check for x CC y ? y : x -- a min/max with reversed arms.
19283     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19284                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19285       switch (CC) {
19286       default: break;
19287       case ISD::SETOGE:
19288         // Converting this to a min would handle comparisons between positive
19289         // and negative zero incorrectly, and swapping the operands would
19290         // cause it to handle NaNs incorrectly.
19291         if (!DAG.getTarget().Options.UnsafeFPMath &&
19292             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19293           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19294             break;
19295           std::swap(LHS, RHS);
19296         }
19297         Opcode = X86ISD::FMIN;
19298         break;
19299       case ISD::SETUGT:
19300         // Converting this to a min would handle NaNs incorrectly.
19301         if (!DAG.getTarget().Options.UnsafeFPMath &&
19302             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19303           break;
19304         Opcode = X86ISD::FMIN;
19305         break;
19306       case ISD::SETUGE:
19307         // Converting this to a min would handle both negative zeros and NaNs
19308         // incorrectly, but we can swap the operands to fix both.
19309         std::swap(LHS, RHS);
19310       case ISD::SETOGT:
19311       case ISD::SETGT:
19312       case ISD::SETGE:
19313         Opcode = X86ISD::FMIN;
19314         break;
19315
19316       case ISD::SETULT:
19317         // Converting this to a max would handle NaNs incorrectly.
19318         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19319           break;
19320         Opcode = X86ISD::FMAX;
19321         break;
19322       case ISD::SETOLE:
19323         // Converting this to a max would handle comparisons between positive
19324         // and negative zero incorrectly, and swapping the operands would
19325         // cause it to handle NaNs incorrectly.
19326         if (!DAG.getTarget().Options.UnsafeFPMath &&
19327             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19328           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19329             break;
19330           std::swap(LHS, RHS);
19331         }
19332         Opcode = X86ISD::FMAX;
19333         break;
19334       case ISD::SETULE:
19335         // Converting this to a max would handle both negative zeros and NaNs
19336         // incorrectly, but we can swap the operands to fix both.
19337         std::swap(LHS, RHS);
19338       case ISD::SETOLT:
19339       case ISD::SETLT:
19340       case ISD::SETLE:
19341         Opcode = X86ISD::FMAX;
19342         break;
19343       }
19344     }
19345
19346     if (Opcode)
19347       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19348   }
19349
19350   EVT CondVT = Cond.getValueType();
19351   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19352       CondVT.getVectorElementType() == MVT::i1) {
19353     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19354     // lowering on AVX-512. In this case we convert it to
19355     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19356     // The same situation for all 128 and 256-bit vectors of i8 and i16
19357     EVT OpVT = LHS.getValueType();
19358     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19359         (OpVT.getVectorElementType() == MVT::i8 ||
19360          OpVT.getVectorElementType() == MVT::i16)) {
19361       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19362       DCI.AddToWorklist(Cond.getNode());
19363       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19364     }
19365   }
19366   // If this is a select between two integer constants, try to do some
19367   // optimizations.
19368   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19369     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19370       // Don't do this for crazy integer types.
19371       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19372         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19373         // so that TrueC (the true value) is larger than FalseC.
19374         bool NeedsCondInvert = false;
19375
19376         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19377             // Efficiently invertible.
19378             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19379              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19380               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19381           NeedsCondInvert = true;
19382           std::swap(TrueC, FalseC);
19383         }
19384
19385         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19386         if (FalseC->getAPIntValue() == 0 &&
19387             TrueC->getAPIntValue().isPowerOf2()) {
19388           if (NeedsCondInvert) // Invert the condition if needed.
19389             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19390                                DAG.getConstant(1, Cond.getValueType()));
19391
19392           // Zero extend the condition if needed.
19393           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19394
19395           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19396           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19397                              DAG.getConstant(ShAmt, MVT::i8));
19398         }
19399
19400         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19401         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19402           if (NeedsCondInvert) // Invert the condition if needed.
19403             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19404                                DAG.getConstant(1, Cond.getValueType()));
19405
19406           // Zero extend the condition if needed.
19407           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19408                              FalseC->getValueType(0), Cond);
19409           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19410                              SDValue(FalseC, 0));
19411         }
19412
19413         // Optimize cases that will turn into an LEA instruction.  This requires
19414         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19415         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19416           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19417           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19418
19419           bool isFastMultiplier = false;
19420           if (Diff < 10) {
19421             switch ((unsigned char)Diff) {
19422               default: break;
19423               case 1:  // result = add base, cond
19424               case 2:  // result = lea base(    , cond*2)
19425               case 3:  // result = lea base(cond, cond*2)
19426               case 4:  // result = lea base(    , cond*4)
19427               case 5:  // result = lea base(cond, cond*4)
19428               case 8:  // result = lea base(    , cond*8)
19429               case 9:  // result = lea base(cond, cond*8)
19430                 isFastMultiplier = true;
19431                 break;
19432             }
19433           }
19434
19435           if (isFastMultiplier) {
19436             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19437             if (NeedsCondInvert) // Invert the condition if needed.
19438               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19439                                  DAG.getConstant(1, Cond.getValueType()));
19440
19441             // Zero extend the condition if needed.
19442             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19443                                Cond);
19444             // Scale the condition by the difference.
19445             if (Diff != 1)
19446               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19447                                  DAG.getConstant(Diff, Cond.getValueType()));
19448
19449             // Add the base if non-zero.
19450             if (FalseC->getAPIntValue() != 0)
19451               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19452                                  SDValue(FalseC, 0));
19453             return Cond;
19454           }
19455         }
19456       }
19457   }
19458
19459   // Canonicalize max and min:
19460   // (x > y) ? x : y -> (x >= y) ? x : y
19461   // (x < y) ? x : y -> (x <= y) ? x : y
19462   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19463   // the need for an extra compare
19464   // against zero. e.g.
19465   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19466   // subl   %esi, %edi
19467   // testl  %edi, %edi
19468   // movl   $0, %eax
19469   // cmovgl %edi, %eax
19470   // =>
19471   // xorl   %eax, %eax
19472   // subl   %esi, $edi
19473   // cmovsl %eax, %edi
19474   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19475       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19476       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19477     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19478     switch (CC) {
19479     default: break;
19480     case ISD::SETLT:
19481     case ISD::SETGT: {
19482       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19483       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19484                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19485       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19486     }
19487     }
19488   }
19489
19490   // Early exit check
19491   if (!TLI.isTypeLegal(VT))
19492     return SDValue();
19493
19494   // Match VSELECTs into subs with unsigned saturation.
19495   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19496       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19497       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19498        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19499     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19500
19501     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19502     // left side invert the predicate to simplify logic below.
19503     SDValue Other;
19504     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19505       Other = RHS;
19506       CC = ISD::getSetCCInverse(CC, true);
19507     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19508       Other = LHS;
19509     }
19510
19511     if (Other.getNode() && Other->getNumOperands() == 2 &&
19512         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19513       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19514       SDValue CondRHS = Cond->getOperand(1);
19515
19516       // Look for a general sub with unsigned saturation first.
19517       // x >= y ? x-y : 0 --> subus x, y
19518       // x >  y ? x-y : 0 --> subus x, y
19519       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19520           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19521         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19522
19523       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
19524         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
19525           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
19526             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
19527               // If the RHS is a constant we have to reverse the const
19528               // canonicalization.
19529               // x > C-1 ? x+-C : 0 --> subus x, C
19530               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19531                   CondRHSConst->getAPIntValue() ==
19532                       (-OpRHSConst->getAPIntValue() - 1))
19533                 return DAG.getNode(
19534                     X86ISD::SUBUS, DL, VT, OpLHS,
19535                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
19536
19537           // Another special case: If C was a sign bit, the sub has been
19538           // canonicalized into a xor.
19539           // FIXME: Would it be better to use computeKnownBits to determine
19540           //        whether it's safe to decanonicalize the xor?
19541           // x s< 0 ? x^C : 0 --> subus x, C
19542           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19543               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19544               OpRHSConst->getAPIntValue().isSignBit())
19545             // Note that we have to rebuild the RHS constant here to ensure we
19546             // don't rely on particular values of undef lanes.
19547             return DAG.getNode(
19548                 X86ISD::SUBUS, DL, VT, OpLHS,
19549                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
19550         }
19551     }
19552   }
19553
19554   // Try to match a min/max vector operation.
19555   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19556     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19557     unsigned Opc = ret.first;
19558     bool NeedSplit = ret.second;
19559
19560     if (Opc && NeedSplit) {
19561       unsigned NumElems = VT.getVectorNumElements();
19562       // Extract the LHS vectors
19563       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19564       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19565
19566       // Extract the RHS vectors
19567       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19568       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19569
19570       // Create min/max for each subvector
19571       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19572       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19573
19574       // Merge the result
19575       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19576     } else if (Opc)
19577       return DAG.getNode(Opc, DL, VT, LHS, RHS);
19578   }
19579
19580   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19581   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19582       // Check if SETCC has already been promoted
19583       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19584       // Check that condition value type matches vselect operand type
19585       CondVT == VT) { 
19586
19587     assert(Cond.getValueType().isVector() &&
19588            "vector select expects a vector selector!");
19589
19590     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19591     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19592
19593     if (!TValIsAllOnes && !FValIsAllZeros) {
19594       // Try invert the condition if true value is not all 1s and false value
19595       // is not all 0s.
19596       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19597       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19598
19599       if (TValIsAllZeros || FValIsAllOnes) {
19600         SDValue CC = Cond.getOperand(2);
19601         ISD::CondCode NewCC =
19602           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19603                                Cond.getOperand(0).getValueType().isInteger());
19604         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19605         std::swap(LHS, RHS);
19606         TValIsAllOnes = FValIsAllOnes;
19607         FValIsAllZeros = TValIsAllZeros;
19608       }
19609     }
19610
19611     if (TValIsAllOnes || FValIsAllZeros) {
19612       SDValue Ret;
19613
19614       if (TValIsAllOnes && FValIsAllZeros)
19615         Ret = Cond;
19616       else if (TValIsAllOnes)
19617         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19618                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19619       else if (FValIsAllZeros)
19620         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19621                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19622
19623       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19624     }
19625   }
19626
19627   // Try to fold this VSELECT into a MOVSS/MOVSD
19628   if (N->getOpcode() == ISD::VSELECT &&
19629       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19630     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19631         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19632       bool CanFold = false;
19633       unsigned NumElems = Cond.getNumOperands();
19634       SDValue A = LHS;
19635       SDValue B = RHS;
19636       
19637       if (isZero(Cond.getOperand(0))) {
19638         CanFold = true;
19639
19640         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19641         // fold (vselect <0,-1> -> (movsd A, B)
19642         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19643           CanFold = isAllOnes(Cond.getOperand(i));
19644       } else if (isAllOnes(Cond.getOperand(0))) {
19645         CanFold = true;
19646         std::swap(A, B);
19647
19648         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19649         // fold (vselect <-1,0> -> (movsd B, A)
19650         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19651           CanFold = isZero(Cond.getOperand(i));
19652       }
19653
19654       if (CanFold) {
19655         if (VT == MVT::v4i32 || VT == MVT::v4f32)
19656           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19657         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19658       }
19659
19660       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19661         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19662         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19663         //                             (v2i64 (bitcast B)))))
19664         //
19665         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19666         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19667         //                             (v2f64 (bitcast B)))))
19668         //
19669         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19670         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19671         //                             (v2i64 (bitcast A)))))
19672         //
19673         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19674         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19675         //                             (v2f64 (bitcast A)))))
19676
19677         CanFold = (isZero(Cond.getOperand(0)) &&
19678                    isZero(Cond.getOperand(1)) &&
19679                    isAllOnes(Cond.getOperand(2)) &&
19680                    isAllOnes(Cond.getOperand(3)));
19681
19682         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19683             isAllOnes(Cond.getOperand(1)) &&
19684             isZero(Cond.getOperand(2)) &&
19685             isZero(Cond.getOperand(3))) {
19686           CanFold = true;
19687           std::swap(LHS, RHS);
19688         }
19689
19690         if (CanFold) {
19691           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19692           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19693           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19694           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19695                                                 NewB, DAG);
19696           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19697         }
19698       }
19699     }
19700   }
19701
19702   // If we know that this node is legal then we know that it is going to be
19703   // matched by one of the SSE/AVX BLEND instructions. These instructions only
19704   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19705   // to simplify previous instructions.
19706   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19707       !DCI.isBeforeLegalize() &&
19708       // We explicitly check against v8i16 and v16i16 because, although
19709       // they're marked as Custom, they might only be legal when Cond is a
19710       // build_vector of constants. This will be taken care in a later
19711       // condition.
19712       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19713        VT != MVT::v8i16)) {
19714     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19715
19716     // Don't optimize vector selects that map to mask-registers.
19717     if (BitWidth == 1)
19718       return SDValue();
19719
19720     // Check all uses of that condition operand to check whether it will be
19721     // consumed by non-BLEND instructions, which may depend on all bits are set
19722     // properly.
19723     for (SDNode::use_iterator I = Cond->use_begin(),
19724                               E = Cond->use_end(); I != E; ++I)
19725       if (I->getOpcode() != ISD::VSELECT)
19726         // TODO: Add other opcodes eventually lowered into BLEND.
19727         return SDValue();
19728
19729     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19730     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19731
19732     APInt KnownZero, KnownOne;
19733     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19734                                           DCI.isBeforeLegalizeOps());
19735     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19736         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19737       DCI.CommitTargetLoweringOpt(TLO);
19738   }
19739
19740   // We should generate an X86ISD::BLENDI from a vselect if its argument
19741   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19742   // constants. This specific pattern gets generated when we split a
19743   // selector for a 512 bit vector in a machine without AVX512 (but with
19744   // 256-bit vectors), during legalization:
19745   //
19746   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19747   //
19748   // Iff we find this pattern and the build_vectors are built from
19749   // constants, we translate the vselect into a shuffle_vector that we
19750   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19751   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19752     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19753     if (Shuffle.getNode())
19754       return Shuffle;
19755   }
19756
19757   return SDValue();
19758 }
19759
19760 // Check whether a boolean test is testing a boolean value generated by
19761 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19762 // code.
19763 //
19764 // Simplify the following patterns:
19765 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19766 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19767 // to (Op EFLAGS Cond)
19768 //
19769 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19770 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19771 // to (Op EFLAGS !Cond)
19772 //
19773 // where Op could be BRCOND or CMOV.
19774 //
19775 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19776   // Quit if not CMP and SUB with its value result used.
19777   if (Cmp.getOpcode() != X86ISD::CMP &&
19778       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19779       return SDValue();
19780
19781   // Quit if not used as a boolean value.
19782   if (CC != X86::COND_E && CC != X86::COND_NE)
19783     return SDValue();
19784
19785   // Check CMP operands. One of them should be 0 or 1 and the other should be
19786   // an SetCC or extended from it.
19787   SDValue Op1 = Cmp.getOperand(0);
19788   SDValue Op2 = Cmp.getOperand(1);
19789
19790   SDValue SetCC;
19791   const ConstantSDNode* C = nullptr;
19792   bool needOppositeCond = (CC == X86::COND_E);
19793   bool checkAgainstTrue = false; // Is it a comparison against 1?
19794
19795   if ((C = dyn_cast<ConstantSDNode>(Op1)))
19796     SetCC = Op2;
19797   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19798     SetCC = Op1;
19799   else // Quit if all operands are not constants.
19800     return SDValue();
19801
19802   if (C->getZExtValue() == 1) {
19803     needOppositeCond = !needOppositeCond;
19804     checkAgainstTrue = true;
19805   } else if (C->getZExtValue() != 0)
19806     // Quit if the constant is neither 0 or 1.
19807     return SDValue();
19808
19809   bool truncatedToBoolWithAnd = false;
19810   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19811   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19812          SetCC.getOpcode() == ISD::TRUNCATE ||
19813          SetCC.getOpcode() == ISD::AND) {
19814     if (SetCC.getOpcode() == ISD::AND) {
19815       int OpIdx = -1;
19816       ConstantSDNode *CS;
19817       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19818           CS->getZExtValue() == 1)
19819         OpIdx = 1;
19820       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19821           CS->getZExtValue() == 1)
19822         OpIdx = 0;
19823       if (OpIdx == -1)
19824         break;
19825       SetCC = SetCC.getOperand(OpIdx);
19826       truncatedToBoolWithAnd = true;
19827     } else
19828       SetCC = SetCC.getOperand(0);
19829   }
19830
19831   switch (SetCC.getOpcode()) {
19832   case X86ISD::SETCC_CARRY:
19833     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19834     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19835     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19836     // truncated to i1 using 'and'.
19837     if (checkAgainstTrue && !truncatedToBoolWithAnd)
19838       break;
19839     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19840            "Invalid use of SETCC_CARRY!");
19841     // FALL THROUGH
19842   case X86ISD::SETCC:
19843     // Set the condition code or opposite one if necessary.
19844     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19845     if (needOppositeCond)
19846       CC = X86::GetOppositeBranchCondition(CC);
19847     return SetCC.getOperand(1);
19848   case X86ISD::CMOV: {
19849     // Check whether false/true value has canonical one, i.e. 0 or 1.
19850     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19851     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19852     // Quit if true value is not a constant.
19853     if (!TVal)
19854       return SDValue();
19855     // Quit if false value is not a constant.
19856     if (!FVal) {
19857       SDValue Op = SetCC.getOperand(0);
19858       // Skip 'zext' or 'trunc' node.
19859       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19860           Op.getOpcode() == ISD::TRUNCATE)
19861         Op = Op.getOperand(0);
19862       // A special case for rdrand/rdseed, where 0 is set if false cond is
19863       // found.
19864       if ((Op.getOpcode() != X86ISD::RDRAND &&
19865            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19866         return SDValue();
19867     }
19868     // Quit if false value is not the constant 0 or 1.
19869     bool FValIsFalse = true;
19870     if (FVal && FVal->getZExtValue() != 0) {
19871       if (FVal->getZExtValue() != 1)
19872         return SDValue();
19873       // If FVal is 1, opposite cond is needed.
19874       needOppositeCond = !needOppositeCond;
19875       FValIsFalse = false;
19876     }
19877     // Quit if TVal is not the constant opposite of FVal.
19878     if (FValIsFalse && TVal->getZExtValue() != 1)
19879       return SDValue();
19880     if (!FValIsFalse && TVal->getZExtValue() != 0)
19881       return SDValue();
19882     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19883     if (needOppositeCond)
19884       CC = X86::GetOppositeBranchCondition(CC);
19885     return SetCC.getOperand(3);
19886   }
19887   }
19888
19889   return SDValue();
19890 }
19891
19892 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19893 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19894                                   TargetLowering::DAGCombinerInfo &DCI,
19895                                   const X86Subtarget *Subtarget) {
19896   SDLoc DL(N);
19897
19898   // If the flag operand isn't dead, don't touch this CMOV.
19899   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19900     return SDValue();
19901
19902   SDValue FalseOp = N->getOperand(0);
19903   SDValue TrueOp = N->getOperand(1);
19904   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19905   SDValue Cond = N->getOperand(3);
19906
19907   if (CC == X86::COND_E || CC == X86::COND_NE) {
19908     switch (Cond.getOpcode()) {
19909     default: break;
19910     case X86ISD::BSR:
19911     case X86ISD::BSF:
19912       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19913       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19914         return (CC == X86::COND_E) ? FalseOp : TrueOp;
19915     }
19916   }
19917
19918   SDValue Flags;
19919
19920   Flags = checkBoolTestSetCCCombine(Cond, CC);
19921   if (Flags.getNode() &&
19922       // Extra check as FCMOV only supports a subset of X86 cond.
19923       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19924     SDValue Ops[] = { FalseOp, TrueOp,
19925                       DAG.getConstant(CC, MVT::i8), Flags };
19926     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19927   }
19928
19929   // If this is a select between two integer constants, try to do some
19930   // optimizations.  Note that the operands are ordered the opposite of SELECT
19931   // operands.
19932   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19933     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19934       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19935       // larger than FalseC (the false value).
19936       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19937         CC = X86::GetOppositeBranchCondition(CC);
19938         std::swap(TrueC, FalseC);
19939         std::swap(TrueOp, FalseOp);
19940       }
19941
19942       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19943       // This is efficient for any integer data type (including i8/i16) and
19944       // shift amount.
19945       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19946         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19947                            DAG.getConstant(CC, MVT::i8), Cond);
19948
19949         // Zero extend the condition if needed.
19950         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19951
19952         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19953         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19954                            DAG.getConstant(ShAmt, MVT::i8));
19955         if (N->getNumValues() == 2)  // Dead flag value?
19956           return DCI.CombineTo(N, Cond, SDValue());
19957         return Cond;
19958       }
19959
19960       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
19961       // for any integer data type, including i8/i16.
19962       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19963         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19964                            DAG.getConstant(CC, MVT::i8), Cond);
19965
19966         // Zero extend the condition if needed.
19967         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19968                            FalseC->getValueType(0), Cond);
19969         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19970                            SDValue(FalseC, 0));
19971
19972         if (N->getNumValues() == 2)  // Dead flag value?
19973           return DCI.CombineTo(N, Cond, SDValue());
19974         return Cond;
19975       }
19976
19977       // Optimize cases that will turn into an LEA instruction.  This requires
19978       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19979       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19980         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19981         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19982
19983         bool isFastMultiplier = false;
19984         if (Diff < 10) {
19985           switch ((unsigned char)Diff) {
19986           default: break;
19987           case 1:  // result = add base, cond
19988           case 2:  // result = lea base(    , cond*2)
19989           case 3:  // result = lea base(cond, cond*2)
19990           case 4:  // result = lea base(    , cond*4)
19991           case 5:  // result = lea base(cond, cond*4)
19992           case 8:  // result = lea base(    , cond*8)
19993           case 9:  // result = lea base(cond, cond*8)
19994             isFastMultiplier = true;
19995             break;
19996           }
19997         }
19998
19999         if (isFastMultiplier) {
20000           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20001           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20002                              DAG.getConstant(CC, MVT::i8), Cond);
20003           // Zero extend the condition if needed.
20004           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20005                              Cond);
20006           // Scale the condition by the difference.
20007           if (Diff != 1)
20008             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20009                                DAG.getConstant(Diff, Cond.getValueType()));
20010
20011           // Add the base if non-zero.
20012           if (FalseC->getAPIntValue() != 0)
20013             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20014                                SDValue(FalseC, 0));
20015           if (N->getNumValues() == 2)  // Dead flag value?
20016             return DCI.CombineTo(N, Cond, SDValue());
20017           return Cond;
20018         }
20019       }
20020     }
20021   }
20022
20023   // Handle these cases:
20024   //   (select (x != c), e, c) -> select (x != c), e, x),
20025   //   (select (x == c), c, e) -> select (x == c), x, e)
20026   // where the c is an integer constant, and the "select" is the combination
20027   // of CMOV and CMP.
20028   //
20029   // The rationale for this change is that the conditional-move from a constant
20030   // needs two instructions, however, conditional-move from a register needs
20031   // only one instruction.
20032   //
20033   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20034   //  some instruction-combining opportunities. This opt needs to be
20035   //  postponed as late as possible.
20036   //
20037   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20038     // the DCI.xxxx conditions are provided to postpone the optimization as
20039     // late as possible.
20040
20041     ConstantSDNode *CmpAgainst = nullptr;
20042     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20043         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20044         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20045
20046       if (CC == X86::COND_NE &&
20047           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20048         CC = X86::GetOppositeBranchCondition(CC);
20049         std::swap(TrueOp, FalseOp);
20050       }
20051
20052       if (CC == X86::COND_E &&
20053           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20054         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20055                           DAG.getConstant(CC, MVT::i8), Cond };
20056         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20057       }
20058     }
20059   }
20060
20061   return SDValue();
20062 }
20063
20064 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20065                                                 const X86Subtarget *Subtarget) {
20066   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20067   switch (IntNo) {
20068   default: return SDValue();
20069   // SSE/AVX/AVX2 blend intrinsics.
20070   case Intrinsic::x86_avx2_pblendvb:
20071   case Intrinsic::x86_avx2_pblendw:
20072   case Intrinsic::x86_avx2_pblendd_128:
20073   case Intrinsic::x86_avx2_pblendd_256:
20074     // Don't try to simplify this intrinsic if we don't have AVX2.
20075     if (!Subtarget->hasAVX2())
20076       return SDValue();
20077     // FALL-THROUGH
20078   case Intrinsic::x86_avx_blend_pd_256:
20079   case Intrinsic::x86_avx_blend_ps_256:
20080   case Intrinsic::x86_avx_blendv_pd_256:
20081   case Intrinsic::x86_avx_blendv_ps_256:
20082     // Don't try to simplify this intrinsic if we don't have AVX.
20083     if (!Subtarget->hasAVX())
20084       return SDValue();
20085     // FALL-THROUGH
20086   case Intrinsic::x86_sse41_pblendw:
20087   case Intrinsic::x86_sse41_blendpd:
20088   case Intrinsic::x86_sse41_blendps:
20089   case Intrinsic::x86_sse41_blendvps:
20090   case Intrinsic::x86_sse41_blendvpd:
20091   case Intrinsic::x86_sse41_pblendvb: {
20092     SDValue Op0 = N->getOperand(1);
20093     SDValue Op1 = N->getOperand(2);
20094     SDValue Mask = N->getOperand(3);
20095
20096     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20097     if (!Subtarget->hasSSE41())
20098       return SDValue();
20099
20100     // fold (blend A, A, Mask) -> A
20101     if (Op0 == Op1)
20102       return Op0;
20103     // fold (blend A, B, allZeros) -> A
20104     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20105       return Op0;
20106     // fold (blend A, B, allOnes) -> B
20107     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20108       return Op1;
20109     
20110     // Simplify the case where the mask is a constant i32 value.
20111     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20112       if (C->isNullValue())
20113         return Op0;
20114       if (C->isAllOnesValue())
20115         return Op1;
20116     }
20117
20118     return SDValue();
20119   }
20120
20121   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20122   case Intrinsic::x86_sse2_psrai_w:
20123   case Intrinsic::x86_sse2_psrai_d:
20124   case Intrinsic::x86_avx2_psrai_w:
20125   case Intrinsic::x86_avx2_psrai_d:
20126   case Intrinsic::x86_sse2_psra_w:
20127   case Intrinsic::x86_sse2_psra_d:
20128   case Intrinsic::x86_avx2_psra_w:
20129   case Intrinsic::x86_avx2_psra_d: {
20130     SDValue Op0 = N->getOperand(1);
20131     SDValue Op1 = N->getOperand(2);
20132     EVT VT = Op0.getValueType();
20133     assert(VT.isVector() && "Expected a vector type!");
20134
20135     if (isa<BuildVectorSDNode>(Op1))
20136       Op1 = Op1.getOperand(0);
20137
20138     if (!isa<ConstantSDNode>(Op1))
20139       return SDValue();
20140
20141     EVT SVT = VT.getVectorElementType();
20142     unsigned SVTBits = SVT.getSizeInBits();
20143
20144     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20145     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20146     uint64_t ShAmt = C.getZExtValue();
20147
20148     // Don't try to convert this shift into a ISD::SRA if the shift
20149     // count is bigger than or equal to the element size.
20150     if (ShAmt >= SVTBits)
20151       return SDValue();
20152
20153     // Trivial case: if the shift count is zero, then fold this
20154     // into the first operand.
20155     if (ShAmt == 0)
20156       return Op0;
20157
20158     // Replace this packed shift intrinsic with a target independent
20159     // shift dag node.
20160     SDValue Splat = DAG.getConstant(C, VT);
20161     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20162   }
20163   }
20164 }
20165
20166 /// PerformMulCombine - Optimize a single multiply with constant into two
20167 /// in order to implement it with two cheaper instructions, e.g.
20168 /// LEA + SHL, LEA + LEA.
20169 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20170                                  TargetLowering::DAGCombinerInfo &DCI) {
20171   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20172     return SDValue();
20173
20174   EVT VT = N->getValueType(0);
20175   if (VT != MVT::i64)
20176     return SDValue();
20177
20178   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20179   if (!C)
20180     return SDValue();
20181   uint64_t MulAmt = C->getZExtValue();
20182   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20183     return SDValue();
20184
20185   uint64_t MulAmt1 = 0;
20186   uint64_t MulAmt2 = 0;
20187   if ((MulAmt % 9) == 0) {
20188     MulAmt1 = 9;
20189     MulAmt2 = MulAmt / 9;
20190   } else if ((MulAmt % 5) == 0) {
20191     MulAmt1 = 5;
20192     MulAmt2 = MulAmt / 5;
20193   } else if ((MulAmt % 3) == 0) {
20194     MulAmt1 = 3;
20195     MulAmt2 = MulAmt / 3;
20196   }
20197   if (MulAmt2 &&
20198       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20199     SDLoc DL(N);
20200
20201     if (isPowerOf2_64(MulAmt2) &&
20202         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20203       // If second multiplifer is pow2, issue it first. We want the multiply by
20204       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20205       // is an add.
20206       std::swap(MulAmt1, MulAmt2);
20207
20208     SDValue NewMul;
20209     if (isPowerOf2_64(MulAmt1))
20210       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20211                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20212     else
20213       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20214                            DAG.getConstant(MulAmt1, VT));
20215
20216     if (isPowerOf2_64(MulAmt2))
20217       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20218                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20219     else
20220       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20221                            DAG.getConstant(MulAmt2, VT));
20222
20223     // Do not add new nodes to DAG combiner worklist.
20224     DCI.CombineTo(N, NewMul, false);
20225   }
20226   return SDValue();
20227 }
20228
20229 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20230   SDValue N0 = N->getOperand(0);
20231   SDValue N1 = N->getOperand(1);
20232   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20233   EVT VT = N0.getValueType();
20234
20235   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20236   // since the result of setcc_c is all zero's or all ones.
20237   if (VT.isInteger() && !VT.isVector() &&
20238       N1C && N0.getOpcode() == ISD::AND &&
20239       N0.getOperand(1).getOpcode() == ISD::Constant) {
20240     SDValue N00 = N0.getOperand(0);
20241     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20242         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20243           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20244          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20245       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20246       APInt ShAmt = N1C->getAPIntValue();
20247       Mask = Mask.shl(ShAmt);
20248       if (Mask != 0)
20249         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20250                            N00, DAG.getConstant(Mask, VT));
20251     }
20252   }
20253
20254   // Hardware support for vector shifts is sparse which makes us scalarize the
20255   // vector operations in many cases. Also, on sandybridge ADD is faster than
20256   // shl.
20257   // (shl V, 1) -> add V,V
20258   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
20259     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
20260       assert(N0.getValueType().isVector() && "Invalid vector shift type");
20261       // We shift all of the values by one. In many cases we do not have
20262       // hardware support for this operation. This is better expressed as an ADD
20263       // of two values.
20264       if (N1SplatC->getZExtValue() == 1)
20265         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20266     }
20267
20268   return SDValue();
20269 }
20270
20271 /// \brief Returns a vector of 0s if the node in input is a vector logical
20272 /// shift by a constant amount which is known to be bigger than or equal
20273 /// to the vector element size in bits.
20274 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20275                                       const X86Subtarget *Subtarget) {
20276   EVT VT = N->getValueType(0);
20277
20278   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20279       (!Subtarget->hasInt256() ||
20280        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20281     return SDValue();
20282
20283   SDValue Amt = N->getOperand(1);
20284   SDLoc DL(N);
20285   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
20286     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
20287       APInt ShiftAmt = AmtSplat->getAPIntValue();
20288       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20289
20290       // SSE2/AVX2 logical shifts always return a vector of 0s
20291       // if the shift amount is bigger than or equal to
20292       // the element size. The constant shift amount will be
20293       // encoded as a 8-bit immediate.
20294       if (ShiftAmt.trunc(8).uge(MaxAmount))
20295         return getZeroVector(VT, Subtarget, DAG, DL);
20296     }
20297
20298   return SDValue();
20299 }
20300
20301 /// PerformShiftCombine - Combine shifts.
20302 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20303                                    TargetLowering::DAGCombinerInfo &DCI,
20304                                    const X86Subtarget *Subtarget) {
20305   if (N->getOpcode() == ISD::SHL) {
20306     SDValue V = PerformSHLCombine(N, DAG);
20307     if (V.getNode()) return V;
20308   }
20309
20310   if (N->getOpcode() != ISD::SRA) {
20311     // Try to fold this logical shift into a zero vector.
20312     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20313     if (V.getNode()) return V;
20314   }
20315
20316   return SDValue();
20317 }
20318
20319 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20320 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20321 // and friends.  Likewise for OR -> CMPNEQSS.
20322 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20323                             TargetLowering::DAGCombinerInfo &DCI,
20324                             const X86Subtarget *Subtarget) {
20325   unsigned opcode;
20326
20327   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20328   // we're requiring SSE2 for both.
20329   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20330     SDValue N0 = N->getOperand(0);
20331     SDValue N1 = N->getOperand(1);
20332     SDValue CMP0 = N0->getOperand(1);
20333     SDValue CMP1 = N1->getOperand(1);
20334     SDLoc DL(N);
20335
20336     // The SETCCs should both refer to the same CMP.
20337     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20338       return SDValue();
20339
20340     SDValue CMP00 = CMP0->getOperand(0);
20341     SDValue CMP01 = CMP0->getOperand(1);
20342     EVT     VT    = CMP00.getValueType();
20343
20344     if (VT == MVT::f32 || VT == MVT::f64) {
20345       bool ExpectingFlags = false;
20346       // Check for any users that want flags:
20347       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20348            !ExpectingFlags && UI != UE; ++UI)
20349         switch (UI->getOpcode()) {
20350         default:
20351         case ISD::BR_CC:
20352         case ISD::BRCOND:
20353         case ISD::SELECT:
20354           ExpectingFlags = true;
20355           break;
20356         case ISD::CopyToReg:
20357         case ISD::SIGN_EXTEND:
20358         case ISD::ZERO_EXTEND:
20359         case ISD::ANY_EXTEND:
20360           break;
20361         }
20362
20363       if (!ExpectingFlags) {
20364         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20365         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20366
20367         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20368           X86::CondCode tmp = cc0;
20369           cc0 = cc1;
20370           cc1 = tmp;
20371         }
20372
20373         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20374             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20375           // FIXME: need symbolic constants for these magic numbers.
20376           // See X86ATTInstPrinter.cpp:printSSECC().
20377           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20378           if (Subtarget->hasAVX512()) {
20379             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20380                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20381             if (N->getValueType(0) != MVT::i1)
20382               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20383                                  FSetCC);
20384             return FSetCC;
20385           }
20386           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20387                                               CMP00.getValueType(), CMP00, CMP01,
20388                                               DAG.getConstant(x86cc, MVT::i8));
20389
20390           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20391           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20392
20393           if (is64BitFP && !Subtarget->is64Bit()) {
20394             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20395             // 64-bit integer, since that's not a legal type. Since
20396             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20397             // bits, but can do this little dance to extract the lowest 32 bits
20398             // and work with those going forward.
20399             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20400                                            OnesOrZeroesF);
20401             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20402                                            Vector64);
20403             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20404                                         Vector32, DAG.getIntPtrConstant(0));
20405             IntVT = MVT::i32;
20406           }
20407
20408           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20409           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20410                                       DAG.getConstant(1, IntVT));
20411           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20412           return OneBitOfTruth;
20413         }
20414       }
20415     }
20416   }
20417   return SDValue();
20418 }
20419
20420 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20421 /// so it can be folded inside ANDNP.
20422 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20423   EVT VT = N->getValueType(0);
20424
20425   // Match direct AllOnes for 128 and 256-bit vectors
20426   if (ISD::isBuildVectorAllOnes(N))
20427     return true;
20428
20429   // Look through a bit convert.
20430   if (N->getOpcode() == ISD::BITCAST)
20431     N = N->getOperand(0).getNode();
20432
20433   // Sometimes the operand may come from a insert_subvector building a 256-bit
20434   // allones vector
20435   if (VT.is256BitVector() &&
20436       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20437     SDValue V1 = N->getOperand(0);
20438     SDValue V2 = N->getOperand(1);
20439
20440     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20441         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20442         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20443         ISD::isBuildVectorAllOnes(V2.getNode()))
20444       return true;
20445   }
20446
20447   return false;
20448 }
20449
20450 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20451 // register. In most cases we actually compare or select YMM-sized registers
20452 // and mixing the two types creates horrible code. This method optimizes
20453 // some of the transition sequences.
20454 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20455                                  TargetLowering::DAGCombinerInfo &DCI,
20456                                  const X86Subtarget *Subtarget) {
20457   EVT VT = N->getValueType(0);
20458   if (!VT.is256BitVector())
20459     return SDValue();
20460
20461   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20462           N->getOpcode() == ISD::ZERO_EXTEND ||
20463           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20464
20465   SDValue Narrow = N->getOperand(0);
20466   EVT NarrowVT = Narrow->getValueType(0);
20467   if (!NarrowVT.is128BitVector())
20468     return SDValue();
20469
20470   if (Narrow->getOpcode() != ISD::XOR &&
20471       Narrow->getOpcode() != ISD::AND &&
20472       Narrow->getOpcode() != ISD::OR)
20473     return SDValue();
20474
20475   SDValue N0  = Narrow->getOperand(0);
20476   SDValue N1  = Narrow->getOperand(1);
20477   SDLoc DL(Narrow);
20478
20479   // The Left side has to be a trunc.
20480   if (N0.getOpcode() != ISD::TRUNCATE)
20481     return SDValue();
20482
20483   // The type of the truncated inputs.
20484   EVT WideVT = N0->getOperand(0)->getValueType(0);
20485   if (WideVT != VT)
20486     return SDValue();
20487
20488   // The right side has to be a 'trunc' or a constant vector.
20489   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20490   ConstantSDNode *RHSConstSplat = nullptr;
20491   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
20492     RHSConstSplat = RHSBV->getConstantSplatNode();
20493   if (!RHSTrunc && !RHSConstSplat)
20494     return SDValue();
20495
20496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20497
20498   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20499     return SDValue();
20500
20501   // Set N0 and N1 to hold the inputs to the new wide operation.
20502   N0 = N0->getOperand(0);
20503   if (RHSConstSplat) {
20504     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20505                      SDValue(RHSConstSplat, 0));
20506     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20507     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20508   } else if (RHSTrunc) {
20509     N1 = N1->getOperand(0);
20510   }
20511
20512   // Generate the wide operation.
20513   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20514   unsigned Opcode = N->getOpcode();
20515   switch (Opcode) {
20516   case ISD::ANY_EXTEND:
20517     return Op;
20518   case ISD::ZERO_EXTEND: {
20519     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20520     APInt Mask = APInt::getAllOnesValue(InBits);
20521     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20522     return DAG.getNode(ISD::AND, DL, VT,
20523                        Op, DAG.getConstant(Mask, VT));
20524   }
20525   case ISD::SIGN_EXTEND:
20526     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20527                        Op, DAG.getValueType(NarrowVT));
20528   default:
20529     llvm_unreachable("Unexpected opcode");
20530   }
20531 }
20532
20533 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20534                                  TargetLowering::DAGCombinerInfo &DCI,
20535                                  const X86Subtarget *Subtarget) {
20536   EVT VT = N->getValueType(0);
20537   if (DCI.isBeforeLegalizeOps())
20538     return SDValue();
20539
20540   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20541   if (R.getNode())
20542     return R;
20543
20544   // Create BEXTR instructions
20545   // BEXTR is ((X >> imm) & (2**size-1))
20546   if (VT == MVT::i32 || VT == MVT::i64) {
20547     SDValue N0 = N->getOperand(0);
20548     SDValue N1 = N->getOperand(1);
20549     SDLoc DL(N);
20550
20551     // Check for BEXTR.
20552     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20553         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20554       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20555       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20556       if (MaskNode && ShiftNode) {
20557         uint64_t Mask = MaskNode->getZExtValue();
20558         uint64_t Shift = ShiftNode->getZExtValue();
20559         if (isMask_64(Mask)) {
20560           uint64_t MaskSize = CountPopulation_64(Mask);
20561           if (Shift + MaskSize <= VT.getSizeInBits())
20562             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20563                                DAG.getConstant(Shift | (MaskSize << 8), VT));
20564         }
20565       }
20566     } // BEXTR
20567
20568     return SDValue();
20569   }
20570
20571   // Want to form ANDNP nodes:
20572   // 1) In the hopes of then easily combining them with OR and AND nodes
20573   //    to form PBLEND/PSIGN.
20574   // 2) To match ANDN packed intrinsics
20575   if (VT != MVT::v2i64 && VT != MVT::v4i64)
20576     return SDValue();
20577
20578   SDValue N0 = N->getOperand(0);
20579   SDValue N1 = N->getOperand(1);
20580   SDLoc DL(N);
20581
20582   // Check LHS for vnot
20583   if (N0.getOpcode() == ISD::XOR &&
20584       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20585       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20586     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20587
20588   // Check RHS for vnot
20589   if (N1.getOpcode() == ISD::XOR &&
20590       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20591       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20592     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20593
20594   return SDValue();
20595 }
20596
20597 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20598                                 TargetLowering::DAGCombinerInfo &DCI,
20599                                 const X86Subtarget *Subtarget) {
20600   if (DCI.isBeforeLegalizeOps())
20601     return SDValue();
20602
20603   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20604   if (R.getNode())
20605     return R;
20606
20607   SDValue N0 = N->getOperand(0);
20608   SDValue N1 = N->getOperand(1);
20609   EVT VT = N->getValueType(0);
20610
20611   // look for psign/blend
20612   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20613     if (!Subtarget->hasSSSE3() ||
20614         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20615       return SDValue();
20616
20617     // Canonicalize pandn to RHS
20618     if (N0.getOpcode() == X86ISD::ANDNP)
20619       std::swap(N0, N1);
20620     // or (and (m, y), (pandn m, x))
20621     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20622       SDValue Mask = N1.getOperand(0);
20623       SDValue X    = N1.getOperand(1);
20624       SDValue Y;
20625       if (N0.getOperand(0) == Mask)
20626         Y = N0.getOperand(1);
20627       if (N0.getOperand(1) == Mask)
20628         Y = N0.getOperand(0);
20629
20630       // Check to see if the mask appeared in both the AND and ANDNP and
20631       if (!Y.getNode())
20632         return SDValue();
20633
20634       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20635       // Look through mask bitcast.
20636       if (Mask.getOpcode() == ISD::BITCAST)
20637         Mask = Mask.getOperand(0);
20638       if (X.getOpcode() == ISD::BITCAST)
20639         X = X.getOperand(0);
20640       if (Y.getOpcode() == ISD::BITCAST)
20641         Y = Y.getOperand(0);
20642
20643       EVT MaskVT = Mask.getValueType();
20644
20645       // Validate that the Mask operand is a vector sra node.
20646       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20647       // there is no psrai.b
20648       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20649       unsigned SraAmt = ~0;
20650       if (Mask.getOpcode() == ISD::SRA) {
20651         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
20652           if (auto *AmtConst = AmtBV->getConstantSplatNode())
20653             SraAmt = AmtConst->getZExtValue();
20654       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20655         SDValue SraC = Mask.getOperand(1);
20656         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
20657       }
20658       if ((SraAmt + 1) != EltBits)
20659         return SDValue();
20660
20661       SDLoc DL(N);
20662
20663       // Now we know we at least have a plendvb with the mask val.  See if
20664       // we can form a psignb/w/d.
20665       // psign = x.type == y.type == mask.type && y = sub(0, x);
20666       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20667           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20668           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20669         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20670                "Unsupported VT for PSIGN");
20671         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20672         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20673       }
20674       // PBLENDVB only available on SSE 4.1
20675       if (!Subtarget->hasSSE41())
20676         return SDValue();
20677
20678       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20679
20680       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20681       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20682       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20683       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20684       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20685     }
20686   }
20687
20688   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20689     return SDValue();
20690
20691   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20692   MachineFunction &MF = DAG.getMachineFunction();
20693   bool OptForSize = MF.getFunction()->getAttributes().
20694     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20695
20696   // SHLD/SHRD instructions have lower register pressure, but on some
20697   // platforms they have higher latency than the equivalent
20698   // series of shifts/or that would otherwise be generated.
20699   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20700   // have higher latencies and we are not optimizing for size.
20701   if (!OptForSize && Subtarget->isSHLDSlow())
20702     return SDValue();
20703
20704   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20705     std::swap(N0, N1);
20706   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20707     return SDValue();
20708   if (!N0.hasOneUse() || !N1.hasOneUse())
20709     return SDValue();
20710
20711   SDValue ShAmt0 = N0.getOperand(1);
20712   if (ShAmt0.getValueType() != MVT::i8)
20713     return SDValue();
20714   SDValue ShAmt1 = N1.getOperand(1);
20715   if (ShAmt1.getValueType() != MVT::i8)
20716     return SDValue();
20717   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20718     ShAmt0 = ShAmt0.getOperand(0);
20719   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20720     ShAmt1 = ShAmt1.getOperand(0);
20721
20722   SDLoc DL(N);
20723   unsigned Opc = X86ISD::SHLD;
20724   SDValue Op0 = N0.getOperand(0);
20725   SDValue Op1 = N1.getOperand(0);
20726   if (ShAmt0.getOpcode() == ISD::SUB) {
20727     Opc = X86ISD::SHRD;
20728     std::swap(Op0, Op1);
20729     std::swap(ShAmt0, ShAmt1);
20730   }
20731
20732   unsigned Bits = VT.getSizeInBits();
20733   if (ShAmt1.getOpcode() == ISD::SUB) {
20734     SDValue Sum = ShAmt1.getOperand(0);
20735     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20736       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20737       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20738         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20739       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20740         return DAG.getNode(Opc, DL, VT,
20741                            Op0, Op1,
20742                            DAG.getNode(ISD::TRUNCATE, DL,
20743                                        MVT::i8, ShAmt0));
20744     }
20745   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20746     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20747     if (ShAmt0C &&
20748         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20749       return DAG.getNode(Opc, DL, VT,
20750                          N0.getOperand(0), N1.getOperand(0),
20751                          DAG.getNode(ISD::TRUNCATE, DL,
20752                                        MVT::i8, ShAmt0));
20753   }
20754
20755   return SDValue();
20756 }
20757
20758 // Generate NEG and CMOV for integer abs.
20759 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20760   EVT VT = N->getValueType(0);
20761
20762   // Since X86 does not have CMOV for 8-bit integer, we don't convert
20763   // 8-bit integer abs to NEG and CMOV.
20764   if (VT.isInteger() && VT.getSizeInBits() == 8)
20765     return SDValue();
20766
20767   SDValue N0 = N->getOperand(0);
20768   SDValue N1 = N->getOperand(1);
20769   SDLoc DL(N);
20770
20771   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20772   // and change it to SUB and CMOV.
20773   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20774       N0.getOpcode() == ISD::ADD &&
20775       N0.getOperand(1) == N1 &&
20776       N1.getOpcode() == ISD::SRA &&
20777       N1.getOperand(0) == N0.getOperand(0))
20778     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20779       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20780         // Generate SUB & CMOV.
20781         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20782                                   DAG.getConstant(0, VT), N0.getOperand(0));
20783
20784         SDValue Ops[] = { N0.getOperand(0), Neg,
20785                           DAG.getConstant(X86::COND_GE, MVT::i8),
20786                           SDValue(Neg.getNode(), 1) };
20787         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20788       }
20789   return SDValue();
20790 }
20791
20792 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20793 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20794                                  TargetLowering::DAGCombinerInfo &DCI,
20795                                  const X86Subtarget *Subtarget) {
20796   if (DCI.isBeforeLegalizeOps())
20797     return SDValue();
20798
20799   if (Subtarget->hasCMov()) {
20800     SDValue RV = performIntegerAbsCombine(N, DAG);
20801     if (RV.getNode())
20802       return RV;
20803   }
20804
20805   return SDValue();
20806 }
20807
20808 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20809 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20810                                   TargetLowering::DAGCombinerInfo &DCI,
20811                                   const X86Subtarget *Subtarget) {
20812   LoadSDNode *Ld = cast<LoadSDNode>(N);
20813   EVT RegVT = Ld->getValueType(0);
20814   EVT MemVT = Ld->getMemoryVT();
20815   SDLoc dl(Ld);
20816   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20817   unsigned RegSz = RegVT.getSizeInBits();
20818
20819   // On Sandybridge unaligned 256bit loads are inefficient.
20820   ISD::LoadExtType Ext = Ld->getExtensionType();
20821   unsigned Alignment = Ld->getAlignment();
20822   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20823   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20824       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20825     unsigned NumElems = RegVT.getVectorNumElements();
20826     if (NumElems < 2)
20827       return SDValue();
20828
20829     SDValue Ptr = Ld->getBasePtr();
20830     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20831
20832     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20833                                   NumElems/2);
20834     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20835                                 Ld->getPointerInfo(), Ld->isVolatile(),
20836                                 Ld->isNonTemporal(), Ld->isInvariant(),
20837                                 Alignment);
20838     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20839     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20840                                 Ld->getPointerInfo(), Ld->isVolatile(),
20841                                 Ld->isNonTemporal(), Ld->isInvariant(),
20842                                 std::min(16U, Alignment));
20843     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20844                              Load1.getValue(1),
20845                              Load2.getValue(1));
20846
20847     SDValue NewVec = DAG.getUNDEF(RegVT);
20848     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20849     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20850     return DCI.CombineTo(N, NewVec, TF, true);
20851   }
20852
20853   // If this is a vector EXT Load then attempt to optimize it using a
20854   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20855   // expansion is still better than scalar code.
20856   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20857   // emit a shuffle and a arithmetic shift.
20858   // TODO: It is possible to support ZExt by zeroing the undef values
20859   // during the shuffle phase or after the shuffle.
20860   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20861       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20862     assert(MemVT != RegVT && "Cannot extend to the same type");
20863     assert(MemVT.isVector() && "Must load a vector from memory");
20864
20865     unsigned NumElems = RegVT.getVectorNumElements();
20866     unsigned MemSz = MemVT.getSizeInBits();
20867     assert(RegSz > MemSz && "Register size must be greater than the mem size");
20868
20869     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20870       return SDValue();
20871
20872     // All sizes must be a power of two.
20873     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20874       return SDValue();
20875
20876     // Attempt to load the original value using scalar loads.
20877     // Find the largest scalar type that divides the total loaded size.
20878     MVT SclrLoadTy = MVT::i8;
20879     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20880          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20881       MVT Tp = (MVT::SimpleValueType)tp;
20882       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20883         SclrLoadTy = Tp;
20884       }
20885     }
20886
20887     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20888     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20889         (64 <= MemSz))
20890       SclrLoadTy = MVT::f64;
20891
20892     // Calculate the number of scalar loads that we need to perform
20893     // in order to load our vector from memory.
20894     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20895     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20896       return SDValue();
20897
20898     unsigned loadRegZize = RegSz;
20899     if (Ext == ISD::SEXTLOAD && RegSz == 256)
20900       loadRegZize /= 2;
20901
20902     // Represent our vector as a sequence of elements which are the
20903     // largest scalar that we can load.
20904     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20905       loadRegZize/SclrLoadTy.getSizeInBits());
20906
20907     // Represent the data using the same element type that is stored in
20908     // memory. In practice, we ''widen'' MemVT.
20909     EVT WideVecVT =
20910           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20911                        loadRegZize/MemVT.getScalarType().getSizeInBits());
20912
20913     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20914       "Invalid vector type");
20915
20916     // We can't shuffle using an illegal type.
20917     if (!TLI.isTypeLegal(WideVecVT))
20918       return SDValue();
20919
20920     SmallVector<SDValue, 8> Chains;
20921     SDValue Ptr = Ld->getBasePtr();
20922     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20923                                         TLI.getPointerTy());
20924     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20925
20926     for (unsigned i = 0; i < NumLoads; ++i) {
20927       // Perform a single load.
20928       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20929                                        Ptr, Ld->getPointerInfo(),
20930                                        Ld->isVolatile(), Ld->isNonTemporal(),
20931                                        Ld->isInvariant(), Ld->getAlignment());
20932       Chains.push_back(ScalarLoad.getValue(1));
20933       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20934       // another round of DAGCombining.
20935       if (i == 0)
20936         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20937       else
20938         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20939                           ScalarLoad, DAG.getIntPtrConstant(i));
20940
20941       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20942     }
20943
20944     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20945
20946     // Bitcast the loaded value to a vector of the original element type, in
20947     // the size of the target vector type.
20948     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20949     unsigned SizeRatio = RegSz/MemSz;
20950
20951     if (Ext == ISD::SEXTLOAD) {
20952       // If we have SSE4.1 we can directly emit a VSEXT node.
20953       if (Subtarget->hasSSE41()) {
20954         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20955         return DCI.CombineTo(N, Sext, TF, true);
20956       }
20957
20958       // Otherwise we'll shuffle the small elements in the high bits of the
20959       // larger type and perform an arithmetic shift. If the shift is not legal
20960       // it's better to scalarize.
20961       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20962         return SDValue();
20963
20964       // Redistribute the loaded elements into the different locations.
20965       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20966       for (unsigned i = 0; i != NumElems; ++i)
20967         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20968
20969       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20970                                            DAG.getUNDEF(WideVecVT),
20971                                            &ShuffleVec[0]);
20972
20973       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20974
20975       // Build the arithmetic shift.
20976       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20977                      MemVT.getVectorElementType().getSizeInBits();
20978       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20979                           DAG.getConstant(Amt, RegVT));
20980
20981       return DCI.CombineTo(N, Shuff, TF, true);
20982     }
20983
20984     // Redistribute the loaded elements into the different locations.
20985     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20986     for (unsigned i = 0; i != NumElems; ++i)
20987       ShuffleVec[i*SizeRatio] = i;
20988
20989     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20990                                          DAG.getUNDEF(WideVecVT),
20991                                          &ShuffleVec[0]);
20992
20993     // Bitcast to the requested type.
20994     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20995     // Replace the original load with the new sequence
20996     // and return the new chain.
20997     return DCI.CombineTo(N, Shuff, TF, true);
20998   }
20999
21000   return SDValue();
21001 }
21002
21003 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21004 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21005                                    const X86Subtarget *Subtarget) {
21006   StoreSDNode *St = cast<StoreSDNode>(N);
21007   EVT VT = St->getValue().getValueType();
21008   EVT StVT = St->getMemoryVT();
21009   SDLoc dl(St);
21010   SDValue StoredVal = St->getOperand(1);
21011   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21012
21013   // If we are saving a concatenation of two XMM registers, perform two stores.
21014   // On Sandy Bridge, 256-bit memory operations are executed by two
21015   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21016   // memory  operation.
21017   unsigned Alignment = St->getAlignment();
21018   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21019   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21020       StVT == VT && !IsAligned) {
21021     unsigned NumElems = VT.getVectorNumElements();
21022     if (NumElems < 2)
21023       return SDValue();
21024
21025     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21026     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21027
21028     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21029     SDValue Ptr0 = St->getBasePtr();
21030     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21031
21032     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21033                                 St->getPointerInfo(), St->isVolatile(),
21034                                 St->isNonTemporal(), Alignment);
21035     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21036                                 St->getPointerInfo(), St->isVolatile(),
21037                                 St->isNonTemporal(),
21038                                 std::min(16U, Alignment));
21039     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21040   }
21041
21042   // Optimize trunc store (of multiple scalars) to shuffle and store.
21043   // First, pack all of the elements in one place. Next, store to memory
21044   // in fewer chunks.
21045   if (St->isTruncatingStore() && VT.isVector()) {
21046     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21047     unsigned NumElems = VT.getVectorNumElements();
21048     assert(StVT != VT && "Cannot truncate to the same type");
21049     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21050     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21051
21052     // From, To sizes and ElemCount must be pow of two
21053     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21054     // We are going to use the original vector elt for storing.
21055     // Accumulated smaller vector elements must be a multiple of the store size.
21056     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21057
21058     unsigned SizeRatio  = FromSz / ToSz;
21059
21060     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21061
21062     // Create a type on which we perform the shuffle
21063     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21064             StVT.getScalarType(), NumElems*SizeRatio);
21065
21066     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21067
21068     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21069     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21070     for (unsigned i = 0; i != NumElems; ++i)
21071       ShuffleVec[i] = i * SizeRatio;
21072
21073     // Can't shuffle using an illegal type.
21074     if (!TLI.isTypeLegal(WideVecVT))
21075       return SDValue();
21076
21077     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21078                                          DAG.getUNDEF(WideVecVT),
21079                                          &ShuffleVec[0]);
21080     // At this point all of the data is stored at the bottom of the
21081     // register. We now need to save it to mem.
21082
21083     // Find the largest store unit
21084     MVT StoreType = MVT::i8;
21085     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21086          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21087       MVT Tp = (MVT::SimpleValueType)tp;
21088       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21089         StoreType = Tp;
21090     }
21091
21092     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21093     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21094         (64 <= NumElems * ToSz))
21095       StoreType = MVT::f64;
21096
21097     // Bitcast the original vector into a vector of store-size units
21098     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21099             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21100     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21101     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21102     SmallVector<SDValue, 8> Chains;
21103     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21104                                         TLI.getPointerTy());
21105     SDValue Ptr = St->getBasePtr();
21106
21107     // Perform one or more big stores into memory.
21108     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21109       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21110                                    StoreType, ShuffWide,
21111                                    DAG.getIntPtrConstant(i));
21112       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21113                                 St->getPointerInfo(), St->isVolatile(),
21114                                 St->isNonTemporal(), St->getAlignment());
21115       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21116       Chains.push_back(Ch);
21117     }
21118
21119     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21120   }
21121
21122   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21123   // the FP state in cases where an emms may be missing.
21124   // A preferable solution to the general problem is to figure out the right
21125   // places to insert EMMS.  This qualifies as a quick hack.
21126
21127   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21128   if (VT.getSizeInBits() != 64)
21129     return SDValue();
21130
21131   const Function *F = DAG.getMachineFunction().getFunction();
21132   bool NoImplicitFloatOps = F->getAttributes().
21133     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21134   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21135                      && Subtarget->hasSSE2();
21136   if ((VT.isVector() ||
21137        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21138       isa<LoadSDNode>(St->getValue()) &&
21139       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21140       St->getChain().hasOneUse() && !St->isVolatile()) {
21141     SDNode* LdVal = St->getValue().getNode();
21142     LoadSDNode *Ld = nullptr;
21143     int TokenFactorIndex = -1;
21144     SmallVector<SDValue, 8> Ops;
21145     SDNode* ChainVal = St->getChain().getNode();
21146     // Must be a store of a load.  We currently handle two cases:  the load
21147     // is a direct child, and it's under an intervening TokenFactor.  It is
21148     // possible to dig deeper under nested TokenFactors.
21149     if (ChainVal == LdVal)
21150       Ld = cast<LoadSDNode>(St->getChain());
21151     else if (St->getValue().hasOneUse() &&
21152              ChainVal->getOpcode() == ISD::TokenFactor) {
21153       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21154         if (ChainVal->getOperand(i).getNode() == LdVal) {
21155           TokenFactorIndex = i;
21156           Ld = cast<LoadSDNode>(St->getValue());
21157         } else
21158           Ops.push_back(ChainVal->getOperand(i));
21159       }
21160     }
21161
21162     if (!Ld || !ISD::isNormalLoad(Ld))
21163       return SDValue();
21164
21165     // If this is not the MMX case, i.e. we are just turning i64 load/store
21166     // into f64 load/store, avoid the transformation if there are multiple
21167     // uses of the loaded value.
21168     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21169       return SDValue();
21170
21171     SDLoc LdDL(Ld);
21172     SDLoc StDL(N);
21173     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21174     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21175     // pair instead.
21176     if (Subtarget->is64Bit() || F64IsLegal) {
21177       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21178       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21179                                   Ld->getPointerInfo(), Ld->isVolatile(),
21180                                   Ld->isNonTemporal(), Ld->isInvariant(),
21181                                   Ld->getAlignment());
21182       SDValue NewChain = NewLd.getValue(1);
21183       if (TokenFactorIndex != -1) {
21184         Ops.push_back(NewChain);
21185         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21186       }
21187       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21188                           St->getPointerInfo(),
21189                           St->isVolatile(), St->isNonTemporal(),
21190                           St->getAlignment());
21191     }
21192
21193     // Otherwise, lower to two pairs of 32-bit loads / stores.
21194     SDValue LoAddr = Ld->getBasePtr();
21195     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21196                                  DAG.getConstant(4, MVT::i32));
21197
21198     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21199                                Ld->getPointerInfo(),
21200                                Ld->isVolatile(), Ld->isNonTemporal(),
21201                                Ld->isInvariant(), Ld->getAlignment());
21202     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21203                                Ld->getPointerInfo().getWithOffset(4),
21204                                Ld->isVolatile(), Ld->isNonTemporal(),
21205                                Ld->isInvariant(),
21206                                MinAlign(Ld->getAlignment(), 4));
21207
21208     SDValue NewChain = LoLd.getValue(1);
21209     if (TokenFactorIndex != -1) {
21210       Ops.push_back(LoLd);
21211       Ops.push_back(HiLd);
21212       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21213     }
21214
21215     LoAddr = St->getBasePtr();
21216     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21217                          DAG.getConstant(4, MVT::i32));
21218
21219     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21220                                 St->getPointerInfo(),
21221                                 St->isVolatile(), St->isNonTemporal(),
21222                                 St->getAlignment());
21223     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21224                                 St->getPointerInfo().getWithOffset(4),
21225                                 St->isVolatile(),
21226                                 St->isNonTemporal(),
21227                                 MinAlign(St->getAlignment(), 4));
21228     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21229   }
21230   return SDValue();
21231 }
21232
21233 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21234 /// and return the operands for the horizontal operation in LHS and RHS.  A
21235 /// horizontal operation performs the binary operation on successive elements
21236 /// of its first operand, then on successive elements of its second operand,
21237 /// returning the resulting values in a vector.  For example, if
21238 ///   A = < float a0, float a1, float a2, float a3 >
21239 /// and
21240 ///   B = < float b0, float b1, float b2, float b3 >
21241 /// then the result of doing a horizontal operation on A and B is
21242 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21243 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21244 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21245 /// set to A, RHS to B, and the routine returns 'true'.
21246 /// Note that the binary operation should have the property that if one of the
21247 /// operands is UNDEF then the result is UNDEF.
21248 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21249   // Look for the following pattern: if
21250   //   A = < float a0, float a1, float a2, float a3 >
21251   //   B = < float b0, float b1, float b2, float b3 >
21252   // and
21253   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21254   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21255   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21256   // which is A horizontal-op B.
21257
21258   // At least one of the operands should be a vector shuffle.
21259   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21260       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21261     return false;
21262
21263   MVT VT = LHS.getSimpleValueType();
21264
21265   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21266          "Unsupported vector type for horizontal add/sub");
21267
21268   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21269   // operate independently on 128-bit lanes.
21270   unsigned NumElts = VT.getVectorNumElements();
21271   unsigned NumLanes = VT.getSizeInBits()/128;
21272   unsigned NumLaneElts = NumElts / NumLanes;
21273   assert((NumLaneElts % 2 == 0) &&
21274          "Vector type should have an even number of elements in each lane");
21275   unsigned HalfLaneElts = NumLaneElts/2;
21276
21277   // View LHS in the form
21278   //   LHS = VECTOR_SHUFFLE A, B, LMask
21279   // If LHS is not a shuffle then pretend it is the shuffle
21280   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21281   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21282   // type VT.
21283   SDValue A, B;
21284   SmallVector<int, 16> LMask(NumElts);
21285   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21286     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21287       A = LHS.getOperand(0);
21288     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21289       B = LHS.getOperand(1);
21290     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21291     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21292   } else {
21293     if (LHS.getOpcode() != ISD::UNDEF)
21294       A = LHS;
21295     for (unsigned i = 0; i != NumElts; ++i)
21296       LMask[i] = i;
21297   }
21298
21299   // Likewise, view RHS in the form
21300   //   RHS = VECTOR_SHUFFLE C, D, RMask
21301   SDValue C, D;
21302   SmallVector<int, 16> RMask(NumElts);
21303   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21304     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21305       C = RHS.getOperand(0);
21306     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21307       D = RHS.getOperand(1);
21308     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21309     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21310   } else {
21311     if (RHS.getOpcode() != ISD::UNDEF)
21312       C = RHS;
21313     for (unsigned i = 0; i != NumElts; ++i)
21314       RMask[i] = i;
21315   }
21316
21317   // Check that the shuffles are both shuffling the same vectors.
21318   if (!(A == C && B == D) && !(A == D && B == C))
21319     return false;
21320
21321   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21322   if (!A.getNode() && !B.getNode())
21323     return false;
21324
21325   // If A and B occur in reverse order in RHS, then "swap" them (which means
21326   // rewriting the mask).
21327   if (A != C)
21328     CommuteVectorShuffleMask(RMask, NumElts);
21329
21330   // At this point LHS and RHS are equivalent to
21331   //   LHS = VECTOR_SHUFFLE A, B, LMask
21332   //   RHS = VECTOR_SHUFFLE A, B, RMask
21333   // Check that the masks correspond to performing a horizontal operation.
21334   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21335     for (unsigned i = 0; i != NumLaneElts; ++i) {
21336       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21337
21338       // Ignore any UNDEF components.
21339       if (LIdx < 0 || RIdx < 0 ||
21340           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21341           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21342         continue;
21343
21344       // Check that successive elements are being operated on.  If not, this is
21345       // not a horizontal operation.
21346       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21347       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21348       if (!(LIdx == Index && RIdx == Index + 1) &&
21349           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21350         return false;
21351     }
21352   }
21353
21354   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21355   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21356   return true;
21357 }
21358
21359 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21360 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21361                                   const X86Subtarget *Subtarget) {
21362   EVT VT = N->getValueType(0);
21363   SDValue LHS = N->getOperand(0);
21364   SDValue RHS = N->getOperand(1);
21365
21366   // Try to synthesize horizontal adds from adds of shuffles.
21367   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21368        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21369       isHorizontalBinOp(LHS, RHS, true))
21370     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21371   return SDValue();
21372 }
21373
21374 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21375 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21376                                   const X86Subtarget *Subtarget) {
21377   EVT VT = N->getValueType(0);
21378   SDValue LHS = N->getOperand(0);
21379   SDValue RHS = N->getOperand(1);
21380
21381   // Try to synthesize horizontal subs from subs of shuffles.
21382   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21383        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21384       isHorizontalBinOp(LHS, RHS, false))
21385     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21386   return SDValue();
21387 }
21388
21389 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21390 /// X86ISD::FXOR nodes.
21391 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21392   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21393   // F[X]OR(0.0, x) -> x
21394   // F[X]OR(x, 0.0) -> x
21395   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21396     if (C->getValueAPF().isPosZero())
21397       return N->getOperand(1);
21398   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21399     if (C->getValueAPF().isPosZero())
21400       return N->getOperand(0);
21401   return SDValue();
21402 }
21403
21404 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21405 /// X86ISD::FMAX nodes.
21406 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21407   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21408
21409   // Only perform optimizations if UnsafeMath is used.
21410   if (!DAG.getTarget().Options.UnsafeFPMath)
21411     return SDValue();
21412
21413   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21414   // into FMINC and FMAXC, which are Commutative operations.
21415   unsigned NewOp = 0;
21416   switch (N->getOpcode()) {
21417     default: llvm_unreachable("unknown opcode");
21418     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21419     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21420   }
21421
21422   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21423                      N->getOperand(0), N->getOperand(1));
21424 }
21425
21426 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21427 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21428   // FAND(0.0, x) -> 0.0
21429   // FAND(x, 0.0) -> 0.0
21430   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21431     if (C->getValueAPF().isPosZero())
21432       return N->getOperand(0);
21433   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21434     if (C->getValueAPF().isPosZero())
21435       return N->getOperand(1);
21436   return SDValue();
21437 }
21438
21439 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21440 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21441   // FANDN(x, 0.0) -> 0.0
21442   // FANDN(0.0, x) -> x
21443   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21444     if (C->getValueAPF().isPosZero())
21445       return N->getOperand(1);
21446   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21447     if (C->getValueAPF().isPosZero())
21448       return N->getOperand(1);
21449   return SDValue();
21450 }
21451
21452 static SDValue PerformBTCombine(SDNode *N,
21453                                 SelectionDAG &DAG,
21454                                 TargetLowering::DAGCombinerInfo &DCI) {
21455   // BT ignores high bits in the bit index operand.
21456   SDValue Op1 = N->getOperand(1);
21457   if (Op1.hasOneUse()) {
21458     unsigned BitWidth = Op1.getValueSizeInBits();
21459     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21460     APInt KnownZero, KnownOne;
21461     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21462                                           !DCI.isBeforeLegalizeOps());
21463     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21464     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21465         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21466       DCI.CommitTargetLoweringOpt(TLO);
21467   }
21468   return SDValue();
21469 }
21470
21471 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21472   SDValue Op = N->getOperand(0);
21473   if (Op.getOpcode() == ISD::BITCAST)
21474     Op = Op.getOperand(0);
21475   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21476   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21477       VT.getVectorElementType().getSizeInBits() ==
21478       OpVT.getVectorElementType().getSizeInBits()) {
21479     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21480   }
21481   return SDValue();
21482 }
21483
21484 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21485                                                const X86Subtarget *Subtarget) {
21486   EVT VT = N->getValueType(0);
21487   if (!VT.isVector())
21488     return SDValue();
21489
21490   SDValue N0 = N->getOperand(0);
21491   SDValue N1 = N->getOperand(1);
21492   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21493   SDLoc dl(N);
21494
21495   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21496   // both SSE and AVX2 since there is no sign-extended shift right
21497   // operation on a vector with 64-bit elements.
21498   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21499   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21500   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21501       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21502     SDValue N00 = N0.getOperand(0);
21503
21504     // EXTLOAD has a better solution on AVX2,
21505     // it may be replaced with X86ISD::VSEXT node.
21506     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21507       if (!ISD::isNormalLoad(N00.getNode()))
21508         return SDValue();
21509
21510     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21511         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21512                                   N00, N1);
21513       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21514     }
21515   }
21516   return SDValue();
21517 }
21518
21519 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21520                                   TargetLowering::DAGCombinerInfo &DCI,
21521                                   const X86Subtarget *Subtarget) {
21522   if (!DCI.isBeforeLegalizeOps())
21523     return SDValue();
21524
21525   if (!Subtarget->hasFp256())
21526     return SDValue();
21527
21528   EVT VT = N->getValueType(0);
21529   if (VT.isVector() && VT.getSizeInBits() == 256) {
21530     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21531     if (R.getNode())
21532       return R;
21533   }
21534
21535   return SDValue();
21536 }
21537
21538 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21539                                  const X86Subtarget* Subtarget) {
21540   SDLoc dl(N);
21541   EVT VT = N->getValueType(0);
21542
21543   // Let legalize expand this if it isn't a legal type yet.
21544   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21545     return SDValue();
21546
21547   EVT ScalarVT = VT.getScalarType();
21548   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21549       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21550     return SDValue();
21551
21552   SDValue A = N->getOperand(0);
21553   SDValue B = N->getOperand(1);
21554   SDValue C = N->getOperand(2);
21555
21556   bool NegA = (A.getOpcode() == ISD::FNEG);
21557   bool NegB = (B.getOpcode() == ISD::FNEG);
21558   bool NegC = (C.getOpcode() == ISD::FNEG);
21559
21560   // Negative multiplication when NegA xor NegB
21561   bool NegMul = (NegA != NegB);
21562   if (NegA)
21563     A = A.getOperand(0);
21564   if (NegB)
21565     B = B.getOperand(0);
21566   if (NegC)
21567     C = C.getOperand(0);
21568
21569   unsigned Opcode;
21570   if (!NegMul)
21571     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21572   else
21573     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21574
21575   return DAG.getNode(Opcode, dl, VT, A, B, C);
21576 }
21577
21578 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21579                                   TargetLowering::DAGCombinerInfo &DCI,
21580                                   const X86Subtarget *Subtarget) {
21581   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21582   //           (and (i32 x86isd::setcc_carry), 1)
21583   // This eliminates the zext. This transformation is necessary because
21584   // ISD::SETCC is always legalized to i8.
21585   SDLoc dl(N);
21586   SDValue N0 = N->getOperand(0);
21587   EVT VT = N->getValueType(0);
21588
21589   if (N0.getOpcode() == ISD::AND &&
21590       N0.hasOneUse() &&
21591       N0.getOperand(0).hasOneUse()) {
21592     SDValue N00 = N0.getOperand(0);
21593     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21594       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21595       if (!C || C->getZExtValue() != 1)
21596         return SDValue();
21597       return DAG.getNode(ISD::AND, dl, VT,
21598                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21599                                      N00.getOperand(0), N00.getOperand(1)),
21600                          DAG.getConstant(1, VT));
21601     }
21602   }
21603
21604   if (N0.getOpcode() == ISD::TRUNCATE &&
21605       N0.hasOneUse() &&
21606       N0.getOperand(0).hasOneUse()) {
21607     SDValue N00 = N0.getOperand(0);
21608     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21609       return DAG.getNode(ISD::AND, dl, VT,
21610                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21611                                      N00.getOperand(0), N00.getOperand(1)),
21612                          DAG.getConstant(1, VT));
21613     }
21614   }
21615   if (VT.is256BitVector()) {
21616     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21617     if (R.getNode())
21618       return R;
21619   }
21620
21621   return SDValue();
21622 }
21623
21624 // Optimize x == -y --> x+y == 0
21625 //          x != -y --> x+y != 0
21626 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21627                                       const X86Subtarget* Subtarget) {
21628   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21629   SDValue LHS = N->getOperand(0);
21630   SDValue RHS = N->getOperand(1);
21631   EVT VT = N->getValueType(0);
21632   SDLoc DL(N);
21633
21634   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21635     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21636       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21637         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21638                                    LHS.getValueType(), RHS, LHS.getOperand(1));
21639         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21640                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21641       }
21642   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21643     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21644       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21645         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21646                                    RHS.getValueType(), LHS, RHS.getOperand(1));
21647         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21648                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21649       }
21650
21651   if (VT.getScalarType() == MVT::i1) {
21652     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21653       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21654     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21655     if (!IsSEXT0 && !IsVZero0)
21656       return SDValue();
21657     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21658       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21659     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21660
21661     if (!IsSEXT1 && !IsVZero1)
21662       return SDValue();
21663
21664     if (IsSEXT0 && IsVZero1) {
21665       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21666       if (CC == ISD::SETEQ)
21667         return DAG.getNOT(DL, LHS.getOperand(0), VT);
21668       return LHS.getOperand(0);
21669     }
21670     if (IsSEXT1 && IsVZero0) {
21671       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21672       if (CC == ISD::SETEQ)
21673         return DAG.getNOT(DL, RHS.getOperand(0), VT);
21674       return RHS.getOperand(0);
21675     }
21676   }
21677
21678   return SDValue();
21679 }
21680
21681 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21682                                       const X86Subtarget *Subtarget) {
21683   SDLoc dl(N);
21684   MVT VT = N->getOperand(1)->getSimpleValueType(0);
21685   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21686          "X86insertps is only defined for v4x32");
21687
21688   SDValue Ld = N->getOperand(1);
21689   if (MayFoldLoad(Ld)) {
21690     // Extract the countS bits from the immediate so we can get the proper
21691     // address when narrowing the vector load to a specific element.
21692     // When the second source op is a memory address, interps doesn't use
21693     // countS and just gets an f32 from that address.
21694     unsigned DestIndex =
21695         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21696     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21697   } else
21698     return SDValue();
21699
21700   // Create this as a scalar to vector to match the instruction pattern.
21701   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21702   // countS bits are ignored when loading from memory on insertps, which
21703   // means we don't need to explicitly set them to 0.
21704   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21705                      LoadScalarToVector, N->getOperand(2));
21706 }
21707
21708 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21709 // as "sbb reg,reg", since it can be extended without zext and produces
21710 // an all-ones bit which is more useful than 0/1 in some cases.
21711 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21712                                MVT VT) {
21713   if (VT == MVT::i8)
21714     return DAG.getNode(ISD::AND, DL, VT,
21715                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21716                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21717                        DAG.getConstant(1, VT));
21718   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21719   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21720                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21721                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21722 }
21723
21724 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21725 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21726                                    TargetLowering::DAGCombinerInfo &DCI,
21727                                    const X86Subtarget *Subtarget) {
21728   SDLoc DL(N);
21729   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21730   SDValue EFLAGS = N->getOperand(1);
21731
21732   if (CC == X86::COND_A) {
21733     // Try to convert COND_A into COND_B in an attempt to facilitate
21734     // materializing "setb reg".
21735     //
21736     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21737     // cannot take an immediate as its first operand.
21738     //
21739     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21740         EFLAGS.getValueType().isInteger() &&
21741         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21742       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21743                                    EFLAGS.getNode()->getVTList(),
21744                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21745       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21746       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21747     }
21748   }
21749
21750   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21751   // a zext and produces an all-ones bit which is more useful than 0/1 in some
21752   // cases.
21753   if (CC == X86::COND_B)
21754     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21755
21756   SDValue Flags;
21757
21758   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21759   if (Flags.getNode()) {
21760     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21761     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21762   }
21763
21764   return SDValue();
21765 }
21766
21767 // Optimize branch condition evaluation.
21768 //
21769 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21770                                     TargetLowering::DAGCombinerInfo &DCI,
21771                                     const X86Subtarget *Subtarget) {
21772   SDLoc DL(N);
21773   SDValue Chain = N->getOperand(0);
21774   SDValue Dest = N->getOperand(1);
21775   SDValue EFLAGS = N->getOperand(3);
21776   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21777
21778   SDValue Flags;
21779
21780   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21781   if (Flags.getNode()) {
21782     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21783     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21784                        Flags);
21785   }
21786
21787   return SDValue();
21788 }
21789
21790 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
21791                                                          SelectionDAG &DAG) {
21792   // Take advantage of vector comparisons producing 0 or -1 in each lane to
21793   // optimize away operation when it's from a constant.
21794   //
21795   // The general transformation is:
21796   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
21797   //       AND(VECTOR_CMP(x,y), constant2)
21798   //    constant2 = UNARYOP(constant)
21799
21800   // Early exit if this isn't a vector operation or if the operand of the
21801   // unary operation isn't a bitwise AND.
21802   EVT VT = N->getValueType(0);
21803   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
21804       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC)
21805     return SDValue();
21806
21807   // Now check that the other operand of the AND is a constant splat. We could
21808   // make the transformation for non-constant splats as well, but it's unclear
21809   // that would be a benefit as it would not eliminate any operations, just
21810   // perform one more step in scalar code before moving to the vector unit.
21811   if (BuildVectorSDNode *BV =
21812           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
21813     // Bail out if the vector isn't a constant splat.
21814     if (!BV->getConstantSplatNode())
21815       return SDValue();
21816
21817     // Everything checks out. Build up the new and improved node.
21818     SDLoc DL(N);
21819     EVT IntVT = BV->getValueType(0);
21820     // Create a new constant of the appropriate type for the transformed
21821     // DAG.
21822     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
21823     // The AND node needs bitcasts to/from an integer vector type around it.
21824     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
21825     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
21826                                  N->getOperand(0)->getOperand(0), MaskConst);
21827     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
21828     return Res;
21829   }
21830
21831   return SDValue();
21832 }
21833
21834 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21835                                         const X86TargetLowering *XTLI) {
21836   // First try to optimize away the conversion entirely when it's
21837   // conditionally from a constant. Vectors only.
21838   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
21839   if (Res != SDValue())
21840     return Res;
21841
21842   // Now move on to more general possibilities.
21843   SDValue Op0 = N->getOperand(0);
21844   EVT InVT = Op0->getValueType(0);
21845
21846   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21847   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21848     SDLoc dl(N);
21849     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21850     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21851     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21852   }
21853
21854   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21855   // a 32-bit target where SSE doesn't support i64->FP operations.
21856   if (Op0.getOpcode() == ISD::LOAD) {
21857     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21858     EVT VT = Ld->getValueType(0);
21859     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21860         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21861         !XTLI->getSubtarget()->is64Bit() &&
21862         VT == MVT::i64) {
21863       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21864                                           Ld->getChain(), Op0, DAG);
21865       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21866       return FILDChain;
21867     }
21868   }
21869   return SDValue();
21870 }
21871
21872 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21873 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21874                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21875   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21876   // the result is either zero or one (depending on the input carry bit).
21877   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21878   if (X86::isZeroNode(N->getOperand(0)) &&
21879       X86::isZeroNode(N->getOperand(1)) &&
21880       // We don't have a good way to replace an EFLAGS use, so only do this when
21881       // dead right now.
21882       SDValue(N, 1).use_empty()) {
21883     SDLoc DL(N);
21884     EVT VT = N->getValueType(0);
21885     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21886     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21887                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21888                                            DAG.getConstant(X86::COND_B,MVT::i8),
21889                                            N->getOperand(2)),
21890                                DAG.getConstant(1, VT));
21891     return DCI.CombineTo(N, Res1, CarryOut);
21892   }
21893
21894   return SDValue();
21895 }
21896
21897 // fold (add Y, (sete  X, 0)) -> adc  0, Y
21898 //      (add Y, (setne X, 0)) -> sbb -1, Y
21899 //      (sub (sete  X, 0), Y) -> sbb  0, Y
21900 //      (sub (setne X, 0), Y) -> adc -1, Y
21901 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21902   SDLoc DL(N);
21903
21904   // Look through ZExts.
21905   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21906   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21907     return SDValue();
21908
21909   SDValue SetCC = Ext.getOperand(0);
21910   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21911     return SDValue();
21912
21913   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21914   if (CC != X86::COND_E && CC != X86::COND_NE)
21915     return SDValue();
21916
21917   SDValue Cmp = SetCC.getOperand(1);
21918   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21919       !X86::isZeroNode(Cmp.getOperand(1)) ||
21920       !Cmp.getOperand(0).getValueType().isInteger())
21921     return SDValue();
21922
21923   SDValue CmpOp0 = Cmp.getOperand(0);
21924   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21925                                DAG.getConstant(1, CmpOp0.getValueType()));
21926
21927   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21928   if (CC == X86::COND_NE)
21929     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21930                        DL, OtherVal.getValueType(), OtherVal,
21931                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21932   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21933                      DL, OtherVal.getValueType(), OtherVal,
21934                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21935 }
21936
21937 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21938 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21939                                  const X86Subtarget *Subtarget) {
21940   EVT VT = N->getValueType(0);
21941   SDValue Op0 = N->getOperand(0);
21942   SDValue Op1 = N->getOperand(1);
21943
21944   // Try to synthesize horizontal adds from adds of shuffles.
21945   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21946        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21947       isHorizontalBinOp(Op0, Op1, true))
21948     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21949
21950   return OptimizeConditionalInDecrement(N, DAG);
21951 }
21952
21953 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21954                                  const X86Subtarget *Subtarget) {
21955   SDValue Op0 = N->getOperand(0);
21956   SDValue Op1 = N->getOperand(1);
21957
21958   // X86 can't encode an immediate LHS of a sub. See if we can push the
21959   // negation into a preceding instruction.
21960   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21961     // If the RHS of the sub is a XOR with one use and a constant, invert the
21962     // immediate. Then add one to the LHS of the sub so we can turn
21963     // X-Y -> X+~Y+1, saving one register.
21964     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21965         isa<ConstantSDNode>(Op1.getOperand(1))) {
21966       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21967       EVT VT = Op0.getValueType();
21968       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21969                                    Op1.getOperand(0),
21970                                    DAG.getConstant(~XorC, VT));
21971       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21972                          DAG.getConstant(C->getAPIntValue()+1, VT));
21973     }
21974   }
21975
21976   // Try to synthesize horizontal adds from adds of shuffles.
21977   EVT VT = N->getValueType(0);
21978   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21979        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21980       isHorizontalBinOp(Op0, Op1, true))
21981     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21982
21983   return OptimizeConditionalInDecrement(N, DAG);
21984 }
21985
21986 /// performVZEXTCombine - Performs build vector combines
21987 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21988                                         TargetLowering::DAGCombinerInfo &DCI,
21989                                         const X86Subtarget *Subtarget) {
21990   // (vzext (bitcast (vzext (x)) -> (vzext x)
21991   SDValue In = N->getOperand(0);
21992   while (In.getOpcode() == ISD::BITCAST)
21993     In = In.getOperand(0);
21994
21995   if (In.getOpcode() != X86ISD::VZEXT)
21996     return SDValue();
21997
21998   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21999                      In.getOperand(0));
22000 }
22001
22002 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22003                                              DAGCombinerInfo &DCI) const {
22004   SelectionDAG &DAG = DCI.DAG;
22005   switch (N->getOpcode()) {
22006   default: break;
22007   case ISD::EXTRACT_VECTOR_ELT:
22008     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22009   case ISD::VSELECT:
22010   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22011   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22012   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22013   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22014   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22015   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22016   case ISD::SHL:
22017   case ISD::SRA:
22018   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22019   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22020   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22021   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22022   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22023   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22024   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22025   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22026   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22027   case X86ISD::FXOR:
22028   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22029   case X86ISD::FMIN:
22030   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22031   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22032   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22033   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22034   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22035   case ISD::ANY_EXTEND:
22036   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22037   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22038   case ISD::SIGN_EXTEND_INREG:
22039     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22040   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22041   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22042   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22043   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22044   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22045   case X86ISD::SHUFP:       // Handle all target specific shuffles
22046   case X86ISD::PALIGNR:
22047   case X86ISD::UNPCKH:
22048   case X86ISD::UNPCKL:
22049   case X86ISD::MOVHLPS:
22050   case X86ISD::MOVLHPS:
22051   case X86ISD::PSHUFD:
22052   case X86ISD::PSHUFHW:
22053   case X86ISD::PSHUFLW:
22054   case X86ISD::MOVSS:
22055   case X86ISD::MOVSD:
22056   case X86ISD::VPERMILP:
22057   case X86ISD::VPERM2X128:
22058   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22059   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22060   case ISD::INTRINSIC_WO_CHAIN:
22061     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22062   case X86ISD::INSERTPS:
22063     return PerformINSERTPSCombine(N, DAG, Subtarget);
22064   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22065   }
22066
22067   return SDValue();
22068 }
22069
22070 /// isTypeDesirableForOp - Return true if the target has native support for
22071 /// the specified value type and it is 'desirable' to use the type for the
22072 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22073 /// instruction encodings are longer and some i16 instructions are slow.
22074 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22075   if (!isTypeLegal(VT))
22076     return false;
22077   if (VT != MVT::i16)
22078     return true;
22079
22080   switch (Opc) {
22081   default:
22082     return true;
22083   case ISD::LOAD:
22084   case ISD::SIGN_EXTEND:
22085   case ISD::ZERO_EXTEND:
22086   case ISD::ANY_EXTEND:
22087   case ISD::SHL:
22088   case ISD::SRL:
22089   case ISD::SUB:
22090   case ISD::ADD:
22091   case ISD::MUL:
22092   case ISD::AND:
22093   case ISD::OR:
22094   case ISD::XOR:
22095     return false;
22096   }
22097 }
22098
22099 /// IsDesirableToPromoteOp - This method query the target whether it is
22100 /// beneficial for dag combiner to promote the specified node. If true, it
22101 /// should return the desired promotion type by reference.
22102 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22103   EVT VT = Op.getValueType();
22104   if (VT != MVT::i16)
22105     return false;
22106
22107   bool Promote = false;
22108   bool Commute = false;
22109   switch (Op.getOpcode()) {
22110   default: break;
22111   case ISD::LOAD: {
22112     LoadSDNode *LD = cast<LoadSDNode>(Op);
22113     // If the non-extending load has a single use and it's not live out, then it
22114     // might be folded.
22115     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22116                                                      Op.hasOneUse()*/) {
22117       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22118              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22119         // The only case where we'd want to promote LOAD (rather then it being
22120         // promoted as an operand is when it's only use is liveout.
22121         if (UI->getOpcode() != ISD::CopyToReg)
22122           return false;
22123       }
22124     }
22125     Promote = true;
22126     break;
22127   }
22128   case ISD::SIGN_EXTEND:
22129   case ISD::ZERO_EXTEND:
22130   case ISD::ANY_EXTEND:
22131     Promote = true;
22132     break;
22133   case ISD::SHL:
22134   case ISD::SRL: {
22135     SDValue N0 = Op.getOperand(0);
22136     // Look out for (store (shl (load), x)).
22137     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22138       return false;
22139     Promote = true;
22140     break;
22141   }
22142   case ISD::ADD:
22143   case ISD::MUL:
22144   case ISD::AND:
22145   case ISD::OR:
22146   case ISD::XOR:
22147     Commute = true;
22148     // fallthrough
22149   case ISD::SUB: {
22150     SDValue N0 = Op.getOperand(0);
22151     SDValue N1 = Op.getOperand(1);
22152     if (!Commute && MayFoldLoad(N1))
22153       return false;
22154     // Avoid disabling potential load folding opportunities.
22155     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22156       return false;
22157     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22158       return false;
22159     Promote = true;
22160   }
22161   }
22162
22163   PVT = MVT::i32;
22164   return Promote;
22165 }
22166
22167 //===----------------------------------------------------------------------===//
22168 //                           X86 Inline Assembly Support
22169 //===----------------------------------------------------------------------===//
22170
22171 namespace {
22172   // Helper to match a string separated by whitespace.
22173   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22174     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22175
22176     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22177       StringRef piece(*args[i]);
22178       if (!s.startswith(piece)) // Check if the piece matches.
22179         return false;
22180
22181       s = s.substr(piece.size());
22182       StringRef::size_type pos = s.find_first_not_of(" \t");
22183       if (pos == 0) // We matched a prefix.
22184         return false;
22185
22186       s = s.substr(pos);
22187     }
22188
22189     return s.empty();
22190   }
22191   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22192 }
22193
22194 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22195
22196   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22197     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22198         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22199         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22200
22201       if (AsmPieces.size() == 3)
22202         return true;
22203       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22204         return true;
22205     }
22206   }
22207   return false;
22208 }
22209
22210 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22211   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22212
22213   std::string AsmStr = IA->getAsmString();
22214
22215   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22216   if (!Ty || Ty->getBitWidth() % 16 != 0)
22217     return false;
22218
22219   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22220   SmallVector<StringRef, 4> AsmPieces;
22221   SplitString(AsmStr, AsmPieces, ";\n");
22222
22223   switch (AsmPieces.size()) {
22224   default: return false;
22225   case 1:
22226     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22227     // we will turn this bswap into something that will be lowered to logical
22228     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22229     // lower so don't worry about this.
22230     // bswap $0
22231     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22232         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22233         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22234         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22235         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22236         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22237       // No need to check constraints, nothing other than the equivalent of
22238       // "=r,0" would be valid here.
22239       return IntrinsicLowering::LowerToByteSwap(CI);
22240     }
22241
22242     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22243     if (CI->getType()->isIntegerTy(16) &&
22244         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22245         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22246          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22247       AsmPieces.clear();
22248       const std::string &ConstraintsStr = IA->getConstraintString();
22249       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22250       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22251       if (clobbersFlagRegisters(AsmPieces))
22252         return IntrinsicLowering::LowerToByteSwap(CI);
22253     }
22254     break;
22255   case 3:
22256     if (CI->getType()->isIntegerTy(32) &&
22257         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22258         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22259         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22260         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22261       AsmPieces.clear();
22262       const std::string &ConstraintsStr = IA->getConstraintString();
22263       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22264       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22265       if (clobbersFlagRegisters(AsmPieces))
22266         return IntrinsicLowering::LowerToByteSwap(CI);
22267     }
22268
22269     if (CI->getType()->isIntegerTy(64)) {
22270       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22271       if (Constraints.size() >= 2 &&
22272           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22273           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22274         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22275         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22276             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22277             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22278           return IntrinsicLowering::LowerToByteSwap(CI);
22279       }
22280     }
22281     break;
22282   }
22283   return false;
22284 }
22285
22286 /// getConstraintType - Given a constraint letter, return the type of
22287 /// constraint it is for this target.
22288 X86TargetLowering::ConstraintType
22289 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22290   if (Constraint.size() == 1) {
22291     switch (Constraint[0]) {
22292     case 'R':
22293     case 'q':
22294     case 'Q':
22295     case 'f':
22296     case 't':
22297     case 'u':
22298     case 'y':
22299     case 'x':
22300     case 'Y':
22301     case 'l':
22302       return C_RegisterClass;
22303     case 'a':
22304     case 'b':
22305     case 'c':
22306     case 'd':
22307     case 'S':
22308     case 'D':
22309     case 'A':
22310       return C_Register;
22311     case 'I':
22312     case 'J':
22313     case 'K':
22314     case 'L':
22315     case 'M':
22316     case 'N':
22317     case 'G':
22318     case 'C':
22319     case 'e':
22320     case 'Z':
22321       return C_Other;
22322     default:
22323       break;
22324     }
22325   }
22326   return TargetLowering::getConstraintType(Constraint);
22327 }
22328
22329 /// Examine constraint type and operand type and determine a weight value.
22330 /// This object must already have been set up with the operand type
22331 /// and the current alternative constraint selected.
22332 TargetLowering::ConstraintWeight
22333   X86TargetLowering::getSingleConstraintMatchWeight(
22334     AsmOperandInfo &info, const char *constraint) const {
22335   ConstraintWeight weight = CW_Invalid;
22336   Value *CallOperandVal = info.CallOperandVal;
22337     // If we don't have a value, we can't do a match,
22338     // but allow it at the lowest weight.
22339   if (!CallOperandVal)
22340     return CW_Default;
22341   Type *type = CallOperandVal->getType();
22342   // Look at the constraint type.
22343   switch (*constraint) {
22344   default:
22345     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22346   case 'R':
22347   case 'q':
22348   case 'Q':
22349   case 'a':
22350   case 'b':
22351   case 'c':
22352   case 'd':
22353   case 'S':
22354   case 'D':
22355   case 'A':
22356     if (CallOperandVal->getType()->isIntegerTy())
22357       weight = CW_SpecificReg;
22358     break;
22359   case 'f':
22360   case 't':
22361   case 'u':
22362     if (type->isFloatingPointTy())
22363       weight = CW_SpecificReg;
22364     break;
22365   case 'y':
22366     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22367       weight = CW_SpecificReg;
22368     break;
22369   case 'x':
22370   case 'Y':
22371     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22372         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22373       weight = CW_Register;
22374     break;
22375   case 'I':
22376     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22377       if (C->getZExtValue() <= 31)
22378         weight = CW_Constant;
22379     }
22380     break;
22381   case 'J':
22382     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22383       if (C->getZExtValue() <= 63)
22384         weight = CW_Constant;
22385     }
22386     break;
22387   case 'K':
22388     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22389       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22390         weight = CW_Constant;
22391     }
22392     break;
22393   case 'L':
22394     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22395       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22396         weight = CW_Constant;
22397     }
22398     break;
22399   case 'M':
22400     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22401       if (C->getZExtValue() <= 3)
22402         weight = CW_Constant;
22403     }
22404     break;
22405   case 'N':
22406     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22407       if (C->getZExtValue() <= 0xff)
22408         weight = CW_Constant;
22409     }
22410     break;
22411   case 'G':
22412   case 'C':
22413     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22414       weight = CW_Constant;
22415     }
22416     break;
22417   case 'e':
22418     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22419       if ((C->getSExtValue() >= -0x80000000LL) &&
22420           (C->getSExtValue() <= 0x7fffffffLL))
22421         weight = CW_Constant;
22422     }
22423     break;
22424   case 'Z':
22425     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22426       if (C->getZExtValue() <= 0xffffffff)
22427         weight = CW_Constant;
22428     }
22429     break;
22430   }
22431   return weight;
22432 }
22433
22434 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22435 /// with another that has more specific requirements based on the type of the
22436 /// corresponding operand.
22437 const char *X86TargetLowering::
22438 LowerXConstraint(EVT ConstraintVT) const {
22439   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22440   // 'f' like normal targets.
22441   if (ConstraintVT.isFloatingPoint()) {
22442     if (Subtarget->hasSSE2())
22443       return "Y";
22444     if (Subtarget->hasSSE1())
22445       return "x";
22446   }
22447
22448   return TargetLowering::LowerXConstraint(ConstraintVT);
22449 }
22450
22451 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22452 /// vector.  If it is invalid, don't add anything to Ops.
22453 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22454                                                      std::string &Constraint,
22455                                                      std::vector<SDValue>&Ops,
22456                                                      SelectionDAG &DAG) const {
22457   SDValue Result;
22458
22459   // Only support length 1 constraints for now.
22460   if (Constraint.length() > 1) return;
22461
22462   char ConstraintLetter = Constraint[0];
22463   switch (ConstraintLetter) {
22464   default: break;
22465   case 'I':
22466     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22467       if (C->getZExtValue() <= 31) {
22468         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22469         break;
22470       }
22471     }
22472     return;
22473   case 'J':
22474     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22475       if (C->getZExtValue() <= 63) {
22476         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22477         break;
22478       }
22479     }
22480     return;
22481   case 'K':
22482     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22483       if (isInt<8>(C->getSExtValue())) {
22484         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22485         break;
22486       }
22487     }
22488     return;
22489   case 'N':
22490     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22491       if (C->getZExtValue() <= 255) {
22492         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22493         break;
22494       }
22495     }
22496     return;
22497   case 'e': {
22498     // 32-bit signed value
22499     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22500       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22501                                            C->getSExtValue())) {
22502         // Widen to 64 bits here to get it sign extended.
22503         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22504         break;
22505       }
22506     // FIXME gcc accepts some relocatable values here too, but only in certain
22507     // memory models; it's complicated.
22508     }
22509     return;
22510   }
22511   case 'Z': {
22512     // 32-bit unsigned value
22513     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22514       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22515                                            C->getZExtValue())) {
22516         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22517         break;
22518       }
22519     }
22520     // FIXME gcc accepts some relocatable values here too, but only in certain
22521     // memory models; it's complicated.
22522     return;
22523   }
22524   case 'i': {
22525     // Literal immediates are always ok.
22526     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22527       // Widen to 64 bits here to get it sign extended.
22528       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22529       break;
22530     }
22531
22532     // In any sort of PIC mode addresses need to be computed at runtime by
22533     // adding in a register or some sort of table lookup.  These can't
22534     // be used as immediates.
22535     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22536       return;
22537
22538     // If we are in non-pic codegen mode, we allow the address of a global (with
22539     // an optional displacement) to be used with 'i'.
22540     GlobalAddressSDNode *GA = nullptr;
22541     int64_t Offset = 0;
22542
22543     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22544     while (1) {
22545       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22546         Offset += GA->getOffset();
22547         break;
22548       } else if (Op.getOpcode() == ISD::ADD) {
22549         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22550           Offset += C->getZExtValue();
22551           Op = Op.getOperand(0);
22552           continue;
22553         }
22554       } else if (Op.getOpcode() == ISD::SUB) {
22555         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22556           Offset += -C->getZExtValue();
22557           Op = Op.getOperand(0);
22558           continue;
22559         }
22560       }
22561
22562       // Otherwise, this isn't something we can handle, reject it.
22563       return;
22564     }
22565
22566     const GlobalValue *GV = GA->getGlobal();
22567     // If we require an extra load to get this address, as in PIC mode, we
22568     // can't accept it.
22569     if (isGlobalStubReference(
22570             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22571       return;
22572
22573     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22574                                         GA->getValueType(0), Offset);
22575     break;
22576   }
22577   }
22578
22579   if (Result.getNode()) {
22580     Ops.push_back(Result);
22581     return;
22582   }
22583   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22584 }
22585
22586 std::pair<unsigned, const TargetRegisterClass*>
22587 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22588                                                 MVT VT) const {
22589   // First, see if this is a constraint that directly corresponds to an LLVM
22590   // register class.
22591   if (Constraint.size() == 1) {
22592     // GCC Constraint Letters
22593     switch (Constraint[0]) {
22594     default: break;
22595       // TODO: Slight differences here in allocation order and leaving
22596       // RIP in the class. Do they matter any more here than they do
22597       // in the normal allocation?
22598     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22599       if (Subtarget->is64Bit()) {
22600         if (VT == MVT::i32 || VT == MVT::f32)
22601           return std::make_pair(0U, &X86::GR32RegClass);
22602         if (VT == MVT::i16)
22603           return std::make_pair(0U, &X86::GR16RegClass);
22604         if (VT == MVT::i8 || VT == MVT::i1)
22605           return std::make_pair(0U, &X86::GR8RegClass);
22606         if (VT == MVT::i64 || VT == MVT::f64)
22607           return std::make_pair(0U, &X86::GR64RegClass);
22608         break;
22609       }
22610       // 32-bit fallthrough
22611     case 'Q':   // Q_REGS
22612       if (VT == MVT::i32 || VT == MVT::f32)
22613         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22614       if (VT == MVT::i16)
22615         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22616       if (VT == MVT::i8 || VT == MVT::i1)
22617         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22618       if (VT == MVT::i64)
22619         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22620       break;
22621     case 'r':   // GENERAL_REGS
22622     case 'l':   // INDEX_REGS
22623       if (VT == MVT::i8 || VT == MVT::i1)
22624         return std::make_pair(0U, &X86::GR8RegClass);
22625       if (VT == MVT::i16)
22626         return std::make_pair(0U, &X86::GR16RegClass);
22627       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22628         return std::make_pair(0U, &X86::GR32RegClass);
22629       return std::make_pair(0U, &X86::GR64RegClass);
22630     case 'R':   // LEGACY_REGS
22631       if (VT == MVT::i8 || VT == MVT::i1)
22632         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22633       if (VT == MVT::i16)
22634         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22635       if (VT == MVT::i32 || !Subtarget->is64Bit())
22636         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22637       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22638     case 'f':  // FP Stack registers.
22639       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22640       // value to the correct fpstack register class.
22641       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22642         return std::make_pair(0U, &X86::RFP32RegClass);
22643       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22644         return std::make_pair(0U, &X86::RFP64RegClass);
22645       return std::make_pair(0U, &X86::RFP80RegClass);
22646     case 'y':   // MMX_REGS if MMX allowed.
22647       if (!Subtarget->hasMMX()) break;
22648       return std::make_pair(0U, &X86::VR64RegClass);
22649     case 'Y':   // SSE_REGS if SSE2 allowed
22650       if (!Subtarget->hasSSE2()) break;
22651       // FALL THROUGH.
22652     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22653       if (!Subtarget->hasSSE1()) break;
22654
22655       switch (VT.SimpleTy) {
22656       default: break;
22657       // Scalar SSE types.
22658       case MVT::f32:
22659       case MVT::i32:
22660         return std::make_pair(0U, &X86::FR32RegClass);
22661       case MVT::f64:
22662       case MVT::i64:
22663         return std::make_pair(0U, &X86::FR64RegClass);
22664       // Vector types.
22665       case MVT::v16i8:
22666       case MVT::v8i16:
22667       case MVT::v4i32:
22668       case MVT::v2i64:
22669       case MVT::v4f32:
22670       case MVT::v2f64:
22671         return std::make_pair(0U, &X86::VR128RegClass);
22672       // AVX types.
22673       case MVT::v32i8:
22674       case MVT::v16i16:
22675       case MVT::v8i32:
22676       case MVT::v4i64:
22677       case MVT::v8f32:
22678       case MVT::v4f64:
22679         return std::make_pair(0U, &X86::VR256RegClass);
22680       case MVT::v8f64:
22681       case MVT::v16f32:
22682       case MVT::v16i32:
22683       case MVT::v8i64:
22684         return std::make_pair(0U, &X86::VR512RegClass);
22685       }
22686       break;
22687     }
22688   }
22689
22690   // Use the default implementation in TargetLowering to convert the register
22691   // constraint into a member of a register class.
22692   std::pair<unsigned, const TargetRegisterClass*> Res;
22693   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22694
22695   // Not found as a standard register?
22696   if (!Res.second) {
22697     // Map st(0) -> st(7) -> ST0
22698     if (Constraint.size() == 7 && Constraint[0] == '{' &&
22699         tolower(Constraint[1]) == 's' &&
22700         tolower(Constraint[2]) == 't' &&
22701         Constraint[3] == '(' &&
22702         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22703         Constraint[5] == ')' &&
22704         Constraint[6] == '}') {
22705
22706       Res.first = X86::ST0+Constraint[4]-'0';
22707       Res.second = &X86::RFP80RegClass;
22708       return Res;
22709     }
22710
22711     // GCC allows "st(0)" to be called just plain "st".
22712     if (StringRef("{st}").equals_lower(Constraint)) {
22713       Res.first = X86::ST0;
22714       Res.second = &X86::RFP80RegClass;
22715       return Res;
22716     }
22717
22718     // flags -> EFLAGS
22719     if (StringRef("{flags}").equals_lower(Constraint)) {
22720       Res.first = X86::EFLAGS;
22721       Res.second = &X86::CCRRegClass;
22722       return Res;
22723     }
22724
22725     // 'A' means EAX + EDX.
22726     if (Constraint == "A") {
22727       Res.first = X86::EAX;
22728       Res.second = &X86::GR32_ADRegClass;
22729       return Res;
22730     }
22731     return Res;
22732   }
22733
22734   // Otherwise, check to see if this is a register class of the wrong value
22735   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22736   // turn into {ax},{dx}.
22737   if (Res.second->hasType(VT))
22738     return Res;   // Correct type already, nothing to do.
22739
22740   // All of the single-register GCC register classes map their values onto
22741   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
22742   // really want an 8-bit or 32-bit register, map to the appropriate register
22743   // class and return the appropriate register.
22744   if (Res.second == &X86::GR16RegClass) {
22745     if (VT == MVT::i8 || VT == MVT::i1) {
22746       unsigned DestReg = 0;
22747       switch (Res.first) {
22748       default: break;
22749       case X86::AX: DestReg = X86::AL; break;
22750       case X86::DX: DestReg = X86::DL; break;
22751       case X86::CX: DestReg = X86::CL; break;
22752       case X86::BX: DestReg = X86::BL; break;
22753       }
22754       if (DestReg) {
22755         Res.first = DestReg;
22756         Res.second = &X86::GR8RegClass;
22757       }
22758     } else if (VT == MVT::i32 || VT == MVT::f32) {
22759       unsigned DestReg = 0;
22760       switch (Res.first) {
22761       default: break;
22762       case X86::AX: DestReg = X86::EAX; break;
22763       case X86::DX: DestReg = X86::EDX; break;
22764       case X86::CX: DestReg = X86::ECX; break;
22765       case X86::BX: DestReg = X86::EBX; break;
22766       case X86::SI: DestReg = X86::ESI; break;
22767       case X86::DI: DestReg = X86::EDI; break;
22768       case X86::BP: DestReg = X86::EBP; break;
22769       case X86::SP: DestReg = X86::ESP; break;
22770       }
22771       if (DestReg) {
22772         Res.first = DestReg;
22773         Res.second = &X86::GR32RegClass;
22774       }
22775     } else if (VT == MVT::i64 || VT == MVT::f64) {
22776       unsigned DestReg = 0;
22777       switch (Res.first) {
22778       default: break;
22779       case X86::AX: DestReg = X86::RAX; break;
22780       case X86::DX: DestReg = X86::RDX; break;
22781       case X86::CX: DestReg = X86::RCX; break;
22782       case X86::BX: DestReg = X86::RBX; break;
22783       case X86::SI: DestReg = X86::RSI; break;
22784       case X86::DI: DestReg = X86::RDI; break;
22785       case X86::BP: DestReg = X86::RBP; break;
22786       case X86::SP: DestReg = X86::RSP; break;
22787       }
22788       if (DestReg) {
22789         Res.first = DestReg;
22790         Res.second = &X86::GR64RegClass;
22791       }
22792     }
22793   } else if (Res.second == &X86::FR32RegClass ||
22794              Res.second == &X86::FR64RegClass ||
22795              Res.second == &X86::VR128RegClass ||
22796              Res.second == &X86::VR256RegClass ||
22797              Res.second == &X86::FR32XRegClass ||
22798              Res.second == &X86::FR64XRegClass ||
22799              Res.second == &X86::VR128XRegClass ||
22800              Res.second == &X86::VR256XRegClass ||
22801              Res.second == &X86::VR512RegClass) {
22802     // Handle references to XMM physical registers that got mapped into the
22803     // wrong class.  This can happen with constraints like {xmm0} where the
22804     // target independent register mapper will just pick the first match it can
22805     // find, ignoring the required type.
22806
22807     if (VT == MVT::f32 || VT == MVT::i32)
22808       Res.second = &X86::FR32RegClass;
22809     else if (VT == MVT::f64 || VT == MVT::i64)
22810       Res.second = &X86::FR64RegClass;
22811     else if (X86::VR128RegClass.hasType(VT))
22812       Res.second = &X86::VR128RegClass;
22813     else if (X86::VR256RegClass.hasType(VT))
22814       Res.second = &X86::VR256RegClass;
22815     else if (X86::VR512RegClass.hasType(VT))
22816       Res.second = &X86::VR512RegClass;
22817   }
22818
22819   return Res;
22820 }
22821
22822 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22823                                             Type *Ty) const {
22824   // Scaling factors are not free at all.
22825   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22826   // will take 2 allocations in the out of order engine instead of 1
22827   // for plain addressing mode, i.e. inst (reg1).
22828   // E.g.,
22829   // vaddps (%rsi,%drx), %ymm0, %ymm1
22830   // Requires two allocations (one for the load, one for the computation)
22831   // whereas:
22832   // vaddps (%rsi), %ymm0, %ymm1
22833   // Requires just 1 allocation, i.e., freeing allocations for other operations
22834   // and having less micro operations to execute.
22835   //
22836   // For some X86 architectures, this is even worse because for instance for
22837   // stores, the complex addressing mode forces the instruction to use the
22838   // "load" ports instead of the dedicated "store" port.
22839   // E.g., on Haswell:
22840   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22841   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
22842   if (isLegalAddressingMode(AM, Ty))
22843     // Scale represents reg2 * scale, thus account for 1
22844     // as soon as we use a second register.
22845     return AM.Scale != 0;
22846   return -1;
22847 }
22848
22849 bool X86TargetLowering::isTargetFTOL() const {
22850   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22851 }