fa804a707e36464d61807e233a1b653bb7c84d84
[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 "X86IntrinsicsInfo.h"
53 #include <bitset>
54 #include <numeric>
55 #include <cctype>
56 using namespace llvm;
57
58 #define DEBUG_TYPE "x86-isel"
59
60 STATISTIC(NumTailCalls, "Number of tail calls");
61
62 static cl::opt<bool> ExperimentalVectorWideningLegalization(
63     "x86-experimental-vector-widening-legalization", cl::init(false),
64     cl::desc("Enable an experimental vector type legalization through widening "
65              "rather than promotion."),
66     cl::Hidden);
67
68 static cl::opt<bool> ExperimentalVectorShuffleLowering(
69     "x86-experimental-vector-shuffle-lowering", cl::init(false),
70     cl::desc("Enable an experimental vector shuffle lowering code path."),
71     cl::Hidden);
72
73 // Forward declarations.
74 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
75                        SDValue V2);
76
77 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
78                                 SelectionDAG &DAG, SDLoc dl,
79                                 unsigned vectorWidth) {
80   assert((vectorWidth == 128 || vectorWidth == 256) &&
81          "Unsupported vector width");
82   EVT VT = Vec.getValueType();
83   EVT ElVT = VT.getVectorElementType();
84   unsigned Factor = VT.getSizeInBits()/vectorWidth;
85   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
86                                   VT.getVectorNumElements()/Factor);
87
88   // Extract from UNDEF is UNDEF.
89   if (Vec.getOpcode() == ISD::UNDEF)
90     return DAG.getUNDEF(ResultVT);
91
92   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
93   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
94
95   // This is the index of the first element of the vectorWidth-bit chunk
96   // we want.
97   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
98                                * ElemsPerChunk);
99
100   // If the input is a buildvector just emit a smaller one.
101   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
102     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
103                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
104                                     ElemsPerChunk));
105
106   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
107   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
108                                VecIdx);
109
110   return Result;
111
112 }
113 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
114 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
115 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
116 /// instructions or a simple subregister reference. Idx is an index in the
117 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
118 /// lowering EXTRACT_VECTOR_ELT operations easier.
119 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
120                                    SelectionDAG &DAG, SDLoc dl) {
121   assert((Vec.getValueType().is256BitVector() ||
122           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
123   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
124 }
125
126 /// Generate a DAG to grab 256-bits from a 512-bit vector.
127 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
128                                    SelectionDAG &DAG, SDLoc dl) {
129   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
130   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
131 }
132
133 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
134                                unsigned IdxVal, SelectionDAG &DAG,
135                                SDLoc dl, unsigned vectorWidth) {
136   assert((vectorWidth == 128 || vectorWidth == 256) &&
137          "Unsupported vector width");
138   // Inserting UNDEF is Result
139   if (Vec.getOpcode() == ISD::UNDEF)
140     return Result;
141   EVT VT = Vec.getValueType();
142   EVT ElVT = VT.getVectorElementType();
143   EVT ResultVT = Result.getValueType();
144
145   // Insert the relevant vectorWidth bits.
146   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
147
148   // This is the index of the first element of the vectorWidth-bit chunk
149   // we want.
150   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
151                                * ElemsPerChunk);
152
153   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
154   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
155                      VecIdx);
156 }
157 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
158 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
159 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
160 /// simple superregister reference.  Idx is an index in the 128 bits
161 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
162 /// lowering INSERT_VECTOR_ELT operations easier.
163 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
164                                   unsigned IdxVal, SelectionDAG &DAG,
165                                   SDLoc dl) {
166   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
167   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
168 }
169
170 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
171                                   unsigned IdxVal, SelectionDAG &DAG,
172                                   SDLoc dl) {
173   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
174   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
175 }
176
177 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
178 /// instructions. This is used because creating CONCAT_VECTOR nodes of
179 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
180 /// large BUILD_VECTORS.
181 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
182                                    unsigned NumElems, SelectionDAG &DAG,
183                                    SDLoc dl) {
184   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
185   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
186 }
187
188 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
189                                    unsigned NumElems, SelectionDAG &DAG,
190                                    SDLoc dl) {
191   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
192   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
193 }
194
195 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
196   if (TT.isOSBinFormatMachO()) {
197     if (TT.getArch() == Triple::x86_64)
198       return new X86_64MachoTargetObjectFile();
199     return new TargetLoweringObjectFileMachO();
200   }
201
202   if (TT.isOSLinux())
203     return new X86LinuxTargetObjectFile();
204   if (TT.isOSBinFormatELF())
205     return new TargetLoweringObjectFileELF();
206   if (TT.isKnownWindowsMSVCEnvironment())
207     return new X86WindowsTargetObjectFile();
208   if (TT.isOSBinFormatCOFF())
209     return new TargetLoweringObjectFileCOFF();
210   llvm_unreachable("unknown subtarget type");
211 }
212
213 // FIXME: This should stop caching the target machine as soon as
214 // we can remove resetOperationActions et al.
215 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
216   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
217   Subtarget = &TM.getSubtarget<X86Subtarget>();
218   X86ScalarSSEf64 = Subtarget->hasSSE2();
219   X86ScalarSSEf32 = Subtarget->hasSSE1();
220   TD = getDataLayout();
221
222   resetOperationActions();
223 }
224
225 void X86TargetLowering::resetOperationActions() {
226   const TargetMachine &TM = getTargetMachine();
227   static bool FirstTimeThrough = true;
228
229   // If none of the target options have changed, then we don't need to reset the
230   // operation actions.
231   if (!FirstTimeThrough && TO == TM.Options) return;
232
233   if (!FirstTimeThrough) {
234     // Reinitialize the actions.
235     initActions();
236     FirstTimeThrough = false;
237   }
238
239   TO = TM.Options;
240
241   // Set up the TargetLowering object.
242   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
243
244   // X86 is weird, it always uses i8 for shift amounts and setcc results.
245   setBooleanContents(ZeroOrOneBooleanContent);
246   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
247   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
248
249   // For 64-bit since we have so many registers use the ILP scheduler, for
250   // 32-bit code use the register pressure specific scheduling.
251   // For Atom, always use ILP scheduling.
252   if (Subtarget->isAtom())
253     setSchedulingPreference(Sched::ILP);
254   else if (Subtarget->is64Bit())
255     setSchedulingPreference(Sched::ILP);
256   else
257     setSchedulingPreference(Sched::RegPressure);
258   const X86RegisterInfo *RegInfo =
259       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
260   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
261
262   // Bypass expensive divides on Atom when compiling with O2
263   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
264     addBypassSlowDiv(32, 8);
265     if (Subtarget->is64Bit())
266       addBypassSlowDiv(64, 16);
267   }
268
269   if (Subtarget->isTargetKnownWindowsMSVC()) {
270     // Setup Windows compiler runtime calls.
271     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
272     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
273     setLibcallName(RTLIB::SREM_I64, "_allrem");
274     setLibcallName(RTLIB::UREM_I64, "_aullrem");
275     setLibcallName(RTLIB::MUL_I64, "_allmul");
276     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
280     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
281
282     // The _ftol2 runtime function has an unusual calling conv, which
283     // is modeled by a special pseudo-instruction.
284     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
287     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
288   }
289
290   if (Subtarget->isTargetDarwin()) {
291     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
292     setUseUnderscoreSetJmp(false);
293     setUseUnderscoreLongJmp(false);
294   } else if (Subtarget->isTargetWindowsGNU()) {
295     // MS runtime is weird: it exports _setjmp, but longjmp!
296     setUseUnderscoreSetJmp(true);
297     setUseUnderscoreLongJmp(false);
298   } else {
299     setUseUnderscoreSetJmp(true);
300     setUseUnderscoreLongJmp(true);
301   }
302
303   // Set up the register classes.
304   addRegisterClass(MVT::i8, &X86::GR8RegClass);
305   addRegisterClass(MVT::i16, &X86::GR16RegClass);
306   addRegisterClass(MVT::i32, &X86::GR32RegClass);
307   if (Subtarget->is64Bit())
308     addRegisterClass(MVT::i64, &X86::GR64RegClass);
309
310   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
311
312   // We don't accept any truncstore of integer registers.
313   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
315   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
316   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
317   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
318   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
319
320   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
321
322   // SETOEQ and SETUNE require checking two conditions.
323   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
326   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
327   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
328   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
329
330   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
331   // operation.
332   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
333   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
334   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
335
336   if (Subtarget->is64Bit()) {
337     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
338     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
339   } else if (!TM.Options.UseSoftFloat) {
340     // We have an algorithm for SSE2->double, and we turn this into a
341     // 64-bit FILD followed by conditional FADD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
343     // We have an algorithm for SSE2, and we turn this into a 64-bit
344     // FILD for other targets.
345     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
346   }
347
348   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
349   // this operation.
350   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
351   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
352
353   if (!TM.Options.UseSoftFloat) {
354     // SSE has no i16 to fp conversion, only i32
355     if (X86ScalarSSEf32) {
356       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
357       // f32 and f64 cases are Legal, f80 case is not
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     } else {
360       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
361       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
362     }
363   } else {
364     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
365     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
366   }
367
368   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
369   // are Legal, f80 is custom lowered.
370   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
371   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
372
373   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
374   // this operation.
375   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
376   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
377
378   if (X86ScalarSSEf32) {
379     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
380     // f32 and f64 cases are Legal, f80 case is not
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   } else {
383     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
384     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
385   }
386
387   // Handle FP_TO_UINT by promoting the destination to a larger signed
388   // conversion.
389   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
390   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
391   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
392
393   if (Subtarget->is64Bit()) {
394     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
395     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
396   } else if (!TM.Options.UseSoftFloat) {
397     // Since AVX is a superset of SSE3, only check for SSE here.
398     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
399       // Expand FP_TO_UINT into a select.
400       // FIXME: We would like to use a Custom expander here eventually to do
401       // the optimal thing for SSE vs. the default expansion in the legalizer.
402       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
403     else
404       // With SSE3 we can use fisttpll to convert to a signed i64; without
405       // SSE, we're stuck with a fistpll.
406       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
407   }
408
409   if (isTargetFTOL()) {
410     // Use the _ftol2 runtime function, which has a pseudo-instruction
411     // to handle its weird calling convention.
412     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
413   }
414
415   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
416   if (!X86ScalarSSEf64) {
417     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
418     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
419     if (Subtarget->is64Bit()) {
420       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
421       // Without SSE, i64->f64 goes through memory.
422       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
423     }
424   }
425
426   // Scalar integer divide and remainder are lowered to use operations that
427   // produce two results, to match the available instructions. This exposes
428   // the two-result form to trivial CSE, which is able to combine x/y and x%y
429   // into a single instruction.
430   //
431   // Scalar integer multiply-high is also lowered to use two-result
432   // operations, to match the available instructions. However, plain multiply
433   // (low) operations are left as Legal, as there are single-result
434   // instructions for this in x86. Using the two-result multiply instructions
435   // when both high and low results are needed must be arranged by dagcombine.
436   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
437     MVT VT = IntVTs[i];
438     setOperationAction(ISD::MULHS, VT, Expand);
439     setOperationAction(ISD::MULHU, VT, Expand);
440     setOperationAction(ISD::SDIV, VT, Expand);
441     setOperationAction(ISD::UDIV, VT, Expand);
442     setOperationAction(ISD::SREM, VT, Expand);
443     setOperationAction(ISD::UREM, VT, Expand);
444
445     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
446     setOperationAction(ISD::ADDC, VT, Custom);
447     setOperationAction(ISD::ADDE, VT, Custom);
448     setOperationAction(ISD::SUBC, VT, Custom);
449     setOperationAction(ISD::SUBE, VT, Custom);
450   }
451
452   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
453   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
454   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
455   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
458   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
459   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
460   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
465   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
466   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
467   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
468   if (Subtarget->is64Bit())
469     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
470   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
471   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
472   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
473   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
474   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
475   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
476   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
477   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
478
479   // Promote the i8 variants and force them on up to i32 which has a shorter
480   // encoding.
481   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
482   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
483   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
484   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
485   if (Subtarget->hasBMI()) {
486     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
487     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
488     if (Subtarget->is64Bit())
489       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
490   } else {
491     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
492     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
493     if (Subtarget->is64Bit())
494       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
495   }
496
497   if (Subtarget->hasLZCNT()) {
498     // When promoting the i8 variants, force them to i32 for a shorter
499     // encoding.
500     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
501     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
503     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
504     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
505     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
506     if (Subtarget->is64Bit())
507       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
508   } else {
509     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
512     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
513     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
514     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
515     if (Subtarget->is64Bit()) {
516       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
517       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
518     }
519   }
520
521   // Special handling for half-precision floating point conversions.
522   // If we don't have F16C support, then lower half float conversions
523   // into library calls.
524   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
525     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
526     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
527   }
528
529   // There's never any support for operations beyond MVT::f32.
530   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
531   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
532   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
533   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
534
535   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
536   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
537   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
538   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
539
540   if (Subtarget->hasPOPCNT()) {
541     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
542   } else {
543     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
544     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
545     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
546     if (Subtarget->is64Bit())
547       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
548   }
549
550   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
551
552   if (!Subtarget->hasMOVBE())
553     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
554
555   // These should be promoted to a larger select which is supported.
556   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
557   // X86 wants to expand cmov itself.
558   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
559   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
561   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
562   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
563   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
565   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
567   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
568   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
569   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
570   if (Subtarget->is64Bit()) {
571     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
572     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
573   }
574   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
575   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
576   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
577   // support continuation, user-level threading, and etc.. As a result, no
578   // other SjLj exception interfaces are implemented and please don't build
579   // your own exception handling based on them.
580   // LLVM/Clang supports zero-cost DWARF exception handling.
581   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
582   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
583
584   // Darwin ABI issue.
585   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
586   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
587   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
588   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
589   if (Subtarget->is64Bit())
590     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
591   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
592   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
593   if (Subtarget->is64Bit()) {
594     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
595     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
596     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
597     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
598     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
599   }
600   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
601   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
602   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
603   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
604   if (Subtarget->is64Bit()) {
605     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
606     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
607     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
608   }
609
610   if (Subtarget->hasSSE1())
611     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
612
613   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
614
615   // Expand certain atomics
616   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
617     MVT VT = IntVTs[i];
618     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
619     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
620     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
621   }
622
623   if (Subtarget->hasCmpxchg16b()) {
624     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
625   }
626
627   // FIXME - use subtarget debug flags
628   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
629       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
630     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
631   }
632
633   if (Subtarget->is64Bit()) {
634     setExceptionPointerRegister(X86::RAX);
635     setExceptionSelectorRegister(X86::RDX);
636   } else {
637     setExceptionPointerRegister(X86::EAX);
638     setExceptionSelectorRegister(X86::EDX);
639   }
640   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
641   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
642
643   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
644   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
645
646   setOperationAction(ISD::TRAP, MVT::Other, Legal);
647   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
648
649   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
650   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
651   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
652   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
653     // TargetInfo::X86_64ABIBuiltinVaList
654     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
655     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
656   } else {
657     // TargetInfo::CharPtrBuiltinVaList
658     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
659     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
660   }
661
662   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
663   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
664
665   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
666
667   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
668     // f32 and f64 use SSE.
669     // Set up the FP register classes.
670     addRegisterClass(MVT::f32, &X86::FR32RegClass);
671     addRegisterClass(MVT::f64, &X86::FR64RegClass);
672
673     // Use ANDPD to simulate FABS.
674     setOperationAction(ISD::FABS , MVT::f64, Custom);
675     setOperationAction(ISD::FABS , MVT::f32, Custom);
676
677     // Use XORP to simulate FNEG.
678     setOperationAction(ISD::FNEG , MVT::f64, Custom);
679     setOperationAction(ISD::FNEG , MVT::f32, Custom);
680
681     // Use ANDPD and ORPD to simulate FCOPYSIGN.
682     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
683     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
684
685     // Lower this to FGETSIGNx86 plus an AND.
686     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
687     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
688
689     // We don't support sin/cos/fmod
690     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
691     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
692     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
693     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
694     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
695     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
696
697     // Expand FP immediates into loads from the stack, except for the special
698     // cases we handle.
699     addLegalFPImmediate(APFloat(+0.0)); // xorpd
700     addLegalFPImmediate(APFloat(+0.0f)); // xorps
701   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
702     // Use SSE for f32, x87 for f64.
703     // Set up the FP register classes.
704     addRegisterClass(MVT::f32, &X86::FR32RegClass);
705     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
706
707     // Use ANDPS to simulate FABS.
708     setOperationAction(ISD::FABS , MVT::f32, Custom);
709
710     // Use XORP to simulate FNEG.
711     setOperationAction(ISD::FNEG , MVT::f32, Custom);
712
713     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
714
715     // Use ANDPS and ORPS to simulate FCOPYSIGN.
716     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
717     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
718
719     // We don't support sin/cos/fmod
720     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
721     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
722     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
723
724     // Special cases we handle for FP constants.
725     addLegalFPImmediate(APFloat(+0.0f)); // xorps
726     addLegalFPImmediate(APFloat(+0.0)); // FLD0
727     addLegalFPImmediate(APFloat(+1.0)); // FLD1
728     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
729     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
730
731     if (!TM.Options.UnsafeFPMath) {
732       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
733       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
735     }
736   } else if (!TM.Options.UseSoftFloat) {
737     // f32 and f64 in x87.
738     // Set up the FP register classes.
739     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
740     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
741
742     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
743     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
744     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
745     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
746
747     if (!TM.Options.UnsafeFPMath) {
748       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
749       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
750       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
751       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
752       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
753       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
754     }
755     addLegalFPImmediate(APFloat(+0.0)); // FLD0
756     addLegalFPImmediate(APFloat(+1.0)); // FLD1
757     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
758     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
759     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
760     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
761     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
762     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
763   }
764
765   // We don't support FMA.
766   setOperationAction(ISD::FMA, MVT::f64, Expand);
767   setOperationAction(ISD::FMA, MVT::f32, Expand);
768
769   // Long double always uses X87.
770   if (!TM.Options.UseSoftFloat) {
771     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
772     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
773     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
774     {
775       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
776       addLegalFPImmediate(TmpFlt);  // FLD0
777       TmpFlt.changeSign();
778       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
779
780       bool ignored;
781       APFloat TmpFlt2(+1.0);
782       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
783                       &ignored);
784       addLegalFPImmediate(TmpFlt2);  // FLD1
785       TmpFlt2.changeSign();
786       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
787     }
788
789     if (!TM.Options.UnsafeFPMath) {
790       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
791       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
792       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
793     }
794
795     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
796     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
797     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
798     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
799     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
800     setOperationAction(ISD::FMA, MVT::f80, Expand);
801   }
802
803   // Always use a library call for pow.
804   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
805   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
806   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
807
808   setOperationAction(ISD::FLOG, MVT::f80, Expand);
809   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
810   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
811   setOperationAction(ISD::FEXP, MVT::f80, Expand);
812   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
813
814   // First set operation action for all vector types to either promote
815   // (for widening) or expand (for scalarization). Then we will selectively
816   // turn on ones that can be effectively codegen'd.
817   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
818            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
819     MVT VT = (MVT::SimpleValueType)i;
820     setOperationAction(ISD::ADD , VT, Expand);
821     setOperationAction(ISD::SUB , VT, Expand);
822     setOperationAction(ISD::FADD, VT, Expand);
823     setOperationAction(ISD::FNEG, VT, Expand);
824     setOperationAction(ISD::FSUB, VT, Expand);
825     setOperationAction(ISD::MUL , VT, Expand);
826     setOperationAction(ISD::FMUL, VT, Expand);
827     setOperationAction(ISD::SDIV, VT, Expand);
828     setOperationAction(ISD::UDIV, VT, Expand);
829     setOperationAction(ISD::FDIV, VT, Expand);
830     setOperationAction(ISD::SREM, VT, Expand);
831     setOperationAction(ISD::UREM, VT, Expand);
832     setOperationAction(ISD::LOAD, VT, Expand);
833     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
834     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
835     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
836     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
837     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
838     setOperationAction(ISD::FABS, VT, Expand);
839     setOperationAction(ISD::FSIN, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FCOS, VT, Expand);
842     setOperationAction(ISD::FSINCOS, VT, Expand);
843     setOperationAction(ISD::FREM, VT, Expand);
844     setOperationAction(ISD::FMA,  VT, Expand);
845     setOperationAction(ISD::FPOWI, VT, Expand);
846     setOperationAction(ISD::FSQRT, VT, Expand);
847     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
848     setOperationAction(ISD::FFLOOR, VT, Expand);
849     setOperationAction(ISD::FCEIL, VT, Expand);
850     setOperationAction(ISD::FTRUNC, VT, Expand);
851     setOperationAction(ISD::FRINT, VT, Expand);
852     setOperationAction(ISD::FNEARBYINT, VT, Expand);
853     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHS, VT, Expand);
855     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
856     setOperationAction(ISD::MULHU, VT, Expand);
857     setOperationAction(ISD::SDIVREM, VT, Expand);
858     setOperationAction(ISD::UDIVREM, VT, Expand);
859     setOperationAction(ISD::FPOW, VT, Expand);
860     setOperationAction(ISD::CTPOP, VT, Expand);
861     setOperationAction(ISD::CTTZ, VT, Expand);
862     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::CTLZ, VT, Expand);
864     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
865     setOperationAction(ISD::SHL, VT, Expand);
866     setOperationAction(ISD::SRA, VT, Expand);
867     setOperationAction(ISD::SRL, VT, Expand);
868     setOperationAction(ISD::ROTL, VT, Expand);
869     setOperationAction(ISD::ROTR, VT, Expand);
870     setOperationAction(ISD::BSWAP, VT, Expand);
871     setOperationAction(ISD::SETCC, VT, Expand);
872     setOperationAction(ISD::FLOG, VT, Expand);
873     setOperationAction(ISD::FLOG2, VT, Expand);
874     setOperationAction(ISD::FLOG10, VT, Expand);
875     setOperationAction(ISD::FEXP, VT, Expand);
876     setOperationAction(ISD::FEXP2, VT, Expand);
877     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
878     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
879     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
880     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
882     setOperationAction(ISD::TRUNCATE, VT, Expand);
883     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
884     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
885     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
886     setOperationAction(ISD::VSELECT, VT, Expand);
887     setOperationAction(ISD::SELECT_CC, VT, Expand);
888     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
889              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
890       setTruncStoreAction(VT,
891                           (MVT::SimpleValueType)InnerVT, Expand);
892     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
893     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
894
895     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
896     // we have to deal with them whether we ask for Expansion or not. Setting
897     // Expand causes its own optimisation problems though, so leave them legal.
898     if (VT.getVectorElementType() == MVT::i1)
899       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
900   }
901
902   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
903   // with -msoft-float, disable use of MMX as well.
904   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
905     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
906     // No operations on x86mmx supported, everything uses intrinsics.
907   }
908
909   // MMX-sized vectors (other than x86mmx) are expected to be expanded
910   // into smaller operations.
911   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
912   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
913   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
914   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
915   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
916   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
917   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
918   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
919   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
920   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
921   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
922   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
923   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
924   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
925   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
926   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
929   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
930   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
931   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
933   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
934   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
935   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
938   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
939   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
940
941   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
942     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
943
944     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
947     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
948     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
949     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
950     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
951     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
952     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
953     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
954     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
955     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
956   }
957
958   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
959     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
960
961     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
962     // registers cannot be used even for integer operations.
963     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
964     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
965     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
966     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
967
968     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
969     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
970     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
971     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
972     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
973     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
974     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
975     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
976     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
977     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
979     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
980     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
981     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
982     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
983     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
986     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
987     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
988     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
989     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
990
991     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
993     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
994     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
995
996     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
997     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1001
1002     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1003     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1004       MVT VT = (MVT::SimpleValueType)i;
1005       // Do not attempt to custom lower non-power-of-2 vectors
1006       if (!isPowerOf2_32(VT.getVectorNumElements()))
1007         continue;
1008       // Do not attempt to custom lower non-128-bit vectors
1009       if (!VT.is128BitVector())
1010         continue;
1011       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1012       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1013       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1014     }
1015
1016     // We support custom legalizing of sext and anyext loads for specific
1017     // memory vector types which we can load as a scalar (or sequence of
1018     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1019     // loads these must work with a single scalar load.
1020     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1021     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1022     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     // Custom lower v2i64 and v2f64 selects.
1063     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1064     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1065     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1066     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1067
1068     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1069     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1070
1071     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1073     // As there is no 64-bit GPR available, we need build a special custom
1074     // sequence to convert from v2i32 to v2f32.
1075     if (!Subtarget->is64Bit())
1076       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1077
1078     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1079     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1080
1081     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1082
1083     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1084     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1086   }
1087
1088   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1089     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1090     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1091     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1094     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1095     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1096     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1099
1100     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1101     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1102     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1105     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1106     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1107     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1110
1111     // FIXME: Do we need to handle scalar-to-vector here?
1112     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1113
1114     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1115     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1119     // There is no BLENDI for byte vectors. We don't need to custom lower
1120     // some vselects for now.
1121     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1122
1123     // SSE41 brings specific instructions for doing vector sign extend even in
1124     // cases where we don't have SRA.
1125     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1128
1129     // i8 and i16 vectors are custom because the source register and source
1130     // source memory operand types are not the same width.  f32 vectors are
1131     // custom since the immediate controlling the insert encodes additional
1132     // information.
1133     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1137
1138     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1142
1143     // FIXME: these should be Legal, but that's only for the case where
1144     // the index is constant.  For now custom expand to deal with that.
1145     if (Subtarget->is64Bit()) {
1146       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1147       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1148     }
1149   }
1150
1151   if (Subtarget->hasSSE2()) {
1152     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1153     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1154
1155     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1156     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1157
1158     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1159     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1160
1161     // In the customized shift lowering, the legal cases in AVX2 will be
1162     // recognized.
1163     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1164     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1165
1166     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1167     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1168
1169     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1170   }
1171
1172   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1173     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1174     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1175     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1179
1180     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1181     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1183
1184     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1185     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1189     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1190     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1195     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1196
1197     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1198     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1202     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1203     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1208     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1209
1210     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1211     // even though v8i16 is a legal type.
1212     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1213     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1215
1216     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1218     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1219
1220     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1222
1223     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1224
1225     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1226     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1227
1228     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1229     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1230
1231     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1232     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1233
1234     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1235     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1238
1239     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1240     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1242
1243     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1244     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1247
1248     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1251     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1254     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1257     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1260
1261     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1262       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1263       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1268     }
1269
1270     if (Subtarget->hasInt256()) {
1271       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1272       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1275
1276       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1277       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1280
1281       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1282       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1283       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1284       // Don't lower v32i8 because there is no 128-bit byte mul
1285
1286       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1287       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1289       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1290
1291       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1292       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1293     } else {
1294       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1295       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1298
1299       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1300       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1303
1304       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1305       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1307       // Don't lower v32i8 because there is no 128-bit byte mul
1308     }
1309
1310     // In the customized shift lowering, the legal cases in AVX2 will be
1311     // recognized.
1312     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1313     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1314
1315     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1316     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1317
1318     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1319
1320     // Custom lower several nodes for 256-bit types.
1321     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1322              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1323       MVT VT = (MVT::SimpleValueType)i;
1324
1325       // Extract subvector is special because the value type
1326       // (result) is 128-bit but the source is 256-bit wide.
1327       if (VT.is128BitVector())
1328         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1329
1330       // Do not attempt to custom lower other non-256-bit vectors
1331       if (!VT.is256BitVector())
1332         continue;
1333
1334       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1335       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1336       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1337       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1338       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1339       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1340       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1341     }
1342
1343     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1344     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1345       MVT VT = (MVT::SimpleValueType)i;
1346
1347       // Do not attempt to promote non-256-bit vectors
1348       if (!VT.is256BitVector())
1349         continue;
1350
1351       setOperationAction(ISD::AND,    VT, Promote);
1352       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1353       setOperationAction(ISD::OR,     VT, Promote);
1354       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1355       setOperationAction(ISD::XOR,    VT, Promote);
1356       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1357       setOperationAction(ISD::LOAD,   VT, Promote);
1358       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1359       setOperationAction(ISD::SELECT, VT, Promote);
1360       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1361     }
1362   }
1363
1364   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1365     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1366     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1369
1370     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1371     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1372     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1373
1374     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1375     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1376     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1377     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1378     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1379     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1380     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1385
1386     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1387     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1391     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1392
1393     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1394     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1398     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1399     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1400     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1401
1402     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1403     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1405     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1406     if (Subtarget->is64Bit()) {
1407       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1408       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1410       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1411     }
1412     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1413     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1416     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1417     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1420     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1421     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1422
1423     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1424     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1429     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1431     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1436
1437     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1443
1444     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1445     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1446
1447     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1448
1449     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1451     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1453     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1455     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1458
1459     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1461
1462     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1463     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1464
1465     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1468     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1469
1470     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1471     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1472
1473     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1474     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1475
1476     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1477     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1478     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1480     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1481     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1482
1483     if (Subtarget->hasCDI()) {
1484       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1485       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1486     }
1487
1488     // Custom lower several nodes.
1489     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1490              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1491       MVT VT = (MVT::SimpleValueType)i;
1492
1493       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1494       // Extract subvector is special because the value type
1495       // (result) is 256/128-bit but the source is 512-bit wide.
1496       if (VT.is128BitVector() || VT.is256BitVector())
1497         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1498
1499       if (VT.getVectorElementType() == MVT::i1)
1500         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1501
1502       // Do not attempt to custom lower other non-512-bit vectors
1503       if (!VT.is512BitVector())
1504         continue;
1505
1506       if ( EltSize >= 32) {
1507         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1508         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1509         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1510         setOperationAction(ISD::VSELECT,             VT, Legal);
1511         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1512         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1513         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1514       }
1515     }
1516     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1517       MVT VT = (MVT::SimpleValueType)i;
1518
1519       // Do not attempt to promote non-256-bit vectors
1520       if (!VT.is512BitVector())
1521         continue;
1522
1523       setOperationAction(ISD::SELECT, VT, Promote);
1524       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1525     }
1526   }// has  AVX-512
1527
1528   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1529     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1530     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1531
1532     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1533     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1534
1535     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1536     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1537     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1538     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1539
1540     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1541       const MVT VT = (MVT::SimpleValueType)i;
1542
1543       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1544
1545       // Do not attempt to promote non-256-bit vectors
1546       if (!VT.is512BitVector())
1547         continue;
1548
1549       if ( EltSize < 32) {
1550         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1551         setOperationAction(ISD::VSELECT,             VT, Legal);
1552       }
1553     }
1554   }
1555
1556   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1557     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1558     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1559
1560     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1561     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1562   }
1563
1564   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1565   // of this type with custom code.
1566   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1567            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1568     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1569                        Custom);
1570   }
1571
1572   // We want to custom lower some of our intrinsics.
1573   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1574   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1575   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1576   if (!Subtarget->is64Bit())
1577     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1578
1579   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1580   // handle type legalization for these operations here.
1581   //
1582   // FIXME: We really should do custom legalization for addition and
1583   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1584   // than generic legalization for 64-bit multiplication-with-overflow, though.
1585   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1586     // Add/Sub/Mul with overflow operations are custom lowered.
1587     MVT VT = IntVTs[i];
1588     setOperationAction(ISD::SADDO, VT, Custom);
1589     setOperationAction(ISD::UADDO, VT, Custom);
1590     setOperationAction(ISD::SSUBO, VT, Custom);
1591     setOperationAction(ISD::USUBO, VT, Custom);
1592     setOperationAction(ISD::SMULO, VT, Custom);
1593     setOperationAction(ISD::UMULO, VT, Custom);
1594   }
1595
1596   // There are no 8-bit 3-address imul/mul instructions
1597   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1598   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1599
1600   if (!Subtarget->is64Bit()) {
1601     // These libcalls are not available in 32-bit.
1602     setLibcallName(RTLIB::SHL_I128, nullptr);
1603     setLibcallName(RTLIB::SRL_I128, nullptr);
1604     setLibcallName(RTLIB::SRA_I128, nullptr);
1605   }
1606
1607   // Combine sin / cos into one node or libcall if possible.
1608   if (Subtarget->hasSinCos()) {
1609     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1610     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1611     if (Subtarget->isTargetDarwin()) {
1612       // For MacOSX, we don't want to the normal expansion of a libcall to
1613       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1614       // traffic.
1615       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1616       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1617     }
1618   }
1619
1620   if (Subtarget->isTargetWin64()) {
1621     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1622     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1623     setOperationAction(ISD::SREM, MVT::i128, Custom);
1624     setOperationAction(ISD::UREM, MVT::i128, Custom);
1625     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1626     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1627   }
1628
1629   // We have target-specific dag combine patterns for the following nodes:
1630   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1631   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1632   setTargetDAGCombine(ISD::VSELECT);
1633   setTargetDAGCombine(ISD::SELECT);
1634   setTargetDAGCombine(ISD::SHL);
1635   setTargetDAGCombine(ISD::SRA);
1636   setTargetDAGCombine(ISD::SRL);
1637   setTargetDAGCombine(ISD::OR);
1638   setTargetDAGCombine(ISD::AND);
1639   setTargetDAGCombine(ISD::ADD);
1640   setTargetDAGCombine(ISD::FADD);
1641   setTargetDAGCombine(ISD::FSUB);
1642   setTargetDAGCombine(ISD::FMA);
1643   setTargetDAGCombine(ISD::SUB);
1644   setTargetDAGCombine(ISD::LOAD);
1645   setTargetDAGCombine(ISD::STORE);
1646   setTargetDAGCombine(ISD::ZERO_EXTEND);
1647   setTargetDAGCombine(ISD::ANY_EXTEND);
1648   setTargetDAGCombine(ISD::SIGN_EXTEND);
1649   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1650   setTargetDAGCombine(ISD::TRUNCATE);
1651   setTargetDAGCombine(ISD::SINT_TO_FP);
1652   setTargetDAGCombine(ISD::SETCC);
1653   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1654   setTargetDAGCombine(ISD::BUILD_VECTOR);
1655   if (Subtarget->is64Bit())
1656     setTargetDAGCombine(ISD::MUL);
1657   setTargetDAGCombine(ISD::XOR);
1658
1659   computeRegisterProperties();
1660
1661   // On Darwin, -Os means optimize for size without hurting performance,
1662   // do not reduce the limit.
1663   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1664   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1665   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1666   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1667   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1668   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1669   setPrefLoopAlignment(4); // 2^4 bytes.
1670
1671   // Predictable cmov don't hurt on atom because it's in-order.
1672   PredictableSelectIsExpensive = !Subtarget->isAtom();
1673
1674   setPrefFunctionAlignment(4); // 2^4 bytes.
1675
1676   verifyIntrinsicTables();
1677 }
1678
1679 // This has so far only been implemented for 64-bit MachO.
1680 bool X86TargetLowering::useLoadStackGuardNode() const {
1681   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1682          Subtarget->is64Bit();
1683 }
1684
1685 TargetLoweringBase::LegalizeTypeAction
1686 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1687   if (ExperimentalVectorWideningLegalization &&
1688       VT.getVectorNumElements() != 1 &&
1689       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1690     return TypeWidenVector;
1691
1692   return TargetLoweringBase::getPreferredVectorAction(VT);
1693 }
1694
1695 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1696   if (!VT.isVector())
1697     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1698
1699   const unsigned NumElts = VT.getVectorNumElements();
1700   const EVT EltVT = VT.getVectorElementType();
1701   if (VT.is512BitVector()) {
1702     if (Subtarget->hasAVX512())
1703       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1704           EltVT == MVT::f32 || EltVT == MVT::f64)
1705         switch(NumElts) {
1706         case  8: return MVT::v8i1;
1707         case 16: return MVT::v16i1;
1708       }
1709     if (Subtarget->hasBWI())
1710       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1711         switch(NumElts) {
1712         case 32: return MVT::v32i1;
1713         case 64: return MVT::v64i1;
1714       }
1715   }
1716
1717   if (VT.is256BitVector() || VT.is128BitVector()) {
1718     if (Subtarget->hasVLX())
1719       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1720           EltVT == MVT::f32 || EltVT == MVT::f64)
1721         switch(NumElts) {
1722         case 2: return MVT::v2i1;
1723         case 4: return MVT::v4i1;
1724         case 8: return MVT::v8i1;
1725       }
1726     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1727       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1728         switch(NumElts) {
1729         case  8: return MVT::v8i1;
1730         case 16: return MVT::v16i1;
1731         case 32: return MVT::v32i1;
1732       }
1733   }
1734
1735   return VT.changeVectorElementTypeToInteger();
1736 }
1737
1738 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1739 /// the desired ByVal argument alignment.
1740 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1741   if (MaxAlign == 16)
1742     return;
1743   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1744     if (VTy->getBitWidth() == 128)
1745       MaxAlign = 16;
1746   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1747     unsigned EltAlign = 0;
1748     getMaxByValAlign(ATy->getElementType(), EltAlign);
1749     if (EltAlign > MaxAlign)
1750       MaxAlign = EltAlign;
1751   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1752     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1753       unsigned EltAlign = 0;
1754       getMaxByValAlign(STy->getElementType(i), EltAlign);
1755       if (EltAlign > MaxAlign)
1756         MaxAlign = EltAlign;
1757       if (MaxAlign == 16)
1758         break;
1759     }
1760   }
1761 }
1762
1763 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1764 /// function arguments in the caller parameter area. For X86, aggregates
1765 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1766 /// are at 4-byte boundaries.
1767 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1768   if (Subtarget->is64Bit()) {
1769     // Max of 8 and alignment of type.
1770     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1771     if (TyAlign > 8)
1772       return TyAlign;
1773     return 8;
1774   }
1775
1776   unsigned Align = 4;
1777   if (Subtarget->hasSSE1())
1778     getMaxByValAlign(Ty, Align);
1779   return Align;
1780 }
1781
1782 /// getOptimalMemOpType - Returns the target specific optimal type for load
1783 /// and store operations as a result of memset, memcpy, and memmove
1784 /// lowering. If DstAlign is zero that means it's safe to destination
1785 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1786 /// means there isn't a need to check it against alignment requirement,
1787 /// probably because the source does not need to be loaded. If 'IsMemset' is
1788 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1789 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1790 /// source is constant so it does not need to be loaded.
1791 /// It returns EVT::Other if the type should be determined using generic
1792 /// target-independent logic.
1793 EVT
1794 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1795                                        unsigned DstAlign, unsigned SrcAlign,
1796                                        bool IsMemset, bool ZeroMemset,
1797                                        bool MemcpyStrSrc,
1798                                        MachineFunction &MF) const {
1799   const Function *F = MF.getFunction();
1800   if ((!IsMemset || ZeroMemset) &&
1801       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1802                                        Attribute::NoImplicitFloat)) {
1803     if (Size >= 16 &&
1804         (Subtarget->isUnalignedMemAccessFast() ||
1805          ((DstAlign == 0 || DstAlign >= 16) &&
1806           (SrcAlign == 0 || SrcAlign >= 16)))) {
1807       if (Size >= 32) {
1808         if (Subtarget->hasInt256())
1809           return MVT::v8i32;
1810         if (Subtarget->hasFp256())
1811           return MVT::v8f32;
1812       }
1813       if (Subtarget->hasSSE2())
1814         return MVT::v4i32;
1815       if (Subtarget->hasSSE1())
1816         return MVT::v4f32;
1817     } else if (!MemcpyStrSrc && Size >= 8 &&
1818                !Subtarget->is64Bit() &&
1819                Subtarget->hasSSE2()) {
1820       // Do not use f64 to lower memcpy if source is string constant. It's
1821       // better to use i32 to avoid the loads.
1822       return MVT::f64;
1823     }
1824   }
1825   if (Subtarget->is64Bit() && Size >= 8)
1826     return MVT::i64;
1827   return MVT::i32;
1828 }
1829
1830 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1831   if (VT == MVT::f32)
1832     return X86ScalarSSEf32;
1833   else if (VT == MVT::f64)
1834     return X86ScalarSSEf64;
1835   return true;
1836 }
1837
1838 bool
1839 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1840                                                   unsigned,
1841                                                   unsigned,
1842                                                   bool *Fast) const {
1843   if (Fast)
1844     *Fast = Subtarget->isUnalignedMemAccessFast();
1845   return true;
1846 }
1847
1848 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1849 /// current function.  The returned value is a member of the
1850 /// MachineJumpTableInfo::JTEntryKind enum.
1851 unsigned X86TargetLowering::getJumpTableEncoding() const {
1852   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1853   // symbol.
1854   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1855       Subtarget->isPICStyleGOT())
1856     return MachineJumpTableInfo::EK_Custom32;
1857
1858   // Otherwise, use the normal jump table encoding heuristics.
1859   return TargetLowering::getJumpTableEncoding();
1860 }
1861
1862 const MCExpr *
1863 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1864                                              const MachineBasicBlock *MBB,
1865                                              unsigned uid,MCContext &Ctx) const{
1866   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1867          Subtarget->isPICStyleGOT());
1868   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1869   // entries.
1870   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1871                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1872 }
1873
1874 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1875 /// jumptable.
1876 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1877                                                     SelectionDAG &DAG) const {
1878   if (!Subtarget->is64Bit())
1879     // This doesn't have SDLoc associated with it, but is not really the
1880     // same as a Register.
1881     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1882   return Table;
1883 }
1884
1885 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1886 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1887 /// MCExpr.
1888 const MCExpr *X86TargetLowering::
1889 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1890                              MCContext &Ctx) const {
1891   // X86-64 uses RIP relative addressing based on the jump table label.
1892   if (Subtarget->isPICStyleRIPRel())
1893     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1894
1895   // Otherwise, the reference is relative to the PIC base.
1896   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1897 }
1898
1899 // FIXME: Why this routine is here? Move to RegInfo!
1900 std::pair<const TargetRegisterClass*, uint8_t>
1901 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1902   const TargetRegisterClass *RRC = nullptr;
1903   uint8_t Cost = 1;
1904   switch (VT.SimpleTy) {
1905   default:
1906     return TargetLowering::findRepresentativeClass(VT);
1907   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1908     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1909     break;
1910   case MVT::x86mmx:
1911     RRC = &X86::VR64RegClass;
1912     break;
1913   case MVT::f32: case MVT::f64:
1914   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1915   case MVT::v4f32: case MVT::v2f64:
1916   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1917   case MVT::v4f64:
1918     RRC = &X86::VR128RegClass;
1919     break;
1920   }
1921   return std::make_pair(RRC, Cost);
1922 }
1923
1924 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1925                                                unsigned &Offset) const {
1926   if (!Subtarget->isTargetLinux())
1927     return false;
1928
1929   if (Subtarget->is64Bit()) {
1930     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1931     Offset = 0x28;
1932     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1933       AddressSpace = 256;
1934     else
1935       AddressSpace = 257;
1936   } else {
1937     // %gs:0x14 on i386
1938     Offset = 0x14;
1939     AddressSpace = 256;
1940   }
1941   return true;
1942 }
1943
1944 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1945                                             unsigned DestAS) const {
1946   assert(SrcAS != DestAS && "Expected different address spaces!");
1947
1948   return SrcAS < 256 && DestAS < 256;
1949 }
1950
1951 //===----------------------------------------------------------------------===//
1952 //               Return Value Calling Convention Implementation
1953 //===----------------------------------------------------------------------===//
1954
1955 #include "X86GenCallingConv.inc"
1956
1957 bool
1958 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1959                                   MachineFunction &MF, bool isVarArg,
1960                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1961                         LLVMContext &Context) const {
1962   SmallVector<CCValAssign, 16> RVLocs;
1963   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1964   return CCInfo.CheckReturn(Outs, RetCC_X86);
1965 }
1966
1967 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1968   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1969   return ScratchRegs;
1970 }
1971
1972 SDValue
1973 X86TargetLowering::LowerReturn(SDValue Chain,
1974                                CallingConv::ID CallConv, bool isVarArg,
1975                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1976                                const SmallVectorImpl<SDValue> &OutVals,
1977                                SDLoc dl, SelectionDAG &DAG) const {
1978   MachineFunction &MF = DAG.getMachineFunction();
1979   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1980
1981   SmallVector<CCValAssign, 16> RVLocs;
1982   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1983   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1984
1985   SDValue Flag;
1986   SmallVector<SDValue, 6> RetOps;
1987   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1988   // Operand #1 = Bytes To Pop
1989   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1990                    MVT::i16));
1991
1992   // Copy the result values into the output registers.
1993   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1994     CCValAssign &VA = RVLocs[i];
1995     assert(VA.isRegLoc() && "Can only return in registers!");
1996     SDValue ValToCopy = OutVals[i];
1997     EVT ValVT = ValToCopy.getValueType();
1998
1999     // Promote values to the appropriate types
2000     if (VA.getLocInfo() == CCValAssign::SExt)
2001       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2002     else if (VA.getLocInfo() == CCValAssign::ZExt)
2003       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2004     else if (VA.getLocInfo() == CCValAssign::AExt)
2005       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2006     else if (VA.getLocInfo() == CCValAssign::BCvt)
2007       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2008
2009     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2010            "Unexpected FP-extend for return value.");  
2011
2012     // If this is x86-64, and we disabled SSE, we can't return FP values,
2013     // or SSE or MMX vectors.
2014     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2015          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2016           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2017       report_fatal_error("SSE register return with SSE disabled");
2018     }
2019     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2020     // llvm-gcc has never done it right and no one has noticed, so this
2021     // should be OK for now.
2022     if (ValVT == MVT::f64 &&
2023         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2024       report_fatal_error("SSE2 register return with SSE2 disabled");
2025
2026     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2027     // the RET instruction and handled by the FP Stackifier.
2028     if (VA.getLocReg() == X86::FP0 ||
2029         VA.getLocReg() == X86::FP1) {
2030       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2031       // change the value to the FP stack register class.
2032       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2033         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2034       RetOps.push_back(ValToCopy);
2035       // Don't emit a copytoreg.
2036       continue;
2037     }
2038
2039     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2040     // which is returned in RAX / RDX.
2041     if (Subtarget->is64Bit()) {
2042       if (ValVT == MVT::x86mmx) {
2043         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2044           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2045           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2046                                   ValToCopy);
2047           // If we don't have SSE2 available, convert to v4f32 so the generated
2048           // register is legal.
2049           if (!Subtarget->hasSSE2())
2050             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2051         }
2052       }
2053     }
2054
2055     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2056     Flag = Chain.getValue(1);
2057     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2058   }
2059
2060   // The x86-64 ABIs require that for returning structs by value we copy
2061   // the sret argument into %rax/%eax (depending on ABI) for the return.
2062   // Win32 requires us to put the sret argument to %eax as well.
2063   // We saved the argument into a virtual register in the entry block,
2064   // so now we copy the value out and into %rax/%eax.
2065   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2066       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2067     MachineFunction &MF = DAG.getMachineFunction();
2068     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2069     unsigned Reg = FuncInfo->getSRetReturnReg();
2070     assert(Reg &&
2071            "SRetReturnReg should have been set in LowerFormalArguments().");
2072     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2073
2074     unsigned RetValReg
2075         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2076           X86::RAX : X86::EAX;
2077     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2078     Flag = Chain.getValue(1);
2079
2080     // RAX/EAX now acts like a return value.
2081     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2082   }
2083
2084   RetOps[0] = Chain;  // Update chain.
2085
2086   // Add the flag if we have it.
2087   if (Flag.getNode())
2088     RetOps.push_back(Flag);
2089
2090   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2091 }
2092
2093 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2094   if (N->getNumValues() != 1)
2095     return false;
2096   if (!N->hasNUsesOfValue(1, 0))
2097     return false;
2098
2099   SDValue TCChain = Chain;
2100   SDNode *Copy = *N->use_begin();
2101   if (Copy->getOpcode() == ISD::CopyToReg) {
2102     // If the copy has a glue operand, we conservatively assume it isn't safe to
2103     // perform a tail call.
2104     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2105       return false;
2106     TCChain = Copy->getOperand(0);
2107   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2108     return false;
2109
2110   bool HasRet = false;
2111   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2112        UI != UE; ++UI) {
2113     if (UI->getOpcode() != X86ISD::RET_FLAG)
2114       return false;
2115     // If we are returning more than one value, we can definitely
2116     // not make a tail call see PR19530
2117     if (UI->getNumOperands() > 4)
2118       return false;
2119     if (UI->getNumOperands() == 4 &&
2120         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2121       return false;
2122     HasRet = true;
2123   }
2124
2125   if (!HasRet)
2126     return false;
2127
2128   Chain = TCChain;
2129   return true;
2130 }
2131
2132 EVT
2133 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2134                                             ISD::NodeType ExtendKind) const {
2135   MVT ReturnMVT;
2136   // TODO: Is this also valid on 32-bit?
2137   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2138     ReturnMVT = MVT::i8;
2139   else
2140     ReturnMVT = MVT::i32;
2141
2142   EVT MinVT = getRegisterType(Context, ReturnMVT);
2143   return VT.bitsLT(MinVT) ? MinVT : VT;
2144 }
2145
2146 /// LowerCallResult - Lower the result values of a call into the
2147 /// appropriate copies out of appropriate physical registers.
2148 ///
2149 SDValue
2150 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2151                                    CallingConv::ID CallConv, bool isVarArg,
2152                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2153                                    SDLoc dl, SelectionDAG &DAG,
2154                                    SmallVectorImpl<SDValue> &InVals) const {
2155
2156   // Assign locations to each value returned by this call.
2157   SmallVector<CCValAssign, 16> RVLocs;
2158   bool Is64Bit = Subtarget->is64Bit();
2159   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2160                  *DAG.getContext());
2161   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2162
2163   // Copy all of the result registers out of their specified physreg.
2164   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2165     CCValAssign &VA = RVLocs[i];
2166     EVT CopyVT = VA.getValVT();
2167
2168     // If this is x86-64, and we disabled SSE, we can't return FP values
2169     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2170         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2171       report_fatal_error("SSE register return with SSE disabled");
2172     }
2173
2174     // If we prefer to use the value in xmm registers, copy it out as f80 and
2175     // use a truncate to move it from fp stack reg to xmm reg.
2176     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2177         isScalarFPTypeInSSEReg(VA.getValVT()))
2178       CopyVT = MVT::f80;
2179
2180     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2181                                CopyVT, InFlag).getValue(1);
2182     SDValue Val = Chain.getValue(0);
2183
2184     if (CopyVT != VA.getValVT())
2185       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2186                         // This truncation won't change the value.
2187                         DAG.getIntPtrConstant(1));
2188
2189     InFlag = Chain.getValue(2);
2190     InVals.push_back(Val);
2191   }
2192
2193   return Chain;
2194 }
2195
2196 //===----------------------------------------------------------------------===//
2197 //                C & StdCall & Fast Calling Convention implementation
2198 //===----------------------------------------------------------------------===//
2199 //  StdCall calling convention seems to be standard for many Windows' API
2200 //  routines and around. It differs from C calling convention just a little:
2201 //  callee should clean up the stack, not caller. Symbols should be also
2202 //  decorated in some fancy way :) It doesn't support any vector arguments.
2203 //  For info on fast calling convention see Fast Calling Convention (tail call)
2204 //  implementation LowerX86_32FastCCCallTo.
2205
2206 /// CallIsStructReturn - Determines whether a call uses struct return
2207 /// semantics.
2208 enum StructReturnType {
2209   NotStructReturn,
2210   RegStructReturn,
2211   StackStructReturn
2212 };
2213 static StructReturnType
2214 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2215   if (Outs.empty())
2216     return NotStructReturn;
2217
2218   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2219   if (!Flags.isSRet())
2220     return NotStructReturn;
2221   if (Flags.isInReg())
2222     return RegStructReturn;
2223   return StackStructReturn;
2224 }
2225
2226 /// ArgsAreStructReturn - Determines whether a function uses struct
2227 /// return semantics.
2228 static StructReturnType
2229 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2230   if (Ins.empty())
2231     return NotStructReturn;
2232
2233   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2234   if (!Flags.isSRet())
2235     return NotStructReturn;
2236   if (Flags.isInReg())
2237     return RegStructReturn;
2238   return StackStructReturn;
2239 }
2240
2241 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2242 /// by "Src" to address "Dst" with size and alignment information specified by
2243 /// the specific parameter attribute. The copy will be passed as a byval
2244 /// function parameter.
2245 static SDValue
2246 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2247                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2248                           SDLoc dl) {
2249   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2250
2251   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2252                        /*isVolatile*/false, /*AlwaysInline=*/true,
2253                        MachinePointerInfo(), MachinePointerInfo());
2254 }
2255
2256 /// IsTailCallConvention - Return true if the calling convention is one that
2257 /// supports tail call optimization.
2258 static bool IsTailCallConvention(CallingConv::ID CC) {
2259   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2260           CC == CallingConv::HiPE);
2261 }
2262
2263 /// \brief Return true if the calling convention is a C calling convention.
2264 static bool IsCCallConvention(CallingConv::ID CC) {
2265   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2266           CC == CallingConv::X86_64_SysV);
2267 }
2268
2269 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2270   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2271     return false;
2272
2273   CallSite CS(CI);
2274   CallingConv::ID CalleeCC = CS.getCallingConv();
2275   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2276     return false;
2277
2278   return true;
2279 }
2280
2281 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2282 /// a tailcall target by changing its ABI.
2283 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2284                                    bool GuaranteedTailCallOpt) {
2285   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2286 }
2287
2288 SDValue
2289 X86TargetLowering::LowerMemArgument(SDValue Chain,
2290                                     CallingConv::ID CallConv,
2291                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2292                                     SDLoc dl, SelectionDAG &DAG,
2293                                     const CCValAssign &VA,
2294                                     MachineFrameInfo *MFI,
2295                                     unsigned i) const {
2296   // Create the nodes corresponding to a load from this parameter slot.
2297   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2298   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2299       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2300   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2301   EVT ValVT;
2302
2303   // If value is passed by pointer we have address passed instead of the value
2304   // itself.
2305   if (VA.getLocInfo() == CCValAssign::Indirect)
2306     ValVT = VA.getLocVT();
2307   else
2308     ValVT = VA.getValVT();
2309
2310   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2311   // changed with more analysis.
2312   // In case of tail call optimization mark all arguments mutable. Since they
2313   // could be overwritten by lowering of arguments in case of a tail call.
2314   if (Flags.isByVal()) {
2315     unsigned Bytes = Flags.getByValSize();
2316     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2317     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2318     return DAG.getFrameIndex(FI, getPointerTy());
2319   } else {
2320     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2321                                     VA.getLocMemOffset(), isImmutable);
2322     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2323     return DAG.getLoad(ValVT, dl, Chain, FIN,
2324                        MachinePointerInfo::getFixedStack(FI),
2325                        false, false, false, 0);
2326   }
2327 }
2328
2329 // FIXME: Get this from tablegen.
2330 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2331                                                 const X86Subtarget *Subtarget) {
2332   assert(Subtarget->is64Bit());
2333
2334   if (Subtarget->isCallingConvWin64(CallConv)) {
2335     static const MCPhysReg GPR64ArgRegsWin64[] = {
2336       X86::RCX, X86::RDX, X86::R8,  X86::R9
2337     };
2338     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2339   }
2340
2341   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2342     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2343   };
2344   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2345 }
2346
2347 // FIXME: Get this from tablegen.
2348 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2349                                                 CallingConv::ID CallConv,
2350                                                 const X86Subtarget *Subtarget) {
2351   assert(Subtarget->is64Bit());
2352   if (Subtarget->isCallingConvWin64(CallConv)) {
2353     // The XMM registers which might contain var arg parameters are shadowed
2354     // in their paired GPR.  So we only need to save the GPR to their home
2355     // slots.
2356     // TODO: __vectorcall will change this.
2357     return None;
2358   }
2359
2360   const Function *Fn = MF.getFunction();
2361   bool NoImplicitFloatOps = Fn->getAttributes().
2362       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2363   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2364          "SSE register cannot be used when SSE is disabled!");
2365   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2366       !Subtarget->hasSSE1())
2367     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2368     // registers.
2369     return None;
2370
2371   static const MCPhysReg XMMArgRegs64Bit[] = {
2372     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2373     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2374   };
2375   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2376 }
2377
2378 SDValue
2379 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2380                                         CallingConv::ID CallConv,
2381                                         bool isVarArg,
2382                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2383                                         SDLoc dl,
2384                                         SelectionDAG &DAG,
2385                                         SmallVectorImpl<SDValue> &InVals)
2386                                           const {
2387   MachineFunction &MF = DAG.getMachineFunction();
2388   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2389
2390   const Function* Fn = MF.getFunction();
2391   if (Fn->hasExternalLinkage() &&
2392       Subtarget->isTargetCygMing() &&
2393       Fn->getName() == "main")
2394     FuncInfo->setForceFramePointer(true);
2395
2396   MachineFrameInfo *MFI = MF.getFrameInfo();
2397   bool Is64Bit = Subtarget->is64Bit();
2398   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2399
2400   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2401          "Var args not supported with calling convention fastcc, ghc or hipe");
2402
2403   // Assign locations to all of the incoming arguments.
2404   SmallVector<CCValAssign, 16> ArgLocs;
2405   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2406
2407   // Allocate shadow area for Win64
2408   if (IsWin64)
2409     CCInfo.AllocateStack(32, 8);
2410
2411   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2412
2413   unsigned LastVal = ~0U;
2414   SDValue ArgValue;
2415   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2416     CCValAssign &VA = ArgLocs[i];
2417     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2418     // places.
2419     assert(VA.getValNo() != LastVal &&
2420            "Don't support value assigned to multiple locs yet");
2421     (void)LastVal;
2422     LastVal = VA.getValNo();
2423
2424     if (VA.isRegLoc()) {
2425       EVT RegVT = VA.getLocVT();
2426       const TargetRegisterClass *RC;
2427       if (RegVT == MVT::i32)
2428         RC = &X86::GR32RegClass;
2429       else if (Is64Bit && RegVT == MVT::i64)
2430         RC = &X86::GR64RegClass;
2431       else if (RegVT == MVT::f32)
2432         RC = &X86::FR32RegClass;
2433       else if (RegVT == MVT::f64)
2434         RC = &X86::FR64RegClass;
2435       else if (RegVT.is512BitVector())
2436         RC = &X86::VR512RegClass;
2437       else if (RegVT.is256BitVector())
2438         RC = &X86::VR256RegClass;
2439       else if (RegVT.is128BitVector())
2440         RC = &X86::VR128RegClass;
2441       else if (RegVT == MVT::x86mmx)
2442         RC = &X86::VR64RegClass;
2443       else if (RegVT == MVT::i1)
2444         RC = &X86::VK1RegClass;
2445       else if (RegVT == MVT::v8i1)
2446         RC = &X86::VK8RegClass;
2447       else if (RegVT == MVT::v16i1)
2448         RC = &X86::VK16RegClass;
2449       else if (RegVT == MVT::v32i1)
2450         RC = &X86::VK32RegClass;
2451       else if (RegVT == MVT::v64i1)
2452         RC = &X86::VK64RegClass;
2453       else
2454         llvm_unreachable("Unknown argument type!");
2455
2456       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2457       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2458
2459       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2460       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2461       // right size.
2462       if (VA.getLocInfo() == CCValAssign::SExt)
2463         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2464                                DAG.getValueType(VA.getValVT()));
2465       else if (VA.getLocInfo() == CCValAssign::ZExt)
2466         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2467                                DAG.getValueType(VA.getValVT()));
2468       else if (VA.getLocInfo() == CCValAssign::BCvt)
2469         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2470
2471       if (VA.isExtInLoc()) {
2472         // Handle MMX values passed in XMM regs.
2473         if (RegVT.isVector())
2474           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2475         else
2476           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2477       }
2478     } else {
2479       assert(VA.isMemLoc());
2480       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2481     }
2482
2483     // If value is passed via pointer - do a load.
2484     if (VA.getLocInfo() == CCValAssign::Indirect)
2485       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2486                              MachinePointerInfo(), false, false, false, 0);
2487
2488     InVals.push_back(ArgValue);
2489   }
2490
2491   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2492     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2493       // The x86-64 ABIs require that for returning structs by value we copy
2494       // the sret argument into %rax/%eax (depending on ABI) for the return.
2495       // Win32 requires us to put the sret argument to %eax as well.
2496       // Save the argument into a virtual register so that we can access it
2497       // from the return points.
2498       if (Ins[i].Flags.isSRet()) {
2499         unsigned Reg = FuncInfo->getSRetReturnReg();
2500         if (!Reg) {
2501           MVT PtrTy = getPointerTy();
2502           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2503           FuncInfo->setSRetReturnReg(Reg);
2504         }
2505         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2506         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2507         break;
2508       }
2509     }
2510   }
2511
2512   unsigned StackSize = CCInfo.getNextStackOffset();
2513   // Align stack specially for tail calls.
2514   if (FuncIsMadeTailCallSafe(CallConv,
2515                              MF.getTarget().Options.GuaranteedTailCallOpt))
2516     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2517
2518   // If the function takes variable number of arguments, make a frame index for
2519   // the start of the first vararg value... for expansion of llvm.va_start. We
2520   // can skip this if there are no va_start calls.
2521   if (MFI->hasVAStart() &&
2522       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2523                    CallConv != CallingConv::X86_ThisCall))) {
2524     FuncInfo->setVarArgsFrameIndex(
2525         MFI->CreateFixedObject(1, StackSize, true));
2526   }
2527
2528   // 64-bit calling conventions support varargs and register parameters, so we
2529   // have to do extra work to spill them in the prologue or forward them to
2530   // musttail calls.
2531   if (Is64Bit && isVarArg &&
2532       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2533     // Find the first unallocated argument registers.
2534     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2535     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2536     unsigned NumIntRegs =
2537         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2538     unsigned NumXMMRegs =
2539         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2540     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2541            "SSE register cannot be used when SSE is disabled!");
2542
2543     // Gather all the live in physical registers.
2544     SmallVector<SDValue, 6> LiveGPRs;
2545     SmallVector<SDValue, 8> LiveXMMRegs;
2546     SDValue ALVal;
2547     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2548       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2549       LiveGPRs.push_back(
2550           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2551     }
2552     if (!ArgXMMs.empty()) {
2553       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2554       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2555       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2556         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2557         LiveXMMRegs.push_back(
2558             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2559       }
2560     }
2561
2562     // Store them to the va_list returned by va_start.
2563     if (MFI->hasVAStart()) {
2564       if (IsWin64) {
2565         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2566         // Get to the caller-allocated home save location.  Add 8 to account
2567         // for the return address.
2568         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2569         FuncInfo->setRegSaveFrameIndex(
2570           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2571         // Fixup to set vararg frame on shadow area (4 x i64).
2572         if (NumIntRegs < 4)
2573           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2574       } else {
2575         // For X86-64, if there are vararg parameters that are passed via
2576         // registers, then we must store them to their spots on the stack so
2577         // they may be loaded by deferencing the result of va_next.
2578         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2579         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2580         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2581             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2582       }
2583
2584       // Store the integer parameter registers.
2585       SmallVector<SDValue, 8> MemOps;
2586       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2587                                         getPointerTy());
2588       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2589       for (SDValue Val : LiveGPRs) {
2590         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2591                                   DAG.getIntPtrConstant(Offset));
2592         SDValue Store =
2593           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2594                        MachinePointerInfo::getFixedStack(
2595                          FuncInfo->getRegSaveFrameIndex(), Offset),
2596                        false, false, 0);
2597         MemOps.push_back(Store);
2598         Offset += 8;
2599       }
2600
2601       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2602         // Now store the XMM (fp + vector) parameter registers.
2603         SmallVector<SDValue, 12> SaveXMMOps;
2604         SaveXMMOps.push_back(Chain);
2605         SaveXMMOps.push_back(ALVal);
2606         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2607                                FuncInfo->getRegSaveFrameIndex()));
2608         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2609                                FuncInfo->getVarArgsFPOffset()));
2610         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2611                           LiveXMMRegs.end());
2612         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2613                                      MVT::Other, SaveXMMOps));
2614       }
2615
2616       if (!MemOps.empty())
2617         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2618     } else {
2619       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2620       // to the liveout set on a musttail call.
2621       assert(MFI->hasMustTailInVarArgFunc());
2622       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2623       typedef X86MachineFunctionInfo::Forward Forward;
2624
2625       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2626         unsigned VReg =
2627             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2628         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2629         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2630       }
2631
2632       if (!ArgXMMs.empty()) {
2633         unsigned ALVReg =
2634             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2635         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2636         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2637
2638         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2639           unsigned VReg =
2640               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2641           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2642           Forwards.push_back(
2643               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2644         }
2645       }
2646     }
2647   }
2648
2649   // Some CCs need callee pop.
2650   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2651                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2652     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2653   } else {
2654     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2655     // If this is an sret function, the return should pop the hidden pointer.
2656     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2657         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2658         argsAreStructReturn(Ins) == StackStructReturn)
2659       FuncInfo->setBytesToPopOnReturn(4);
2660   }
2661
2662   if (!Is64Bit) {
2663     // RegSaveFrameIndex is X86-64 only.
2664     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2665     if (CallConv == CallingConv::X86_FastCall ||
2666         CallConv == CallingConv::X86_ThisCall)
2667       // fastcc functions can't have varargs.
2668       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2669   }
2670
2671   FuncInfo->setArgumentStackSize(StackSize);
2672
2673   return Chain;
2674 }
2675
2676 SDValue
2677 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2678                                     SDValue StackPtr, SDValue Arg,
2679                                     SDLoc dl, SelectionDAG &DAG,
2680                                     const CCValAssign &VA,
2681                                     ISD::ArgFlagsTy Flags) const {
2682   unsigned LocMemOffset = VA.getLocMemOffset();
2683   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2684   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2685   if (Flags.isByVal())
2686     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2687
2688   return DAG.getStore(Chain, dl, Arg, PtrOff,
2689                       MachinePointerInfo::getStack(LocMemOffset),
2690                       false, false, 0);
2691 }
2692
2693 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2694 /// optimization is performed and it is required.
2695 SDValue
2696 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2697                                            SDValue &OutRetAddr, SDValue Chain,
2698                                            bool IsTailCall, bool Is64Bit,
2699                                            int FPDiff, SDLoc dl) const {
2700   // Adjust the Return address stack slot.
2701   EVT VT = getPointerTy();
2702   OutRetAddr = getReturnAddressFrameIndex(DAG);
2703
2704   // Load the "old" Return address.
2705   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2706                            false, false, false, 0);
2707   return SDValue(OutRetAddr.getNode(), 1);
2708 }
2709
2710 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2711 /// optimization is performed and it is required (FPDiff!=0).
2712 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2713                                         SDValue Chain, SDValue RetAddrFrIdx,
2714                                         EVT PtrVT, unsigned SlotSize,
2715                                         int FPDiff, SDLoc dl) {
2716   // Store the return address to the appropriate stack slot.
2717   if (!FPDiff) return Chain;
2718   // Calculate the new stack slot for the return address.
2719   int NewReturnAddrFI =
2720     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2721                                          false);
2722   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2723   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2724                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2725                        false, false, 0);
2726   return Chain;
2727 }
2728
2729 SDValue
2730 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2731                              SmallVectorImpl<SDValue> &InVals) const {
2732   SelectionDAG &DAG                     = CLI.DAG;
2733   SDLoc &dl                             = CLI.DL;
2734   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2735   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2736   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2737   SDValue Chain                         = CLI.Chain;
2738   SDValue Callee                        = CLI.Callee;
2739   CallingConv::ID CallConv              = CLI.CallConv;
2740   bool &isTailCall                      = CLI.IsTailCall;
2741   bool isVarArg                         = CLI.IsVarArg;
2742
2743   MachineFunction &MF = DAG.getMachineFunction();
2744   bool Is64Bit        = Subtarget->is64Bit();
2745   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2746   StructReturnType SR = callIsStructReturn(Outs);
2747   bool IsSibcall      = false;
2748   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2749
2750   if (MF.getTarget().Options.DisableTailCalls)
2751     isTailCall = false;
2752
2753   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2754   if (IsMustTail) {
2755     // Force this to be a tail call.  The verifier rules are enough to ensure
2756     // that we can lower this successfully without moving the return address
2757     // around.
2758     isTailCall = true;
2759   } else if (isTailCall) {
2760     // Check if it's really possible to do a tail call.
2761     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2762                     isVarArg, SR != NotStructReturn,
2763                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2764                     Outs, OutVals, Ins, DAG);
2765
2766     // Sibcalls are automatically detected tailcalls which do not require
2767     // ABI changes.
2768     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2769       IsSibcall = true;
2770
2771     if (isTailCall)
2772       ++NumTailCalls;
2773   }
2774
2775   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2776          "Var args not supported with calling convention fastcc, ghc or hipe");
2777
2778   // Analyze operands of the call, assigning locations to each operand.
2779   SmallVector<CCValAssign, 16> ArgLocs;
2780   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2781
2782   // Allocate shadow area for Win64
2783   if (IsWin64)
2784     CCInfo.AllocateStack(32, 8);
2785
2786   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2787
2788   // Get a count of how many bytes are to be pushed on the stack.
2789   unsigned NumBytes = CCInfo.getNextStackOffset();
2790   if (IsSibcall)
2791     // This is a sibcall. The memory operands are available in caller's
2792     // own caller's stack.
2793     NumBytes = 0;
2794   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2795            IsTailCallConvention(CallConv))
2796     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2797
2798   int FPDiff = 0;
2799   if (isTailCall && !IsSibcall && !IsMustTail) {
2800     // Lower arguments at fp - stackoffset + fpdiff.
2801     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2802
2803     FPDiff = NumBytesCallerPushed - NumBytes;
2804
2805     // Set the delta of movement of the returnaddr stackslot.
2806     // But only set if delta is greater than previous delta.
2807     if (FPDiff < X86Info->getTCReturnAddrDelta())
2808       X86Info->setTCReturnAddrDelta(FPDiff);
2809   }
2810
2811   unsigned NumBytesToPush = NumBytes;
2812   unsigned NumBytesToPop = NumBytes;
2813
2814   // If we have an inalloca argument, all stack space has already been allocated
2815   // for us and be right at the top of the stack.  We don't support multiple
2816   // arguments passed in memory when using inalloca.
2817   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2818     NumBytesToPush = 0;
2819     if (!ArgLocs.back().isMemLoc())
2820       report_fatal_error("cannot use inalloca attribute on a register "
2821                          "parameter");
2822     if (ArgLocs.back().getLocMemOffset() != 0)
2823       report_fatal_error("any parameter with the inalloca attribute must be "
2824                          "the only memory argument");
2825   }
2826
2827   if (!IsSibcall)
2828     Chain = DAG.getCALLSEQ_START(
2829         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2830
2831   SDValue RetAddrFrIdx;
2832   // Load return address for tail calls.
2833   if (isTailCall && FPDiff)
2834     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2835                                     Is64Bit, FPDiff, dl);
2836
2837   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2838   SmallVector<SDValue, 8> MemOpChains;
2839   SDValue StackPtr;
2840
2841   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2842   // of tail call optimization arguments are handle later.
2843   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2844       DAG.getSubtarget().getRegisterInfo());
2845   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2846     // Skip inalloca arguments, they have already been written.
2847     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2848     if (Flags.isInAlloca())
2849       continue;
2850
2851     CCValAssign &VA = ArgLocs[i];
2852     EVT RegVT = VA.getLocVT();
2853     SDValue Arg = OutVals[i];
2854     bool isByVal = Flags.isByVal();
2855
2856     // Promote the value if needed.
2857     switch (VA.getLocInfo()) {
2858     default: llvm_unreachable("Unknown loc info!");
2859     case CCValAssign::Full: break;
2860     case CCValAssign::SExt:
2861       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2862       break;
2863     case CCValAssign::ZExt:
2864       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2865       break;
2866     case CCValAssign::AExt:
2867       if (RegVT.is128BitVector()) {
2868         // Special case: passing MMX values in XMM registers.
2869         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2870         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2871         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2872       } else
2873         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2874       break;
2875     case CCValAssign::BCvt:
2876       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2877       break;
2878     case CCValAssign::Indirect: {
2879       // Store the argument.
2880       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2881       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2882       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2883                            MachinePointerInfo::getFixedStack(FI),
2884                            false, false, 0);
2885       Arg = SpillSlot;
2886       break;
2887     }
2888     }
2889
2890     if (VA.isRegLoc()) {
2891       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2892       if (isVarArg && IsWin64) {
2893         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2894         // shadow reg if callee is a varargs function.
2895         unsigned ShadowReg = 0;
2896         switch (VA.getLocReg()) {
2897         case X86::XMM0: ShadowReg = X86::RCX; break;
2898         case X86::XMM1: ShadowReg = X86::RDX; break;
2899         case X86::XMM2: ShadowReg = X86::R8; break;
2900         case X86::XMM3: ShadowReg = X86::R9; break;
2901         }
2902         if (ShadowReg)
2903           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2904       }
2905     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2906       assert(VA.isMemLoc());
2907       if (!StackPtr.getNode())
2908         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2909                                       getPointerTy());
2910       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2911                                              dl, DAG, VA, Flags));
2912     }
2913   }
2914
2915   if (!MemOpChains.empty())
2916     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2917
2918   if (Subtarget->isPICStyleGOT()) {
2919     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2920     // GOT pointer.
2921     if (!isTailCall) {
2922       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2923                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2924     } else {
2925       // If we are tail calling and generating PIC/GOT style code load the
2926       // address of the callee into ECX. The value in ecx is used as target of
2927       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2928       // for tail calls on PIC/GOT architectures. Normally we would just put the
2929       // address of GOT into ebx and then call target@PLT. But for tail calls
2930       // ebx would be restored (since ebx is callee saved) before jumping to the
2931       // target@PLT.
2932
2933       // Note: The actual moving to ECX is done further down.
2934       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2935       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2936           !G->getGlobal()->hasProtectedVisibility())
2937         Callee = LowerGlobalAddress(Callee, DAG);
2938       else if (isa<ExternalSymbolSDNode>(Callee))
2939         Callee = LowerExternalSymbol(Callee, DAG);
2940     }
2941   }
2942
2943   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2944     // From AMD64 ABI document:
2945     // For calls that may call functions that use varargs or stdargs
2946     // (prototype-less calls or calls to functions containing ellipsis (...) in
2947     // the declaration) %al is used as hidden argument to specify the number
2948     // of SSE registers used. The contents of %al do not need to match exactly
2949     // the number of registers, but must be an ubound on the number of SSE
2950     // registers used and is in the range 0 - 8 inclusive.
2951
2952     // Count the number of XMM registers allocated.
2953     static const MCPhysReg XMMArgRegs[] = {
2954       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2955       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2956     };
2957     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2958     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2959            && "SSE registers cannot be used when SSE is disabled");
2960
2961     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2962                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2963   }
2964
2965   if (Is64Bit && isVarArg && IsMustTail) {
2966     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2967     for (const auto &F : Forwards) {
2968       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2969       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2970     }
2971   }
2972
2973   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2974   // don't need this because the eligibility check rejects calls that require
2975   // shuffling arguments passed in memory.
2976   if (!IsSibcall && isTailCall) {
2977     // Force all the incoming stack arguments to be loaded from the stack
2978     // before any new outgoing arguments are stored to the stack, because the
2979     // outgoing stack slots may alias the incoming argument stack slots, and
2980     // the alias isn't otherwise explicit. This is slightly more conservative
2981     // than necessary, because it means that each store effectively depends
2982     // on every argument instead of just those arguments it would clobber.
2983     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2984
2985     SmallVector<SDValue, 8> MemOpChains2;
2986     SDValue FIN;
2987     int FI = 0;
2988     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2989       CCValAssign &VA = ArgLocs[i];
2990       if (VA.isRegLoc())
2991         continue;
2992       assert(VA.isMemLoc());
2993       SDValue Arg = OutVals[i];
2994       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2995       // Skip inalloca arguments.  They don't require any work.
2996       if (Flags.isInAlloca())
2997         continue;
2998       // Create frame index.
2999       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3000       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3001       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3002       FIN = DAG.getFrameIndex(FI, getPointerTy());
3003
3004       if (Flags.isByVal()) {
3005         // Copy relative to framepointer.
3006         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3007         if (!StackPtr.getNode())
3008           StackPtr = DAG.getCopyFromReg(Chain, dl,
3009                                         RegInfo->getStackRegister(),
3010                                         getPointerTy());
3011         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3012
3013         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3014                                                          ArgChain,
3015                                                          Flags, DAG, dl));
3016       } else {
3017         // Store relative to framepointer.
3018         MemOpChains2.push_back(
3019           DAG.getStore(ArgChain, dl, Arg, FIN,
3020                        MachinePointerInfo::getFixedStack(FI),
3021                        false, false, 0));
3022       }
3023     }
3024
3025     if (!MemOpChains2.empty())
3026       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3027
3028     // Store the return address to the appropriate stack slot.
3029     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3030                                      getPointerTy(), RegInfo->getSlotSize(),
3031                                      FPDiff, dl);
3032   }
3033
3034   // Build a sequence of copy-to-reg nodes chained together with token chain
3035   // and flag operands which copy the outgoing args into registers.
3036   SDValue InFlag;
3037   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3038     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3039                              RegsToPass[i].second, InFlag);
3040     InFlag = Chain.getValue(1);
3041   }
3042
3043   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3044     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3045     // In the 64-bit large code model, we have to make all calls
3046     // through a register, since the call instruction's 32-bit
3047     // pc-relative offset may not be large enough to hold the whole
3048     // address.
3049   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3050     // If the callee is a GlobalAddress node (quite common, every direct call
3051     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3052     // it.
3053
3054     // We should use extra load for direct calls to dllimported functions in
3055     // non-JIT mode.
3056     const GlobalValue *GV = G->getGlobal();
3057     if (!GV->hasDLLImportStorageClass()) {
3058       unsigned char OpFlags = 0;
3059       bool ExtraLoad = false;
3060       unsigned WrapperKind = ISD::DELETED_NODE;
3061
3062       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3063       // external symbols most go through the PLT in PIC mode.  If the symbol
3064       // has hidden or protected visibility, or if it is static or local, then
3065       // we don't need to use the PLT - we can directly call it.
3066       if (Subtarget->isTargetELF() &&
3067           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3068           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3069         OpFlags = X86II::MO_PLT;
3070       } else if (Subtarget->isPICStyleStubAny() &&
3071                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3072                  (!Subtarget->getTargetTriple().isMacOSX() ||
3073                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3074         // PC-relative references to external symbols should go through $stub,
3075         // unless we're building with the leopard linker or later, which
3076         // automatically synthesizes these stubs.
3077         OpFlags = X86II::MO_DARWIN_STUB;
3078       } else if (Subtarget->isPICStyleRIPRel() &&
3079                  isa<Function>(GV) &&
3080                  cast<Function>(GV)->getAttributes().
3081                    hasAttribute(AttributeSet::FunctionIndex,
3082                                 Attribute::NonLazyBind)) {
3083         // If the function is marked as non-lazy, generate an indirect call
3084         // which loads from the GOT directly. This avoids runtime overhead
3085         // at the cost of eager binding (and one extra byte of encoding).
3086         OpFlags = X86II::MO_GOTPCREL;
3087         WrapperKind = X86ISD::WrapperRIP;
3088         ExtraLoad = true;
3089       }
3090
3091       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3092                                           G->getOffset(), OpFlags);
3093
3094       // Add a wrapper if needed.
3095       if (WrapperKind != ISD::DELETED_NODE)
3096         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3097       // Add extra indirection if needed.
3098       if (ExtraLoad)
3099         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3100                              MachinePointerInfo::getGOT(),
3101                              false, false, false, 0);
3102     }
3103   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3104     unsigned char OpFlags = 0;
3105
3106     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3107     // external symbols should go through the PLT.
3108     if (Subtarget->isTargetELF() &&
3109         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3110       OpFlags = X86II::MO_PLT;
3111     } else if (Subtarget->isPICStyleStubAny() &&
3112                (!Subtarget->getTargetTriple().isMacOSX() ||
3113                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3114       // PC-relative references to external symbols should go through $stub,
3115       // unless we're building with the leopard linker or later, which
3116       // automatically synthesizes these stubs.
3117       OpFlags = X86II::MO_DARWIN_STUB;
3118     }
3119
3120     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3121                                          OpFlags);
3122   }
3123
3124   // Returns a chain & a flag for retval copy to use.
3125   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3126   SmallVector<SDValue, 8> Ops;
3127
3128   if (!IsSibcall && isTailCall) {
3129     Chain = DAG.getCALLSEQ_END(Chain,
3130                                DAG.getIntPtrConstant(NumBytesToPop, true),
3131                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3132     InFlag = Chain.getValue(1);
3133   }
3134
3135   Ops.push_back(Chain);
3136   Ops.push_back(Callee);
3137
3138   if (isTailCall)
3139     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3140
3141   // Add argument registers to the end of the list so that they are known live
3142   // into the call.
3143   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3144     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3145                                   RegsToPass[i].second.getValueType()));
3146
3147   // Add a register mask operand representing the call-preserved registers.
3148   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3149   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3150   assert(Mask && "Missing call preserved mask for calling convention");
3151   Ops.push_back(DAG.getRegisterMask(Mask));
3152
3153   if (InFlag.getNode())
3154     Ops.push_back(InFlag);
3155
3156   if (isTailCall) {
3157     // We used to do:
3158     //// If this is the first return lowered for this function, add the regs
3159     //// to the liveout set for the function.
3160     // This isn't right, although it's probably harmless on x86; liveouts
3161     // should be computed from returns not tail calls.  Consider a void
3162     // function making a tail call to a function returning int.
3163     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3164   }
3165
3166   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3167   InFlag = Chain.getValue(1);
3168
3169   // Create the CALLSEQ_END node.
3170   unsigned NumBytesForCalleeToPop;
3171   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3172                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3173     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3174   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3175            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3176            SR == StackStructReturn)
3177     // If this is a call to a struct-return function, the callee
3178     // pops the hidden struct pointer, so we have to push it back.
3179     // This is common for Darwin/X86, Linux & Mingw32 targets.
3180     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3181     NumBytesForCalleeToPop = 4;
3182   else
3183     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3184
3185   // Returns a flag for retval copy to use.
3186   if (!IsSibcall) {
3187     Chain = DAG.getCALLSEQ_END(Chain,
3188                                DAG.getIntPtrConstant(NumBytesToPop, true),
3189                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3190                                                      true),
3191                                InFlag, dl);
3192     InFlag = Chain.getValue(1);
3193   }
3194
3195   // Handle result values, copying them out of physregs into vregs that we
3196   // return.
3197   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3198                          Ins, dl, DAG, InVals);
3199 }
3200
3201 //===----------------------------------------------------------------------===//
3202 //                Fast Calling Convention (tail call) implementation
3203 //===----------------------------------------------------------------------===//
3204
3205 //  Like std call, callee cleans arguments, convention except that ECX is
3206 //  reserved for storing the tail called function address. Only 2 registers are
3207 //  free for argument passing (inreg). Tail call optimization is performed
3208 //  provided:
3209 //                * tailcallopt is enabled
3210 //                * caller/callee are fastcc
3211 //  On X86_64 architecture with GOT-style position independent code only local
3212 //  (within module) calls are supported at the moment.
3213 //  To keep the stack aligned according to platform abi the function
3214 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3215 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3216 //  If a tail called function callee has more arguments than the caller the
3217 //  caller needs to make sure that there is room to move the RETADDR to. This is
3218 //  achieved by reserving an area the size of the argument delta right after the
3219 //  original RETADDR, but before the saved framepointer or the spilled registers
3220 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3221 //  stack layout:
3222 //    arg1
3223 //    arg2
3224 //    RETADDR
3225 //    [ new RETADDR
3226 //      move area ]
3227 //    (possible EBP)
3228 //    ESI
3229 //    EDI
3230 //    local1 ..
3231
3232 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3233 /// for a 16 byte align requirement.
3234 unsigned
3235 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3236                                                SelectionDAG& DAG) const {
3237   MachineFunction &MF = DAG.getMachineFunction();
3238   const TargetMachine &TM = MF.getTarget();
3239   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3240       TM.getSubtargetImpl()->getRegisterInfo());
3241   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3242   unsigned StackAlignment = TFI.getStackAlignment();
3243   uint64_t AlignMask = StackAlignment - 1;
3244   int64_t Offset = StackSize;
3245   unsigned SlotSize = RegInfo->getSlotSize();
3246   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3247     // Number smaller than 12 so just add the difference.
3248     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3249   } else {
3250     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3251     Offset = ((~AlignMask) & Offset) + StackAlignment +
3252       (StackAlignment-SlotSize);
3253   }
3254   return Offset;
3255 }
3256
3257 /// MatchingStackOffset - Return true if the given stack call argument is
3258 /// already available in the same position (relatively) of the caller's
3259 /// incoming argument stack.
3260 static
3261 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3262                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3263                          const X86InstrInfo *TII) {
3264   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3265   int FI = INT_MAX;
3266   if (Arg.getOpcode() == ISD::CopyFromReg) {
3267     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3268     if (!TargetRegisterInfo::isVirtualRegister(VR))
3269       return false;
3270     MachineInstr *Def = MRI->getVRegDef(VR);
3271     if (!Def)
3272       return false;
3273     if (!Flags.isByVal()) {
3274       if (!TII->isLoadFromStackSlot(Def, FI))
3275         return false;
3276     } else {
3277       unsigned Opcode = Def->getOpcode();
3278       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3279           Def->getOperand(1).isFI()) {
3280         FI = Def->getOperand(1).getIndex();
3281         Bytes = Flags.getByValSize();
3282       } else
3283         return false;
3284     }
3285   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3286     if (Flags.isByVal())
3287       // ByVal argument is passed in as a pointer but it's now being
3288       // dereferenced. e.g.
3289       // define @foo(%struct.X* %A) {
3290       //   tail call @bar(%struct.X* byval %A)
3291       // }
3292       return false;
3293     SDValue Ptr = Ld->getBasePtr();
3294     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3295     if (!FINode)
3296       return false;
3297     FI = FINode->getIndex();
3298   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3299     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3300     FI = FINode->getIndex();
3301     Bytes = Flags.getByValSize();
3302   } else
3303     return false;
3304
3305   assert(FI != INT_MAX);
3306   if (!MFI->isFixedObjectIndex(FI))
3307     return false;
3308   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3309 }
3310
3311 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3312 /// for tail call optimization. Targets which want to do tail call
3313 /// optimization should implement this function.
3314 bool
3315 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3316                                                      CallingConv::ID CalleeCC,
3317                                                      bool isVarArg,
3318                                                      bool isCalleeStructRet,
3319                                                      bool isCallerStructRet,
3320                                                      Type *RetTy,
3321                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3322                                     const SmallVectorImpl<SDValue> &OutVals,
3323                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3324                                                      SelectionDAG &DAG) const {
3325   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3326     return false;
3327
3328   // If -tailcallopt is specified, make fastcc functions tail-callable.
3329   const MachineFunction &MF = DAG.getMachineFunction();
3330   const Function *CallerF = MF.getFunction();
3331
3332   // If the function return type is x86_fp80 and the callee return type is not,
3333   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3334   // perform a tailcall optimization here.
3335   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3336     return false;
3337
3338   CallingConv::ID CallerCC = CallerF->getCallingConv();
3339   bool CCMatch = CallerCC == CalleeCC;
3340   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3341   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3342
3343   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3344     if (IsTailCallConvention(CalleeCC) && CCMatch)
3345       return true;
3346     return false;
3347   }
3348
3349   // Look for obvious safe cases to perform tail call optimization that do not
3350   // require ABI changes. This is what gcc calls sibcall.
3351
3352   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3353   // emit a special epilogue.
3354   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3355       DAG.getSubtarget().getRegisterInfo());
3356   if (RegInfo->needsStackRealignment(MF))
3357     return false;
3358
3359   // Also avoid sibcall optimization if either caller or callee uses struct
3360   // return semantics.
3361   if (isCalleeStructRet || isCallerStructRet)
3362     return false;
3363
3364   // An stdcall/thiscall caller is expected to clean up its arguments; the
3365   // callee isn't going to do that.
3366   // FIXME: this is more restrictive than needed. We could produce a tailcall
3367   // when the stack adjustment matches. For example, with a thiscall that takes
3368   // only one argument.
3369   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3370                    CallerCC == CallingConv::X86_ThisCall))
3371     return false;
3372
3373   // Do not sibcall optimize vararg calls unless all arguments are passed via
3374   // registers.
3375   if (isVarArg && !Outs.empty()) {
3376
3377     // Optimizing for varargs on Win64 is unlikely to be safe without
3378     // additional testing.
3379     if (IsCalleeWin64 || IsCallerWin64)
3380       return false;
3381
3382     SmallVector<CCValAssign, 16> ArgLocs;
3383     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3384                    *DAG.getContext());
3385
3386     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3387     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3388       if (!ArgLocs[i].isRegLoc())
3389         return false;
3390   }
3391
3392   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3393   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3394   // this into a sibcall.
3395   bool Unused = false;
3396   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3397     if (!Ins[i].Used) {
3398       Unused = true;
3399       break;
3400     }
3401   }
3402   if (Unused) {
3403     SmallVector<CCValAssign, 16> RVLocs;
3404     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3405                    *DAG.getContext());
3406     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3407     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3408       CCValAssign &VA = RVLocs[i];
3409       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3410         return false;
3411     }
3412   }
3413
3414   // If the calling conventions do not match, then we'd better make sure the
3415   // results are returned in the same way as what the caller expects.
3416   if (!CCMatch) {
3417     SmallVector<CCValAssign, 16> RVLocs1;
3418     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3419                     *DAG.getContext());
3420     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3421
3422     SmallVector<CCValAssign, 16> RVLocs2;
3423     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3424                     *DAG.getContext());
3425     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3426
3427     if (RVLocs1.size() != RVLocs2.size())
3428       return false;
3429     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3430       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3431         return false;
3432       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3433         return false;
3434       if (RVLocs1[i].isRegLoc()) {
3435         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3436           return false;
3437       } else {
3438         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3439           return false;
3440       }
3441     }
3442   }
3443
3444   // If the callee takes no arguments then go on to check the results of the
3445   // call.
3446   if (!Outs.empty()) {
3447     // Check if stack adjustment is needed. For now, do not do this if any
3448     // argument is passed on the stack.
3449     SmallVector<CCValAssign, 16> ArgLocs;
3450     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3451                    *DAG.getContext());
3452
3453     // Allocate shadow area for Win64
3454     if (IsCalleeWin64)
3455       CCInfo.AllocateStack(32, 8);
3456
3457     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3458     if (CCInfo.getNextStackOffset()) {
3459       MachineFunction &MF = DAG.getMachineFunction();
3460       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3461         return false;
3462
3463       // Check if the arguments are already laid out in the right way as
3464       // the caller's fixed stack objects.
3465       MachineFrameInfo *MFI = MF.getFrameInfo();
3466       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3467       const X86InstrInfo *TII =
3468           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3469       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3470         CCValAssign &VA = ArgLocs[i];
3471         SDValue Arg = OutVals[i];
3472         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3473         if (VA.getLocInfo() == CCValAssign::Indirect)
3474           return false;
3475         if (!VA.isRegLoc()) {
3476           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3477                                    MFI, MRI, TII))
3478             return false;
3479         }
3480       }
3481     }
3482
3483     // If the tailcall address may be in a register, then make sure it's
3484     // possible to register allocate for it. In 32-bit, the call address can
3485     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3486     // callee-saved registers are restored. These happen to be the same
3487     // registers used to pass 'inreg' arguments so watch out for those.
3488     if (!Subtarget->is64Bit() &&
3489         ((!isa<GlobalAddressSDNode>(Callee) &&
3490           !isa<ExternalSymbolSDNode>(Callee)) ||
3491          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3492       unsigned NumInRegs = 0;
3493       // In PIC we need an extra register to formulate the address computation
3494       // for the callee.
3495       unsigned MaxInRegs =
3496         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3497
3498       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3499         CCValAssign &VA = ArgLocs[i];
3500         if (!VA.isRegLoc())
3501           continue;
3502         unsigned Reg = VA.getLocReg();
3503         switch (Reg) {
3504         default: break;
3505         case X86::EAX: case X86::EDX: case X86::ECX:
3506           if (++NumInRegs == MaxInRegs)
3507             return false;
3508           break;
3509         }
3510       }
3511     }
3512   }
3513
3514   return true;
3515 }
3516
3517 FastISel *
3518 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3519                                   const TargetLibraryInfo *libInfo) const {
3520   return X86::createFastISel(funcInfo, libInfo);
3521 }
3522
3523 //===----------------------------------------------------------------------===//
3524 //                           Other Lowering Hooks
3525 //===----------------------------------------------------------------------===//
3526
3527 static bool MayFoldLoad(SDValue Op) {
3528   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3529 }
3530
3531 static bool MayFoldIntoStore(SDValue Op) {
3532   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3533 }
3534
3535 static bool isTargetShuffle(unsigned Opcode) {
3536   switch(Opcode) {
3537   default: return false;
3538   case X86ISD::PSHUFB:
3539   case X86ISD::PSHUFD:
3540   case X86ISD::PSHUFHW:
3541   case X86ISD::PSHUFLW:
3542   case X86ISD::SHUFP:
3543   case X86ISD::PALIGNR:
3544   case X86ISD::MOVLHPS:
3545   case X86ISD::MOVLHPD:
3546   case X86ISD::MOVHLPS:
3547   case X86ISD::MOVLPS:
3548   case X86ISD::MOVLPD:
3549   case X86ISD::MOVSHDUP:
3550   case X86ISD::MOVSLDUP:
3551   case X86ISD::MOVDDUP:
3552   case X86ISD::MOVSS:
3553   case X86ISD::MOVSD:
3554   case X86ISD::UNPCKL:
3555   case X86ISD::UNPCKH:
3556   case X86ISD::VPERMILP:
3557   case X86ISD::VPERM2X128:
3558   case X86ISD::VPERMI:
3559     return true;
3560   }
3561 }
3562
3563 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3564                                     SDValue V1, SelectionDAG &DAG) {
3565   switch(Opc) {
3566   default: llvm_unreachable("Unknown x86 shuffle node");
3567   case X86ISD::MOVSHDUP:
3568   case X86ISD::MOVSLDUP:
3569   case X86ISD::MOVDDUP:
3570     return DAG.getNode(Opc, dl, VT, V1);
3571   }
3572 }
3573
3574 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3575                                     SDValue V1, unsigned TargetMask,
3576                                     SelectionDAG &DAG) {
3577   switch(Opc) {
3578   default: llvm_unreachable("Unknown x86 shuffle node");
3579   case X86ISD::PSHUFD:
3580   case X86ISD::PSHUFHW:
3581   case X86ISD::PSHUFLW:
3582   case X86ISD::VPERMILP:
3583   case X86ISD::VPERMI:
3584     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3585   }
3586 }
3587
3588 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3589                                     SDValue V1, SDValue V2, unsigned TargetMask,
3590                                     SelectionDAG &DAG) {
3591   switch(Opc) {
3592   default: llvm_unreachable("Unknown x86 shuffle node");
3593   case X86ISD::PALIGNR:
3594   case X86ISD::VALIGN:
3595   case X86ISD::SHUFP:
3596   case X86ISD::VPERM2X128:
3597     return DAG.getNode(Opc, dl, VT, V1, V2,
3598                        DAG.getConstant(TargetMask, MVT::i8));
3599   }
3600 }
3601
3602 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3603                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3604   switch(Opc) {
3605   default: llvm_unreachable("Unknown x86 shuffle node");
3606   case X86ISD::MOVLHPS:
3607   case X86ISD::MOVLHPD:
3608   case X86ISD::MOVHLPS:
3609   case X86ISD::MOVLPS:
3610   case X86ISD::MOVLPD:
3611   case X86ISD::MOVSS:
3612   case X86ISD::MOVSD:
3613   case X86ISD::UNPCKL:
3614   case X86ISD::UNPCKH:
3615     return DAG.getNode(Opc, dl, VT, V1, V2);
3616   }
3617 }
3618
3619 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3620   MachineFunction &MF = DAG.getMachineFunction();
3621   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3622       DAG.getSubtarget().getRegisterInfo());
3623   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3624   int ReturnAddrIndex = FuncInfo->getRAIndex();
3625
3626   if (ReturnAddrIndex == 0) {
3627     // Set up a frame object for the return address.
3628     unsigned SlotSize = RegInfo->getSlotSize();
3629     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3630                                                            -(int64_t)SlotSize,
3631                                                            false);
3632     FuncInfo->setRAIndex(ReturnAddrIndex);
3633   }
3634
3635   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3636 }
3637
3638 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3639                                        bool hasSymbolicDisplacement) {
3640   // Offset should fit into 32 bit immediate field.
3641   if (!isInt<32>(Offset))
3642     return false;
3643
3644   // If we don't have a symbolic displacement - we don't have any extra
3645   // restrictions.
3646   if (!hasSymbolicDisplacement)
3647     return true;
3648
3649   // FIXME: Some tweaks might be needed for medium code model.
3650   if (M != CodeModel::Small && M != CodeModel::Kernel)
3651     return false;
3652
3653   // For small code model we assume that latest object is 16MB before end of 31
3654   // bits boundary. We may also accept pretty large negative constants knowing
3655   // that all objects are in the positive half of address space.
3656   if (M == CodeModel::Small && Offset < 16*1024*1024)
3657     return true;
3658
3659   // For kernel code model we know that all object resist in the negative half
3660   // of 32bits address space. We may not accept negative offsets, since they may
3661   // be just off and we may accept pretty large positive ones.
3662   if (M == CodeModel::Kernel && Offset > 0)
3663     return true;
3664
3665   return false;
3666 }
3667
3668 /// isCalleePop - Determines whether the callee is required to pop its
3669 /// own arguments. Callee pop is necessary to support tail calls.
3670 bool X86::isCalleePop(CallingConv::ID CallingConv,
3671                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3672   switch (CallingConv) {
3673   default:
3674     return false;
3675   case CallingConv::X86_StdCall:
3676   case CallingConv::X86_FastCall:
3677   case CallingConv::X86_ThisCall:
3678     return !is64Bit;
3679   case CallingConv::Fast:
3680   case CallingConv::GHC:
3681   case CallingConv::HiPE:
3682     if (IsVarArg)
3683       return false;
3684     return TailCallOpt;
3685   }
3686 }
3687
3688 /// \brief Return true if the condition is an unsigned comparison operation.
3689 static bool isX86CCUnsigned(unsigned X86CC) {
3690   switch (X86CC) {
3691   default: llvm_unreachable("Invalid integer condition!");
3692   case X86::COND_E:     return true;
3693   case X86::COND_G:     return false;
3694   case X86::COND_GE:    return false;
3695   case X86::COND_L:     return false;
3696   case X86::COND_LE:    return false;
3697   case X86::COND_NE:    return true;
3698   case X86::COND_B:     return true;
3699   case X86::COND_A:     return true;
3700   case X86::COND_BE:    return true;
3701   case X86::COND_AE:    return true;
3702   }
3703   llvm_unreachable("covered switch fell through?!");
3704 }
3705
3706 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3707 /// specific condition code, returning the condition code and the LHS/RHS of the
3708 /// comparison to make.
3709 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3710                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3711   if (!isFP) {
3712     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3713       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3714         // X > -1   -> X == 0, jump !sign.
3715         RHS = DAG.getConstant(0, RHS.getValueType());
3716         return X86::COND_NS;
3717       }
3718       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3719         // X < 0   -> X == 0, jump on sign.
3720         return X86::COND_S;
3721       }
3722       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3723         // X < 1   -> X <= 0
3724         RHS = DAG.getConstant(0, RHS.getValueType());
3725         return X86::COND_LE;
3726       }
3727     }
3728
3729     switch (SetCCOpcode) {
3730     default: llvm_unreachable("Invalid integer condition!");
3731     case ISD::SETEQ:  return X86::COND_E;
3732     case ISD::SETGT:  return X86::COND_G;
3733     case ISD::SETGE:  return X86::COND_GE;
3734     case ISD::SETLT:  return X86::COND_L;
3735     case ISD::SETLE:  return X86::COND_LE;
3736     case ISD::SETNE:  return X86::COND_NE;
3737     case ISD::SETULT: return X86::COND_B;
3738     case ISD::SETUGT: return X86::COND_A;
3739     case ISD::SETULE: return X86::COND_BE;
3740     case ISD::SETUGE: return X86::COND_AE;
3741     }
3742   }
3743
3744   // First determine if it is required or is profitable to flip the operands.
3745
3746   // If LHS is a foldable load, but RHS is not, flip the condition.
3747   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3748       !ISD::isNON_EXTLoad(RHS.getNode())) {
3749     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3750     std::swap(LHS, RHS);
3751   }
3752
3753   switch (SetCCOpcode) {
3754   default: break;
3755   case ISD::SETOLT:
3756   case ISD::SETOLE:
3757   case ISD::SETUGT:
3758   case ISD::SETUGE:
3759     std::swap(LHS, RHS);
3760     break;
3761   }
3762
3763   // On a floating point condition, the flags are set as follows:
3764   // ZF  PF  CF   op
3765   //  0 | 0 | 0 | X > Y
3766   //  0 | 0 | 1 | X < Y
3767   //  1 | 0 | 0 | X == Y
3768   //  1 | 1 | 1 | unordered
3769   switch (SetCCOpcode) {
3770   default: llvm_unreachable("Condcode should be pre-legalized away");
3771   case ISD::SETUEQ:
3772   case ISD::SETEQ:   return X86::COND_E;
3773   case ISD::SETOLT:              // flipped
3774   case ISD::SETOGT:
3775   case ISD::SETGT:   return X86::COND_A;
3776   case ISD::SETOLE:              // flipped
3777   case ISD::SETOGE:
3778   case ISD::SETGE:   return X86::COND_AE;
3779   case ISD::SETUGT:              // flipped
3780   case ISD::SETULT:
3781   case ISD::SETLT:   return X86::COND_B;
3782   case ISD::SETUGE:              // flipped
3783   case ISD::SETULE:
3784   case ISD::SETLE:   return X86::COND_BE;
3785   case ISD::SETONE:
3786   case ISD::SETNE:   return X86::COND_NE;
3787   case ISD::SETUO:   return X86::COND_P;
3788   case ISD::SETO:    return X86::COND_NP;
3789   case ISD::SETOEQ:
3790   case ISD::SETUNE:  return X86::COND_INVALID;
3791   }
3792 }
3793
3794 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3795 /// code. Current x86 isa includes the following FP cmov instructions:
3796 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3797 static bool hasFPCMov(unsigned X86CC) {
3798   switch (X86CC) {
3799   default:
3800     return false;
3801   case X86::COND_B:
3802   case X86::COND_BE:
3803   case X86::COND_E:
3804   case X86::COND_P:
3805   case X86::COND_A:
3806   case X86::COND_AE:
3807   case X86::COND_NE:
3808   case X86::COND_NP:
3809     return true;
3810   }
3811 }
3812
3813 /// isFPImmLegal - Returns true if the target can instruction select the
3814 /// specified FP immediate natively. If false, the legalizer will
3815 /// materialize the FP immediate as a load from a constant pool.
3816 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3817   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3818     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3819       return true;
3820   }
3821   return false;
3822 }
3823
3824 /// \brief Returns true if it is beneficial to convert a load of a constant
3825 /// to just the constant itself.
3826 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3827                                                           Type *Ty) const {
3828   assert(Ty->isIntegerTy());
3829
3830   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3831   if (BitSize == 0 || BitSize > 64)
3832     return false;
3833   return true;
3834 }
3835
3836 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3837 /// the specified range (L, H].
3838 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3839   return (Val < 0) || (Val >= Low && Val < Hi);
3840 }
3841
3842 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3843 /// specified value.
3844 static bool isUndefOrEqual(int Val, int CmpVal) {
3845   return (Val < 0 || Val == CmpVal);
3846 }
3847
3848 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3849 /// from position Pos and ending in Pos+Size, falls within the specified
3850 /// sequential range (L, L+Pos]. or is undef.
3851 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3852                                        unsigned Pos, unsigned Size, int Low) {
3853   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3854     if (!isUndefOrEqual(Mask[i], Low))
3855       return false;
3856   return true;
3857 }
3858
3859 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3860 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3861 /// the second operand.
3862 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3863   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3864     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3865   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3866     return (Mask[0] < 2 && Mask[1] < 2);
3867   return false;
3868 }
3869
3870 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3871 /// is suitable for input to PSHUFHW.
3872 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3873   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3874     return false;
3875
3876   // Lower quadword copied in order or undef.
3877   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3878     return false;
3879
3880   // Upper quadword shuffled.
3881   for (unsigned i = 4; i != 8; ++i)
3882     if (!isUndefOrInRange(Mask[i], 4, 8))
3883       return false;
3884
3885   if (VT == MVT::v16i16) {
3886     // Lower quadword copied in order or undef.
3887     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3888       return false;
3889
3890     // Upper quadword shuffled.
3891     for (unsigned i = 12; i != 16; ++i)
3892       if (!isUndefOrInRange(Mask[i], 12, 16))
3893         return false;
3894   }
3895
3896   return true;
3897 }
3898
3899 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3900 /// is suitable for input to PSHUFLW.
3901 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3902   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3903     return false;
3904
3905   // Upper quadword copied in order.
3906   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3907     return false;
3908
3909   // Lower quadword shuffled.
3910   for (unsigned i = 0; i != 4; ++i)
3911     if (!isUndefOrInRange(Mask[i], 0, 4))
3912       return false;
3913
3914   if (VT == MVT::v16i16) {
3915     // Upper quadword copied in order.
3916     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3917       return false;
3918
3919     // Lower quadword shuffled.
3920     for (unsigned i = 8; i != 12; ++i)
3921       if (!isUndefOrInRange(Mask[i], 8, 12))
3922         return false;
3923   }
3924
3925   return true;
3926 }
3927
3928 /// \brief Return true if the mask specifies a shuffle of elements that is
3929 /// suitable for input to intralane (palignr) or interlane (valign) vector
3930 /// right-shift.
3931 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3932   unsigned NumElts = VT.getVectorNumElements();
3933   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3934   unsigned NumLaneElts = NumElts/NumLanes;
3935
3936   // Do not handle 64-bit element shuffles with palignr.
3937   if (NumLaneElts == 2)
3938     return false;
3939
3940   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3941     unsigned i;
3942     for (i = 0; i != NumLaneElts; ++i) {
3943       if (Mask[i+l] >= 0)
3944         break;
3945     }
3946
3947     // Lane is all undef, go to next lane
3948     if (i == NumLaneElts)
3949       continue;
3950
3951     int Start = Mask[i+l];
3952
3953     // Make sure its in this lane in one of the sources
3954     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3955         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3956       return false;
3957
3958     // If not lane 0, then we must match lane 0
3959     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3960       return false;
3961
3962     // Correct second source to be contiguous with first source
3963     if (Start >= (int)NumElts)
3964       Start -= NumElts - NumLaneElts;
3965
3966     // Make sure we're shifting in the right direction.
3967     if (Start <= (int)(i+l))
3968       return false;
3969
3970     Start -= i;
3971
3972     // Check the rest of the elements to see if they are consecutive.
3973     for (++i; i != NumLaneElts; ++i) {
3974       int Idx = Mask[i+l];
3975
3976       // Make sure its in this lane
3977       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3978           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3979         return false;
3980
3981       // If not lane 0, then we must match lane 0
3982       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3983         return false;
3984
3985       if (Idx >= (int)NumElts)
3986         Idx -= NumElts - NumLaneElts;
3987
3988       if (!isUndefOrEqual(Idx, Start+i))
3989         return false;
3990
3991     }
3992   }
3993
3994   return true;
3995 }
3996
3997 /// \brief Return true if the node specifies a shuffle of elements that is
3998 /// suitable for input to PALIGNR.
3999 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4000                           const X86Subtarget *Subtarget) {
4001   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4002       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4003       VT.is512BitVector())
4004     // FIXME: Add AVX512BW.
4005     return false;
4006
4007   return isAlignrMask(Mask, VT, false);
4008 }
4009
4010 /// \brief Return true if the node specifies a shuffle of elements that is
4011 /// suitable for input to VALIGN.
4012 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4013                           const X86Subtarget *Subtarget) {
4014   // FIXME: Add AVX512VL.
4015   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4016     return false;
4017   return isAlignrMask(Mask, VT, true);
4018 }
4019
4020 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4021 /// the two vector operands have swapped position.
4022 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4023                                      unsigned NumElems) {
4024   for (unsigned i = 0; i != NumElems; ++i) {
4025     int idx = Mask[i];
4026     if (idx < 0)
4027       continue;
4028     else if (idx < (int)NumElems)
4029       Mask[i] = idx + NumElems;
4030     else
4031       Mask[i] = idx - NumElems;
4032   }
4033 }
4034
4035 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4036 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4037 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4038 /// reverse of what x86 shuffles want.
4039 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4040
4041   unsigned NumElems = VT.getVectorNumElements();
4042   unsigned NumLanes = VT.getSizeInBits()/128;
4043   unsigned NumLaneElems = NumElems/NumLanes;
4044
4045   if (NumLaneElems != 2 && NumLaneElems != 4)
4046     return false;
4047
4048   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4049   bool symetricMaskRequired =
4050     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4051
4052   // VSHUFPSY divides the resulting vector into 4 chunks.
4053   // The sources are also splitted into 4 chunks, and each destination
4054   // chunk must come from a different source chunk.
4055   //
4056   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4057   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4058   //
4059   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4060   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4061   //
4062   // VSHUFPDY divides the resulting vector into 4 chunks.
4063   // The sources are also splitted into 4 chunks, and each destination
4064   // chunk must come from a different source chunk.
4065   //
4066   //  SRC1 =>      X3       X2       X1       X0
4067   //  SRC2 =>      Y3       Y2       Y1       Y0
4068   //
4069   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4070   //
4071   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4072   unsigned HalfLaneElems = NumLaneElems/2;
4073   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4074     for (unsigned i = 0; i != NumLaneElems; ++i) {
4075       int Idx = Mask[i+l];
4076       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4077       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4078         return false;
4079       // For VSHUFPSY, the mask of the second half must be the same as the
4080       // first but with the appropriate offsets. This works in the same way as
4081       // VPERMILPS works with masks.
4082       if (!symetricMaskRequired || Idx < 0)
4083         continue;
4084       if (MaskVal[i] < 0) {
4085         MaskVal[i] = Idx - l;
4086         continue;
4087       }
4088       if ((signed)(Idx - l) != MaskVal[i])
4089         return false;
4090     }
4091   }
4092
4093   return true;
4094 }
4095
4096 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4097 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4098 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4099   if (!VT.is128BitVector())
4100     return false;
4101
4102   unsigned NumElems = VT.getVectorNumElements();
4103
4104   if (NumElems != 4)
4105     return false;
4106
4107   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4108   return isUndefOrEqual(Mask[0], 6) &&
4109          isUndefOrEqual(Mask[1], 7) &&
4110          isUndefOrEqual(Mask[2], 2) &&
4111          isUndefOrEqual(Mask[3], 3);
4112 }
4113
4114 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4115 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4116 /// <2, 3, 2, 3>
4117 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4118   if (!VT.is128BitVector())
4119     return false;
4120
4121   unsigned NumElems = VT.getVectorNumElements();
4122
4123   if (NumElems != 4)
4124     return false;
4125
4126   return isUndefOrEqual(Mask[0], 2) &&
4127          isUndefOrEqual(Mask[1], 3) &&
4128          isUndefOrEqual(Mask[2], 2) &&
4129          isUndefOrEqual(Mask[3], 3);
4130 }
4131
4132 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4133 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4134 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4135   if (!VT.is128BitVector())
4136     return false;
4137
4138   unsigned NumElems = VT.getVectorNumElements();
4139
4140   if (NumElems != 2 && NumElems != 4)
4141     return false;
4142
4143   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4144     if (!isUndefOrEqual(Mask[i], i + NumElems))
4145       return false;
4146
4147   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4148     if (!isUndefOrEqual(Mask[i], i))
4149       return false;
4150
4151   return true;
4152 }
4153
4154 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4155 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4156 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4157   if (!VT.is128BitVector())
4158     return false;
4159
4160   unsigned NumElems = VT.getVectorNumElements();
4161
4162   if (NumElems != 2 && NumElems != 4)
4163     return false;
4164
4165   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4166     if (!isUndefOrEqual(Mask[i], i))
4167       return false;
4168
4169   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4170     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4171       return false;
4172
4173   return true;
4174 }
4175
4176 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4177 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4178 /// i. e: If all but one element come from the same vector.
4179 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4180   // TODO: Deal with AVX's VINSERTPS
4181   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4182     return false;
4183
4184   unsigned CorrectPosV1 = 0;
4185   unsigned CorrectPosV2 = 0;
4186   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4187     if (Mask[i] == -1) {
4188       ++CorrectPosV1;
4189       ++CorrectPosV2;
4190       continue;
4191     }
4192
4193     if (Mask[i] == i)
4194       ++CorrectPosV1;
4195     else if (Mask[i] == i + 4)
4196       ++CorrectPosV2;
4197   }
4198
4199   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4200     // We have 3 elements (undefs count as elements from any vector) from one
4201     // vector, and one from another.
4202     return true;
4203
4204   return false;
4205 }
4206
4207 //
4208 // Some special combinations that can be optimized.
4209 //
4210 static
4211 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4212                                SelectionDAG &DAG) {
4213   MVT VT = SVOp->getSimpleValueType(0);
4214   SDLoc dl(SVOp);
4215
4216   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4217     return SDValue();
4218
4219   ArrayRef<int> Mask = SVOp->getMask();
4220
4221   // These are the special masks that may be optimized.
4222   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4223   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4224   bool MatchEvenMask = true;
4225   bool MatchOddMask  = true;
4226   for (int i=0; i<8; ++i) {
4227     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4228       MatchEvenMask = false;
4229     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4230       MatchOddMask = false;
4231   }
4232
4233   if (!MatchEvenMask && !MatchOddMask)
4234     return SDValue();
4235
4236   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4237
4238   SDValue Op0 = SVOp->getOperand(0);
4239   SDValue Op1 = SVOp->getOperand(1);
4240
4241   if (MatchEvenMask) {
4242     // Shift the second operand right to 32 bits.
4243     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4244     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4245   } else {
4246     // Shift the first operand left to 32 bits.
4247     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4248     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4249   }
4250   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4251   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4252 }
4253
4254 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4255 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4256 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4257                          bool HasInt256, bool V2IsSplat = false) {
4258
4259   assert(VT.getSizeInBits() >= 128 &&
4260          "Unsupported vector type for unpckl");
4261
4262   unsigned NumElts = VT.getVectorNumElements();
4263   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4264       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4265     return false;
4266
4267   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4268          "Unsupported vector type for unpckh");
4269
4270   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4271   unsigned NumLanes = VT.getSizeInBits()/128;
4272   unsigned NumLaneElts = NumElts/NumLanes;
4273
4274   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4275     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4276       int BitI  = Mask[l+i];
4277       int BitI1 = Mask[l+i+1];
4278       if (!isUndefOrEqual(BitI, j))
4279         return false;
4280       if (V2IsSplat) {
4281         if (!isUndefOrEqual(BitI1, NumElts))
4282           return false;
4283       } else {
4284         if (!isUndefOrEqual(BitI1, j + NumElts))
4285           return false;
4286       }
4287     }
4288   }
4289
4290   return true;
4291 }
4292
4293 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4294 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4295 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4296                          bool HasInt256, bool V2IsSplat = false) {
4297   assert(VT.getSizeInBits() >= 128 &&
4298          "Unsupported vector type for unpckh");
4299
4300   unsigned NumElts = VT.getVectorNumElements();
4301   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4302       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4303     return false;
4304
4305   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4306          "Unsupported vector type for unpckh");
4307
4308   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4309   unsigned NumLanes = VT.getSizeInBits()/128;
4310   unsigned NumLaneElts = NumElts/NumLanes;
4311
4312   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4313     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4314       int BitI  = Mask[l+i];
4315       int BitI1 = Mask[l+i+1];
4316       if (!isUndefOrEqual(BitI, j))
4317         return false;
4318       if (V2IsSplat) {
4319         if (isUndefOrEqual(BitI1, NumElts))
4320           return false;
4321       } else {
4322         if (!isUndefOrEqual(BitI1, j+NumElts))
4323           return false;
4324       }
4325     }
4326   }
4327   return true;
4328 }
4329
4330 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4331 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4332 /// <0, 0, 1, 1>
4333 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4334   unsigned NumElts = VT.getVectorNumElements();
4335   bool Is256BitVec = VT.is256BitVector();
4336
4337   if (VT.is512BitVector())
4338     return false;
4339   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4340          "Unsupported vector type for unpckh");
4341
4342   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4343       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4344     return false;
4345
4346   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4347   // FIXME: Need a better way to get rid of this, there's no latency difference
4348   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4349   // the former later. We should also remove the "_undef" special mask.
4350   if (NumElts == 4 && Is256BitVec)
4351     return false;
4352
4353   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4354   // independently on 128-bit lanes.
4355   unsigned NumLanes = VT.getSizeInBits()/128;
4356   unsigned NumLaneElts = NumElts/NumLanes;
4357
4358   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4359     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4360       int BitI  = Mask[l+i];
4361       int BitI1 = Mask[l+i+1];
4362
4363       if (!isUndefOrEqual(BitI, j))
4364         return false;
4365       if (!isUndefOrEqual(BitI1, j))
4366         return false;
4367     }
4368   }
4369
4370   return true;
4371 }
4372
4373 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4374 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4375 /// <2, 2, 3, 3>
4376 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4377   unsigned NumElts = VT.getVectorNumElements();
4378
4379   if (VT.is512BitVector())
4380     return false;
4381
4382   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4383          "Unsupported vector type for unpckh");
4384
4385   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4386       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4387     return false;
4388
4389   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4390   // independently on 128-bit lanes.
4391   unsigned NumLanes = VT.getSizeInBits()/128;
4392   unsigned NumLaneElts = NumElts/NumLanes;
4393
4394   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4395     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4396       int BitI  = Mask[l+i];
4397       int BitI1 = Mask[l+i+1];
4398       if (!isUndefOrEqual(BitI, j))
4399         return false;
4400       if (!isUndefOrEqual(BitI1, j))
4401         return false;
4402     }
4403   }
4404   return true;
4405 }
4406
4407 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4408 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4409 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4410   if (!VT.is512BitVector())
4411     return false;
4412
4413   unsigned NumElts = VT.getVectorNumElements();
4414   unsigned HalfSize = NumElts/2;
4415   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4416     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4417       *Imm = 1;
4418       return true;
4419     }
4420   }
4421   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4422     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4423       *Imm = 0;
4424       return true;
4425     }
4426   }
4427   return false;
4428 }
4429
4430 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4431 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4432 /// MOVSD, and MOVD, i.e. setting the lowest element.
4433 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4434   if (VT.getVectorElementType().getSizeInBits() < 32)
4435     return false;
4436   if (!VT.is128BitVector())
4437     return false;
4438
4439   unsigned NumElts = VT.getVectorNumElements();
4440
4441   if (!isUndefOrEqual(Mask[0], NumElts))
4442     return false;
4443
4444   for (unsigned i = 1; i != NumElts; ++i)
4445     if (!isUndefOrEqual(Mask[i], i))
4446       return false;
4447
4448   return true;
4449 }
4450
4451 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4452 /// as permutations between 128-bit chunks or halves. As an example: this
4453 /// shuffle bellow:
4454 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4455 /// The first half comes from the second half of V1 and the second half from the
4456 /// the second half of V2.
4457 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4458   if (!HasFp256 || !VT.is256BitVector())
4459     return false;
4460
4461   // The shuffle result is divided into half A and half B. In total the two
4462   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4463   // B must come from C, D, E or F.
4464   unsigned HalfSize = VT.getVectorNumElements()/2;
4465   bool MatchA = false, MatchB = false;
4466
4467   // Check if A comes from one of C, D, E, F.
4468   for (unsigned Half = 0; Half != 4; ++Half) {
4469     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4470       MatchA = true;
4471       break;
4472     }
4473   }
4474
4475   // Check if B comes from one of C, D, E, F.
4476   for (unsigned Half = 0; Half != 4; ++Half) {
4477     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4478       MatchB = true;
4479       break;
4480     }
4481   }
4482
4483   return MatchA && MatchB;
4484 }
4485
4486 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4487 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4488 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4489   MVT VT = SVOp->getSimpleValueType(0);
4490
4491   unsigned HalfSize = VT.getVectorNumElements()/2;
4492
4493   unsigned FstHalf = 0, SndHalf = 0;
4494   for (unsigned i = 0; i < HalfSize; ++i) {
4495     if (SVOp->getMaskElt(i) > 0) {
4496       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4497       break;
4498     }
4499   }
4500   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4501     if (SVOp->getMaskElt(i) > 0) {
4502       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4503       break;
4504     }
4505   }
4506
4507   return (FstHalf | (SndHalf << 4));
4508 }
4509
4510 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4511 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4512   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4513   if (EltSize < 32)
4514     return false;
4515
4516   unsigned NumElts = VT.getVectorNumElements();
4517   Imm8 = 0;
4518   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4519     for (unsigned i = 0; i != NumElts; ++i) {
4520       if (Mask[i] < 0)
4521         continue;
4522       Imm8 |= Mask[i] << (i*2);
4523     }
4524     return true;
4525   }
4526
4527   unsigned LaneSize = 4;
4528   SmallVector<int, 4> MaskVal(LaneSize, -1);
4529
4530   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4531     for (unsigned i = 0; i != LaneSize; ++i) {
4532       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4533         return false;
4534       if (Mask[i+l] < 0)
4535         continue;
4536       if (MaskVal[i] < 0) {
4537         MaskVal[i] = Mask[i+l] - l;
4538         Imm8 |= MaskVal[i] << (i*2);
4539         continue;
4540       }
4541       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4542         return false;
4543     }
4544   }
4545   return true;
4546 }
4547
4548 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4549 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4550 /// Note that VPERMIL mask matching is different depending whether theunderlying
4551 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4552 /// to the same elements of the low, but to the higher half of the source.
4553 /// In VPERMILPD the two lanes could be shuffled independently of each other
4554 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4555 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4556   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4557   if (VT.getSizeInBits() < 256 || EltSize < 32)
4558     return false;
4559   bool symetricMaskRequired = (EltSize == 32);
4560   unsigned NumElts = VT.getVectorNumElements();
4561
4562   unsigned NumLanes = VT.getSizeInBits()/128;
4563   unsigned LaneSize = NumElts/NumLanes;
4564   // 2 or 4 elements in one lane
4565
4566   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4567   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4568     for (unsigned i = 0; i != LaneSize; ++i) {
4569       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4570         return false;
4571       if (symetricMaskRequired) {
4572         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4573           ExpectedMaskVal[i] = Mask[i+l] - l;
4574           continue;
4575         }
4576         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4577           return false;
4578       }
4579     }
4580   }
4581   return true;
4582 }
4583
4584 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4585 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4586 /// element of vector 2 and the other elements to come from vector 1 in order.
4587 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4588                                bool V2IsSplat = false, bool V2IsUndef = false) {
4589   if (!VT.is128BitVector())
4590     return false;
4591
4592   unsigned NumOps = VT.getVectorNumElements();
4593   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4594     return false;
4595
4596   if (!isUndefOrEqual(Mask[0], 0))
4597     return false;
4598
4599   for (unsigned i = 1; i != NumOps; ++i)
4600     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4601           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4602           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4603       return false;
4604
4605   return true;
4606 }
4607
4608 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4609 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4610 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4611 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4612                            const X86Subtarget *Subtarget) {
4613   if (!Subtarget->hasSSE3())
4614     return false;
4615
4616   unsigned NumElems = VT.getVectorNumElements();
4617
4618   if ((VT.is128BitVector() && NumElems != 4) ||
4619       (VT.is256BitVector() && NumElems != 8) ||
4620       (VT.is512BitVector() && NumElems != 16))
4621     return false;
4622
4623   // "i+1" is the value the indexed mask element must have
4624   for (unsigned i = 0; i != NumElems; i += 2)
4625     if (!isUndefOrEqual(Mask[i], i+1) ||
4626         !isUndefOrEqual(Mask[i+1], i+1))
4627       return false;
4628
4629   return true;
4630 }
4631
4632 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4633 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4634 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4635 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4636                            const X86Subtarget *Subtarget) {
4637   if (!Subtarget->hasSSE3())
4638     return false;
4639
4640   unsigned NumElems = VT.getVectorNumElements();
4641
4642   if ((VT.is128BitVector() && NumElems != 4) ||
4643       (VT.is256BitVector() && NumElems != 8) ||
4644       (VT.is512BitVector() && NumElems != 16))
4645     return false;
4646
4647   // "i" is the value the indexed mask element must have
4648   for (unsigned i = 0; i != NumElems; i += 2)
4649     if (!isUndefOrEqual(Mask[i], i) ||
4650         !isUndefOrEqual(Mask[i+1], i))
4651       return false;
4652
4653   return true;
4654 }
4655
4656 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4657 /// specifies a shuffle of elements that is suitable for input to 256-bit
4658 /// version of MOVDDUP.
4659 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4660   if (!HasFp256 || !VT.is256BitVector())
4661     return false;
4662
4663   unsigned NumElts = VT.getVectorNumElements();
4664   if (NumElts != 4)
4665     return false;
4666
4667   for (unsigned i = 0; i != NumElts/2; ++i)
4668     if (!isUndefOrEqual(Mask[i], 0))
4669       return false;
4670   for (unsigned i = NumElts/2; i != NumElts; ++i)
4671     if (!isUndefOrEqual(Mask[i], NumElts/2))
4672       return false;
4673   return true;
4674 }
4675
4676 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4677 /// specifies a shuffle of elements that is suitable for input to 128-bit
4678 /// version of MOVDDUP.
4679 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4680   if (!VT.is128BitVector())
4681     return false;
4682
4683   unsigned e = VT.getVectorNumElements() / 2;
4684   for (unsigned i = 0; i != e; ++i)
4685     if (!isUndefOrEqual(Mask[i], i))
4686       return false;
4687   for (unsigned i = 0; i != e; ++i)
4688     if (!isUndefOrEqual(Mask[e+i], i))
4689       return false;
4690   return true;
4691 }
4692
4693 /// isVEXTRACTIndex - Return true if the specified
4694 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4695 /// suitable for instruction that extract 128 or 256 bit vectors
4696 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4697   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4698   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4699     return false;
4700
4701   // The index should be aligned on a vecWidth-bit boundary.
4702   uint64_t Index =
4703     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4704
4705   MVT VT = N->getSimpleValueType(0);
4706   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4707   bool Result = (Index * ElSize) % vecWidth == 0;
4708
4709   return Result;
4710 }
4711
4712 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4713 /// operand specifies a subvector insert that is suitable for input to
4714 /// insertion of 128 or 256-bit subvectors
4715 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4716   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4717   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4718     return false;
4719   // The index should be aligned on a vecWidth-bit boundary.
4720   uint64_t Index =
4721     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4722
4723   MVT VT = N->getSimpleValueType(0);
4724   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4725   bool Result = (Index * ElSize) % vecWidth == 0;
4726
4727   return Result;
4728 }
4729
4730 bool X86::isVINSERT128Index(SDNode *N) {
4731   return isVINSERTIndex(N, 128);
4732 }
4733
4734 bool X86::isVINSERT256Index(SDNode *N) {
4735   return isVINSERTIndex(N, 256);
4736 }
4737
4738 bool X86::isVEXTRACT128Index(SDNode *N) {
4739   return isVEXTRACTIndex(N, 128);
4740 }
4741
4742 bool X86::isVEXTRACT256Index(SDNode *N) {
4743   return isVEXTRACTIndex(N, 256);
4744 }
4745
4746 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4747 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4748 /// Handles 128-bit and 256-bit.
4749 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4750   MVT VT = N->getSimpleValueType(0);
4751
4752   assert((VT.getSizeInBits() >= 128) &&
4753          "Unsupported vector type for PSHUF/SHUFP");
4754
4755   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4756   // independently on 128-bit lanes.
4757   unsigned NumElts = VT.getVectorNumElements();
4758   unsigned NumLanes = VT.getSizeInBits()/128;
4759   unsigned NumLaneElts = NumElts/NumLanes;
4760
4761   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4762          "Only supports 2, 4 or 8 elements per lane");
4763
4764   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4765   unsigned Mask = 0;
4766   for (unsigned i = 0; i != NumElts; ++i) {
4767     int Elt = N->getMaskElt(i);
4768     if (Elt < 0) continue;
4769     Elt &= NumLaneElts - 1;
4770     unsigned ShAmt = (i << Shift) % 8;
4771     Mask |= Elt << ShAmt;
4772   }
4773
4774   return Mask;
4775 }
4776
4777 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4778 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4779 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4780   MVT VT = N->getSimpleValueType(0);
4781
4782   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4783          "Unsupported vector type for PSHUFHW");
4784
4785   unsigned NumElts = VT.getVectorNumElements();
4786
4787   unsigned Mask = 0;
4788   for (unsigned l = 0; l != NumElts; l += 8) {
4789     // 8 nodes per lane, but we only care about the last 4.
4790     for (unsigned i = 0; i < 4; ++i) {
4791       int Elt = N->getMaskElt(l+i+4);
4792       if (Elt < 0) continue;
4793       Elt &= 0x3; // only 2-bits.
4794       Mask |= Elt << (i * 2);
4795     }
4796   }
4797
4798   return Mask;
4799 }
4800
4801 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4802 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4803 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4804   MVT VT = N->getSimpleValueType(0);
4805
4806   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4807          "Unsupported vector type for PSHUFHW");
4808
4809   unsigned NumElts = VT.getVectorNumElements();
4810
4811   unsigned Mask = 0;
4812   for (unsigned l = 0; l != NumElts; l += 8) {
4813     // 8 nodes per lane, but we only care about the first 4.
4814     for (unsigned i = 0; i < 4; ++i) {
4815       int Elt = N->getMaskElt(l+i);
4816       if (Elt < 0) continue;
4817       Elt &= 0x3; // only 2-bits
4818       Mask |= Elt << (i * 2);
4819     }
4820   }
4821
4822   return Mask;
4823 }
4824
4825 /// \brief Return the appropriate immediate to shuffle the specified
4826 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4827 /// VALIGN (if Interlane is true) instructions.
4828 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4829                                            bool InterLane) {
4830   MVT VT = SVOp->getSimpleValueType(0);
4831   unsigned EltSize = InterLane ? 1 :
4832     VT.getVectorElementType().getSizeInBits() >> 3;
4833
4834   unsigned NumElts = VT.getVectorNumElements();
4835   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4836   unsigned NumLaneElts = NumElts/NumLanes;
4837
4838   int Val = 0;
4839   unsigned i;
4840   for (i = 0; i != NumElts; ++i) {
4841     Val = SVOp->getMaskElt(i);
4842     if (Val >= 0)
4843       break;
4844   }
4845   if (Val >= (int)NumElts)
4846     Val -= NumElts - NumLaneElts;
4847
4848   assert(Val - i > 0 && "PALIGNR imm should be positive");
4849   return (Val - i) * EltSize;
4850 }
4851
4852 /// \brief Return the appropriate immediate to shuffle the specified
4853 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4854 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4855   return getShuffleAlignrImmediate(SVOp, false);
4856 }
4857
4858 /// \brief Return the appropriate immediate to shuffle the specified
4859 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4860 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4861   return getShuffleAlignrImmediate(SVOp, true);
4862 }
4863
4864
4865 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4866   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4867   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4868     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4869
4870   uint64_t Index =
4871     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4872
4873   MVT VecVT = N->getOperand(0).getSimpleValueType();
4874   MVT ElVT = VecVT.getVectorElementType();
4875
4876   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4877   return Index / NumElemsPerChunk;
4878 }
4879
4880 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4881   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4882   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4883     llvm_unreachable("Illegal insert subvector for VINSERT");
4884
4885   uint64_t Index =
4886     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4887
4888   MVT VecVT = N->getSimpleValueType(0);
4889   MVT ElVT = VecVT.getVectorElementType();
4890
4891   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4892   return Index / NumElemsPerChunk;
4893 }
4894
4895 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4896 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4897 /// and VINSERTI128 instructions.
4898 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4899   return getExtractVEXTRACTImmediate(N, 128);
4900 }
4901
4902 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4903 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4904 /// and VINSERTI64x4 instructions.
4905 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4906   return getExtractVEXTRACTImmediate(N, 256);
4907 }
4908
4909 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4910 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4911 /// and VINSERTI128 instructions.
4912 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4913   return getInsertVINSERTImmediate(N, 128);
4914 }
4915
4916 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4917 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4918 /// and VINSERTI64x4 instructions.
4919 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4920   return getInsertVINSERTImmediate(N, 256);
4921 }
4922
4923 /// isZero - Returns true if Elt is a constant integer zero
4924 static bool isZero(SDValue V) {
4925   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4926   return C && C->isNullValue();
4927 }
4928
4929 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4930 /// constant +0.0.
4931 bool X86::isZeroNode(SDValue Elt) {
4932   if (isZero(Elt))
4933     return true;
4934   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4935     return CFP->getValueAPF().isPosZero();
4936   return false;
4937 }
4938
4939 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4940 /// match movhlps. The lower half elements should come from upper half of
4941 /// V1 (and in order), and the upper half elements should come from the upper
4942 /// half of V2 (and in order).
4943 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4944   if (!VT.is128BitVector())
4945     return false;
4946   if (VT.getVectorNumElements() != 4)
4947     return false;
4948   for (unsigned i = 0, e = 2; i != e; ++i)
4949     if (!isUndefOrEqual(Mask[i], i+2))
4950       return false;
4951   for (unsigned i = 2; i != 4; ++i)
4952     if (!isUndefOrEqual(Mask[i], i+4))
4953       return false;
4954   return true;
4955 }
4956
4957 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4958 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4959 /// required.
4960 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4961   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4962     return false;
4963   N = N->getOperand(0).getNode();
4964   if (!ISD::isNON_EXTLoad(N))
4965     return false;
4966   if (LD)
4967     *LD = cast<LoadSDNode>(N);
4968   return true;
4969 }
4970
4971 // Test whether the given value is a vector value which will be legalized
4972 // into a load.
4973 static bool WillBeConstantPoolLoad(SDNode *N) {
4974   if (N->getOpcode() != ISD::BUILD_VECTOR)
4975     return false;
4976
4977   // Check for any non-constant elements.
4978   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4979     switch (N->getOperand(i).getNode()->getOpcode()) {
4980     case ISD::UNDEF:
4981     case ISD::ConstantFP:
4982     case ISD::Constant:
4983       break;
4984     default:
4985       return false;
4986     }
4987
4988   // Vectors of all-zeros and all-ones are materialized with special
4989   // instructions rather than being loaded.
4990   return !ISD::isBuildVectorAllZeros(N) &&
4991          !ISD::isBuildVectorAllOnes(N);
4992 }
4993
4994 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4995 /// match movlp{s|d}. The lower half elements should come from lower half of
4996 /// V1 (and in order), and the upper half elements should come from the upper
4997 /// half of V2 (and in order). And since V1 will become the source of the
4998 /// MOVLP, it must be either a vector load or a scalar load to vector.
4999 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5000                                ArrayRef<int> Mask, MVT VT) {
5001   if (!VT.is128BitVector())
5002     return false;
5003
5004   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5005     return false;
5006   // Is V2 is a vector load, don't do this transformation. We will try to use
5007   // load folding shufps op.
5008   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5009     return false;
5010
5011   unsigned NumElems = VT.getVectorNumElements();
5012
5013   if (NumElems != 2 && NumElems != 4)
5014     return false;
5015   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5016     if (!isUndefOrEqual(Mask[i], i))
5017       return false;
5018   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5019     if (!isUndefOrEqual(Mask[i], i+NumElems))
5020       return false;
5021   return true;
5022 }
5023
5024 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5025 /// to an zero vector.
5026 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5027 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5028   SDValue V1 = N->getOperand(0);
5029   SDValue V2 = N->getOperand(1);
5030   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5031   for (unsigned i = 0; i != NumElems; ++i) {
5032     int Idx = N->getMaskElt(i);
5033     if (Idx >= (int)NumElems) {
5034       unsigned Opc = V2.getOpcode();
5035       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5036         continue;
5037       if (Opc != ISD::BUILD_VECTOR ||
5038           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5039         return false;
5040     } else if (Idx >= 0) {
5041       unsigned Opc = V1.getOpcode();
5042       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5043         continue;
5044       if (Opc != ISD::BUILD_VECTOR ||
5045           !X86::isZeroNode(V1.getOperand(Idx)))
5046         return false;
5047     }
5048   }
5049   return true;
5050 }
5051
5052 /// getZeroVector - Returns a vector of specified type with all zero elements.
5053 ///
5054 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5055                              SelectionDAG &DAG, SDLoc dl) {
5056   assert(VT.isVector() && "Expected a vector type");
5057
5058   // Always build SSE zero vectors as <4 x i32> bitcasted
5059   // to their dest type. This ensures they get CSE'd.
5060   SDValue Vec;
5061   if (VT.is128BitVector()) {  // SSE
5062     if (Subtarget->hasSSE2()) {  // SSE2
5063       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5064       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5065     } else { // SSE1
5066       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5067       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5068     }
5069   } else if (VT.is256BitVector()) { // AVX
5070     if (Subtarget->hasInt256()) { // AVX2
5071       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5072       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5073       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5074     } else {
5075       // 256-bit logic and arithmetic instructions in AVX are all
5076       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5077       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5078       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5079       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5080     }
5081   } else if (VT.is512BitVector()) { // AVX-512
5082       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5083       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5084                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5085       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5086   } else if (VT.getScalarType() == MVT::i1) {
5087     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5088     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5089     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5090     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5091   } else
5092     llvm_unreachable("Unexpected vector type");
5093
5094   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5095 }
5096
5097 /// getOnesVector - Returns a vector of specified type with all bits set.
5098 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5099 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5100 /// Then bitcast to their original type, ensuring they get CSE'd.
5101 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5102                              SDLoc dl) {
5103   assert(VT.isVector() && "Expected a vector type");
5104
5105   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5106   SDValue Vec;
5107   if (VT.is256BitVector()) {
5108     if (HasInt256) { // AVX2
5109       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5110       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5111     } else { // AVX
5112       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5113       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5114     }
5115   } else if (VT.is128BitVector()) {
5116     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5117   } else
5118     llvm_unreachable("Unexpected vector type");
5119
5120   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5121 }
5122
5123 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5124 /// that point to V2 points to its first element.
5125 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5126   for (unsigned i = 0; i != NumElems; ++i) {
5127     if (Mask[i] > (int)NumElems) {
5128       Mask[i] = NumElems;
5129     }
5130   }
5131 }
5132
5133 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5134 /// operation of specified width.
5135 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5136                        SDValue V2) {
5137   unsigned NumElems = VT.getVectorNumElements();
5138   SmallVector<int, 8> Mask;
5139   Mask.push_back(NumElems);
5140   for (unsigned i = 1; i != NumElems; ++i)
5141     Mask.push_back(i);
5142   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5143 }
5144
5145 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5146 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5147                           SDValue V2) {
5148   unsigned NumElems = VT.getVectorNumElements();
5149   SmallVector<int, 8> Mask;
5150   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5151     Mask.push_back(i);
5152     Mask.push_back(i + NumElems);
5153   }
5154   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5155 }
5156
5157 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5158 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5159                           SDValue V2) {
5160   unsigned NumElems = VT.getVectorNumElements();
5161   SmallVector<int, 8> Mask;
5162   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5163     Mask.push_back(i + Half);
5164     Mask.push_back(i + NumElems + Half);
5165   }
5166   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5167 }
5168
5169 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5170 // a generic shuffle instruction because the target has no such instructions.
5171 // Generate shuffles which repeat i16 and i8 several times until they can be
5172 // represented by v4f32 and then be manipulated by target suported shuffles.
5173 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5174   MVT VT = V.getSimpleValueType();
5175   int NumElems = VT.getVectorNumElements();
5176   SDLoc dl(V);
5177
5178   while (NumElems > 4) {
5179     if (EltNo < NumElems/2) {
5180       V = getUnpackl(DAG, dl, VT, V, V);
5181     } else {
5182       V = getUnpackh(DAG, dl, VT, V, V);
5183       EltNo -= NumElems/2;
5184     }
5185     NumElems >>= 1;
5186   }
5187   return V;
5188 }
5189
5190 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5191 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5192   MVT VT = V.getSimpleValueType();
5193   SDLoc dl(V);
5194
5195   if (VT.is128BitVector()) {
5196     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5197     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5198     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5199                              &SplatMask[0]);
5200   } else if (VT.is256BitVector()) {
5201     // To use VPERMILPS to splat scalars, the second half of indicies must
5202     // refer to the higher part, which is a duplication of the lower one,
5203     // because VPERMILPS can only handle in-lane permutations.
5204     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5205                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5206
5207     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5208     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5209                              &SplatMask[0]);
5210   } else
5211     llvm_unreachable("Vector size not supported");
5212
5213   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5214 }
5215
5216 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5217 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5218   MVT SrcVT = SV->getSimpleValueType(0);
5219   SDValue V1 = SV->getOperand(0);
5220   SDLoc dl(SV);
5221
5222   int EltNo = SV->getSplatIndex();
5223   int NumElems = SrcVT.getVectorNumElements();
5224   bool Is256BitVec = SrcVT.is256BitVector();
5225
5226   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5227          "Unknown how to promote splat for type");
5228
5229   // Extract the 128-bit part containing the splat element and update
5230   // the splat element index when it refers to the higher register.
5231   if (Is256BitVec) {
5232     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5233     if (EltNo >= NumElems/2)
5234       EltNo -= NumElems/2;
5235   }
5236
5237   // All i16 and i8 vector types can't be used directly by a generic shuffle
5238   // instruction because the target has no such instruction. Generate shuffles
5239   // which repeat i16 and i8 several times until they fit in i32, and then can
5240   // be manipulated by target suported shuffles.
5241   MVT EltVT = SrcVT.getVectorElementType();
5242   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5243     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5244
5245   // Recreate the 256-bit vector and place the same 128-bit vector
5246   // into the low and high part. This is necessary because we want
5247   // to use VPERM* to shuffle the vectors
5248   if (Is256BitVec) {
5249     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5250   }
5251
5252   return getLegalSplat(DAG, V1, EltNo);
5253 }
5254
5255 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5256 /// vector of zero or undef vector.  This produces a shuffle where the low
5257 /// element of V2 is swizzled into the zero/undef vector, landing at element
5258 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5259 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5260                                            bool IsZero,
5261                                            const X86Subtarget *Subtarget,
5262                                            SelectionDAG &DAG) {
5263   MVT VT = V2.getSimpleValueType();
5264   SDValue V1 = IsZero
5265     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5266   unsigned NumElems = VT.getVectorNumElements();
5267   SmallVector<int, 16> MaskVec;
5268   for (unsigned i = 0; i != NumElems; ++i)
5269     // If this is the insertion idx, put the low elt of V2 here.
5270     MaskVec.push_back(i == Idx ? NumElems : i);
5271   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5272 }
5273
5274 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5275 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5276 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5277 /// shuffles which use a single input multiple times, and in those cases it will
5278 /// adjust the mask to only have indices within that single input.
5279 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5280                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5281   unsigned NumElems = VT.getVectorNumElements();
5282   SDValue ImmN;
5283
5284   IsUnary = false;
5285   bool IsFakeUnary = false;
5286   switch(N->getOpcode()) {
5287   case X86ISD::SHUFP:
5288     ImmN = N->getOperand(N->getNumOperands()-1);
5289     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5290     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5291     break;
5292   case X86ISD::UNPCKH:
5293     DecodeUNPCKHMask(VT, Mask);
5294     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5295     break;
5296   case X86ISD::UNPCKL:
5297     DecodeUNPCKLMask(VT, Mask);
5298     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5299     break;
5300   case X86ISD::MOVHLPS:
5301     DecodeMOVHLPSMask(NumElems, Mask);
5302     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5303     break;
5304   case X86ISD::MOVLHPS:
5305     DecodeMOVLHPSMask(NumElems, Mask);
5306     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5307     break;
5308   case X86ISD::PALIGNR:
5309     ImmN = N->getOperand(N->getNumOperands()-1);
5310     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5311     break;
5312   case X86ISD::PSHUFD:
5313   case X86ISD::VPERMILP:
5314     ImmN = N->getOperand(N->getNumOperands()-1);
5315     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5316     IsUnary = true;
5317     break;
5318   case X86ISD::PSHUFHW:
5319     ImmN = N->getOperand(N->getNumOperands()-1);
5320     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5321     IsUnary = true;
5322     break;
5323   case X86ISD::PSHUFLW:
5324     ImmN = N->getOperand(N->getNumOperands()-1);
5325     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5326     IsUnary = true;
5327     break;
5328   case X86ISD::PSHUFB: {
5329     IsUnary = true;
5330     SDValue MaskNode = N->getOperand(1);
5331     while (MaskNode->getOpcode() == ISD::BITCAST)
5332       MaskNode = MaskNode->getOperand(0);
5333
5334     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5335       // If we have a build-vector, then things are easy.
5336       EVT VT = MaskNode.getValueType();
5337       assert(VT.isVector() &&
5338              "Can't produce a non-vector with a build_vector!");
5339       if (!VT.isInteger())
5340         return false;
5341
5342       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5343
5344       SmallVector<uint64_t, 32> RawMask;
5345       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5346         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5347         if (!CN)
5348           return false;
5349         APInt MaskElement = CN->getAPIntValue();
5350
5351         // We now have to decode the element which could be any integer size and
5352         // extract each byte of it.
5353         for (int j = 0; j < NumBytesPerElement; ++j) {
5354           // Note that this is x86 and so always little endian: the low byte is
5355           // the first byte of the mask.
5356           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5357           MaskElement = MaskElement.lshr(8);
5358         }
5359       }
5360       DecodePSHUFBMask(RawMask, Mask);
5361       break;
5362     }
5363
5364     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5365     if (!MaskLoad)
5366       return false;
5367
5368     SDValue Ptr = MaskLoad->getBasePtr();
5369     if (Ptr->getOpcode() == X86ISD::Wrapper)
5370       Ptr = Ptr->getOperand(0);
5371
5372     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5373     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5374       return false;
5375
5376     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5377       // FIXME: Support AVX-512 here.
5378       if (!C->getType()->isVectorTy() ||
5379           (C->getNumElements() != 16 && C->getNumElements() != 32))
5380         return false;
5381
5382       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5383       DecodePSHUFBMask(C, Mask);
5384       break;
5385     }
5386
5387     return false;
5388   }
5389   case X86ISD::VPERMI:
5390     ImmN = N->getOperand(N->getNumOperands()-1);
5391     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5392     IsUnary = true;
5393     break;
5394   case X86ISD::MOVSS:
5395   case X86ISD::MOVSD: {
5396     // The index 0 always comes from the first element of the second source,
5397     // this is why MOVSS and MOVSD are used in the first place. The other
5398     // elements come from the other positions of the first source vector
5399     Mask.push_back(NumElems);
5400     for (unsigned i = 1; i != NumElems; ++i) {
5401       Mask.push_back(i);
5402     }
5403     break;
5404   }
5405   case X86ISD::VPERM2X128:
5406     ImmN = N->getOperand(N->getNumOperands()-1);
5407     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5408     if (Mask.empty()) return false;
5409     break;
5410   case X86ISD::MOVSLDUP:
5411     DecodeMOVSLDUPMask(VT, Mask);
5412     break;
5413   case X86ISD::MOVSHDUP:
5414     DecodeMOVSHDUPMask(VT, Mask);
5415     break;
5416   case X86ISD::MOVDDUP:
5417   case X86ISD::MOVLHPD:
5418   case X86ISD::MOVLPD:
5419   case X86ISD::MOVLPS:
5420     // Not yet implemented
5421     return false;
5422   default: llvm_unreachable("unknown target shuffle node");
5423   }
5424
5425   // If we have a fake unary shuffle, the shuffle mask is spread across two
5426   // inputs that are actually the same node. Re-map the mask to always point
5427   // into the first input.
5428   if (IsFakeUnary)
5429     for (int &M : Mask)
5430       if (M >= (int)Mask.size())
5431         M -= Mask.size();
5432
5433   return true;
5434 }
5435
5436 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5437 /// element of the result of the vector shuffle.
5438 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5439                                    unsigned Depth) {
5440   if (Depth == 6)
5441     return SDValue();  // Limit search depth.
5442
5443   SDValue V = SDValue(N, 0);
5444   EVT VT = V.getValueType();
5445   unsigned Opcode = V.getOpcode();
5446
5447   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5448   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5449     int Elt = SV->getMaskElt(Index);
5450
5451     if (Elt < 0)
5452       return DAG.getUNDEF(VT.getVectorElementType());
5453
5454     unsigned NumElems = VT.getVectorNumElements();
5455     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5456                                          : SV->getOperand(1);
5457     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5458   }
5459
5460   // Recurse into target specific vector shuffles to find scalars.
5461   if (isTargetShuffle(Opcode)) {
5462     MVT ShufVT = V.getSimpleValueType();
5463     unsigned NumElems = ShufVT.getVectorNumElements();
5464     SmallVector<int, 16> ShuffleMask;
5465     bool IsUnary;
5466
5467     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5468       return SDValue();
5469
5470     int Elt = ShuffleMask[Index];
5471     if (Elt < 0)
5472       return DAG.getUNDEF(ShufVT.getVectorElementType());
5473
5474     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5475                                          : N->getOperand(1);
5476     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5477                                Depth+1);
5478   }
5479
5480   // Actual nodes that may contain scalar elements
5481   if (Opcode == ISD::BITCAST) {
5482     V = V.getOperand(0);
5483     EVT SrcVT = V.getValueType();
5484     unsigned NumElems = VT.getVectorNumElements();
5485
5486     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5487       return SDValue();
5488   }
5489
5490   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5491     return (Index == 0) ? V.getOperand(0)
5492                         : DAG.getUNDEF(VT.getVectorElementType());
5493
5494   if (V.getOpcode() == ISD::BUILD_VECTOR)
5495     return V.getOperand(Index);
5496
5497   return SDValue();
5498 }
5499
5500 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5501 /// shuffle operation which come from a consecutively from a zero. The
5502 /// search can start in two different directions, from left or right.
5503 /// We count undefs as zeros until PreferredNum is reached.
5504 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5505                                          unsigned NumElems, bool ZerosFromLeft,
5506                                          SelectionDAG &DAG,
5507                                          unsigned PreferredNum = -1U) {
5508   unsigned NumZeros = 0;
5509   for (unsigned i = 0; i != NumElems; ++i) {
5510     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5511     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5512     if (!Elt.getNode())
5513       break;
5514
5515     if (X86::isZeroNode(Elt))
5516       ++NumZeros;
5517     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5518       NumZeros = std::min(NumZeros + 1, PreferredNum);
5519     else
5520       break;
5521   }
5522
5523   return NumZeros;
5524 }
5525
5526 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5527 /// correspond consecutively to elements from one of the vector operands,
5528 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5529 static
5530 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5531                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5532                               unsigned NumElems, unsigned &OpNum) {
5533   bool SeenV1 = false;
5534   bool SeenV2 = false;
5535
5536   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5537     int Idx = SVOp->getMaskElt(i);
5538     // Ignore undef indicies
5539     if (Idx < 0)
5540       continue;
5541
5542     if (Idx < (int)NumElems)
5543       SeenV1 = true;
5544     else
5545       SeenV2 = true;
5546
5547     // Only accept consecutive elements from the same vector
5548     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5549       return false;
5550   }
5551
5552   OpNum = SeenV1 ? 0 : 1;
5553   return true;
5554 }
5555
5556 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5557 /// logical left shift of a vector.
5558 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5559                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5560   unsigned NumElems =
5561     SVOp->getSimpleValueType(0).getVectorNumElements();
5562   unsigned NumZeros = getNumOfConsecutiveZeros(
5563       SVOp, NumElems, false /* check zeros from right */, DAG,
5564       SVOp->getMaskElt(0));
5565   unsigned OpSrc;
5566
5567   if (!NumZeros)
5568     return false;
5569
5570   // Considering the elements in the mask that are not consecutive zeros,
5571   // check if they consecutively come from only one of the source vectors.
5572   //
5573   //               V1 = {X, A, B, C}     0
5574   //                         \  \  \    /
5575   //   vector_shuffle V1, V2 <1, 2, 3, X>
5576   //
5577   if (!isShuffleMaskConsecutive(SVOp,
5578             0,                   // Mask Start Index
5579             NumElems-NumZeros,   // Mask End Index(exclusive)
5580             NumZeros,            // Where to start looking in the src vector
5581             NumElems,            // Number of elements in vector
5582             OpSrc))              // Which source operand ?
5583     return false;
5584
5585   isLeft = false;
5586   ShAmt = NumZeros;
5587   ShVal = SVOp->getOperand(OpSrc);
5588   return true;
5589 }
5590
5591 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5592 /// logical left shift of a vector.
5593 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5594                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5595   unsigned NumElems =
5596     SVOp->getSimpleValueType(0).getVectorNumElements();
5597   unsigned NumZeros = getNumOfConsecutiveZeros(
5598       SVOp, NumElems, true /* check zeros from left */, DAG,
5599       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5600   unsigned OpSrc;
5601
5602   if (!NumZeros)
5603     return false;
5604
5605   // Considering the elements in the mask that are not consecutive zeros,
5606   // check if they consecutively come from only one of the source vectors.
5607   //
5608   //                           0    { A, B, X, X } = V2
5609   //                          / \    /  /
5610   //   vector_shuffle V1, V2 <X, X, 4, 5>
5611   //
5612   if (!isShuffleMaskConsecutive(SVOp,
5613             NumZeros,     // Mask Start Index
5614             NumElems,     // Mask End Index(exclusive)
5615             0,            // Where to start looking in the src vector
5616             NumElems,     // Number of elements in vector
5617             OpSrc))       // Which source operand ?
5618     return false;
5619
5620   isLeft = true;
5621   ShAmt = NumZeros;
5622   ShVal = SVOp->getOperand(OpSrc);
5623   return true;
5624 }
5625
5626 /// isVectorShift - Returns true if the shuffle can be implemented as a
5627 /// logical left or right shift of a vector.
5628 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5629                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5630   // Although the logic below support any bitwidth size, there are no
5631   // shift instructions which handle more than 128-bit vectors.
5632   if (!SVOp->getSimpleValueType(0).is128BitVector())
5633     return false;
5634
5635   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5636       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5637     return true;
5638
5639   return false;
5640 }
5641
5642 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5643 ///
5644 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5645                                        unsigned NumNonZero, unsigned NumZero,
5646                                        SelectionDAG &DAG,
5647                                        const X86Subtarget* Subtarget,
5648                                        const TargetLowering &TLI) {
5649   if (NumNonZero > 8)
5650     return SDValue();
5651
5652   SDLoc dl(Op);
5653   SDValue V;
5654   bool First = true;
5655   for (unsigned i = 0; i < 16; ++i) {
5656     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5657     if (ThisIsNonZero && First) {
5658       if (NumZero)
5659         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5660       else
5661         V = DAG.getUNDEF(MVT::v8i16);
5662       First = false;
5663     }
5664
5665     if ((i & 1) != 0) {
5666       SDValue ThisElt, LastElt;
5667       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5668       if (LastIsNonZero) {
5669         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5670                               MVT::i16, Op.getOperand(i-1));
5671       }
5672       if (ThisIsNonZero) {
5673         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5674         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5675                               ThisElt, DAG.getConstant(8, MVT::i8));
5676         if (LastIsNonZero)
5677           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5678       } else
5679         ThisElt = LastElt;
5680
5681       if (ThisElt.getNode())
5682         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5683                         DAG.getIntPtrConstant(i/2));
5684     }
5685   }
5686
5687   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5688 }
5689
5690 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5691 ///
5692 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5693                                      unsigned NumNonZero, unsigned NumZero,
5694                                      SelectionDAG &DAG,
5695                                      const X86Subtarget* Subtarget,
5696                                      const TargetLowering &TLI) {
5697   if (NumNonZero > 4)
5698     return SDValue();
5699
5700   SDLoc dl(Op);
5701   SDValue V;
5702   bool First = true;
5703   for (unsigned i = 0; i < 8; ++i) {
5704     bool isNonZero = (NonZeros & (1 << i)) != 0;
5705     if (isNonZero) {
5706       if (First) {
5707         if (NumZero)
5708           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5709         else
5710           V = DAG.getUNDEF(MVT::v8i16);
5711         First = false;
5712       }
5713       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5714                       MVT::v8i16, V, Op.getOperand(i),
5715                       DAG.getIntPtrConstant(i));
5716     }
5717   }
5718
5719   return V;
5720 }
5721
5722 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5723 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5724                                      unsigned NonZeros, unsigned NumNonZero,
5725                                      unsigned NumZero, SelectionDAG &DAG,
5726                                      const X86Subtarget *Subtarget,
5727                                      const TargetLowering &TLI) {
5728   // We know there's at least one non-zero element
5729   unsigned FirstNonZeroIdx = 0;
5730   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5731   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5732          X86::isZeroNode(FirstNonZero)) {
5733     ++FirstNonZeroIdx;
5734     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5735   }
5736
5737   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5738       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5739     return SDValue();
5740
5741   SDValue V = FirstNonZero.getOperand(0);
5742   MVT VVT = V.getSimpleValueType();
5743   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5744     return SDValue();
5745
5746   unsigned FirstNonZeroDst =
5747       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5748   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5749   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5750   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5751
5752   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5753     SDValue Elem = Op.getOperand(Idx);
5754     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5755       continue;
5756
5757     // TODO: What else can be here? Deal with it.
5758     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5759       return SDValue();
5760
5761     // TODO: Some optimizations are still possible here
5762     // ex: Getting one element from a vector, and the rest from another.
5763     if (Elem.getOperand(0) != V)
5764       return SDValue();
5765
5766     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5767     if (Dst == Idx)
5768       ++CorrectIdx;
5769     else if (IncorrectIdx == -1U) {
5770       IncorrectIdx = Idx;
5771       IncorrectDst = Dst;
5772     } else
5773       // There was already one element with an incorrect index.
5774       // We can't optimize this case to an insertps.
5775       return SDValue();
5776   }
5777
5778   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5779     SDLoc dl(Op);
5780     EVT VT = Op.getSimpleValueType();
5781     unsigned ElementMoveMask = 0;
5782     if (IncorrectIdx == -1U)
5783       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5784     else
5785       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5786
5787     SDValue InsertpsMask =
5788         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5789     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5790   }
5791
5792   return SDValue();
5793 }
5794
5795 /// getVShift - Return a vector logical shift node.
5796 ///
5797 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5798                          unsigned NumBits, SelectionDAG &DAG,
5799                          const TargetLowering &TLI, SDLoc dl) {
5800   assert(VT.is128BitVector() && "Unknown type for VShift");
5801   EVT ShVT = MVT::v2i64;
5802   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5803   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5804   return DAG.getNode(ISD::BITCAST, dl, VT,
5805                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5806                              DAG.getConstant(NumBits,
5807                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5808 }
5809
5810 static SDValue
5811 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5812
5813   // Check if the scalar load can be widened into a vector load. And if
5814   // the address is "base + cst" see if the cst can be "absorbed" into
5815   // the shuffle mask.
5816   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5817     SDValue Ptr = LD->getBasePtr();
5818     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5819       return SDValue();
5820     EVT PVT = LD->getValueType(0);
5821     if (PVT != MVT::i32 && PVT != MVT::f32)
5822       return SDValue();
5823
5824     int FI = -1;
5825     int64_t Offset = 0;
5826     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5827       FI = FINode->getIndex();
5828       Offset = 0;
5829     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5830                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5831       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5832       Offset = Ptr.getConstantOperandVal(1);
5833       Ptr = Ptr.getOperand(0);
5834     } else {
5835       return SDValue();
5836     }
5837
5838     // FIXME: 256-bit vector instructions don't require a strict alignment,
5839     // improve this code to support it better.
5840     unsigned RequiredAlign = VT.getSizeInBits()/8;
5841     SDValue Chain = LD->getChain();
5842     // Make sure the stack object alignment is at least 16 or 32.
5843     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5844     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5845       if (MFI->isFixedObjectIndex(FI)) {
5846         // Can't change the alignment. FIXME: It's possible to compute
5847         // the exact stack offset and reference FI + adjust offset instead.
5848         // If someone *really* cares about this. That's the way to implement it.
5849         return SDValue();
5850       } else {
5851         MFI->setObjectAlignment(FI, RequiredAlign);
5852       }
5853     }
5854
5855     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5856     // Ptr + (Offset & ~15).
5857     if (Offset < 0)
5858       return SDValue();
5859     if ((Offset % RequiredAlign) & 3)
5860       return SDValue();
5861     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5862     if (StartOffset)
5863       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5864                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5865
5866     int EltNo = (Offset - StartOffset) >> 2;
5867     unsigned NumElems = VT.getVectorNumElements();
5868
5869     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5870     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5871                              LD->getPointerInfo().getWithOffset(StartOffset),
5872                              false, false, false, 0);
5873
5874     SmallVector<int, 8> Mask;
5875     for (unsigned i = 0; i != NumElems; ++i)
5876       Mask.push_back(EltNo);
5877
5878     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5879   }
5880
5881   return SDValue();
5882 }
5883
5884 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5885 /// vector of type 'VT', see if the elements can be replaced by a single large
5886 /// load which has the same value as a build_vector whose operands are 'elts'.
5887 ///
5888 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5889 ///
5890 /// FIXME: we'd also like to handle the case where the last elements are zero
5891 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5892 /// There's even a handy isZeroNode for that purpose.
5893 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5894                                         SDLoc &DL, SelectionDAG &DAG,
5895                                         bool isAfterLegalize) {
5896   EVT EltVT = VT.getVectorElementType();
5897   unsigned NumElems = Elts.size();
5898
5899   LoadSDNode *LDBase = nullptr;
5900   unsigned LastLoadedElt = -1U;
5901
5902   // For each element in the initializer, see if we've found a load or an undef.
5903   // If we don't find an initial load element, or later load elements are
5904   // non-consecutive, bail out.
5905   for (unsigned i = 0; i < NumElems; ++i) {
5906     SDValue Elt = Elts[i];
5907
5908     if (!Elt.getNode() ||
5909         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5910       return SDValue();
5911     if (!LDBase) {
5912       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5913         return SDValue();
5914       LDBase = cast<LoadSDNode>(Elt.getNode());
5915       LastLoadedElt = i;
5916       continue;
5917     }
5918     if (Elt.getOpcode() == ISD::UNDEF)
5919       continue;
5920
5921     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5922     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5923       return SDValue();
5924     LastLoadedElt = i;
5925   }
5926
5927   // If we have found an entire vector of loads and undefs, then return a large
5928   // load of the entire vector width starting at the base pointer.  If we found
5929   // consecutive loads for the low half, generate a vzext_load node.
5930   if (LastLoadedElt == NumElems - 1) {
5931
5932     if (isAfterLegalize &&
5933         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5934       return SDValue();
5935
5936     SDValue NewLd = SDValue();
5937
5938     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5939       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5940                           LDBase->getPointerInfo(),
5941                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5942                           LDBase->isInvariant(), 0);
5943     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5944                         LDBase->getPointerInfo(),
5945                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5946                         LDBase->isInvariant(), LDBase->getAlignment());
5947
5948     if (LDBase->hasAnyUseOfValue(1)) {
5949       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5950                                      SDValue(LDBase, 1),
5951                                      SDValue(NewLd.getNode(), 1));
5952       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5953       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5954                              SDValue(NewLd.getNode(), 1));
5955     }
5956
5957     return NewLd;
5958   }
5959   if (NumElems == 4 && LastLoadedElt == 1 &&
5960       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5961     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5962     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5963     SDValue ResNode =
5964         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5965                                 LDBase->getPointerInfo(),
5966                                 LDBase->getAlignment(),
5967                                 false/*isVolatile*/, true/*ReadMem*/,
5968                                 false/*WriteMem*/);
5969
5970     // Make sure the newly-created LOAD is in the same position as LDBase in
5971     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5972     // update uses of LDBase's output chain to use the TokenFactor.
5973     if (LDBase->hasAnyUseOfValue(1)) {
5974       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5975                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5976       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5977       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5978                              SDValue(ResNode.getNode(), 1));
5979     }
5980
5981     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5982   }
5983   return SDValue();
5984 }
5985
5986 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5987 /// to generate a splat value for the following cases:
5988 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5989 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5990 /// a scalar load, or a constant.
5991 /// The VBROADCAST node is returned when a pattern is found,
5992 /// or SDValue() otherwise.
5993 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5994                                     SelectionDAG &DAG) {
5995   if (!Subtarget->hasFp256())
5996     return SDValue();
5997
5998   MVT VT = Op.getSimpleValueType();
5999   SDLoc dl(Op);
6000
6001   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6002          "Unsupported vector type for broadcast.");
6003
6004   SDValue Ld;
6005   bool ConstSplatVal;
6006
6007   switch (Op.getOpcode()) {
6008     default:
6009       // Unknown pattern found.
6010       return SDValue();
6011
6012     case ISD::BUILD_VECTOR: {
6013       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6014       BitVector UndefElements;
6015       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6016
6017       // We need a splat of a single value to use broadcast, and it doesn't
6018       // make any sense if the value is only in one element of the vector.
6019       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6020         return SDValue();
6021
6022       Ld = Splat;
6023       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6024                        Ld.getOpcode() == ISD::ConstantFP);
6025
6026       // Make sure that all of the users of a non-constant load are from the
6027       // BUILD_VECTOR node.
6028       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6029         return SDValue();
6030       break;
6031     }
6032
6033     case ISD::VECTOR_SHUFFLE: {
6034       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6035
6036       // Shuffles must have a splat mask where the first element is
6037       // broadcasted.
6038       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6039         return SDValue();
6040
6041       SDValue Sc = Op.getOperand(0);
6042       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6043           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6044
6045         if (!Subtarget->hasInt256())
6046           return SDValue();
6047
6048         // Use the register form of the broadcast instruction available on AVX2.
6049         if (VT.getSizeInBits() >= 256)
6050           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6051         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6052       }
6053
6054       Ld = Sc.getOperand(0);
6055       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6056                        Ld.getOpcode() == ISD::ConstantFP);
6057
6058       // The scalar_to_vector node and the suspected
6059       // load node must have exactly one user.
6060       // Constants may have multiple users.
6061
6062       // AVX-512 has register version of the broadcast
6063       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6064         Ld.getValueType().getSizeInBits() >= 32;
6065       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6066           !hasRegVer))
6067         return SDValue();
6068       break;
6069     }
6070   }
6071
6072   bool IsGE256 = (VT.getSizeInBits() >= 256);
6073
6074   // Handle the broadcasting a single constant scalar from the constant pool
6075   // into a vector. On Sandybridge it is still better to load a constant vector
6076   // from the constant pool and not to broadcast it from a scalar.
6077   if (ConstSplatVal && Subtarget->hasInt256()) {
6078     EVT CVT = Ld.getValueType();
6079     assert(!CVT.isVector() && "Must not broadcast a vector type");
6080     unsigned ScalarSize = CVT.getSizeInBits();
6081
6082     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
6083       const Constant *C = nullptr;
6084       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6085         C = CI->getConstantIntValue();
6086       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6087         C = CF->getConstantFPValue();
6088
6089       assert(C && "Invalid constant type");
6090
6091       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6092       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6093       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6094       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6095                        MachinePointerInfo::getConstantPool(),
6096                        false, false, false, Alignment);
6097
6098       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6099     }
6100   }
6101
6102   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6103   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6104
6105   // Handle AVX2 in-register broadcasts.
6106   if (!IsLoad && Subtarget->hasInt256() &&
6107       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6108     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6109
6110   // The scalar source must be a normal load.
6111   if (!IsLoad)
6112     return SDValue();
6113
6114   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6115     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6116
6117   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6118   // double since there is no vbroadcastsd xmm
6119   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6120     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6121       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6122   }
6123
6124   // Unsupported broadcast.
6125   return SDValue();
6126 }
6127
6128 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6129 /// underlying vector and index.
6130 ///
6131 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6132 /// index.
6133 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6134                                          SDValue ExtIdx) {
6135   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6136   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6137     return Idx;
6138
6139   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6140   // lowered this:
6141   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6142   // to:
6143   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6144   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6145   //                           undef)
6146   //                       Constant<0>)
6147   // In this case the vector is the extract_subvector expression and the index
6148   // is 2, as specified by the shuffle.
6149   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6150   SDValue ShuffleVec = SVOp->getOperand(0);
6151   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6152   assert(ShuffleVecVT.getVectorElementType() ==
6153          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6154
6155   int ShuffleIdx = SVOp->getMaskElt(Idx);
6156   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6157     ExtractedFromVec = ShuffleVec;
6158     return ShuffleIdx;
6159   }
6160   return Idx;
6161 }
6162
6163 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6164   MVT VT = Op.getSimpleValueType();
6165
6166   // Skip if insert_vec_elt is not supported.
6167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6168   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6169     return SDValue();
6170
6171   SDLoc DL(Op);
6172   unsigned NumElems = Op.getNumOperands();
6173
6174   SDValue VecIn1;
6175   SDValue VecIn2;
6176   SmallVector<unsigned, 4> InsertIndices;
6177   SmallVector<int, 8> Mask(NumElems, -1);
6178
6179   for (unsigned i = 0; i != NumElems; ++i) {
6180     unsigned Opc = Op.getOperand(i).getOpcode();
6181
6182     if (Opc == ISD::UNDEF)
6183       continue;
6184
6185     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6186       // Quit if more than 1 elements need inserting.
6187       if (InsertIndices.size() > 1)
6188         return SDValue();
6189
6190       InsertIndices.push_back(i);
6191       continue;
6192     }
6193
6194     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6195     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6196     // Quit if non-constant index.
6197     if (!isa<ConstantSDNode>(ExtIdx))
6198       return SDValue();
6199     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6200
6201     // Quit if extracted from vector of different type.
6202     if (ExtractedFromVec.getValueType() != VT)
6203       return SDValue();
6204
6205     if (!VecIn1.getNode())
6206       VecIn1 = ExtractedFromVec;
6207     else if (VecIn1 != ExtractedFromVec) {
6208       if (!VecIn2.getNode())
6209         VecIn2 = ExtractedFromVec;
6210       else if (VecIn2 != ExtractedFromVec)
6211         // Quit if more than 2 vectors to shuffle
6212         return SDValue();
6213     }
6214
6215     if (ExtractedFromVec == VecIn1)
6216       Mask[i] = Idx;
6217     else if (ExtractedFromVec == VecIn2)
6218       Mask[i] = Idx + NumElems;
6219   }
6220
6221   if (!VecIn1.getNode())
6222     return SDValue();
6223
6224   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6225   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6226   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6227     unsigned Idx = InsertIndices[i];
6228     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6229                      DAG.getIntPtrConstant(Idx));
6230   }
6231
6232   return NV;
6233 }
6234
6235 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6236 SDValue
6237 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6238
6239   MVT VT = Op.getSimpleValueType();
6240   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6241          "Unexpected type in LowerBUILD_VECTORvXi1!");
6242
6243   SDLoc dl(Op);
6244   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6245     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6246     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6247     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6248   }
6249
6250   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6251     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6252     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6253     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6254   }
6255
6256   bool AllContants = true;
6257   uint64_t Immediate = 0;
6258   int NonConstIdx = -1;
6259   bool IsSplat = true;
6260   unsigned NumNonConsts = 0;
6261   unsigned NumConsts = 0;
6262   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6263     SDValue In = Op.getOperand(idx);
6264     if (In.getOpcode() == ISD::UNDEF)
6265       continue;
6266     if (!isa<ConstantSDNode>(In)) {
6267       AllContants = false;
6268       NonConstIdx = idx;
6269       NumNonConsts++;
6270     }
6271     else {
6272       NumConsts++;
6273       if (cast<ConstantSDNode>(In)->getZExtValue())
6274       Immediate |= (1ULL << idx);
6275     }
6276     if (In != Op.getOperand(0))
6277       IsSplat = false;
6278   }
6279
6280   if (AllContants) {
6281     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6282       DAG.getConstant(Immediate, MVT::i16));
6283     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6284                        DAG.getIntPtrConstant(0));
6285   }
6286
6287   if (NumNonConsts == 1 && NonConstIdx != 0) {
6288     SDValue DstVec;
6289     if (NumConsts) {
6290       SDValue VecAsImm = DAG.getConstant(Immediate,
6291                                          MVT::getIntegerVT(VT.getSizeInBits()));
6292       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6293     }
6294     else 
6295       DstVec = DAG.getUNDEF(VT);
6296     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6297                        Op.getOperand(NonConstIdx),
6298                        DAG.getIntPtrConstant(NonConstIdx));
6299   }
6300   if (!IsSplat && (NonConstIdx != 0))
6301     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6302   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6303   SDValue Select;
6304   if (IsSplat)
6305     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6306                           DAG.getConstant(-1, SelectVT),
6307                           DAG.getConstant(0, SelectVT));
6308   else
6309     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6310                          DAG.getConstant((Immediate | 1), SelectVT),
6311                          DAG.getConstant(Immediate, SelectVT));
6312   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6313 }
6314
6315 /// \brief Return true if \p N implements a horizontal binop and return the
6316 /// operands for the horizontal binop into V0 and V1.
6317 /// 
6318 /// This is a helper function of PerformBUILD_VECTORCombine.
6319 /// This function checks that the build_vector \p N in input implements a
6320 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6321 /// operation to match.
6322 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6323 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6324 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6325 /// arithmetic sub.
6326 ///
6327 /// This function only analyzes elements of \p N whose indices are
6328 /// in range [BaseIdx, LastIdx).
6329 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6330                               SelectionDAG &DAG,
6331                               unsigned BaseIdx, unsigned LastIdx,
6332                               SDValue &V0, SDValue &V1) {
6333   EVT VT = N->getValueType(0);
6334
6335   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6336   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6337          "Invalid Vector in input!");
6338   
6339   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6340   bool CanFold = true;
6341   unsigned ExpectedVExtractIdx = BaseIdx;
6342   unsigned NumElts = LastIdx - BaseIdx;
6343   V0 = DAG.getUNDEF(VT);
6344   V1 = DAG.getUNDEF(VT);
6345
6346   // Check if N implements a horizontal binop.
6347   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6348     SDValue Op = N->getOperand(i + BaseIdx);
6349
6350     // Skip UNDEFs.
6351     if (Op->getOpcode() == ISD::UNDEF) {
6352       // Update the expected vector extract index.
6353       if (i * 2 == NumElts)
6354         ExpectedVExtractIdx = BaseIdx;
6355       ExpectedVExtractIdx += 2;
6356       continue;
6357     }
6358
6359     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6360
6361     if (!CanFold)
6362       break;
6363
6364     SDValue Op0 = Op.getOperand(0);
6365     SDValue Op1 = Op.getOperand(1);
6366
6367     // Try to match the following pattern:
6368     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6369     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6370         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6371         Op0.getOperand(0) == Op1.getOperand(0) &&
6372         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6373         isa<ConstantSDNode>(Op1.getOperand(1)));
6374     if (!CanFold)
6375       break;
6376
6377     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6378     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6379
6380     if (i * 2 < NumElts) {
6381       if (V0.getOpcode() == ISD::UNDEF)
6382         V0 = Op0.getOperand(0);
6383     } else {
6384       if (V1.getOpcode() == ISD::UNDEF)
6385         V1 = Op0.getOperand(0);
6386       if (i * 2 == NumElts)
6387         ExpectedVExtractIdx = BaseIdx;
6388     }
6389
6390     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6391     if (I0 == ExpectedVExtractIdx)
6392       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6393     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6394       // Try to match the following dag sequence:
6395       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6396       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6397     } else
6398       CanFold = false;
6399
6400     ExpectedVExtractIdx += 2;
6401   }
6402
6403   return CanFold;
6404 }
6405
6406 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6407 /// a concat_vector. 
6408 ///
6409 /// This is a helper function of PerformBUILD_VECTORCombine.
6410 /// This function expects two 256-bit vectors called V0 and V1.
6411 /// At first, each vector is split into two separate 128-bit vectors.
6412 /// Then, the resulting 128-bit vectors are used to implement two
6413 /// horizontal binary operations. 
6414 ///
6415 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6416 ///
6417 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6418 /// the two new horizontal binop.
6419 /// When Mode is set, the first horizontal binop dag node would take as input
6420 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6421 /// horizontal binop dag node would take as input the lower 128-bit of V1
6422 /// and the upper 128-bit of V1.
6423 ///   Example:
6424 ///     HADD V0_LO, V0_HI
6425 ///     HADD V1_LO, V1_HI
6426 ///
6427 /// Otherwise, the first horizontal binop dag node takes as input the lower
6428 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6429 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6430 ///   Example:
6431 ///     HADD V0_LO, V1_LO
6432 ///     HADD V0_HI, V1_HI
6433 ///
6434 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6435 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6436 /// the upper 128-bits of the result.
6437 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6438                                      SDLoc DL, SelectionDAG &DAG,
6439                                      unsigned X86Opcode, bool Mode,
6440                                      bool isUndefLO, bool isUndefHI) {
6441   EVT VT = V0.getValueType();
6442   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6443          "Invalid nodes in input!");
6444
6445   unsigned NumElts = VT.getVectorNumElements();
6446   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6447   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6448   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6449   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6450   EVT NewVT = V0_LO.getValueType();
6451
6452   SDValue LO = DAG.getUNDEF(NewVT);
6453   SDValue HI = DAG.getUNDEF(NewVT);
6454
6455   if (Mode) {
6456     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6457     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6458       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6459     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6460       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6461   } else {
6462     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6463     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6464                        V1_LO->getOpcode() != ISD::UNDEF))
6465       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6466
6467     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6468                        V1_HI->getOpcode() != ISD::UNDEF))
6469       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6470   }
6471
6472   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6473 }
6474
6475 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6476 /// sequence of 'vadd + vsub + blendi'.
6477 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6478                            const X86Subtarget *Subtarget) {
6479   SDLoc DL(BV);
6480   EVT VT = BV->getValueType(0);
6481   unsigned NumElts = VT.getVectorNumElements();
6482   SDValue InVec0 = DAG.getUNDEF(VT);
6483   SDValue InVec1 = DAG.getUNDEF(VT);
6484
6485   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6486           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6487
6488   // Odd-numbered elements in the input build vector are obtained from
6489   // adding two integer/float elements.
6490   // Even-numbered elements in the input build vector are obtained from
6491   // subtracting two integer/float elements.
6492   unsigned ExpectedOpcode = ISD::FSUB;
6493   unsigned NextExpectedOpcode = ISD::FADD;
6494   bool AddFound = false;
6495   bool SubFound = false;
6496
6497   for (unsigned i = 0, e = NumElts; i != e; i++) {
6498     SDValue Op = BV->getOperand(i);
6499
6500     // Skip 'undef' values.
6501     unsigned Opcode = Op.getOpcode();
6502     if (Opcode == ISD::UNDEF) {
6503       std::swap(ExpectedOpcode, NextExpectedOpcode);
6504       continue;
6505     }
6506
6507     // Early exit if we found an unexpected opcode.
6508     if (Opcode != ExpectedOpcode)
6509       return SDValue();
6510
6511     SDValue Op0 = Op.getOperand(0);
6512     SDValue Op1 = Op.getOperand(1);
6513
6514     // Try to match the following pattern:
6515     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6516     // Early exit if we cannot match that sequence.
6517     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6518         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6519         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6520         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6521         Op0.getOperand(1) != Op1.getOperand(1))
6522       return SDValue();
6523
6524     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6525     if (I0 != i)
6526       return SDValue();
6527
6528     // We found a valid add/sub node. Update the information accordingly.
6529     if (i & 1)
6530       AddFound = true;
6531     else
6532       SubFound = true;
6533
6534     // Update InVec0 and InVec1.
6535     if (InVec0.getOpcode() == ISD::UNDEF)
6536       InVec0 = Op0.getOperand(0);
6537     if (InVec1.getOpcode() == ISD::UNDEF)
6538       InVec1 = Op1.getOperand(0);
6539
6540     // Make sure that operands in input to each add/sub node always
6541     // come from a same pair of vectors.
6542     if (InVec0 != Op0.getOperand(0)) {
6543       if (ExpectedOpcode == ISD::FSUB)
6544         return SDValue();
6545
6546       // FADD is commutable. Try to commute the operands
6547       // and then test again.
6548       std::swap(Op0, Op1);
6549       if (InVec0 != Op0.getOperand(0))
6550         return SDValue();
6551     }
6552
6553     if (InVec1 != Op1.getOperand(0))
6554       return SDValue();
6555
6556     // Update the pair of expected opcodes.
6557     std::swap(ExpectedOpcode, NextExpectedOpcode);
6558   }
6559
6560   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6561   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6562       InVec1.getOpcode() != ISD::UNDEF)
6563     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6564
6565   return SDValue();
6566 }
6567
6568 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6569                                           const X86Subtarget *Subtarget) {
6570   SDLoc DL(N);
6571   EVT VT = N->getValueType(0);
6572   unsigned NumElts = VT.getVectorNumElements();
6573   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6574   SDValue InVec0, InVec1;
6575
6576   // Try to match an ADDSUB.
6577   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6578       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6579     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6580     if (Value.getNode())
6581       return Value;
6582   }
6583
6584   // Try to match horizontal ADD/SUB.
6585   unsigned NumUndefsLO = 0;
6586   unsigned NumUndefsHI = 0;
6587   unsigned Half = NumElts/2;
6588
6589   // Count the number of UNDEF operands in the build_vector in input.
6590   for (unsigned i = 0, e = Half; i != e; ++i)
6591     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6592       NumUndefsLO++;
6593
6594   for (unsigned i = Half, e = NumElts; i != e; ++i)
6595     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6596       NumUndefsHI++;
6597
6598   // Early exit if this is either a build_vector of all UNDEFs or all the
6599   // operands but one are UNDEF.
6600   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6601     return SDValue();
6602
6603   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6604     // Try to match an SSE3 float HADD/HSUB.
6605     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6606       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6607     
6608     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6609       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6610   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6611     // Try to match an SSSE3 integer HADD/HSUB.
6612     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6613       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6614     
6615     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6616       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6617   }
6618   
6619   if (!Subtarget->hasAVX())
6620     return SDValue();
6621
6622   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6623     // Try to match an AVX horizontal add/sub of packed single/double
6624     // precision floating point values from 256-bit vectors.
6625     SDValue InVec2, InVec3;
6626     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6627         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6628         ((InVec0.getOpcode() == ISD::UNDEF ||
6629           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6630         ((InVec1.getOpcode() == ISD::UNDEF ||
6631           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6632       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6633
6634     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6635         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6636         ((InVec0.getOpcode() == ISD::UNDEF ||
6637           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6638         ((InVec1.getOpcode() == ISD::UNDEF ||
6639           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6640       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6641   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6642     // Try to match an AVX2 horizontal add/sub of signed integers.
6643     SDValue InVec2, InVec3;
6644     unsigned X86Opcode;
6645     bool CanFold = true;
6646
6647     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6648         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6649         ((InVec0.getOpcode() == ISD::UNDEF ||
6650           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6651         ((InVec1.getOpcode() == ISD::UNDEF ||
6652           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6653       X86Opcode = X86ISD::HADD;
6654     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6655         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6656         ((InVec0.getOpcode() == ISD::UNDEF ||
6657           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6658         ((InVec1.getOpcode() == ISD::UNDEF ||
6659           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6660       X86Opcode = X86ISD::HSUB;
6661     else
6662       CanFold = false;
6663
6664     if (CanFold) {
6665       // Fold this build_vector into a single horizontal add/sub.
6666       // Do this only if the target has AVX2.
6667       if (Subtarget->hasAVX2())
6668         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6669  
6670       // Do not try to expand this build_vector into a pair of horizontal
6671       // add/sub if we can emit a pair of scalar add/sub.
6672       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6673         return SDValue();
6674
6675       // Convert this build_vector into a pair of horizontal binop followed by
6676       // a concat vector.
6677       bool isUndefLO = NumUndefsLO == Half;
6678       bool isUndefHI = NumUndefsHI == Half;
6679       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6680                                    isUndefLO, isUndefHI);
6681     }
6682   }
6683
6684   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6685        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6686     unsigned X86Opcode;
6687     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6688       X86Opcode = X86ISD::HADD;
6689     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6690       X86Opcode = X86ISD::HSUB;
6691     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6692       X86Opcode = X86ISD::FHADD;
6693     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6694       X86Opcode = X86ISD::FHSUB;
6695     else
6696       return SDValue();
6697
6698     // Don't try to expand this build_vector into a pair of horizontal add/sub
6699     // if we can simply emit a pair of scalar add/sub.
6700     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6701       return SDValue();
6702
6703     // Convert this build_vector into two horizontal add/sub followed by
6704     // a concat vector.
6705     bool isUndefLO = NumUndefsLO == Half;
6706     bool isUndefHI = NumUndefsHI == Half;
6707     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6708                                  isUndefLO, isUndefHI);
6709   }
6710
6711   return SDValue();
6712 }
6713
6714 SDValue
6715 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6716   SDLoc dl(Op);
6717
6718   MVT VT = Op.getSimpleValueType();
6719   MVT ExtVT = VT.getVectorElementType();
6720   unsigned NumElems = Op.getNumOperands();
6721
6722   // Generate vectors for predicate vectors.
6723   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6724     return LowerBUILD_VECTORvXi1(Op, DAG);
6725
6726   // Vectors containing all zeros can be matched by pxor and xorps later
6727   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6728     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6729     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6730     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6731       return Op;
6732
6733     return getZeroVector(VT, Subtarget, DAG, dl);
6734   }
6735
6736   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6737   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6738   // vpcmpeqd on 256-bit vectors.
6739   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6740     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6741       return Op;
6742
6743     if (!VT.is512BitVector())
6744       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6745   }
6746
6747   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6748   if (Broadcast.getNode())
6749     return Broadcast;
6750
6751   unsigned EVTBits = ExtVT.getSizeInBits();
6752
6753   unsigned NumZero  = 0;
6754   unsigned NumNonZero = 0;
6755   unsigned NonZeros = 0;
6756   bool IsAllConstants = true;
6757   SmallSet<SDValue, 8> Values;
6758   for (unsigned i = 0; i < NumElems; ++i) {
6759     SDValue Elt = Op.getOperand(i);
6760     if (Elt.getOpcode() == ISD::UNDEF)
6761       continue;
6762     Values.insert(Elt);
6763     if (Elt.getOpcode() != ISD::Constant &&
6764         Elt.getOpcode() != ISD::ConstantFP)
6765       IsAllConstants = false;
6766     if (X86::isZeroNode(Elt))
6767       NumZero++;
6768     else {
6769       NonZeros |= (1 << i);
6770       NumNonZero++;
6771     }
6772   }
6773
6774   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6775   if (NumNonZero == 0)
6776     return DAG.getUNDEF(VT);
6777
6778   // Special case for single non-zero, non-undef, element.
6779   if (NumNonZero == 1) {
6780     unsigned Idx = countTrailingZeros(NonZeros);
6781     SDValue Item = Op.getOperand(Idx);
6782
6783     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6784     // the value are obviously zero, truncate the value to i32 and do the
6785     // insertion that way.  Only do this if the value is non-constant or if the
6786     // value is a constant being inserted into element 0.  It is cheaper to do
6787     // a constant pool load than it is to do a movd + shuffle.
6788     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6789         (!IsAllConstants || Idx == 0)) {
6790       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6791         // Handle SSE only.
6792         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6793         EVT VecVT = MVT::v4i32;
6794         unsigned VecElts = 4;
6795
6796         // Truncate the value (which may itself be a constant) to i32, and
6797         // convert it to a vector with movd (S2V+shuffle to zero extend).
6798         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6799         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6800
6801         // If using the new shuffle lowering, just directly insert this.
6802         if (ExperimentalVectorShuffleLowering)
6803           return DAG.getNode(
6804               ISD::BITCAST, dl, VT,
6805               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6806
6807         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6808
6809         // Now we have our 32-bit value zero extended in the low element of
6810         // a vector.  If Idx != 0, swizzle it into place.
6811         if (Idx != 0) {
6812           SmallVector<int, 4> Mask;
6813           Mask.push_back(Idx);
6814           for (unsigned i = 1; i != VecElts; ++i)
6815             Mask.push_back(i);
6816           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6817                                       &Mask[0]);
6818         }
6819         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6820       }
6821     }
6822
6823     // If we have a constant or non-constant insertion into the low element of
6824     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6825     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6826     // depending on what the source datatype is.
6827     if (Idx == 0) {
6828       if (NumZero == 0)
6829         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6830
6831       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6832           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6833         if (VT.is256BitVector() || VT.is512BitVector()) {
6834           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6835           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6836                              Item, DAG.getIntPtrConstant(0));
6837         }
6838         assert(VT.is128BitVector() && "Expected an SSE value type!");
6839         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6840         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6841         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6842       }
6843
6844       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6845         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6846         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6847         if (VT.is256BitVector()) {
6848           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6849           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6850         } else {
6851           assert(VT.is128BitVector() && "Expected an SSE value type!");
6852           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6853         }
6854         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6855       }
6856     }
6857
6858     // Is it a vector logical left shift?
6859     if (NumElems == 2 && Idx == 1 &&
6860         X86::isZeroNode(Op.getOperand(0)) &&
6861         !X86::isZeroNode(Op.getOperand(1))) {
6862       unsigned NumBits = VT.getSizeInBits();
6863       return getVShift(true, VT,
6864                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6865                                    VT, Op.getOperand(1)),
6866                        NumBits/2, DAG, *this, dl);
6867     }
6868
6869     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6870       return SDValue();
6871
6872     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6873     // is a non-constant being inserted into an element other than the low one,
6874     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6875     // movd/movss) to move this into the low element, then shuffle it into
6876     // place.
6877     if (EVTBits == 32) {
6878       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6879
6880       // If using the new shuffle lowering, just directly insert this.
6881       if (ExperimentalVectorShuffleLowering)
6882         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6883
6884       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6885       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6886       SmallVector<int, 8> MaskVec;
6887       for (unsigned i = 0; i != NumElems; ++i)
6888         MaskVec.push_back(i == Idx ? 0 : 1);
6889       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6890     }
6891   }
6892
6893   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6894   if (Values.size() == 1) {
6895     if (EVTBits == 32) {
6896       // Instead of a shuffle like this:
6897       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6898       // Check if it's possible to issue this instead.
6899       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6900       unsigned Idx = countTrailingZeros(NonZeros);
6901       SDValue Item = Op.getOperand(Idx);
6902       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6903         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6904     }
6905     return SDValue();
6906   }
6907
6908   // A vector full of immediates; various special cases are already
6909   // handled, so this is best done with a single constant-pool load.
6910   if (IsAllConstants)
6911     return SDValue();
6912
6913   // For AVX-length vectors, build the individual 128-bit pieces and use
6914   // shuffles to put them in place.
6915   if (VT.is256BitVector() || VT.is512BitVector()) {
6916     SmallVector<SDValue, 64> V;
6917     for (unsigned i = 0; i != NumElems; ++i)
6918       V.push_back(Op.getOperand(i));
6919
6920     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6921
6922     // Build both the lower and upper subvector.
6923     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6924                                 makeArrayRef(&V[0], NumElems/2));
6925     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6926                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6927
6928     // Recreate the wider vector with the lower and upper part.
6929     if (VT.is256BitVector())
6930       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6931     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6932   }
6933
6934   // Let legalizer expand 2-wide build_vectors.
6935   if (EVTBits == 64) {
6936     if (NumNonZero == 1) {
6937       // One half is zero or undef.
6938       unsigned Idx = countTrailingZeros(NonZeros);
6939       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6940                                  Op.getOperand(Idx));
6941       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6942     }
6943     return SDValue();
6944   }
6945
6946   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6947   if (EVTBits == 8 && NumElems == 16) {
6948     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6949                                         Subtarget, *this);
6950     if (V.getNode()) return V;
6951   }
6952
6953   if (EVTBits == 16 && NumElems == 8) {
6954     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6955                                       Subtarget, *this);
6956     if (V.getNode()) return V;
6957   }
6958
6959   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6960   if (EVTBits == 32 && NumElems == 4) {
6961     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6962                                       NumZero, DAG, Subtarget, *this);
6963     if (V.getNode())
6964       return V;
6965   }
6966
6967   // If element VT is == 32 bits, turn it into a number of shuffles.
6968   SmallVector<SDValue, 8> V(NumElems);
6969   if (NumElems == 4 && NumZero > 0) {
6970     for (unsigned i = 0; i < 4; ++i) {
6971       bool isZero = !(NonZeros & (1 << i));
6972       if (isZero)
6973         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6974       else
6975         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6976     }
6977
6978     for (unsigned i = 0; i < 2; ++i) {
6979       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6980         default: break;
6981         case 0:
6982           V[i] = V[i*2];  // Must be a zero vector.
6983           break;
6984         case 1:
6985           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6986           break;
6987         case 2:
6988           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6989           break;
6990         case 3:
6991           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6992           break;
6993       }
6994     }
6995
6996     bool Reverse1 = (NonZeros & 0x3) == 2;
6997     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6998     int MaskVec[] = {
6999       Reverse1 ? 1 : 0,
7000       Reverse1 ? 0 : 1,
7001       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7002       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7003     };
7004     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7005   }
7006
7007   if (Values.size() > 1 && VT.is128BitVector()) {
7008     // Check for a build vector of consecutive loads.
7009     for (unsigned i = 0; i < NumElems; ++i)
7010       V[i] = Op.getOperand(i);
7011
7012     // Check for elements which are consecutive loads.
7013     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7014     if (LD.getNode())
7015       return LD;
7016
7017     // Check for a build vector from mostly shuffle plus few inserting.
7018     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7019     if (Sh.getNode())
7020       return Sh;
7021
7022     // For SSE 4.1, use insertps to put the high elements into the low element.
7023     if (getSubtarget()->hasSSE41()) {
7024       SDValue Result;
7025       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7026         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7027       else
7028         Result = DAG.getUNDEF(VT);
7029
7030       for (unsigned i = 1; i < NumElems; ++i) {
7031         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7032         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7033                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7034       }
7035       return Result;
7036     }
7037
7038     // Otherwise, expand into a number of unpckl*, start by extending each of
7039     // our (non-undef) elements to the full vector width with the element in the
7040     // bottom slot of the vector (which generates no code for SSE).
7041     for (unsigned i = 0; i < NumElems; ++i) {
7042       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7043         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7044       else
7045         V[i] = DAG.getUNDEF(VT);
7046     }
7047
7048     // Next, we iteratively mix elements, e.g. for v4f32:
7049     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7050     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7051     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7052     unsigned EltStride = NumElems >> 1;
7053     while (EltStride != 0) {
7054       for (unsigned i = 0; i < EltStride; ++i) {
7055         // If V[i+EltStride] is undef and this is the first round of mixing,
7056         // then it is safe to just drop this shuffle: V[i] is already in the
7057         // right place, the one element (since it's the first round) being
7058         // inserted as undef can be dropped.  This isn't safe for successive
7059         // rounds because they will permute elements within both vectors.
7060         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7061             EltStride == NumElems/2)
7062           continue;
7063
7064         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7065       }
7066       EltStride >>= 1;
7067     }
7068     return V[0];
7069   }
7070   return SDValue();
7071 }
7072
7073 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7074 // to create 256-bit vectors from two other 128-bit ones.
7075 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7076   SDLoc dl(Op);
7077   MVT ResVT = Op.getSimpleValueType();
7078
7079   assert((ResVT.is256BitVector() ||
7080           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7081
7082   SDValue V1 = Op.getOperand(0);
7083   SDValue V2 = Op.getOperand(1);
7084   unsigned NumElems = ResVT.getVectorNumElements();
7085   if(ResVT.is256BitVector())
7086     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7087
7088   if (Op.getNumOperands() == 4) {
7089     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7090                                 ResVT.getVectorNumElements()/2);
7091     SDValue V3 = Op.getOperand(2);
7092     SDValue V4 = Op.getOperand(3);
7093     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7094       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7095   }
7096   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7097 }
7098
7099 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7100   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7101   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7102          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7103           Op.getNumOperands() == 4)));
7104
7105   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7106   // from two other 128-bit ones.
7107
7108   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7109   return LowerAVXCONCAT_VECTORS(Op, DAG);
7110 }
7111
7112
7113 //===----------------------------------------------------------------------===//
7114 // Vector shuffle lowering
7115 //
7116 // This is an experimental code path for lowering vector shuffles on x86. It is
7117 // designed to handle arbitrary vector shuffles and blends, gracefully
7118 // degrading performance as necessary. It works hard to recognize idiomatic
7119 // shuffles and lower them to optimal instruction patterns without leaving
7120 // a framework that allows reasonably efficient handling of all vector shuffle
7121 // patterns.
7122 //===----------------------------------------------------------------------===//
7123
7124 /// \brief Tiny helper function to identify a no-op mask.
7125 ///
7126 /// This is a somewhat boring predicate function. It checks whether the mask
7127 /// array input, which is assumed to be a single-input shuffle mask of the kind
7128 /// used by the X86 shuffle instructions (not a fully general
7129 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7130 /// in-place shuffle are 'no-op's.
7131 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7132   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7133     if (Mask[i] != -1 && Mask[i] != i)
7134       return false;
7135   return true;
7136 }
7137
7138 /// \brief Helper function to classify a mask as a single-input mask.
7139 ///
7140 /// This isn't a generic single-input test because in the vector shuffle
7141 /// lowering we canonicalize single inputs to be the first input operand. This
7142 /// means we can more quickly test for a single input by only checking whether
7143 /// an input from the second operand exists. We also assume that the size of
7144 /// mask corresponds to the size of the input vectors which isn't true in the
7145 /// fully general case.
7146 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7147   for (int M : Mask)
7148     if (M >= (int)Mask.size())
7149       return false;
7150   return true;
7151 }
7152
7153 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7154 // 2013 will allow us to use it as a non-type template parameter.
7155 namespace {
7156
7157 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7158 ///
7159 /// See its documentation for details.
7160 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7161   if (Mask.size() != Args.size())
7162     return false;
7163   for (int i = 0, e = Mask.size(); i < e; ++i) {
7164     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7165     assert(*Args[i] < (int)Args.size() * 2 &&
7166            "Argument outside the range of possible shuffle inputs!");
7167     if (Mask[i] != -1 && Mask[i] != *Args[i])
7168       return false;
7169   }
7170   return true;
7171 }
7172
7173 } // namespace
7174
7175 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7176 /// arguments.
7177 ///
7178 /// This is a fast way to test a shuffle mask against a fixed pattern:
7179 ///
7180 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7181 ///
7182 /// It returns true if the mask is exactly as wide as the argument list, and
7183 /// each element of the mask is either -1 (signifying undef) or the value given
7184 /// in the argument.
7185 static const VariadicFunction1<
7186     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7187
7188 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7189 ///
7190 /// This helper function produces an 8-bit shuffle immediate corresponding to
7191 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7192 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7193 /// example.
7194 ///
7195 /// NB: We rely heavily on "undef" masks preserving the input lane.
7196 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7197                                           SelectionDAG &DAG) {
7198   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7199   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7200   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7201   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7202   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7203
7204   unsigned Imm = 0;
7205   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7206   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7207   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7208   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7209   return DAG.getConstant(Imm, MVT::i8);
7210 }
7211
7212 /// \brief Try to emit a blend instruction for a shuffle.
7213 ///
7214 /// This doesn't do any checks for the availability of instructions for blending
7215 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7216 /// be matched in the backend with the type given. What it does check for is
7217 /// that the shuffle mask is in fact a blend.
7218 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7219                                          SDValue V2, ArrayRef<int> Mask,
7220                                          SelectionDAG &DAG) {
7221
7222   unsigned BlendMask = 0;
7223   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7224     if (Mask[i] >= Size) {
7225       if (Mask[i] != i + Size)
7226         return SDValue(); // Shuffled V2 input!
7227       BlendMask |= 1u << i;
7228       continue;
7229     }
7230     if (Mask[i] >= 0 && Mask[i] != i)
7231       return SDValue(); // Shuffled V1 input!
7232   }
7233   if (VT == MVT::v4f32 || VT == MVT::v2f64)
7234     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7235                        DAG.getConstant(BlendMask, MVT::i8));
7236   assert(!VT.isFloatingPoint() && "Only v4f32 and v2f64 are supported!");
7237
7238   // For integer shuffles we need to expand the mask and cast the inputs to
7239   // v8i16s prior to blending.
7240   assert((VT == MVT::v8i16 || VT == MVT::v4i32 || VT == MVT::v2i64) &&
7241          "Not a supported integer vector type!");
7242   int Scale = 8 / VT.getVectorNumElements();
7243   BlendMask = 0;
7244   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7245     if (Mask[i] >= Size)
7246       for (int j = 0; j < Scale; ++j)
7247         BlendMask |= 1u << (i * Scale + j);
7248
7249   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7250   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7251   return DAG.getNode(ISD::BITCAST, DL, VT,
7252                      DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7253                                  DAG.getConstant(BlendMask, MVT::i8)));
7254 }
7255
7256 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7257 ///
7258 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7259 /// support for floating point shuffles but not integer shuffles. These
7260 /// instructions will incur a domain crossing penalty on some chips though so
7261 /// it is better to avoid lowering through this for integer vectors where
7262 /// possible.
7263 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7264                                        const X86Subtarget *Subtarget,
7265                                        SelectionDAG &DAG) {
7266   SDLoc DL(Op);
7267   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7268   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7269   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7270   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7271   ArrayRef<int> Mask = SVOp->getMask();
7272   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7273
7274   if (isSingleInputShuffleMask(Mask)) {
7275     // Straight shuffle of a single input vector. Simulate this by using the
7276     // single input as both of the "inputs" to this instruction..
7277     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7278     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7279                        DAG.getConstant(SHUFPDMask, MVT::i8));
7280   }
7281   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7282   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7283
7284   // Use dedicated unpack instructions for masks that match their pattern.
7285   if (isShuffleEquivalent(Mask, 0, 2))
7286     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7287   if (isShuffleEquivalent(Mask, 1, 3))
7288     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7289
7290   if (Subtarget->hasSSE41())
7291     if (SDValue Blend =
7292             lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask, DAG))
7293       return Blend;
7294
7295   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7296   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7297                      DAG.getConstant(SHUFPDMask, MVT::i8));
7298 }
7299
7300 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7301 ///
7302 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7303 /// the integer unit to minimize domain crossing penalties. However, for blends
7304 /// it falls back to the floating point shuffle operation with appropriate bit
7305 /// casting.
7306 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7307                                        const X86Subtarget *Subtarget,
7308                                        SelectionDAG &DAG) {
7309   SDLoc DL(Op);
7310   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7311   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7312   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7313   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7314   ArrayRef<int> Mask = SVOp->getMask();
7315   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7316
7317   if (isSingleInputShuffleMask(Mask)) {
7318     // Straight shuffle of a single input vector. For everything from SSE2
7319     // onward this has a single fast instruction with no scary immediates.
7320     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7321     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7322     int WidenedMask[4] = {
7323         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7324         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7325     return DAG.getNode(
7326         ISD::BITCAST, DL, MVT::v2i64,
7327         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7328                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7329   }
7330
7331   // Use dedicated unpack instructions for masks that match their pattern.
7332   if (isShuffleEquivalent(Mask, 0, 2))
7333     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7334   if (isShuffleEquivalent(Mask, 1, 3))
7335     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7336
7337   if (Subtarget->hasSSE41())
7338     if (SDValue Blend =
7339             lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask, DAG))
7340       return Blend;
7341
7342   // We implement this with SHUFPD which is pretty lame because it will likely
7343   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7344   // However, all the alternatives are still more cycles and newer chips don't
7345   // have this problem. It would be really nice if x86 had better shuffles here.
7346   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7347   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7348   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7349                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7350 }
7351
7352 /// \brief Lower 4-lane 32-bit floating point shuffles.
7353 ///
7354 /// Uses instructions exclusively from the floating point unit to minimize
7355 /// domain crossing penalties, as these are sufficient to implement all v4f32
7356 /// shuffles.
7357 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7358                                        const X86Subtarget *Subtarget,
7359                                        SelectionDAG &DAG) {
7360   SDLoc DL(Op);
7361   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7362   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7363   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7364   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7365   ArrayRef<int> Mask = SVOp->getMask();
7366   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7367
7368   SDValue LowV = V1, HighV = V2;
7369   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7370
7371   int NumV2Elements =
7372       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7373
7374   if (NumV2Elements == 0)
7375     // Straight shuffle of a single input vector. We pass the input vector to
7376     // both operands to simulate this with a SHUFPS.
7377     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7378                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7379
7380   // Use dedicated unpack instructions for masks that match their pattern.
7381   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7382     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7383   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7384     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7385
7386   if (Subtarget->hasSSE41())
7387     if (SDValue Blend =
7388             lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask, DAG))
7389       return Blend;
7390
7391   if (NumV2Elements == 1) {
7392     int V2Index =
7393         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7394         Mask.begin();
7395
7396     // Check for whether we can use INSERTPS to perform the blend. We only use
7397     // INSERTPS when the V1 elements are already in the correct locations
7398     // because otherwise we can just always use two SHUFPS instructions which
7399     // are much smaller to encode than a SHUFPS and an INSERTPS.
7400     if (Subtarget->hasSSE41()) {
7401       // When using INSERTPS we can zero any lane of the destination. Collect
7402       // the zero inputs into a mask and drop them from the lanes of V1 which
7403       // actually need to be present as inputs to the INSERTPS.
7404       unsigned ZMask = 0;
7405       if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7406         ZMask = 0xF ^ (1 << V2Index);
7407       } else if (V1.getOpcode() == ISD::BUILD_VECTOR) {
7408         for (int i = 0; i < 4; ++i) {
7409           int M = Mask[i];
7410           if (M >= 4)
7411             continue;
7412           if (M > -1) {
7413             SDValue Input = V1.getOperand(M);
7414             if (Input.getOpcode() != ISD::UNDEF &&
7415                 !X86::isZeroNode(Input)) {
7416               // A non-zero input!
7417               ZMask = 0;
7418               break;
7419             }
7420           }
7421           ZMask |= 1 << i;
7422         }
7423       }
7424
7425       // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
7426       int InsertShuffleMask[4] = {-1, -1, -1, -1};
7427       for (int i = 0; i < 4; ++i)
7428         if (i != V2Index && (ZMask & (1 << i)) == 0)
7429           InsertShuffleMask[i] = Mask[i];
7430
7431       if (isNoopShuffleMask(InsertShuffleMask)) {
7432         // Replace V1 with undef if nothing from V1 survives the INSERTPS.
7433         if ((ZMask | 1 << V2Index) == 0xF)
7434           V1 = DAG.getUNDEF(MVT::v4f32);
7435
7436         unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
7437         assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7438
7439         // Insert the V2 element into the desired position.
7440         return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7441                            DAG.getConstant(InsertPSMask, MVT::i8));
7442       }
7443     }
7444
7445     // Compute the index adjacent to V2Index and in the same half by toggling
7446     // the low bit.
7447     int V2AdjIndex = V2Index ^ 1;
7448
7449     if (Mask[V2AdjIndex] == -1) {
7450       // Handles all the cases where we have a single V2 element and an undef.
7451       // This will only ever happen in the high lanes because we commute the
7452       // vector otherwise.
7453       if (V2Index < 2)
7454         std::swap(LowV, HighV);
7455       NewMask[V2Index] -= 4;
7456     } else {
7457       // Handle the case where the V2 element ends up adjacent to a V1 element.
7458       // To make this work, blend them together as the first step.
7459       int V1Index = V2AdjIndex;
7460       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7461       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7462                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7463
7464       // Now proceed to reconstruct the final blend as we have the necessary
7465       // high or low half formed.
7466       if (V2Index < 2) {
7467         LowV = V2;
7468         HighV = V1;
7469       } else {
7470         HighV = V2;
7471       }
7472       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7473       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7474     }
7475   } else if (NumV2Elements == 2) {
7476     if (Mask[0] < 4 && Mask[1] < 4) {
7477       // Handle the easy case where we have V1 in the low lanes and V2 in the
7478       // high lanes. We never see this reversed because we sort the shuffle.
7479       NewMask[2] -= 4;
7480       NewMask[3] -= 4;
7481     } else {
7482       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7483       // trying to place elements directly, just blend them and set up the final
7484       // shuffle to place them.
7485
7486       // The first two blend mask elements are for V1, the second two are for
7487       // V2.
7488       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7489                           Mask[2] < 4 ? Mask[2] : Mask[3],
7490                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7491                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7492       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7493                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7494
7495       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7496       // a blend.
7497       LowV = HighV = V1;
7498       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7499       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7500       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7501       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7502     }
7503   }
7504   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7505                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7506 }
7507
7508 static SDValue lowerIntegerElementInsertionVectorShuffle(
7509     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7510     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7511   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7512                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7513                 Mask.begin();
7514
7515   // Check for a single input from a SCALAR_TO_VECTOR node.
7516   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7517   // all the smarts here sunk into that routine. However, the current
7518   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7519   // vector shuffle lowering is dead.
7520   if ((Mask[V2Index] == (int)Mask.size() &&
7521        V2.getOpcode() == ISD::SCALAR_TO_VECTOR) ||
7522       V2.getOpcode() == ISD::BUILD_VECTOR) {
7523     SDValue V2S = V2.getOperand(Mask[V2Index] - Mask.size());
7524
7525     bool V1IsAllZero = false;
7526     if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7527       V1IsAllZero = true;
7528     } else if (V1.getOpcode() == ISD::BUILD_VECTOR) {
7529       V1IsAllZero = true;
7530       for (int M : Mask) {
7531         if (M < 0 || M >= (int)Mask.size())
7532           continue;
7533         SDValue Input = V1.getOperand(M);
7534         if (Input.getOpcode() != ISD::UNDEF && !X86::isZeroNode(Input)) {
7535           // A non-zero input!
7536           V1IsAllZero = false;
7537           break;
7538         }
7539       }
7540     }
7541     if (V1IsAllZero) {
7542       // First, we need to zext the scalar if it is smaller than an i32.
7543       MVT EltVT = VT.getVectorElementType();
7544       assert(EltVT == V2S.getSimpleValueType() &&
7545              "Different scalar and element types!");
7546       MVT ExtVT = VT;
7547       if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7548         // Zero-extend directly to i32.
7549         ExtVT = MVT::v4i32;
7550         V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7551       }
7552
7553       V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT,
7554                        DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S));
7555       if (ExtVT != VT)
7556         V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7557
7558       if (V2Index != 0) {
7559         // If we have 4 or fewer lanes we can cheaply shuffle the element into
7560         // the desired position. Otherwise it is more efficient to do a vector
7561         // shift left. We know that we can do a vector shift left because all
7562         // the inputs are zero.
7563         if (VT.getVectorNumElements() <= 4) {
7564           SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7565           V2Shuffle[V2Index] = 0;
7566           V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7567         } else {
7568           V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7569           V2 = DAG.getNode(
7570               X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7571               DAG.getConstant(
7572                   V2Index * EltVT.getSizeInBits(),
7573                   DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7574           V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7575         }
7576       }
7577       return V2;
7578     }
7579   }
7580   return SDValue();
7581 }
7582
7583 /// \brief Lower 4-lane i32 vector shuffles.
7584 ///
7585 /// We try to handle these with integer-domain shuffles where we can, but for
7586 /// blends we use the floating point domain blend instructions.
7587 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7588                                        const X86Subtarget *Subtarget,
7589                                        SelectionDAG &DAG) {
7590   SDLoc DL(Op);
7591   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7592   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7593   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7594   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7595   ArrayRef<int> Mask = SVOp->getMask();
7596   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7597
7598   int NumV2Elements =
7599       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7600
7601   if (NumV2Elements == 0) {
7602     // Straight shuffle of a single input vector. For everything from SSE2
7603     // onward this has a single fast instruction with no scary immediates.
7604     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7605     // but we aren't actually going to use the UNPCK instruction because doing
7606     // so prevents folding a load into this instruction or making a copy.
7607     const int UnpackLoMask[] = {0, 0, 1, 1};
7608     const int UnpackHiMask[] = {2, 2, 3, 3};
7609     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
7610       Mask = UnpackLoMask;
7611     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
7612       Mask = UnpackHiMask;
7613
7614     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7615                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7616   }
7617
7618   // Use dedicated unpack instructions for masks that match their pattern.
7619   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7620     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7621   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7622     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7623
7624   // There are special ways we can lower some single-element blends.
7625   if (NumV2Elements == 1)
7626     if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
7627             MVT::v4i32, DL, V1, V2, Mask, Subtarget, DAG))
7628       return V;
7629
7630   if (Subtarget->hasSSE41())
7631     if (SDValue Blend =
7632             lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask, DAG))
7633       return Blend;
7634
7635   // We implement this with SHUFPS because it can blend from two vectors.
7636   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7637   // up the inputs, bypassing domain shift penalties that we would encur if we
7638   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7639   // relevant.
7640   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7641                      DAG.getVectorShuffle(
7642                          MVT::v4f32, DL,
7643                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7644                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7645 }
7646
7647 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7648 /// shuffle lowering, and the most complex part.
7649 ///
7650 /// The lowering strategy is to try to form pairs of input lanes which are
7651 /// targeted at the same half of the final vector, and then use a dword shuffle
7652 /// to place them onto the right half, and finally unpack the paired lanes into
7653 /// their final position.
7654 ///
7655 /// The exact breakdown of how to form these dword pairs and align them on the
7656 /// correct sides is really tricky. See the comments within the function for
7657 /// more of the details.
7658 static SDValue lowerV8I16SingleInputVectorShuffle(
7659     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7660     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7661   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7662   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7663   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7664
7665   SmallVector<int, 4> LoInputs;
7666   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7667                [](int M) { return M >= 0; });
7668   std::sort(LoInputs.begin(), LoInputs.end());
7669   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7670   SmallVector<int, 4> HiInputs;
7671   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7672                [](int M) { return M >= 0; });
7673   std::sort(HiInputs.begin(), HiInputs.end());
7674   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7675   int NumLToL =
7676       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7677   int NumHToL = LoInputs.size() - NumLToL;
7678   int NumLToH =
7679       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7680   int NumHToH = HiInputs.size() - NumLToH;
7681   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7682   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7683   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7684   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7685
7686   // Use dedicated unpack instructions for masks that match their pattern.
7687   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
7688     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
7689   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
7690     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
7691
7692   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7693   // such inputs we can swap two of the dwords across the half mark and end up
7694   // with <=2 inputs to each half in each half. Once there, we can fall through
7695   // to the generic code below. For example:
7696   //
7697   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7698   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7699   //
7700   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
7701   // and an existing 2-into-2 on the other half. In this case we may have to
7702   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
7703   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
7704   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
7705   // because any other situation (including a 3-into-1 or 1-into-3 in the other
7706   // half than the one we target for fixing) will be fixed when we re-enter this
7707   // path. We will also combine away any sequence of PSHUFD instructions that
7708   // result into a single instruction. Here is an example of the tricky case:
7709   //
7710   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7711   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
7712   //
7713   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
7714   //
7715   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
7716   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
7717   //
7718   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
7719   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
7720   //
7721   // The result is fine to be handled by the generic logic.
7722   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
7723                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
7724                           int AOffset, int BOffset) {
7725     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
7726            "Must call this with A having 3 or 1 inputs from the A half.");
7727     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
7728            "Must call this with B having 1 or 3 inputs from the B half.");
7729     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
7730            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
7731
7732     // Compute the index of dword with only one word among the three inputs in
7733     // a half by taking the sum of the half with three inputs and subtracting
7734     // the sum of the actual three inputs. The difference is the remaining
7735     // slot.
7736     int ADWord, BDWord;
7737     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
7738     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
7739     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
7740     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
7741     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
7742     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
7743     int TripleNonInputIdx =
7744         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
7745     TripleDWord = TripleNonInputIdx / 2;
7746
7747     // We use xor with one to compute the adjacent DWord to whichever one the
7748     // OneInput is in.
7749     OneInputDWord = (OneInput / 2) ^ 1;
7750
7751     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
7752     // and BToA inputs. If there is also such a problem with the BToB and AToB
7753     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
7754     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
7755     // is essential that we don't *create* a 3<-1 as then we might oscillate.
7756     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
7757       // Compute how many inputs will be flipped by swapping these DWords. We
7758       // need
7759       // to balance this to ensure we don't form a 3-1 shuffle in the other
7760       // half.
7761       int NumFlippedAToBInputs =
7762           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
7763           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
7764       int NumFlippedBToBInputs =
7765           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
7766           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
7767       if ((NumFlippedAToBInputs == 1 &&
7768            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
7769           (NumFlippedBToBInputs == 1 &&
7770            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
7771         // We choose whether to fix the A half or B half based on whether that
7772         // half has zero flipped inputs. At zero, we may not be able to fix it
7773         // with that half. We also bias towards fixing the B half because that
7774         // will more commonly be the high half, and we have to bias one way.
7775         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
7776                                                        ArrayRef<int> Inputs) {
7777           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
7778           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
7779                                          PinnedIdx ^ 1) != Inputs.end();
7780           // Determine whether the free index is in the flipped dword or the
7781           // unflipped dword based on where the pinned index is. We use this bit
7782           // in an xor to conditionally select the adjacent dword.
7783           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
7784           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7785                                              FixFreeIdx) != Inputs.end();
7786           if (IsFixIdxInput == IsFixFreeIdxInput)
7787             FixFreeIdx += 1;
7788           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
7789                                         FixFreeIdx) != Inputs.end();
7790           assert(IsFixIdxInput != IsFixFreeIdxInput &&
7791                  "We need to be changing the number of flipped inputs!");
7792           int PSHUFHalfMask[] = {0, 1, 2, 3};
7793           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
7794           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
7795                           MVT::v8i16, V,
7796                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
7797
7798           for (int &M : Mask)
7799             if (M != -1 && M == FixIdx)
7800               M = FixFreeIdx;
7801             else if (M != -1 && M == FixFreeIdx)
7802               M = FixIdx;
7803         };
7804         if (NumFlippedBToBInputs != 0) {
7805           int BPinnedIdx =
7806               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7807           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
7808         } else {
7809           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
7810           int APinnedIdx =
7811               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
7812           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
7813         }
7814       }
7815     }
7816
7817     int PSHUFDMask[] = {0, 1, 2, 3};
7818     PSHUFDMask[ADWord] = BDWord;
7819     PSHUFDMask[BDWord] = ADWord;
7820     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7821                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7822                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7823                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7824
7825     // Adjust the mask to match the new locations of A and B.
7826     for (int &M : Mask)
7827       if (M != -1 && M/2 == ADWord)
7828         M = 2 * BDWord + M % 2;
7829       else if (M != -1 && M/2 == BDWord)
7830         M = 2 * ADWord + M % 2;
7831
7832     // Recurse back into this routine to re-compute state now that this isn't
7833     // a 3 and 1 problem.
7834     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7835                                 Mask);
7836   };
7837   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
7838     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
7839   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
7840     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
7841
7842   // At this point there are at most two inputs to the low and high halves from
7843   // each half. That means the inputs can always be grouped into dwords and
7844   // those dwords can then be moved to the correct half with a dword shuffle.
7845   // We use at most one low and one high word shuffle to collect these paired
7846   // inputs into dwords, and finally a dword shuffle to place them.
7847   int PSHUFLMask[4] = {-1, -1, -1, -1};
7848   int PSHUFHMask[4] = {-1, -1, -1, -1};
7849   int PSHUFDMask[4] = {-1, -1, -1, -1};
7850
7851   // First fix the masks for all the inputs that are staying in their
7852   // original halves. This will then dictate the targets of the cross-half
7853   // shuffles.
7854   auto fixInPlaceInputs =
7855       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
7856                     MutableArrayRef<int> SourceHalfMask,
7857                     MutableArrayRef<int> HalfMask, int HalfOffset) {
7858     if (InPlaceInputs.empty())
7859       return;
7860     if (InPlaceInputs.size() == 1) {
7861       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7862           InPlaceInputs[0] - HalfOffset;
7863       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7864       return;
7865     }
7866     if (IncomingInputs.empty()) {
7867       // Just fix all of the in place inputs.
7868       for (int Input : InPlaceInputs) {
7869         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
7870         PSHUFDMask[Input / 2] = Input / 2;
7871       }
7872       return;
7873     }
7874
7875     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7876     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7877         InPlaceInputs[0] - HalfOffset;
7878     // Put the second input next to the first so that they are packed into
7879     // a dword. We find the adjacent index by toggling the low bit.
7880     int AdjIndex = InPlaceInputs[0] ^ 1;
7881     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7882     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7883     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7884   };
7885   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
7886   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
7887
7888   // Now gather the cross-half inputs and place them into a free dword of
7889   // their target half.
7890   // FIXME: This operation could almost certainly be simplified dramatically to
7891   // look more like the 3-1 fixing operation.
7892   auto moveInputsToRightHalf = [&PSHUFDMask](
7893       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7894       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7895       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
7896       int DestOffset) {
7897     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7898       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7899     };
7900     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7901                                                int Word) {
7902       int LowWord = Word & ~1;
7903       int HighWord = Word | 1;
7904       return isWordClobbered(SourceHalfMask, LowWord) ||
7905              isWordClobbered(SourceHalfMask, HighWord);
7906     };
7907
7908     if (IncomingInputs.empty())
7909       return;
7910
7911     if (ExistingInputs.empty()) {
7912       // Map any dwords with inputs from them into the right half.
7913       for (int Input : IncomingInputs) {
7914         // If the source half mask maps over the inputs, turn those into
7915         // swaps and use the swapped lane.
7916         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7917           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7918             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7919                 Input - SourceOffset;
7920             // We have to swap the uses in our half mask in one sweep.
7921             for (int &M : HalfMask)
7922               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
7923                 M = Input;
7924               else if (M == Input)
7925                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7926           } else {
7927             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7928                        Input - SourceOffset &&
7929                    "Previous placement doesn't match!");
7930           }
7931           // Note that this correctly re-maps both when we do a swap and when
7932           // we observe the other side of the swap above. We rely on that to
7933           // avoid swapping the members of the input list directly.
7934           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7935         }
7936
7937         // Map the input's dword into the correct half.
7938         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7939           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7940         else
7941           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7942                      Input / 2 &&
7943                  "Previous placement doesn't match!");
7944       }
7945
7946       // And just directly shift any other-half mask elements to be same-half
7947       // as we will have mirrored the dword containing the element into the
7948       // same position within that half.
7949       for (int &M : HalfMask)
7950         if (M >= SourceOffset && M < SourceOffset + 4) {
7951           M = M - SourceOffset + DestOffset;
7952           assert(M >= 0 && "This should never wrap below zero!");
7953         }
7954       return;
7955     }
7956
7957     // Ensure we have the input in a viable dword of its current half. This
7958     // is particularly tricky because the original position may be clobbered
7959     // by inputs being moved and *staying* in that half.
7960     if (IncomingInputs.size() == 1) {
7961       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7962         int InputFixed = std::find(std::begin(SourceHalfMask),
7963                                    std::end(SourceHalfMask), -1) -
7964                          std::begin(SourceHalfMask) + SourceOffset;
7965         SourceHalfMask[InputFixed - SourceOffset] =
7966             IncomingInputs[0] - SourceOffset;
7967         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7968                      InputFixed);
7969         IncomingInputs[0] = InputFixed;
7970       }
7971     } else if (IncomingInputs.size() == 2) {
7972       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7973           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7974         // We have two non-adjacent or clobbered inputs we need to extract from
7975         // the source half. To do this, we need to map them into some adjacent
7976         // dword slot in the source mask.
7977         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
7978                               IncomingInputs[1] - SourceOffset};
7979
7980         // If there is a free slot in the source half mask adjacent to one of
7981         // the inputs, place the other input in it. We use (Index XOR 1) to
7982         // compute an adjacent index.
7983         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
7984             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
7985           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
7986           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
7987           InputsFixed[1] = InputsFixed[0] ^ 1;
7988         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
7989                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
7990           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
7991           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
7992           InputsFixed[0] = InputsFixed[1] ^ 1;
7993         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
7994                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
7995           // The two inputs are in the same DWord but it is clobbered and the
7996           // adjacent DWord isn't used at all. Move both inputs to the free
7997           // slot.
7998           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
7999           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8000           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8001           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8002         } else {
8003           // The only way we hit this point is if there is no clobbering
8004           // (because there are no off-half inputs to this half) and there is no
8005           // free slot adjacent to one of the inputs. In this case, we have to
8006           // swap an input with a non-input.
8007           for (int i = 0; i < 4; ++i)
8008             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8009                    "We can't handle any clobbers here!");
8010           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8011                  "Cannot have adjacent inputs here!");
8012
8013           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8014           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8015
8016           // We also have to update the final source mask in this case because
8017           // it may need to undo the above swap.
8018           for (int &M : FinalSourceHalfMask)
8019             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8020               M = InputsFixed[1] + SourceOffset;
8021             else if (M == InputsFixed[1] + SourceOffset)
8022               M = (InputsFixed[0] ^ 1) + SourceOffset;
8023
8024           InputsFixed[1] = InputsFixed[0] ^ 1;
8025         }
8026
8027         // Point everything at the fixed inputs.
8028         for (int &M : HalfMask)
8029           if (M == IncomingInputs[0])
8030             M = InputsFixed[0] + SourceOffset;
8031           else if (M == IncomingInputs[1])
8032             M = InputsFixed[1] + SourceOffset;
8033
8034         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8035         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8036       }
8037     } else {
8038       llvm_unreachable("Unhandled input size!");
8039     }
8040
8041     // Now hoist the DWord down to the right half.
8042     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8043     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8044     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8045     for (int &M : HalfMask)
8046       for (int Input : IncomingInputs)
8047         if (M == Input)
8048           M = FreeDWord * 2 + Input % 2;
8049   };
8050   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8051                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8052   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8053                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8054
8055   // Now enact all the shuffles we've computed to move the inputs into their
8056   // target half.
8057   if (!isNoopShuffleMask(PSHUFLMask))
8058     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8059                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8060   if (!isNoopShuffleMask(PSHUFHMask))
8061     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8062                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8063   if (!isNoopShuffleMask(PSHUFDMask))
8064     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8065                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8066                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8067                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8068
8069   // At this point, each half should contain all its inputs, and we can then
8070   // just shuffle them into their final position.
8071   assert(std::count_if(LoMask.begin(), LoMask.end(),
8072                        [](int M) { return M >= 4; }) == 0 &&
8073          "Failed to lift all the high half inputs to the low mask!");
8074   assert(std::count_if(HiMask.begin(), HiMask.end(),
8075                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8076          "Failed to lift all the low half inputs to the high mask!");
8077
8078   // Do a half shuffle for the low mask.
8079   if (!isNoopShuffleMask(LoMask))
8080     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8081                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8082
8083   // Do a half shuffle with the high mask after shifting its values down.
8084   for (int &M : HiMask)
8085     if (M >= 0)
8086       M -= 4;
8087   if (!isNoopShuffleMask(HiMask))
8088     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8089                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8090
8091   return V;
8092 }
8093
8094 /// \brief Detect whether the mask pattern should be lowered through
8095 /// interleaving.
8096 ///
8097 /// This essentially tests whether viewing the mask as an interleaving of two
8098 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
8099 /// lowering it through interleaving is a significantly better strategy.
8100 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
8101   int NumEvenInputs[2] = {0, 0};
8102   int NumOddInputs[2] = {0, 0};
8103   int NumLoInputs[2] = {0, 0};
8104   int NumHiInputs[2] = {0, 0};
8105   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
8106     if (Mask[i] < 0)
8107       continue;
8108
8109     int InputIdx = Mask[i] >= Size;
8110
8111     if (i < Size / 2)
8112       ++NumLoInputs[InputIdx];
8113     else
8114       ++NumHiInputs[InputIdx];
8115
8116     if ((i % 2) == 0)
8117       ++NumEvenInputs[InputIdx];
8118     else
8119       ++NumOddInputs[InputIdx];
8120   }
8121
8122   // The minimum number of cross-input results for both the interleaved and
8123   // split cases. If interleaving results in fewer cross-input results, return
8124   // true.
8125   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
8126                                     NumEvenInputs[0] + NumOddInputs[1]);
8127   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
8128                               NumLoInputs[0] + NumHiInputs[1]);
8129   return InterleavedCrosses < SplitCrosses;
8130 }
8131
8132 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
8133 ///
8134 /// This strategy only works when the inputs from each vector fit into a single
8135 /// half of that vector, and generally there are not so many inputs as to leave
8136 /// the in-place shuffles required highly constrained (and thus expensive). It
8137 /// shifts all the inputs into a single side of both input vectors and then
8138 /// uses an unpack to interleave these inputs in a single vector. At that
8139 /// point, we will fall back on the generic single input shuffle lowering.
8140 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
8141                                                  SDValue V2,
8142                                                  MutableArrayRef<int> Mask,
8143                                                  const X86Subtarget *Subtarget,
8144                                                  SelectionDAG &DAG) {
8145   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8146   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8147   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
8148   for (int i = 0; i < 8; ++i)
8149     if (Mask[i] >= 0 && Mask[i] < 4)
8150       LoV1Inputs.push_back(i);
8151     else if (Mask[i] >= 4 && Mask[i] < 8)
8152       HiV1Inputs.push_back(i);
8153     else if (Mask[i] >= 8 && Mask[i] < 12)
8154       LoV2Inputs.push_back(i);
8155     else if (Mask[i] >= 12)
8156       HiV2Inputs.push_back(i);
8157
8158   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
8159   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
8160   (void)NumV1Inputs;
8161   (void)NumV2Inputs;
8162   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
8163   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
8164   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
8165
8166   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
8167                      HiV1Inputs.size() + HiV2Inputs.size();
8168
8169   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
8170                               ArrayRef<int> HiInputs, bool MoveToLo,
8171                               int MaskOffset) {
8172     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
8173     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
8174     if (BadInputs.empty())
8175       return V;
8176
8177     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8178     int MoveOffset = MoveToLo ? 0 : 4;
8179
8180     if (GoodInputs.empty()) {
8181       for (int BadInput : BadInputs) {
8182         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
8183         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
8184       }
8185     } else {
8186       if (GoodInputs.size() == 2) {
8187         // If the low inputs are spread across two dwords, pack them into
8188         // a single dword.
8189         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
8190         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
8191         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
8192         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
8193       } else {
8194         // Otherwise pin the good inputs.
8195         for (int GoodInput : GoodInputs)
8196           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
8197       }
8198
8199       if (BadInputs.size() == 2) {
8200         // If we have two bad inputs then there may be either one or two good
8201         // inputs fixed in place. Find a fixed input, and then find the *other*
8202         // two adjacent indices by using modular arithmetic.
8203         int GoodMaskIdx =
8204             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
8205                          [](int M) { return M >= 0; }) -
8206             std::begin(MoveMask);
8207         int MoveMaskIdx =
8208             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
8209         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
8210         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
8211         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8212         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
8213         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8214         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
8215       } else {
8216         assert(BadInputs.size() == 1 && "All sizes handled");
8217         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
8218                                     std::end(MoveMask), -1) -
8219                           std::begin(MoveMask);
8220         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8221         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8222       }
8223     }
8224
8225     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8226                                 MoveMask);
8227   };
8228   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
8229                         /*MaskOffset*/ 0);
8230   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
8231                         /*MaskOffset*/ 8);
8232
8233   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
8234   // cross-half traffic in the final shuffle.
8235
8236   // Munge the mask to be a single-input mask after the unpack merges the
8237   // results.
8238   for (int &M : Mask)
8239     if (M != -1)
8240       M = 2 * (M % 4) + (M / 8);
8241
8242   return DAG.getVectorShuffle(
8243       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
8244                                   DL, MVT::v8i16, V1, V2),
8245       DAG.getUNDEF(MVT::v8i16), Mask);
8246 }
8247
8248 /// \brief Generic lowering of 8-lane i16 shuffles.
8249 ///
8250 /// This handles both single-input shuffles and combined shuffle/blends with
8251 /// two inputs. The single input shuffles are immediately delegated to
8252 /// a dedicated lowering routine.
8253 ///
8254 /// The blends are lowered in one of three fundamental ways. If there are few
8255 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8256 /// of the input is significantly cheaper when lowered as an interleaving of
8257 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8258 /// halves of the inputs separately (making them have relatively few inputs)
8259 /// and then concatenate them.
8260 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8261                                        const X86Subtarget *Subtarget,
8262                                        SelectionDAG &DAG) {
8263   SDLoc DL(Op);
8264   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8265   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8266   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8267   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8268   ArrayRef<int> OrigMask = SVOp->getMask();
8269   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8270                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8271   MutableArrayRef<int> Mask(MaskStorage);
8272
8273   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8274
8275   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8276   auto isV2 = [](int M) { return M >= 8; };
8277
8278   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
8279   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8280
8281   if (NumV2Inputs == 0)
8282     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8283
8284   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
8285                             "to be V1-input shuffles.");
8286
8287   // There are special ways we can lower some single-element blends.
8288   if (NumV2Inputs == 1)
8289     if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
8290             MVT::v8i16, DL, V1, V2, Mask, Subtarget, DAG))
8291       return V;
8292
8293   if (Subtarget->hasSSE41())
8294     if (SDValue Blend =
8295             lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8296       return Blend;
8297
8298   if (NumV1Inputs + NumV2Inputs <= 4)
8299     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
8300
8301   // Check whether an interleaving lowering is likely to be more efficient.
8302   // This isn't perfect but it is a strong heuristic that tends to work well on
8303   // the kinds of shuffles that show up in practice.
8304   //
8305   // FIXME: Handle 1x, 2x, and 4x interleaving.
8306   if (shouldLowerAsInterleaving(Mask)) {
8307     // FIXME: Figure out whether we should pack these into the low or high
8308     // halves.
8309
8310     int EMask[8], OMask[8];
8311     for (int i = 0; i < 4; ++i) {
8312       EMask[i] = Mask[2*i];
8313       OMask[i] = Mask[2*i + 1];
8314       EMask[i + 4] = -1;
8315       OMask[i + 4] = -1;
8316     }
8317
8318     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8319     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8320
8321     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8322   }
8323
8324   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8325   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8326
8327   for (int i = 0; i < 4; ++i) {
8328     LoBlendMask[i] = Mask[i];
8329     HiBlendMask[i] = Mask[i + 4];
8330   }
8331
8332   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8333   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8334   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8335   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8336
8337   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8338                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8339 }
8340
8341 /// \brief Check whether a compaction lowering can be done by dropping even
8342 /// elements and compute how many times even elements must be dropped.
8343 ///
8344 /// This handles shuffles which take every Nth element where N is a power of
8345 /// two. Example shuffle masks:
8346 ///
8347 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8348 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8349 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8350 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8351 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8352 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8353 ///
8354 /// Any of these lanes can of course be undef.
8355 ///
8356 /// This routine only supports N <= 3.
8357 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8358 /// for larger N.
8359 ///
8360 /// \returns N above, or the number of times even elements must be dropped if
8361 /// there is such a number. Otherwise returns zero.
8362 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8363   // Figure out whether we're looping over two inputs or just one.
8364   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8365
8366   // The modulus for the shuffle vector entries is based on whether this is
8367   // a single input or not.
8368   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8369   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8370          "We should only be called with masks with a power-of-2 size!");
8371
8372   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8373
8374   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8375   // and 2^3 simultaneously. This is because we may have ambiguity with
8376   // partially undef inputs.
8377   bool ViableForN[3] = {true, true, true};
8378
8379   for (int i = 0, e = Mask.size(); i < e; ++i) {
8380     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8381     // want.
8382     if (Mask[i] == -1)
8383       continue;
8384
8385     bool IsAnyViable = false;
8386     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8387       if (ViableForN[j]) {
8388         uint64_t N = j + 1;
8389
8390         // The shuffle mask must be equal to (i * 2^N) % M.
8391         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8392           IsAnyViable = true;
8393         else
8394           ViableForN[j] = false;
8395       }
8396     // Early exit if we exhaust the possible powers of two.
8397     if (!IsAnyViable)
8398       break;
8399   }
8400
8401   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8402     if (ViableForN[j])
8403       return j + 1;
8404
8405   // Return 0 as there is no viable power of two.
8406   return 0;
8407 }
8408
8409 /// \brief Generic lowering of v16i8 shuffles.
8410 ///
8411 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8412 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8413 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8414 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8415 /// back together.
8416 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8417                                        const X86Subtarget *Subtarget,
8418                                        SelectionDAG &DAG) {
8419   SDLoc DL(Op);
8420   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8421   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8422   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8423   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8424   ArrayRef<int> OrigMask = SVOp->getMask();
8425   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8426   int MaskStorage[16] = {
8427       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8428       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8429       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8430       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8431   MutableArrayRef<int> Mask(MaskStorage);
8432   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8433   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8434
8435   int NumV2Elements =
8436       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8437
8438   // For single-input shuffles, there are some nicer lowering tricks we can use.
8439   if (NumV2Elements == 0) {
8440     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8441     // Notably, this handles splat and partial-splat shuffles more efficiently.
8442     // However, it only makes sense if the pre-duplication shuffle simplifies
8443     // things significantly. Currently, this means we need to be able to
8444     // express the pre-duplication shuffle as an i16 shuffle.
8445     //
8446     // FIXME: We should check for other patterns which can be widened into an
8447     // i16 shuffle as well.
8448     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8449       for (int i = 0; i < 16; i += 2) {
8450         if (Mask[i] != Mask[i + 1])
8451           return false;
8452       }
8453       return true;
8454     };
8455     auto tryToWidenViaDuplication = [&]() -> SDValue {
8456       if (!canWidenViaDuplication(Mask))
8457         return SDValue();
8458       SmallVector<int, 4> LoInputs;
8459       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8460                    [](int M) { return M >= 0 && M < 8; });
8461       std::sort(LoInputs.begin(), LoInputs.end());
8462       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8463                      LoInputs.end());
8464       SmallVector<int, 4> HiInputs;
8465       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8466                    [](int M) { return M >= 8; });
8467       std::sort(HiInputs.begin(), HiInputs.end());
8468       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8469                      HiInputs.end());
8470
8471       bool TargetLo = LoInputs.size() >= HiInputs.size();
8472       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8473       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8474
8475       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8476       SmallDenseMap<int, int, 8> LaneMap;
8477       for (int I : InPlaceInputs) {
8478         PreDupI16Shuffle[I/2] = I/2;
8479         LaneMap[I] = I;
8480       }
8481       int j = TargetLo ? 0 : 4, je = j + 4;
8482       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8483         // Check if j is already a shuffle of this input. This happens when
8484         // there are two adjacent bytes after we move the low one.
8485         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8486           // If we haven't yet mapped the input, search for a slot into which
8487           // we can map it.
8488           while (j < je && PreDupI16Shuffle[j] != -1)
8489             ++j;
8490
8491           if (j == je)
8492             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8493             return SDValue();
8494
8495           // Map this input with the i16 shuffle.
8496           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8497         }
8498
8499         // Update the lane map based on the mapping we ended up with.
8500         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8501       }
8502       V1 = DAG.getNode(
8503           ISD::BITCAST, DL, MVT::v16i8,
8504           DAG.getVectorShuffle(MVT::v8i16, DL,
8505                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8506                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8507
8508       // Unpack the bytes to form the i16s that will be shuffled into place.
8509       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8510                        MVT::v16i8, V1, V1);
8511
8512       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8513       for (int i = 0; i < 16; i += 2) {
8514         if (Mask[i] != -1)
8515           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8516         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8517       }
8518       return DAG.getNode(
8519           ISD::BITCAST, DL, MVT::v16i8,
8520           DAG.getVectorShuffle(MVT::v8i16, DL,
8521                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8522                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8523     };
8524     if (SDValue V = tryToWidenViaDuplication())
8525       return V;
8526   }
8527
8528   // Check whether an interleaving lowering is likely to be more efficient.
8529   // This isn't perfect but it is a strong heuristic that tends to work well on
8530   // the kinds of shuffles that show up in practice.
8531   //
8532   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8533   if (shouldLowerAsInterleaving(Mask)) {
8534     // FIXME: Figure out whether we should pack these into the low or high
8535     // halves.
8536
8537     int EMask[16], OMask[16];
8538     for (int i = 0; i < 8; ++i) {
8539       EMask[i] = Mask[2*i];
8540       OMask[i] = Mask[2*i + 1];
8541       EMask[i + 8] = -1;
8542       OMask[i + 8] = -1;
8543     }
8544
8545     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
8546     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
8547
8548     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
8549   }
8550
8551   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8552   // with PSHUFB. It is important to do this before we attempt to generate any
8553   // blends but after all of the single-input lowerings. If the single input
8554   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8555   // want to preserve that and we can DAG combine any longer sequences into
8556   // a PSHUFB in the end. But once we start blending from multiple inputs,
8557   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8558   // and there are *very* few patterns that would actually be faster than the
8559   // PSHUFB approach because of its ability to zero lanes.
8560   //
8561   // FIXME: The only exceptions to the above are blends which are exact
8562   // interleavings with direct instructions supporting them. We currently don't
8563   // handle those well here.
8564   if (Subtarget->hasSSSE3()) {
8565     SDValue V1Mask[16];
8566     SDValue V2Mask[16];
8567     for (int i = 0; i < 16; ++i)
8568       if (Mask[i] == -1) {
8569         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
8570       } else {
8571         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
8572         V2Mask[i] =
8573             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8574       }
8575     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8576                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8577     if (isSingleInputShuffleMask(Mask))
8578       return V1; // Single inputs are easy.
8579
8580     // Otherwise, blend the two.
8581     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8582                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8583     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8584   }
8585
8586   // There are special ways we can lower some single-element blends.
8587   if (NumV2Elements == 1)
8588     if (SDValue V = lowerIntegerElementInsertionVectorShuffle(
8589             MVT::v16i8, DL, V1, V2, Mask, Subtarget, DAG))
8590       return V;
8591
8592   // Check whether a compaction lowering can be done. This handles shuffles
8593   // which take every Nth element for some even N. See the helper function for
8594   // details.
8595   //
8596   // We special case these as they can be particularly efficiently handled with
8597   // the PACKUSB instruction on x86 and they show up in common patterns of
8598   // rearranging bytes to truncate wide elements.
8599   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8600     // NumEvenDrops is the power of two stride of the elements. Another way of
8601     // thinking about it is that we need to drop the even elements this many
8602     // times to get the original input.
8603     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8604
8605     // First we need to zero all the dropped bytes.
8606     assert(NumEvenDrops <= 3 &&
8607            "No support for dropping even elements more than 3 times.");
8608     // We use the mask type to pick which bytes are preserved based on how many
8609     // elements are dropped.
8610     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8611     SDValue ByteClearMask =
8612         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8613                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8614     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8615     if (!IsSingleInput)
8616       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8617
8618     // Now pack things back together.
8619     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8620     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8621     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8622     for (int i = 1; i < NumEvenDrops; ++i) {
8623       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8624       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8625     }
8626
8627     return Result;
8628   }
8629
8630   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8631   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8632   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8633   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8634
8635   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8636                             MutableArrayRef<int> V1HalfBlendMask,
8637                             MutableArrayRef<int> V2HalfBlendMask) {
8638     for (int i = 0; i < 8; ++i)
8639       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8640         V1HalfBlendMask[i] = HalfMask[i];
8641         HalfMask[i] = i;
8642       } else if (HalfMask[i] >= 16) {
8643         V2HalfBlendMask[i] = HalfMask[i] - 16;
8644         HalfMask[i] = i + 8;
8645       }
8646   };
8647   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8648   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8649
8650   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8651
8652   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8653                              MutableArrayRef<int> HiBlendMask) {
8654     SDValue V1, V2;
8655     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8656     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8657     // i16s.
8658     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8659                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8660         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8661                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8662       // Use a mask to drop the high bytes.
8663       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8664       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8665                        DAG.getConstant(0x00FF, MVT::v8i16));
8666
8667       // This will be a single vector shuffle instead of a blend so nuke V2.
8668       V2 = DAG.getUNDEF(MVT::v8i16);
8669
8670       // Squash the masks to point directly into V1.
8671       for (int &M : LoBlendMask)
8672         if (M >= 0)
8673           M /= 2;
8674       for (int &M : HiBlendMask)
8675         if (M >= 0)
8676           M /= 2;
8677     } else {
8678       // Otherwise just unpack the low half of V into V1 and the high half into
8679       // V2 so that we can blend them as i16s.
8680       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8681                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8682       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8683                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8684     }
8685
8686     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8687     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8688     return std::make_pair(BlendedLo, BlendedHi);
8689   };
8690   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8691   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8692   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8693
8694   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8695   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8696
8697   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8698 }
8699
8700 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8701 ///
8702 /// This routine breaks down the specific type of 128-bit shuffle and
8703 /// dispatches to the lowering routines accordingly.
8704 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8705                                         MVT VT, const X86Subtarget *Subtarget,
8706                                         SelectionDAG &DAG) {
8707   switch (VT.SimpleTy) {
8708   case MVT::v2i64:
8709     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8710   case MVT::v2f64:
8711     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8712   case MVT::v4i32:
8713     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8714   case MVT::v4f32:
8715     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8716   case MVT::v8i16:
8717     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8718   case MVT::v16i8:
8719     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8720
8721   default:
8722     llvm_unreachable("Unimplemented!");
8723   }
8724 }
8725
8726 static bool isHalfCrossingShuffleMask(ArrayRef<int> Mask) {
8727   int Size = Mask.size();
8728   for (int M : Mask.slice(0, Size / 2))
8729     if (M >= 0 && (M % Size) >= Size / 2)
8730       return true;
8731   for (int M : Mask.slice(Size / 2, Size / 2))
8732     if (M >= 0 && (M % Size) < Size / 2)
8733       return true;
8734   return false;
8735 }
8736
8737 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
8738 /// shuffles.
8739 ///
8740 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
8741 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
8742 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
8743 /// we encode the logic here for specific shuffle lowering routines to bail to
8744 /// when they exhaust the features avaible to more directly handle the shuffle.
8745 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
8746                                                 SDValue V2,
8747                                                 const X86Subtarget *Subtarget,
8748                                                 SelectionDAG &DAG) {
8749   SDLoc DL(Op);
8750   MVT VT = Op.getSimpleValueType();
8751   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
8752   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
8753   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
8754   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8755   ArrayRef<int> Mask = SVOp->getMask();
8756
8757   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
8758   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
8759
8760   int NumElements = VT.getVectorNumElements();
8761   int SplitNumElements = NumElements / 2;
8762   MVT ScalarVT = VT.getScalarType();
8763   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
8764
8765   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8766                              DAG.getIntPtrConstant(0));
8767   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
8768                              DAG.getIntPtrConstant(SplitNumElements));
8769   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8770                              DAG.getIntPtrConstant(0));
8771   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
8772                              DAG.getIntPtrConstant(SplitNumElements));
8773
8774   // Now create two 4-way blends of these half-width vectors.
8775   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
8776     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
8777     for (int i = 0; i < SplitNumElements; ++i) {
8778       int M = HalfMask[i];
8779       if (M >= NumElements) {
8780         V2BlendMask.push_back(M - NumElements);
8781         V1BlendMask.push_back(-1);
8782         BlendMask.push_back(SplitNumElements + i);
8783       } else if (M >= 0) {
8784         V2BlendMask.push_back(-1);
8785         V1BlendMask.push_back(M);
8786         BlendMask.push_back(i);
8787       } else {
8788         V2BlendMask.push_back(-1);
8789         V1BlendMask.push_back(-1);
8790         BlendMask.push_back(-1);
8791       }
8792     }
8793     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
8794     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
8795     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
8796   };
8797   SDValue Lo = HalfBlend(LoMask);
8798   SDValue Hi = HalfBlend(HiMask);
8799   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
8800 }
8801
8802 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
8803 ///
8804 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
8805 /// isn't available.
8806 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8807                                        const X86Subtarget *Subtarget,
8808                                        SelectionDAG &DAG) {
8809   SDLoc DL(Op);
8810   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8811   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
8812   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8813   ArrayRef<int> Mask = SVOp->getMask();
8814   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8815
8816   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8817   // shuffles aren't a problem and FP and int have the same patterns.
8818
8819   // FIXME: We can handle these more cleverly than splitting for v4f64.
8820   if (isHalfCrossingShuffleMask(Mask))
8821     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8822
8823   if (isSingleInputShuffleMask(Mask)) {
8824     // Non-half-crossing single input shuffles can be lowerid with an
8825     // interleaved permutation.
8826     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
8827                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
8828     return DAG.getNode(X86ISD::VPERMILP, DL, MVT::v4f64, V1,
8829                        DAG.getConstant(VPERMILPMask, MVT::i8));
8830   }
8831
8832   // X86 has dedicated unpack instructions that can handle specific blend
8833   // operations: UNPCKH and UNPCKL.
8834   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
8835     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
8836   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
8837     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
8838   // FIXME: It would be nice to find a way to get canonicalization to commute
8839   // these patterns.
8840   if (isShuffleEquivalent(Mask, 4, 0, 6, 2))
8841     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
8842   if (isShuffleEquivalent(Mask, 5, 1, 7, 3))
8843     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
8844
8845   // Check if the blend happens to exactly fit that of SHUFPD.
8846   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
8847       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
8848     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
8849                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
8850     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
8851                        DAG.getConstant(SHUFPDMask, MVT::i8));
8852   }
8853   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
8854       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
8855     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
8856                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
8857     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
8858                        DAG.getConstant(SHUFPDMask, MVT::i8));
8859   }
8860
8861   // Shuffle the input elements into the desired positions in V1 and V2 and
8862   // blend them together.
8863   int V1Mask[] = {-1, -1, -1, -1};
8864   int V2Mask[] = {-1, -1, -1, -1};
8865   for (int i = 0; i < 4; ++i)
8866     if (Mask[i] >= 0 && Mask[i] < 4)
8867       V1Mask[i] = Mask[i];
8868     else if (Mask[i] >= 4)
8869       V2Mask[i] = Mask[i] - 4;
8870
8871   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
8872   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
8873
8874   unsigned BlendMask = 0;
8875   for (int i = 0; i < 4; ++i)
8876     if (Mask[i] >= 4)
8877       BlendMask |= 1 << i;
8878
8879   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
8880                      DAG.getConstant(BlendMask, MVT::i8));
8881 }
8882
8883 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
8884 ///
8885 /// Largely delegates to common code when we have AVX2 and to the floating-point
8886 /// code when we only have AVX.
8887 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8888                                        const X86Subtarget *Subtarget,
8889                                        SelectionDAG &DAG) {
8890   SDLoc DL(Op);
8891   assert(Op.getSimpleValueType() == MVT::v4i64 && "Bad shuffle type!");
8892   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8893   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
8894   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8895   ArrayRef<int> Mask = SVOp->getMask();
8896   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8897
8898   // FIXME: If we have AVX2, we should delegate to generic code as crossing
8899   // shuffles aren't a problem and FP and int have the same patterns.
8900
8901   if (isHalfCrossingShuffleMask(Mask))
8902     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8903
8904   // AVX1 doesn't provide any facilities for v4i64 shuffles, bitcast and
8905   // delegate to floating point code.
8906   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V1);
8907   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f64, V2);
8908   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i64,
8909                      lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG));
8910 }
8911
8912 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
8913 ///
8914 /// This routine either breaks down the specific type of a 256-bit x86 vector
8915 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
8916 /// together based on the available instructions.
8917 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8918                                         MVT VT, const X86Subtarget *Subtarget,
8919                                         SelectionDAG &DAG) {
8920   switch (VT.SimpleTy) {
8921   case MVT::v4f64:
8922     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8923   case MVT::v4i64:
8924     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8925   case MVT::v8i32:
8926   case MVT::v8f32:
8927   case MVT::v16i16:
8928   case MVT::v32i8:
8929     // Fall back to the basic pattern of extracting the high half and forming
8930     // a 4-way blend.
8931     // FIXME: Add targeted lowering for each type that can document rationale
8932     // for delegating to this when necessary.
8933     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
8934
8935   default:
8936     llvm_unreachable("Not a valid 256-bit x86 vector type!");
8937   }
8938 }
8939
8940 /// \brief Tiny helper function to test whether a shuffle mask could be
8941 /// simplified by widening the elements being shuffled.
8942 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
8943   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8944     if ((Mask[i] != -1 && Mask[i] % 2 != 0) ||
8945         (Mask[i + 1] != -1 && (Mask[i + 1] % 2 != 1 ||
8946                                (Mask[i] != -1 && Mask[i] + 1 != Mask[i + 1]))))
8947       return false;
8948
8949   return true;
8950 }
8951
8952 /// \brief Top-level lowering for x86 vector shuffles.
8953 ///
8954 /// This handles decomposition, canonicalization, and lowering of all x86
8955 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8956 /// above in helper routines. The canonicalization attempts to widen shuffles
8957 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8958 /// s.t. only one of the two inputs needs to be tested, etc.
8959 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8960                                   SelectionDAG &DAG) {
8961   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8962   ArrayRef<int> Mask = SVOp->getMask();
8963   SDValue V1 = Op.getOperand(0);
8964   SDValue V2 = Op.getOperand(1);
8965   MVT VT = Op.getSimpleValueType();
8966   int NumElements = VT.getVectorNumElements();
8967   SDLoc dl(Op);
8968
8969   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8970
8971   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8972   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8973   if (V1IsUndef && V2IsUndef)
8974     return DAG.getUNDEF(VT);
8975
8976   // When we create a shuffle node we put the UNDEF node to second operand,
8977   // but in some cases the first operand may be transformed to UNDEF.
8978   // In this case we should just commute the node.
8979   if (V1IsUndef)
8980     return DAG.getCommutedVectorShuffle(*SVOp);
8981
8982   // Check for non-undef masks pointing at an undef vector and make the masks
8983   // undef as well. This makes it easier to match the shuffle based solely on
8984   // the mask.
8985   if (V2IsUndef)
8986     for (int M : Mask)
8987       if (M >= NumElements) {
8988         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8989         for (int &M : NewMask)
8990           if (M >= NumElements)
8991             M = -1;
8992         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8993       }
8994
8995   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8996   // lanes but wider integers. We cap this to not form integers larger than i64
8997   // but it might be interesting to form i128 integers to handle flipping the
8998   // low and high halves of AVX 256-bit vectors.
8999   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
9000       canWidenShuffleElements(Mask)) {
9001     SmallVector<int, 8> NewMask;
9002     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
9003       NewMask.push_back(Mask[i] != -1
9004                             ? Mask[i] / 2
9005                             : (Mask[i + 1] != -1 ? Mask[i + 1] / 2 : -1));
9006     MVT NewVT =
9007         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
9008                          VT.getVectorNumElements() / 2);
9009     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
9010     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
9011     return DAG.getNode(ISD::BITCAST, dl, VT,
9012                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
9013   }
9014
9015   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
9016   for (int M : SVOp->getMask())
9017     if (M < 0)
9018       ++NumUndefElements;
9019     else if (M < NumElements)
9020       ++NumV1Elements;
9021     else
9022       ++NumV2Elements;
9023
9024   // Commute the shuffle as needed such that more elements come from V1 than
9025   // V2. This allows us to match the shuffle pattern strictly on how many
9026   // elements come from V1 without handling the symmetric cases.
9027   if (NumV2Elements > NumV1Elements)
9028     return DAG.getCommutedVectorShuffle(*SVOp);
9029
9030   // When the number of V1 and V2 elements are the same, try to minimize the
9031   // number of uses of V2 in the low half of the vector.
9032   if (NumV1Elements == NumV2Elements) {
9033     int LowV1Elements = 0, LowV2Elements = 0;
9034     for (int M : SVOp->getMask().slice(0, NumElements / 2))
9035       if (M >= NumElements)
9036         ++LowV2Elements;
9037       else if (M >= 0)
9038         ++LowV1Elements;
9039     if (LowV2Elements > LowV1Elements)
9040       return DAG.getCommutedVectorShuffle(*SVOp);
9041   }
9042
9043   // For each vector width, delegate to a specialized lowering routine.
9044   if (VT.getSizeInBits() == 128)
9045     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
9046
9047   if (VT.getSizeInBits() == 256)
9048     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
9049
9050   llvm_unreachable("Unimplemented!");
9051 }
9052
9053
9054 //===----------------------------------------------------------------------===//
9055 // Legacy vector shuffle lowering
9056 //
9057 // This code is the legacy code handling vector shuffles until the above
9058 // replaces its functionality and performance.
9059 //===----------------------------------------------------------------------===//
9060
9061 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
9062                         bool hasInt256, unsigned *MaskOut = nullptr) {
9063   MVT EltVT = VT.getVectorElementType();
9064
9065   // There is no blend with immediate in AVX-512.
9066   if (VT.is512BitVector())
9067     return false;
9068
9069   if (!hasSSE41 || EltVT == MVT::i8)
9070     return false;
9071   if (!hasInt256 && VT == MVT::v16i16)
9072     return false;
9073
9074   unsigned MaskValue = 0;
9075   unsigned NumElems = VT.getVectorNumElements();
9076   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9077   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9078   unsigned NumElemsInLane = NumElems / NumLanes;
9079
9080   // Blend for v16i16 should be symetric for the both lanes.
9081   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9082
9083     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
9084     int EltIdx = MaskVals[i];
9085
9086     if ((EltIdx < 0 || EltIdx == (int)i) &&
9087         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
9088       continue;
9089
9090     if (((unsigned)EltIdx == (i + NumElems)) &&
9091         (SndLaneEltIdx < 0 ||
9092          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
9093       MaskValue |= (1 << i);
9094     else
9095       return false;
9096   }
9097
9098   if (MaskOut)
9099     *MaskOut = MaskValue;
9100   return true;
9101 }
9102
9103 // Try to lower a shuffle node into a simple blend instruction.
9104 // This function assumes isBlendMask returns true for this
9105 // SuffleVectorSDNode
9106 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
9107                                           unsigned MaskValue,
9108                                           const X86Subtarget *Subtarget,
9109                                           SelectionDAG &DAG) {
9110   MVT VT = SVOp->getSimpleValueType(0);
9111   MVT EltVT = VT.getVectorElementType();
9112   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
9113                      Subtarget->hasInt256() && "Trying to lower a "
9114                                                "VECTOR_SHUFFLE to a Blend but "
9115                                                "with the wrong mask"));
9116   SDValue V1 = SVOp->getOperand(0);
9117   SDValue V2 = SVOp->getOperand(1);
9118   SDLoc dl(SVOp);
9119   unsigned NumElems = VT.getVectorNumElements();
9120
9121   // Convert i32 vectors to floating point if it is not AVX2.
9122   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9123   MVT BlendVT = VT;
9124   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9125     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9126                                NumElems);
9127     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
9128     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
9129   }
9130
9131   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
9132                             DAG.getConstant(MaskValue, MVT::i32));
9133   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9134 }
9135
9136 /// In vector type \p VT, return true if the element at index \p InputIdx
9137 /// falls on a different 128-bit lane than \p OutputIdx.
9138 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
9139                                      unsigned OutputIdx) {
9140   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
9141   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
9142 }
9143
9144 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
9145 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
9146 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
9147 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
9148 /// zero.
9149 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
9150                          SelectionDAG &DAG) {
9151   MVT VT = V1.getSimpleValueType();
9152   assert(VT.is128BitVector() || VT.is256BitVector());
9153
9154   MVT EltVT = VT.getVectorElementType();
9155   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
9156   unsigned NumElts = VT.getVectorNumElements();
9157
9158   SmallVector<SDValue, 32> PshufbMask;
9159   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
9160     int InputIdx = MaskVals[OutputIdx];
9161     unsigned InputByteIdx;
9162
9163     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
9164       InputByteIdx = 0x80;
9165     else {
9166       // Cross lane is not allowed.
9167       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
9168         return SDValue();
9169       InputByteIdx = InputIdx * EltSizeInBytes;
9170       // Index is an byte offset within the 128-bit lane.
9171       InputByteIdx &= 0xf;
9172     }
9173
9174     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
9175       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
9176       if (InputByteIdx != 0x80)
9177         ++InputByteIdx;
9178     }
9179   }
9180
9181   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
9182   if (ShufVT != VT)
9183     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
9184   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
9185                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
9186 }
9187
9188 // v8i16 shuffles - Prefer shuffles in the following order:
9189 // 1. [all]   pshuflw, pshufhw, optional move
9190 // 2. [ssse3] 1 x pshufb
9191 // 3. [ssse3] 2 x pshufb + 1 x por
9192 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
9193 static SDValue
9194 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
9195                          SelectionDAG &DAG) {
9196   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9197   SDValue V1 = SVOp->getOperand(0);
9198   SDValue V2 = SVOp->getOperand(1);
9199   SDLoc dl(SVOp);
9200   SmallVector<int, 8> MaskVals;
9201
9202   // Determine if more than 1 of the words in each of the low and high quadwords
9203   // of the result come from the same quadword of one of the two inputs.  Undef
9204   // mask values count as coming from any quadword, for better codegen.
9205   //
9206   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
9207   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
9208   unsigned LoQuad[] = { 0, 0, 0, 0 };
9209   unsigned HiQuad[] = { 0, 0, 0, 0 };
9210   // Indices of quads used.
9211   std::bitset<4> InputQuads;
9212   for (unsigned i = 0; i < 8; ++i) {
9213     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
9214     int EltIdx = SVOp->getMaskElt(i);
9215     MaskVals.push_back(EltIdx);
9216     if (EltIdx < 0) {
9217       ++Quad[0];
9218       ++Quad[1];
9219       ++Quad[2];
9220       ++Quad[3];
9221       continue;
9222     }
9223     ++Quad[EltIdx / 4];
9224     InputQuads.set(EltIdx / 4);
9225   }
9226
9227   int BestLoQuad = -1;
9228   unsigned MaxQuad = 1;
9229   for (unsigned i = 0; i < 4; ++i) {
9230     if (LoQuad[i] > MaxQuad) {
9231       BestLoQuad = i;
9232       MaxQuad = LoQuad[i];
9233     }
9234   }
9235
9236   int BestHiQuad = -1;
9237   MaxQuad = 1;
9238   for (unsigned i = 0; i < 4; ++i) {
9239     if (HiQuad[i] > MaxQuad) {
9240       BestHiQuad = i;
9241       MaxQuad = HiQuad[i];
9242     }
9243   }
9244
9245   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
9246   // of the two input vectors, shuffle them into one input vector so only a
9247   // single pshufb instruction is necessary. If there are more than 2 input
9248   // quads, disable the next transformation since it does not help SSSE3.
9249   bool V1Used = InputQuads[0] || InputQuads[1];
9250   bool V2Used = InputQuads[2] || InputQuads[3];
9251   if (Subtarget->hasSSSE3()) {
9252     if (InputQuads.count() == 2 && V1Used && V2Used) {
9253       BestLoQuad = InputQuads[0] ? 0 : 1;
9254       BestHiQuad = InputQuads[2] ? 2 : 3;
9255     }
9256     if (InputQuads.count() > 2) {
9257       BestLoQuad = -1;
9258       BestHiQuad = -1;
9259     }
9260   }
9261
9262   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
9263   // the shuffle mask.  If a quad is scored as -1, that means that it contains
9264   // words from all 4 input quadwords.
9265   SDValue NewV;
9266   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
9267     int MaskV[] = {
9268       BestLoQuad < 0 ? 0 : BestLoQuad,
9269       BestHiQuad < 0 ? 1 : BestHiQuad
9270     };
9271     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
9272                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
9273                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
9274     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
9275
9276     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
9277     // source words for the shuffle, to aid later transformations.
9278     bool AllWordsInNewV = true;
9279     bool InOrder[2] = { true, true };
9280     for (unsigned i = 0; i != 8; ++i) {
9281       int idx = MaskVals[i];
9282       if (idx != (int)i)
9283         InOrder[i/4] = false;
9284       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
9285         continue;
9286       AllWordsInNewV = false;
9287       break;
9288     }
9289
9290     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
9291     if (AllWordsInNewV) {
9292       for (int i = 0; i != 8; ++i) {
9293         int idx = MaskVals[i];
9294         if (idx < 0)
9295           continue;
9296         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
9297         if ((idx != i) && idx < 4)
9298           pshufhw = false;
9299         if ((idx != i) && idx > 3)
9300           pshuflw = false;
9301       }
9302       V1 = NewV;
9303       V2Used = false;
9304       BestLoQuad = 0;
9305       BestHiQuad = 1;
9306     }
9307
9308     // If we've eliminated the use of V2, and the new mask is a pshuflw or
9309     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
9310     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
9311       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
9312       unsigned TargetMask = 0;
9313       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
9314                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
9315       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9316       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
9317                              getShufflePSHUFLWImmediate(SVOp);
9318       V1 = NewV.getOperand(0);
9319       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
9320     }
9321   }
9322
9323   // Promote splats to a larger type which usually leads to more efficient code.
9324   // FIXME: Is this true if pshufb is available?
9325   if (SVOp->isSplat())
9326     return PromoteSplat(SVOp, DAG);
9327
9328   // If we have SSSE3, and all words of the result are from 1 input vector,
9329   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
9330   // is present, fall back to case 4.
9331   if (Subtarget->hasSSSE3()) {
9332     SmallVector<SDValue,16> pshufbMask;
9333
9334     // If we have elements from both input vectors, set the high bit of the
9335     // shuffle mask element to zero out elements that come from V2 in the V1
9336     // mask, and elements that come from V1 in the V2 mask, so that the two
9337     // results can be OR'd together.
9338     bool TwoInputs = V1Used && V2Used;
9339     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
9340     if (!TwoInputs)
9341       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9342
9343     // Calculate the shuffle mask for the second input, shuffle it, and
9344     // OR it with the first shuffled input.
9345     CommuteVectorShuffleMask(MaskVals, 8);
9346     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
9347     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9348     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9349   }
9350
9351   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
9352   // and update MaskVals with new element order.
9353   std::bitset<8> InOrder;
9354   if (BestLoQuad >= 0) {
9355     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
9356     for (int i = 0; i != 4; ++i) {
9357       int idx = MaskVals[i];
9358       if (idx < 0) {
9359         InOrder.set(i);
9360       } else if ((idx / 4) == BestLoQuad) {
9361         MaskV[i] = idx & 3;
9362         InOrder.set(i);
9363       }
9364     }
9365     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9366                                 &MaskV[0]);
9367
9368     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9369       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9370       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
9371                                   NewV.getOperand(0),
9372                                   getShufflePSHUFLWImmediate(SVOp), DAG);
9373     }
9374   }
9375
9376   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
9377   // and update MaskVals with the new element order.
9378   if (BestHiQuad >= 0) {
9379     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
9380     for (unsigned i = 4; i != 8; ++i) {
9381       int idx = MaskVals[i];
9382       if (idx < 0) {
9383         InOrder.set(i);
9384       } else if ((idx / 4) == BestHiQuad) {
9385         MaskV[i] = (idx & 3) + 4;
9386         InOrder.set(i);
9387       }
9388     }
9389     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
9390                                 &MaskV[0]);
9391
9392     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
9393       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
9394       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
9395                                   NewV.getOperand(0),
9396                                   getShufflePSHUFHWImmediate(SVOp), DAG);
9397     }
9398   }
9399
9400   // In case BestHi & BestLo were both -1, which means each quadword has a word
9401   // from each of the four input quadwords, calculate the InOrder bitvector now
9402   // before falling through to the insert/extract cleanup.
9403   if (BestLoQuad == -1 && BestHiQuad == -1) {
9404     NewV = V1;
9405     for (int i = 0; i != 8; ++i)
9406       if (MaskVals[i] < 0 || MaskVals[i] == i)
9407         InOrder.set(i);
9408   }
9409
9410   // The other elements are put in the right place using pextrw and pinsrw.
9411   for (unsigned i = 0; i != 8; ++i) {
9412     if (InOrder[i])
9413       continue;
9414     int EltIdx = MaskVals[i];
9415     if (EltIdx < 0)
9416       continue;
9417     SDValue ExtOp = (EltIdx < 8) ?
9418       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
9419                   DAG.getIntPtrConstant(EltIdx)) :
9420       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
9421                   DAG.getIntPtrConstant(EltIdx - 8));
9422     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
9423                        DAG.getIntPtrConstant(i));
9424   }
9425   return NewV;
9426 }
9427
9428 /// \brief v16i16 shuffles
9429 ///
9430 /// FIXME: We only support generation of a single pshufb currently.  We can
9431 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
9432 /// well (e.g 2 x pshufb + 1 x por).
9433 static SDValue
9434 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
9435   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9436   SDValue V1 = SVOp->getOperand(0);
9437   SDValue V2 = SVOp->getOperand(1);
9438   SDLoc dl(SVOp);
9439
9440   if (V2.getOpcode() != ISD::UNDEF)
9441     return SDValue();
9442
9443   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9444   return getPSHUFB(MaskVals, V1, dl, DAG);
9445 }
9446
9447 // v16i8 shuffles - Prefer shuffles in the following order:
9448 // 1. [ssse3] 1 x pshufb
9449 // 2. [ssse3] 2 x pshufb + 1 x por
9450 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
9451 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
9452                                         const X86Subtarget* Subtarget,
9453                                         SelectionDAG &DAG) {
9454   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9455   SDValue V1 = SVOp->getOperand(0);
9456   SDValue V2 = SVOp->getOperand(1);
9457   SDLoc dl(SVOp);
9458   ArrayRef<int> MaskVals = SVOp->getMask();
9459
9460   // Promote splats to a larger type which usually leads to more efficient code.
9461   // FIXME: Is this true if pshufb is available?
9462   if (SVOp->isSplat())
9463     return PromoteSplat(SVOp, DAG);
9464
9465   // If we have SSSE3, case 1 is generated when all result bytes come from
9466   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
9467   // present, fall back to case 3.
9468
9469   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
9470   if (Subtarget->hasSSSE3()) {
9471     SmallVector<SDValue,16> pshufbMask;
9472
9473     // If all result elements are from one input vector, then only translate
9474     // undef mask values to 0x80 (zero out result) in the pshufb mask.
9475     //
9476     // Otherwise, we have elements from both input vectors, and must zero out
9477     // elements that come from V2 in the first mask, and V1 in the second mask
9478     // so that we can OR them together.
9479     for (unsigned i = 0; i != 16; ++i) {
9480       int EltIdx = MaskVals[i];
9481       if (EltIdx < 0 || EltIdx >= 16)
9482         EltIdx = 0x80;
9483       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9484     }
9485     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
9486                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9487                                  MVT::v16i8, pshufbMask));
9488
9489     // As PSHUFB will zero elements with negative indices, it's safe to ignore
9490     // the 2nd operand if it's undefined or zero.
9491     if (V2.getOpcode() == ISD::UNDEF ||
9492         ISD::isBuildVectorAllZeros(V2.getNode()))
9493       return V1;
9494
9495     // Calculate the shuffle mask for the second input, shuffle it, and
9496     // OR it with the first shuffled input.
9497     pshufbMask.clear();
9498     for (unsigned i = 0; i != 16; ++i) {
9499       int EltIdx = MaskVals[i];
9500       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
9501       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
9502     }
9503     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
9504                      DAG.getNode(ISD::BUILD_VECTOR, dl,
9505                                  MVT::v16i8, pshufbMask));
9506     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
9507   }
9508
9509   // No SSSE3 - Calculate in place words and then fix all out of place words
9510   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
9511   // the 16 different words that comprise the two doublequadword input vectors.
9512   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
9513   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
9514   SDValue NewV = V1;
9515   for (int i = 0; i != 8; ++i) {
9516     int Elt0 = MaskVals[i*2];
9517     int Elt1 = MaskVals[i*2+1];
9518
9519     // This word of the result is all undef, skip it.
9520     if (Elt0 < 0 && Elt1 < 0)
9521       continue;
9522
9523     // This word of the result is already in the correct place, skip it.
9524     if ((Elt0 == i*2) && (Elt1 == i*2+1))
9525       continue;
9526
9527     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
9528     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
9529     SDValue InsElt;
9530
9531     // If Elt0 and Elt1 are defined, are consecutive, and can be load
9532     // using a single extract together, load it and store it.
9533     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
9534       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9535                            DAG.getIntPtrConstant(Elt1 / 2));
9536       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9537                         DAG.getIntPtrConstant(i));
9538       continue;
9539     }
9540
9541     // If Elt1 is defined, extract it from the appropriate source.  If the
9542     // source byte is not also odd, shift the extracted word left 8 bits
9543     // otherwise clear the bottom 8 bits if we need to do an or.
9544     if (Elt1 >= 0) {
9545       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
9546                            DAG.getIntPtrConstant(Elt1 / 2));
9547       if ((Elt1 & 1) == 0)
9548         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
9549                              DAG.getConstant(8,
9550                                   TLI.getShiftAmountTy(InsElt.getValueType())));
9551       else if (Elt0 >= 0)
9552         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
9553                              DAG.getConstant(0xFF00, MVT::i16));
9554     }
9555     // If Elt0 is defined, extract it from the appropriate source.  If the
9556     // source byte is not also even, shift the extracted word right 8 bits. If
9557     // Elt1 was also defined, OR the extracted values together before
9558     // inserting them in the result.
9559     if (Elt0 >= 0) {
9560       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
9561                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
9562       if ((Elt0 & 1) != 0)
9563         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
9564                               DAG.getConstant(8,
9565                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
9566       else if (Elt1 >= 0)
9567         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
9568                              DAG.getConstant(0x00FF, MVT::i16));
9569       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
9570                          : InsElt0;
9571     }
9572     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
9573                        DAG.getIntPtrConstant(i));
9574   }
9575   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
9576 }
9577
9578 // v32i8 shuffles - Translate to VPSHUFB if possible.
9579 static
9580 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
9581                                  const X86Subtarget *Subtarget,
9582                                  SelectionDAG &DAG) {
9583   MVT VT = SVOp->getSimpleValueType(0);
9584   SDValue V1 = SVOp->getOperand(0);
9585   SDValue V2 = SVOp->getOperand(1);
9586   SDLoc dl(SVOp);
9587   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
9588
9589   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9590   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
9591   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
9592
9593   // VPSHUFB may be generated if
9594   // (1) one of input vector is undefined or zeroinitializer.
9595   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
9596   // And (2) the mask indexes don't cross the 128-bit lane.
9597   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
9598       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
9599     return SDValue();
9600
9601   if (V1IsAllZero && !V2IsAllZero) {
9602     CommuteVectorShuffleMask(MaskVals, 32);
9603     V1 = V2;
9604   }
9605   return getPSHUFB(MaskVals, V1, dl, DAG);
9606 }
9607
9608 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
9609 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
9610 /// done when every pair / quad of shuffle mask elements point to elements in
9611 /// the right sequence. e.g.
9612 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
9613 static
9614 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
9615                                  SelectionDAG &DAG) {
9616   MVT VT = SVOp->getSimpleValueType(0);
9617   SDLoc dl(SVOp);
9618   unsigned NumElems = VT.getVectorNumElements();
9619   MVT NewVT;
9620   unsigned Scale;
9621   switch (VT.SimpleTy) {
9622   default: llvm_unreachable("Unexpected!");
9623   case MVT::v2i64:
9624   case MVT::v2f64:
9625            return SDValue(SVOp, 0);
9626   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
9627   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
9628   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
9629   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
9630   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
9631   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
9632   }
9633
9634   SmallVector<int, 8> MaskVec;
9635   for (unsigned i = 0; i != NumElems; i += Scale) {
9636     int StartIdx = -1;
9637     for (unsigned j = 0; j != Scale; ++j) {
9638       int EltIdx = SVOp->getMaskElt(i+j);
9639       if (EltIdx < 0)
9640         continue;
9641       if (StartIdx < 0)
9642         StartIdx = (EltIdx / Scale);
9643       if (EltIdx != (int)(StartIdx*Scale + j))
9644         return SDValue();
9645     }
9646     MaskVec.push_back(StartIdx);
9647   }
9648
9649   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
9650   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
9651   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
9652 }
9653
9654 /// getVZextMovL - Return a zero-extending vector move low node.
9655 ///
9656 static SDValue getVZextMovL(MVT VT, MVT OpVT,
9657                             SDValue SrcOp, SelectionDAG &DAG,
9658                             const X86Subtarget *Subtarget, SDLoc dl) {
9659   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
9660     LoadSDNode *LD = nullptr;
9661     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
9662       LD = dyn_cast<LoadSDNode>(SrcOp);
9663     if (!LD) {
9664       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
9665       // instead.
9666       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
9667       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
9668           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9669           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
9670           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
9671         // PR2108
9672         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
9673         return DAG.getNode(ISD::BITCAST, dl, VT,
9674                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9675                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9676                                                    OpVT,
9677                                                    SrcOp.getOperand(0)
9678                                                           .getOperand(0))));
9679       }
9680     }
9681   }
9682
9683   return DAG.getNode(ISD::BITCAST, dl, VT,
9684                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
9685                                  DAG.getNode(ISD::BITCAST, dl,
9686                                              OpVT, SrcOp)));
9687 }
9688
9689 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
9690 /// which could not be matched by any known target speficic shuffle
9691 static SDValue
9692 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9693
9694   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
9695   if (NewOp.getNode())
9696     return NewOp;
9697
9698   MVT VT = SVOp->getSimpleValueType(0);
9699
9700   unsigned NumElems = VT.getVectorNumElements();
9701   unsigned NumLaneElems = NumElems / 2;
9702
9703   SDLoc dl(SVOp);
9704   MVT EltVT = VT.getVectorElementType();
9705   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
9706   SDValue Output[2];
9707
9708   SmallVector<int, 16> Mask;
9709   for (unsigned l = 0; l < 2; ++l) {
9710     // Build a shuffle mask for the output, discovering on the fly which
9711     // input vectors to use as shuffle operands (recorded in InputUsed).
9712     // If building a suitable shuffle vector proves too hard, then bail
9713     // out with UseBuildVector set.
9714     bool UseBuildVector = false;
9715     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
9716     unsigned LaneStart = l * NumLaneElems;
9717     for (unsigned i = 0; i != NumLaneElems; ++i) {
9718       // The mask element.  This indexes into the input.
9719       int Idx = SVOp->getMaskElt(i+LaneStart);
9720       if (Idx < 0) {
9721         // the mask element does not index into any input vector.
9722         Mask.push_back(-1);
9723         continue;
9724       }
9725
9726       // The input vector this mask element indexes into.
9727       int Input = Idx / NumLaneElems;
9728
9729       // Turn the index into an offset from the start of the input vector.
9730       Idx -= Input * NumLaneElems;
9731
9732       // Find or create a shuffle vector operand to hold this input.
9733       unsigned OpNo;
9734       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
9735         if (InputUsed[OpNo] == Input)
9736           // This input vector is already an operand.
9737           break;
9738         if (InputUsed[OpNo] < 0) {
9739           // Create a new operand for this input vector.
9740           InputUsed[OpNo] = Input;
9741           break;
9742         }
9743       }
9744
9745       if (OpNo >= array_lengthof(InputUsed)) {
9746         // More than two input vectors used!  Give up on trying to create a
9747         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
9748         UseBuildVector = true;
9749         break;
9750       }
9751
9752       // Add the mask index for the new shuffle vector.
9753       Mask.push_back(Idx + OpNo * NumLaneElems);
9754     }
9755
9756     if (UseBuildVector) {
9757       SmallVector<SDValue, 16> SVOps;
9758       for (unsigned i = 0; i != NumLaneElems; ++i) {
9759         // The mask element.  This indexes into the input.
9760         int Idx = SVOp->getMaskElt(i+LaneStart);
9761         if (Idx < 0) {
9762           SVOps.push_back(DAG.getUNDEF(EltVT));
9763           continue;
9764         }
9765
9766         // The input vector this mask element indexes into.
9767         int Input = Idx / NumElems;
9768
9769         // Turn the index into an offset from the start of the input vector.
9770         Idx -= Input * NumElems;
9771
9772         // Extract the vector element by hand.
9773         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
9774                                     SVOp->getOperand(Input),
9775                                     DAG.getIntPtrConstant(Idx)));
9776       }
9777
9778       // Construct the output using a BUILD_VECTOR.
9779       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
9780     } else if (InputUsed[0] < 0) {
9781       // No input vectors were used! The result is undefined.
9782       Output[l] = DAG.getUNDEF(NVT);
9783     } else {
9784       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
9785                                         (InputUsed[0] % 2) * NumLaneElems,
9786                                         DAG, dl);
9787       // If only one input was used, use an undefined vector for the other.
9788       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
9789         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
9790                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
9791       // At least one input vector was used. Create a new shuffle vector.
9792       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
9793     }
9794
9795     Mask.clear();
9796   }
9797
9798   // Concatenate the result back
9799   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
9800 }
9801
9802 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9803 /// 4 elements, and match them with several different shuffle types.
9804 static SDValue
9805 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9806   SDValue V1 = SVOp->getOperand(0);
9807   SDValue V2 = SVOp->getOperand(1);
9808   SDLoc dl(SVOp);
9809   MVT VT = SVOp->getSimpleValueType(0);
9810
9811   assert(VT.is128BitVector() && "Unsupported vector size");
9812
9813   std::pair<int, int> Locs[4];
9814   int Mask1[] = { -1, -1, -1, -1 };
9815   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9816
9817   unsigned NumHi = 0;
9818   unsigned NumLo = 0;
9819   for (unsigned i = 0; i != 4; ++i) {
9820     int Idx = PermMask[i];
9821     if (Idx < 0) {
9822       Locs[i] = std::make_pair(-1, -1);
9823     } else {
9824       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9825       if (Idx < 4) {
9826         Locs[i] = std::make_pair(0, NumLo);
9827         Mask1[NumLo] = Idx;
9828         NumLo++;
9829       } else {
9830         Locs[i] = std::make_pair(1, NumHi);
9831         if (2+NumHi < 4)
9832           Mask1[2+NumHi] = Idx;
9833         NumHi++;
9834       }
9835     }
9836   }
9837
9838   if (NumLo <= 2 && NumHi <= 2) {
9839     // If no more than two elements come from either vector. This can be
9840     // implemented with two shuffles. First shuffle gather the elements.
9841     // The second shuffle, which takes the first shuffle as both of its
9842     // vector operands, put the elements into the right order.
9843     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9844
9845     int Mask2[] = { -1, -1, -1, -1 };
9846
9847     for (unsigned i = 0; i != 4; ++i)
9848       if (Locs[i].first != -1) {
9849         unsigned Idx = (i < 2) ? 0 : 4;
9850         Idx += Locs[i].first * 2 + Locs[i].second;
9851         Mask2[i] = Idx;
9852       }
9853
9854     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9855   }
9856
9857   if (NumLo == 3 || NumHi == 3) {
9858     // Otherwise, we must have three elements from one vector, call it X, and
9859     // one element from the other, call it Y.  First, use a shufps to build an
9860     // intermediate vector with the one element from Y and the element from X
9861     // that will be in the same half in the final destination (the indexes don't
9862     // matter). Then, use a shufps to build the final vector, taking the half
9863     // containing the element from Y from the intermediate, and the other half
9864     // from X.
9865     if (NumHi == 3) {
9866       // Normalize it so the 3 elements come from V1.
9867       CommuteVectorShuffleMask(PermMask, 4);
9868       std::swap(V1, V2);
9869     }
9870
9871     // Find the element from V2.
9872     unsigned HiIndex;
9873     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9874       int Val = PermMask[HiIndex];
9875       if (Val < 0)
9876         continue;
9877       if (Val >= 4)
9878         break;
9879     }
9880
9881     Mask1[0] = PermMask[HiIndex];
9882     Mask1[1] = -1;
9883     Mask1[2] = PermMask[HiIndex^1];
9884     Mask1[3] = -1;
9885     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9886
9887     if (HiIndex >= 2) {
9888       Mask1[0] = PermMask[0];
9889       Mask1[1] = PermMask[1];
9890       Mask1[2] = HiIndex & 1 ? 6 : 4;
9891       Mask1[3] = HiIndex & 1 ? 4 : 6;
9892       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9893     }
9894
9895     Mask1[0] = HiIndex & 1 ? 2 : 0;
9896     Mask1[1] = HiIndex & 1 ? 0 : 2;
9897     Mask1[2] = PermMask[2];
9898     Mask1[3] = PermMask[3];
9899     if (Mask1[2] >= 0)
9900       Mask1[2] += 4;
9901     if (Mask1[3] >= 0)
9902       Mask1[3] += 4;
9903     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9904   }
9905
9906   // Break it into (shuffle shuffle_hi, shuffle_lo).
9907   int LoMask[] = { -1, -1, -1, -1 };
9908   int HiMask[] = { -1, -1, -1, -1 };
9909
9910   int *MaskPtr = LoMask;
9911   unsigned MaskIdx = 0;
9912   unsigned LoIdx = 0;
9913   unsigned HiIdx = 2;
9914   for (unsigned i = 0; i != 4; ++i) {
9915     if (i == 2) {
9916       MaskPtr = HiMask;
9917       MaskIdx = 1;
9918       LoIdx = 0;
9919       HiIdx = 2;
9920     }
9921     int Idx = PermMask[i];
9922     if (Idx < 0) {
9923       Locs[i] = std::make_pair(-1, -1);
9924     } else if (Idx < 4) {
9925       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9926       MaskPtr[LoIdx] = Idx;
9927       LoIdx++;
9928     } else {
9929       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9930       MaskPtr[HiIdx] = Idx;
9931       HiIdx++;
9932     }
9933   }
9934
9935   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9936   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9937   int MaskOps[] = { -1, -1, -1, -1 };
9938   for (unsigned i = 0; i != 4; ++i)
9939     if (Locs[i].first != -1)
9940       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9941   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9942 }
9943
9944 static bool MayFoldVectorLoad(SDValue V) {
9945   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9946     V = V.getOperand(0);
9947
9948   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9949     V = V.getOperand(0);
9950   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9951       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9952     // BUILD_VECTOR (load), undef
9953     V = V.getOperand(0);
9954
9955   return MayFoldLoad(V);
9956 }
9957
9958 static
9959 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9960   MVT VT = Op.getSimpleValueType();
9961
9962   // Canonizalize to v2f64.
9963   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9964   return DAG.getNode(ISD::BITCAST, dl, VT,
9965                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9966                                           V1, DAG));
9967 }
9968
9969 static
9970 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9971                         bool HasSSE2) {
9972   SDValue V1 = Op.getOperand(0);
9973   SDValue V2 = Op.getOperand(1);
9974   MVT VT = Op.getSimpleValueType();
9975
9976   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9977
9978   if (HasSSE2 && VT == MVT::v2f64)
9979     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9980
9981   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9982   return DAG.getNode(ISD::BITCAST, dl, VT,
9983                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9984                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9985                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9986 }
9987
9988 static
9989 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9990   SDValue V1 = Op.getOperand(0);
9991   SDValue V2 = Op.getOperand(1);
9992   MVT VT = Op.getSimpleValueType();
9993
9994   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9995          "unsupported shuffle type");
9996
9997   if (V2.getOpcode() == ISD::UNDEF)
9998     V2 = V1;
9999
10000   // v4i32 or v4f32
10001   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
10002 }
10003
10004 static
10005 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
10006   SDValue V1 = Op.getOperand(0);
10007   SDValue V2 = Op.getOperand(1);
10008   MVT VT = Op.getSimpleValueType();
10009   unsigned NumElems = VT.getVectorNumElements();
10010
10011   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
10012   // operand of these instructions is only memory, so check if there's a
10013   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
10014   // same masks.
10015   bool CanFoldLoad = false;
10016
10017   // Trivial case, when V2 comes from a load.
10018   if (MayFoldVectorLoad(V2))
10019     CanFoldLoad = true;
10020
10021   // When V1 is a load, it can be folded later into a store in isel, example:
10022   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
10023   //    turns into:
10024   //  (MOVLPSmr addr:$src1, VR128:$src2)
10025   // So, recognize this potential and also use MOVLPS or MOVLPD
10026   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
10027     CanFoldLoad = true;
10028
10029   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10030   if (CanFoldLoad) {
10031     if (HasSSE2 && NumElems == 2)
10032       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
10033
10034     if (NumElems == 4)
10035       // If we don't care about the second element, proceed to use movss.
10036       if (SVOp->getMaskElt(1) != -1)
10037         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
10038   }
10039
10040   // movl and movlp will both match v2i64, but v2i64 is never matched by
10041   // movl earlier because we make it strict to avoid messing with the movlp load
10042   // folding logic (see the code above getMOVLP call). Match it here then,
10043   // this is horrible, but will stay like this until we move all shuffle
10044   // matching to x86 specific nodes. Note that for the 1st condition all
10045   // types are matched with movsd.
10046   if (HasSSE2) {
10047     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
10048     // as to remove this logic from here, as much as possible
10049     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
10050       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10051     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10052   }
10053
10054   assert(VT != MVT::v4i32 && "unsupported shuffle type");
10055
10056   // Invert the operand order and use SHUFPS to match it.
10057   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
10058                               getShuffleSHUFImmediate(SVOp), DAG);
10059 }
10060
10061 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
10062                                          SelectionDAG &DAG) {
10063   SDLoc dl(Load);
10064   MVT VT = Load->getSimpleValueType(0);
10065   MVT EVT = VT.getVectorElementType();
10066   SDValue Addr = Load->getOperand(1);
10067   SDValue NewAddr = DAG.getNode(
10068       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
10069       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
10070
10071   SDValue NewLoad =
10072       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
10073                   DAG.getMachineFunction().getMachineMemOperand(
10074                       Load->getMemOperand(), 0, EVT.getStoreSize()));
10075   return NewLoad;
10076 }
10077
10078 // It is only safe to call this function if isINSERTPSMask is true for
10079 // this shufflevector mask.
10080 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
10081                            SelectionDAG &DAG) {
10082   // Generate an insertps instruction when inserting an f32 from memory onto a
10083   // v4f32 or when copying a member from one v4f32 to another.
10084   // We also use it for transferring i32 from one register to another,
10085   // since it simply copies the same bits.
10086   // If we're transferring an i32 from memory to a specific element in a
10087   // register, we output a generic DAG that will match the PINSRD
10088   // instruction.
10089   MVT VT = SVOp->getSimpleValueType(0);
10090   MVT EVT = VT.getVectorElementType();
10091   SDValue V1 = SVOp->getOperand(0);
10092   SDValue V2 = SVOp->getOperand(1);
10093   auto Mask = SVOp->getMask();
10094   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
10095          "unsupported vector type for insertps/pinsrd");
10096
10097   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
10098   auto FromV2Predicate = [](const int &i) { return i >= 4; };
10099   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
10100
10101   SDValue From;
10102   SDValue To;
10103   unsigned DestIndex;
10104   if (FromV1 == 1) {
10105     From = V1;
10106     To = V2;
10107     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
10108                 Mask.begin();
10109
10110     // If we have 1 element from each vector, we have to check if we're
10111     // changing V1's element's place. If so, we're done. Otherwise, we
10112     // should assume we're changing V2's element's place and behave
10113     // accordingly.
10114     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
10115     assert(DestIndex <= INT32_MAX && "truncated destination index");
10116     if (FromV1 == FromV2 &&
10117         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
10118       From = V2;
10119       To = V1;
10120       DestIndex =
10121           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
10122     }
10123   } else {
10124     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
10125            "More than one element from V1 and from V2, or no elements from one "
10126            "of the vectors. This case should not have returned true from "
10127            "isINSERTPSMask");
10128     From = V2;
10129     To = V1;
10130     DestIndex =
10131         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
10132   }
10133
10134   // Get an index into the source vector in the range [0,4) (the mask is
10135   // in the range [0,8) because it can address V1 and V2)
10136   unsigned SrcIndex = Mask[DestIndex] % 4;
10137   if (MayFoldLoad(From)) {
10138     // Trivial case, when From comes from a load and is only used by the
10139     // shuffle. Make it use insertps from the vector that we need from that
10140     // load.
10141     SDValue NewLoad =
10142         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
10143     if (!NewLoad.getNode())
10144       return SDValue();
10145
10146     if (EVT == MVT::f32) {
10147       // Create this as a scalar to vector to match the instruction pattern.
10148       SDValue LoadScalarToVector =
10149           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
10150       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
10151       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
10152                          InsertpsMask);
10153     } else { // EVT == MVT::i32
10154       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
10155       // instruction, to match the PINSRD instruction, which loads an i32 to a
10156       // certain vector element.
10157       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
10158                          DAG.getConstant(DestIndex, MVT::i32));
10159     }
10160   }
10161
10162   // Vector-element-to-vector
10163   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
10164   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
10165 }
10166
10167 // Reduce a vector shuffle to zext.
10168 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
10169                                     SelectionDAG &DAG) {
10170   // PMOVZX is only available from SSE41.
10171   if (!Subtarget->hasSSE41())
10172     return SDValue();
10173
10174   MVT VT = Op.getSimpleValueType();
10175
10176   // Only AVX2 support 256-bit vector integer extending.
10177   if (!Subtarget->hasInt256() && VT.is256BitVector())
10178     return SDValue();
10179
10180   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10181   SDLoc DL(Op);
10182   SDValue V1 = Op.getOperand(0);
10183   SDValue V2 = Op.getOperand(1);
10184   unsigned NumElems = VT.getVectorNumElements();
10185
10186   // Extending is an unary operation and the element type of the source vector
10187   // won't be equal to or larger than i64.
10188   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
10189       VT.getVectorElementType() == MVT::i64)
10190     return SDValue();
10191
10192   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
10193   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
10194   while ((1U << Shift) < NumElems) {
10195     if (SVOp->getMaskElt(1U << Shift) == 1)
10196       break;
10197     Shift += 1;
10198     // The maximal ratio is 8, i.e. from i8 to i64.
10199     if (Shift > 3)
10200       return SDValue();
10201   }
10202
10203   // Check the shuffle mask.
10204   unsigned Mask = (1U << Shift) - 1;
10205   for (unsigned i = 0; i != NumElems; ++i) {
10206     int EltIdx = SVOp->getMaskElt(i);
10207     if ((i & Mask) != 0 && EltIdx != -1)
10208       return SDValue();
10209     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
10210       return SDValue();
10211   }
10212
10213   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
10214   MVT NeVT = MVT::getIntegerVT(NBits);
10215   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
10216
10217   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
10218     return SDValue();
10219
10220   // Simplify the operand as it's prepared to be fed into shuffle.
10221   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
10222   if (V1.getOpcode() == ISD::BITCAST &&
10223       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
10224       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10225       V1.getOperand(0).getOperand(0)
10226         .getSimpleValueType().getSizeInBits() == SignificantBits) {
10227     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
10228     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
10229     ConstantSDNode *CIdx =
10230       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
10231     // If it's foldable, i.e. normal load with single use, we will let code
10232     // selection to fold it. Otherwise, we will short the conversion sequence.
10233     if (CIdx && CIdx->getZExtValue() == 0 &&
10234         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
10235       MVT FullVT = V.getSimpleValueType();
10236       MVT V1VT = V1.getSimpleValueType();
10237       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
10238         // The "ext_vec_elt" node is wider than the result node.
10239         // In this case we should extract subvector from V.
10240         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
10241         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
10242         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
10243                                         FullVT.getVectorNumElements()/Ratio);
10244         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
10245                         DAG.getIntPtrConstant(0));
10246       }
10247       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
10248     }
10249   }
10250
10251   return DAG.getNode(ISD::BITCAST, DL, VT,
10252                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
10253 }
10254
10255 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10256                                       SelectionDAG &DAG) {
10257   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10258   MVT VT = Op.getSimpleValueType();
10259   SDLoc dl(Op);
10260   SDValue V1 = Op.getOperand(0);
10261   SDValue V2 = Op.getOperand(1);
10262
10263   if (isZeroShuffle(SVOp))
10264     return getZeroVector(VT, Subtarget, DAG, dl);
10265
10266   // Handle splat operations
10267   if (SVOp->isSplat()) {
10268     // Use vbroadcast whenever the splat comes from a foldable load
10269     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
10270     if (Broadcast.getNode())
10271       return Broadcast;
10272   }
10273
10274   // Check integer expanding shuffles.
10275   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
10276   if (NewOp.getNode())
10277     return NewOp;
10278
10279   // If the shuffle can be profitably rewritten as a narrower shuffle, then
10280   // do it!
10281   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
10282       VT == MVT::v32i8) {
10283     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10284     if (NewOp.getNode())
10285       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
10286   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
10287     // FIXME: Figure out a cleaner way to do this.
10288     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
10289       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10290       if (NewOp.getNode()) {
10291         MVT NewVT = NewOp.getSimpleValueType();
10292         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
10293                                NewVT, true, false))
10294           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
10295                               dl);
10296       }
10297     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
10298       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
10299       if (NewOp.getNode()) {
10300         MVT NewVT = NewOp.getSimpleValueType();
10301         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
10302           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
10303                               dl);
10304       }
10305     }
10306   }
10307   return SDValue();
10308 }
10309
10310 SDValue
10311 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
10312   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10313   SDValue V1 = Op.getOperand(0);
10314   SDValue V2 = Op.getOperand(1);
10315   MVT VT = Op.getSimpleValueType();
10316   SDLoc dl(Op);
10317   unsigned NumElems = VT.getVectorNumElements();
10318   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10319   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10320   bool V1IsSplat = false;
10321   bool V2IsSplat = false;
10322   bool HasSSE2 = Subtarget->hasSSE2();
10323   bool HasFp256    = Subtarget->hasFp256();
10324   bool HasInt256   = Subtarget->hasInt256();
10325   MachineFunction &MF = DAG.getMachineFunction();
10326   bool OptForSize = MF.getFunction()->getAttributes().
10327     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
10328
10329   // Check if we should use the experimental vector shuffle lowering. If so,
10330   // delegate completely to that code path.
10331   if (ExperimentalVectorShuffleLowering)
10332     return lowerVectorShuffle(Op, Subtarget, DAG);
10333
10334   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10335
10336   if (V1IsUndef && V2IsUndef)
10337     return DAG.getUNDEF(VT);
10338
10339   // When we create a shuffle node we put the UNDEF node to second operand,
10340   // but in some cases the first operand may be transformed to UNDEF.
10341   // In this case we should just commute the node.
10342   if (V1IsUndef)
10343     return DAG.getCommutedVectorShuffle(*SVOp);
10344
10345   // Vector shuffle lowering takes 3 steps:
10346   //
10347   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
10348   //    narrowing and commutation of operands should be handled.
10349   // 2) Matching of shuffles with known shuffle masks to x86 target specific
10350   //    shuffle nodes.
10351   // 3) Rewriting of unmatched masks into new generic shuffle operations,
10352   //    so the shuffle can be broken into other shuffles and the legalizer can
10353   //    try the lowering again.
10354   //
10355   // The general idea is that no vector_shuffle operation should be left to
10356   // be matched during isel, all of them must be converted to a target specific
10357   // node here.
10358
10359   // Normalize the input vectors. Here splats, zeroed vectors, profitable
10360   // narrowing and commutation of operands should be handled. The actual code
10361   // doesn't include all of those, work in progress...
10362   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
10363   if (NewOp.getNode())
10364     return NewOp;
10365
10366   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
10367
10368   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
10369   // unpckh_undef). Only use pshufd if speed is more important than size.
10370   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10371     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10372   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10373     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10374
10375   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
10376       V2IsUndef && MayFoldVectorLoad(V1))
10377     return getMOVDDup(Op, dl, V1, DAG);
10378
10379   if (isMOVHLPS_v_undef_Mask(M, VT))
10380     return getMOVHighToLow(Op, dl, DAG);
10381
10382   // Use to match splats
10383   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
10384       (VT == MVT::v2f64 || VT == MVT::v2i64))
10385     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10386
10387   if (isPSHUFDMask(M, VT)) {
10388     // The actual implementation will match the mask in the if above and then
10389     // during isel it can match several different instructions, not only pshufd
10390     // as its name says, sad but true, emulate the behavior for now...
10391     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
10392       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
10393
10394     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
10395
10396     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
10397       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
10398
10399     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
10400       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
10401                                   DAG);
10402
10403     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
10404                                 TargetMask, DAG);
10405   }
10406
10407   if (isPALIGNRMask(M, VT, Subtarget))
10408     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
10409                                 getShufflePALIGNRImmediate(SVOp),
10410                                 DAG);
10411
10412   if (isVALIGNMask(M, VT, Subtarget))
10413     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
10414                                 getShuffleVALIGNImmediate(SVOp),
10415                                 DAG);
10416
10417   // Check if this can be converted into a logical shift.
10418   bool isLeft = false;
10419   unsigned ShAmt = 0;
10420   SDValue ShVal;
10421   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
10422   if (isShift && ShVal.hasOneUse()) {
10423     // If the shifted value has multiple uses, it may be cheaper to use
10424     // v_set0 + movlhps or movhlps, etc.
10425     MVT EltVT = VT.getVectorElementType();
10426     ShAmt *= EltVT.getSizeInBits();
10427     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10428   }
10429
10430   if (isMOVLMask(M, VT)) {
10431     if (ISD::isBuildVectorAllZeros(V1.getNode()))
10432       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
10433     if (!isMOVLPMask(M, VT)) {
10434       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
10435         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10436
10437       if (VT == MVT::v4i32 || VT == MVT::v4f32)
10438         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10439     }
10440   }
10441
10442   // FIXME: fold these into legal mask.
10443   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
10444     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
10445
10446   if (isMOVHLPSMask(M, VT))
10447     return getMOVHighToLow(Op, dl, DAG);
10448
10449   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
10450     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
10451
10452   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
10453     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
10454
10455   if (isMOVLPMask(M, VT))
10456     return getMOVLP(Op, dl, DAG, HasSSE2);
10457
10458   if (ShouldXformToMOVHLPS(M, VT) ||
10459       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
10460     return DAG.getCommutedVectorShuffle(*SVOp);
10461
10462   if (isShift) {
10463     // No better options. Use a vshldq / vsrldq.
10464     MVT EltVT = VT.getVectorElementType();
10465     ShAmt *= EltVT.getSizeInBits();
10466     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
10467   }
10468
10469   bool Commuted = false;
10470   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
10471   // 1,1,1,1 -> v8i16 though.
10472   BitVector UndefElements;
10473   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
10474     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10475       V1IsSplat = true;
10476   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
10477     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
10478       V2IsSplat = true;
10479
10480   // Canonicalize the splat or undef, if present, to be on the RHS.
10481   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
10482     CommuteVectorShuffleMask(M, NumElems);
10483     std::swap(V1, V2);
10484     std::swap(V1IsSplat, V2IsSplat);
10485     Commuted = true;
10486   }
10487
10488   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
10489     // Shuffling low element of v1 into undef, just return v1.
10490     if (V2IsUndef)
10491       return V1;
10492     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
10493     // the instruction selector will not match, so get a canonical MOVL with
10494     // swapped operands to undo the commute.
10495     return getMOVL(DAG, dl, VT, V2, V1);
10496   }
10497
10498   if (isUNPCKLMask(M, VT, HasInt256))
10499     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10500
10501   if (isUNPCKHMask(M, VT, HasInt256))
10502     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10503
10504   if (V2IsSplat) {
10505     // Normalize mask so all entries that point to V2 points to its first
10506     // element then try to match unpck{h|l} again. If match, return a
10507     // new vector_shuffle with the corrected mask.p
10508     SmallVector<int, 8> NewMask(M.begin(), M.end());
10509     NormalizeMask(NewMask, NumElems);
10510     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
10511       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10512     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
10513       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10514   }
10515
10516   if (Commuted) {
10517     // Commute is back and try unpck* again.
10518     // FIXME: this seems wrong.
10519     CommuteVectorShuffleMask(M, NumElems);
10520     std::swap(V1, V2);
10521     std::swap(V1IsSplat, V2IsSplat);
10522
10523     if (isUNPCKLMask(M, VT, HasInt256))
10524       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
10525
10526     if (isUNPCKHMask(M, VT, HasInt256))
10527       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
10528   }
10529
10530   // Normalize the node to match x86 shuffle ops if needed
10531   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
10532     return DAG.getCommutedVectorShuffle(*SVOp);
10533
10534   // The checks below are all present in isShuffleMaskLegal, but they are
10535   // inlined here right now to enable us to directly emit target specific
10536   // nodes, and remove one by one until they don't return Op anymore.
10537
10538   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
10539       SVOp->getSplatIndex() == 0 && V2IsUndef) {
10540     if (VT == MVT::v2f64 || VT == MVT::v2i64)
10541       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10542   }
10543
10544   if (isPSHUFHWMask(M, VT, HasInt256))
10545     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
10546                                 getShufflePSHUFHWImmediate(SVOp),
10547                                 DAG);
10548
10549   if (isPSHUFLWMask(M, VT, HasInt256))
10550     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
10551                                 getShufflePSHUFLWImmediate(SVOp),
10552                                 DAG);
10553
10554   unsigned MaskValue;
10555   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
10556                   &MaskValue))
10557     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
10558
10559   if (isSHUFPMask(M, VT))
10560     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
10561                                 getShuffleSHUFImmediate(SVOp), DAG);
10562
10563   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
10564     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
10565   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
10566     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
10567
10568   //===--------------------------------------------------------------------===//
10569   // Generate target specific nodes for 128 or 256-bit shuffles only
10570   // supported in the AVX instruction set.
10571   //
10572
10573   // Handle VMOVDDUPY permutations
10574   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
10575     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
10576
10577   // Handle VPERMILPS/D* permutations
10578   if (isVPERMILPMask(M, VT)) {
10579     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
10580       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
10581                                   getShuffleSHUFImmediate(SVOp), DAG);
10582     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
10583                                 getShuffleSHUFImmediate(SVOp), DAG);
10584   }
10585
10586   unsigned Idx;
10587   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
10588     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
10589                               Idx*(NumElems/2), DAG, dl);
10590
10591   // Handle VPERM2F128/VPERM2I128 permutations
10592   if (isVPERM2X128Mask(M, VT, HasFp256))
10593     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
10594                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
10595
10596   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
10597     return getINSERTPS(SVOp, dl, DAG);
10598
10599   unsigned Imm8;
10600   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
10601     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
10602
10603   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
10604       VT.is512BitVector()) {
10605     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
10606     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
10607     SmallVector<SDValue, 16> permclMask;
10608     for (unsigned i = 0; i != NumElems; ++i) {
10609       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
10610     }
10611
10612     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
10613     if (V2IsUndef)
10614       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
10615       return DAG.getNode(X86ISD::VPERMV, dl, VT,
10616                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
10617     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
10618                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
10619   }
10620
10621   //===--------------------------------------------------------------------===//
10622   // Since no target specific shuffle was selected for this generic one,
10623   // lower it into other known shuffles. FIXME: this isn't true yet, but
10624   // this is the plan.
10625   //
10626
10627   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
10628   if (VT == MVT::v8i16) {
10629     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
10630     if (NewOp.getNode())
10631       return NewOp;
10632   }
10633
10634   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
10635     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
10636     if (NewOp.getNode())
10637       return NewOp;
10638   }
10639
10640   if (VT == MVT::v16i8) {
10641     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
10642     if (NewOp.getNode())
10643       return NewOp;
10644   }
10645
10646   if (VT == MVT::v32i8) {
10647     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
10648     if (NewOp.getNode())
10649       return NewOp;
10650   }
10651
10652   // Handle all 128-bit wide vectors with 4 elements, and match them with
10653   // several different shuffle types.
10654   if (NumElems == 4 && VT.is128BitVector())
10655     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
10656
10657   // Handle general 256-bit shuffles
10658   if (VT.is256BitVector())
10659     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
10660
10661   return SDValue();
10662 }
10663
10664 // This function assumes its argument is a BUILD_VECTOR of constants or
10665 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10666 // true.
10667 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10668                                     unsigned &MaskValue) {
10669   MaskValue = 0;
10670   unsigned NumElems = BuildVector->getNumOperands();
10671   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10672   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10673   unsigned NumElemsInLane = NumElems / NumLanes;
10674
10675   // Blend for v16i16 should be symetric for the both lanes.
10676   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10677     SDValue EltCond = BuildVector->getOperand(i);
10678     SDValue SndLaneEltCond =
10679         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10680
10681     int Lane1Cond = -1, Lane2Cond = -1;
10682     if (isa<ConstantSDNode>(EltCond))
10683       Lane1Cond = !isZero(EltCond);
10684     if (isa<ConstantSDNode>(SndLaneEltCond))
10685       Lane2Cond = !isZero(SndLaneEltCond);
10686
10687     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10688       // Lane1Cond != 0, means we want the first argument.
10689       // Lane1Cond == 0, means we want the second argument.
10690       // The encoding of this argument is 0 for the first argument, 1
10691       // for the second. Therefore, invert the condition.
10692       MaskValue |= !Lane1Cond << i;
10693     else if (Lane1Cond < 0)
10694       MaskValue |= !Lane2Cond << i;
10695     else
10696       return false;
10697   }
10698   return true;
10699 }
10700
10701 // Try to lower a vselect node into a simple blend instruction.
10702 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
10703                                    SelectionDAG &DAG) {
10704   SDValue Cond = Op.getOperand(0);
10705   SDValue LHS = Op.getOperand(1);
10706   SDValue RHS = Op.getOperand(2);
10707   SDLoc dl(Op);
10708   MVT VT = Op.getSimpleValueType();
10709   MVT EltVT = VT.getVectorElementType();
10710   unsigned NumElems = VT.getVectorNumElements();
10711
10712   // There is no blend with immediate in AVX-512.
10713   if (VT.is512BitVector())
10714     return SDValue();
10715
10716   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
10717     return SDValue();
10718   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
10719     return SDValue();
10720
10721   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10722     return SDValue();
10723
10724   // Check the mask for BLEND and build the value.
10725   unsigned MaskValue = 0;
10726   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
10727     return SDValue();
10728
10729   // Convert i32 vectors to floating point if it is not AVX2.
10730   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
10731   MVT BlendVT = VT;
10732   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
10733     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
10734                                NumElems);
10735     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
10736     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
10737   }
10738
10739   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
10740                             DAG.getConstant(MaskValue, MVT::i32));
10741   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
10742 }
10743
10744 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10745   // A vselect where all conditions and data are constants can be optimized into
10746   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10747   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10748       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10749       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10750     return SDValue();
10751   
10752   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
10753   if (BlendOp.getNode())
10754     return BlendOp;
10755
10756   // Some types for vselect were previously set to Expand, not Legal or
10757   // Custom. Return an empty SDValue so we fall-through to Expand, after
10758   // the Custom lowering phase.
10759   MVT VT = Op.getSimpleValueType();
10760   switch (VT.SimpleTy) {
10761   default:
10762     break;
10763   case MVT::v8i16:
10764   case MVT::v16i16:
10765     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10766       break;
10767     return SDValue();
10768   }
10769
10770   // We couldn't create a "Blend with immediate" node.
10771   // This node should still be legal, but we'll have to emit a blendv*
10772   // instruction.
10773   return Op;
10774 }
10775
10776 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10777   MVT VT = Op.getSimpleValueType();
10778   SDLoc dl(Op);
10779
10780   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10781     return SDValue();
10782
10783   if (VT.getSizeInBits() == 8) {
10784     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10785                                   Op.getOperand(0), Op.getOperand(1));
10786     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10787                                   DAG.getValueType(VT));
10788     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10789   }
10790
10791   if (VT.getSizeInBits() == 16) {
10792     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10793     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10794     if (Idx == 0)
10795       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10796                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10797                                      DAG.getNode(ISD::BITCAST, dl,
10798                                                  MVT::v4i32,
10799                                                  Op.getOperand(0)),
10800                                      Op.getOperand(1)));
10801     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10802                                   Op.getOperand(0), Op.getOperand(1));
10803     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10804                                   DAG.getValueType(VT));
10805     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10806   }
10807
10808   if (VT == MVT::f32) {
10809     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10810     // the result back to FR32 register. It's only worth matching if the
10811     // result has a single use which is a store or a bitcast to i32.  And in
10812     // the case of a store, it's not worth it if the index is a constant 0,
10813     // because a MOVSSmr can be used instead, which is smaller and faster.
10814     if (!Op.hasOneUse())
10815       return SDValue();
10816     SDNode *User = *Op.getNode()->use_begin();
10817     if ((User->getOpcode() != ISD::STORE ||
10818          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10819           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10820         (User->getOpcode() != ISD::BITCAST ||
10821          User->getValueType(0) != MVT::i32))
10822       return SDValue();
10823     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10824                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10825                                               Op.getOperand(0)),
10826                                               Op.getOperand(1));
10827     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10828   }
10829
10830   if (VT == MVT::i32 || VT == MVT::i64) {
10831     // ExtractPS/pextrq works with constant index.
10832     if (isa<ConstantSDNode>(Op.getOperand(1)))
10833       return Op;
10834   }
10835   return SDValue();
10836 }
10837
10838 /// Extract one bit from mask vector, like v16i1 or v8i1.
10839 /// AVX-512 feature.
10840 SDValue
10841 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10842   SDValue Vec = Op.getOperand(0);
10843   SDLoc dl(Vec);
10844   MVT VecVT = Vec.getSimpleValueType();
10845   SDValue Idx = Op.getOperand(1);
10846   MVT EltVT = Op.getSimpleValueType();
10847
10848   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10849
10850   // variable index can't be handled in mask registers,
10851   // extend vector to VR512
10852   if (!isa<ConstantSDNode>(Idx)) {
10853     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10854     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10855     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10856                               ExtVT.getVectorElementType(), Ext, Idx);
10857     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10858   }
10859
10860   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10861   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10862   unsigned MaxSift = rc->getSize()*8 - 1;
10863   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10864                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10865   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10866                     DAG.getConstant(MaxSift, MVT::i8));
10867   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10868                        DAG.getIntPtrConstant(0));
10869 }
10870
10871 SDValue
10872 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10873                                            SelectionDAG &DAG) const {
10874   SDLoc dl(Op);
10875   SDValue Vec = Op.getOperand(0);
10876   MVT VecVT = Vec.getSimpleValueType();
10877   SDValue Idx = Op.getOperand(1);
10878
10879   if (Op.getSimpleValueType() == MVT::i1)
10880     return ExtractBitFromMaskVector(Op, DAG);
10881
10882   if (!isa<ConstantSDNode>(Idx)) {
10883     if (VecVT.is512BitVector() ||
10884         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10885          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10886
10887       MVT MaskEltVT =
10888         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10889       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10890                                     MaskEltVT.getSizeInBits());
10891
10892       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10893       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10894                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10895                                 Idx, DAG.getConstant(0, getPointerTy()));
10896       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10897       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10898                         Perm, DAG.getConstant(0, getPointerTy()));
10899     }
10900     return SDValue();
10901   }
10902
10903   // If this is a 256-bit vector result, first extract the 128-bit vector and
10904   // then extract the element from the 128-bit vector.
10905   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10906
10907     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10908     // Get the 128-bit vector.
10909     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10910     MVT EltVT = VecVT.getVectorElementType();
10911
10912     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10913
10914     //if (IdxVal >= NumElems/2)
10915     //  IdxVal -= NumElems/2;
10916     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10917     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10918                        DAG.getConstant(IdxVal, MVT::i32));
10919   }
10920
10921   assert(VecVT.is128BitVector() && "Unexpected vector length");
10922
10923   if (Subtarget->hasSSE41()) {
10924     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10925     if (Res.getNode())
10926       return Res;
10927   }
10928
10929   MVT VT = Op.getSimpleValueType();
10930   // TODO: handle v16i8.
10931   if (VT.getSizeInBits() == 16) {
10932     SDValue Vec = Op.getOperand(0);
10933     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10934     if (Idx == 0)
10935       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10936                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10937                                      DAG.getNode(ISD::BITCAST, dl,
10938                                                  MVT::v4i32, Vec),
10939                                      Op.getOperand(1)));
10940     // Transform it so it match pextrw which produces a 32-bit result.
10941     MVT EltVT = MVT::i32;
10942     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10943                                   Op.getOperand(0), Op.getOperand(1));
10944     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10945                                   DAG.getValueType(VT));
10946     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10947   }
10948
10949   if (VT.getSizeInBits() == 32) {
10950     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10951     if (Idx == 0)
10952       return Op;
10953
10954     // SHUFPS the element to the lowest double word, then movss.
10955     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10956     MVT VVT = Op.getOperand(0).getSimpleValueType();
10957     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10958                                        DAG.getUNDEF(VVT), Mask);
10959     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10960                        DAG.getIntPtrConstant(0));
10961   }
10962
10963   if (VT.getSizeInBits() == 64) {
10964     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10965     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10966     //        to match extract_elt for f64.
10967     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10968     if (Idx == 0)
10969       return Op;
10970
10971     // UNPCKHPD the element to the lowest double word, then movsd.
10972     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10973     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10974     int Mask[2] = { 1, -1 };
10975     MVT VVT = Op.getOperand(0).getSimpleValueType();
10976     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10977                                        DAG.getUNDEF(VVT), Mask);
10978     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10979                        DAG.getIntPtrConstant(0));
10980   }
10981
10982   return SDValue();
10983 }
10984
10985 /// Insert one bit to mask vector, like v16i1 or v8i1.
10986 /// AVX-512 feature.
10987 SDValue 
10988 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10989   SDLoc dl(Op);
10990   SDValue Vec = Op.getOperand(0);
10991   SDValue Elt = Op.getOperand(1);
10992   SDValue Idx = Op.getOperand(2);
10993   MVT VecVT = Vec.getSimpleValueType();
10994
10995   if (!isa<ConstantSDNode>(Idx)) {
10996     // Non constant index. Extend source and destination,
10997     // insert element and then truncate the result.
10998     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10999     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11000     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
11001       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11002       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11003     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11004   }
11005
11006   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11007   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11008   if (Vec.getOpcode() == ISD::UNDEF)
11009     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11010                        DAG.getConstant(IdxVal, MVT::i8));
11011   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11012   unsigned MaxSift = rc->getSize()*8 - 1;
11013   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11014                     DAG.getConstant(MaxSift, MVT::i8));
11015   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
11016                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
11017   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11018 }
11019
11020 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11021                                                   SelectionDAG &DAG) const {
11022   MVT VT = Op.getSimpleValueType();
11023   MVT EltVT = VT.getVectorElementType();
11024
11025   if (EltVT == MVT::i1)
11026     return InsertBitToMaskVector(Op, DAG);
11027
11028   SDLoc dl(Op);
11029   SDValue N0 = Op.getOperand(0);
11030   SDValue N1 = Op.getOperand(1);
11031   SDValue N2 = Op.getOperand(2);
11032   if (!isa<ConstantSDNode>(N2))
11033     return SDValue();
11034   auto *N2C = cast<ConstantSDNode>(N2);
11035   unsigned IdxVal = N2C->getZExtValue();
11036
11037   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11038   // into that, and then insert the subvector back into the result.
11039   if (VT.is256BitVector() || VT.is512BitVector()) {
11040     // Get the desired 128-bit vector half.
11041     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11042
11043     // Insert the element into the desired half.
11044     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11045     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11046
11047     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11048                     DAG.getConstant(IdxIn128, MVT::i32));
11049
11050     // Insert the changed part back to the 256-bit vector
11051     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11052   }
11053   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11054
11055   if (Subtarget->hasSSE41()) {
11056     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11057       unsigned Opc;
11058       if (VT == MVT::v8i16) {
11059         Opc = X86ISD::PINSRW;
11060       } else {
11061         assert(VT == MVT::v16i8);
11062         Opc = X86ISD::PINSRB;
11063       }
11064
11065       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11066       // argument.
11067       if (N1.getValueType() != MVT::i32)
11068         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11069       if (N2.getValueType() != MVT::i32)
11070         N2 = DAG.getIntPtrConstant(IdxVal);
11071       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11072     }
11073
11074     if (EltVT == MVT::f32) {
11075       // Bits [7:6] of the constant are the source select.  This will always be
11076       //  zero here.  The DAG Combiner may combine an extract_elt index into
11077       //  these
11078       //  bits.  For example (insert (extract, 3), 2) could be matched by
11079       //  putting
11080       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
11081       // Bits [5:4] of the constant are the destination select.  This is the
11082       //  value of the incoming immediate.
11083       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
11084       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11085       N2 = DAG.getIntPtrConstant(IdxVal << 4);
11086       // Create this as a scalar to vector..
11087       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11088       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11089     }
11090
11091     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11092       // PINSR* works with constant index.
11093       return Op;
11094     }
11095   }
11096
11097   if (EltVT == MVT::i8)
11098     return SDValue();
11099
11100   if (EltVT.getSizeInBits() == 16) {
11101     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11102     // as its second argument.
11103     if (N1.getValueType() != MVT::i32)
11104       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11105     if (N2.getValueType() != MVT::i32)
11106       N2 = DAG.getIntPtrConstant(IdxVal);
11107     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11108   }
11109   return SDValue();
11110 }
11111
11112 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11113   SDLoc dl(Op);
11114   MVT OpVT = Op.getSimpleValueType();
11115
11116   // If this is a 256-bit vector result, first insert into a 128-bit
11117   // vector and then insert into the 256-bit vector.
11118   if (!OpVT.is128BitVector()) {
11119     // Insert into a 128-bit vector.
11120     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11121     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11122                                  OpVT.getVectorNumElements() / SizeFactor);
11123
11124     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11125
11126     // Insert the 128-bit vector.
11127     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11128   }
11129
11130   if (OpVT == MVT::v1i64 &&
11131       Op.getOperand(0).getValueType() == MVT::i64)
11132     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11133
11134   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11135   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11136   return DAG.getNode(ISD::BITCAST, dl, OpVT,
11137                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
11138 }
11139
11140 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11141 // a simple subregister reference or explicit instructions to grab
11142 // upper bits of a vector.
11143 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11144                                       SelectionDAG &DAG) {
11145   SDLoc dl(Op);
11146   SDValue In =  Op.getOperand(0);
11147   SDValue Idx = Op.getOperand(1);
11148   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11149   MVT ResVT   = Op.getSimpleValueType();
11150   MVT InVT    = In.getSimpleValueType();
11151
11152   if (Subtarget->hasFp256()) {
11153     if (ResVT.is128BitVector() &&
11154         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11155         isa<ConstantSDNode>(Idx)) {
11156       return Extract128BitVector(In, IdxVal, DAG, dl);
11157     }
11158     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11159         isa<ConstantSDNode>(Idx)) {
11160       return Extract256BitVector(In, IdxVal, DAG, dl);
11161     }
11162   }
11163   return SDValue();
11164 }
11165
11166 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11167 // simple superregister reference or explicit instructions to insert
11168 // the upper bits of a vector.
11169 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11170                                      SelectionDAG &DAG) {
11171   if (Subtarget->hasFp256()) {
11172     SDLoc dl(Op.getNode());
11173     SDValue Vec = Op.getNode()->getOperand(0);
11174     SDValue SubVec = Op.getNode()->getOperand(1);
11175     SDValue Idx = Op.getNode()->getOperand(2);
11176
11177     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
11178          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
11179         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
11180         isa<ConstantSDNode>(Idx)) {
11181       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11182       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11183     }
11184
11185     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
11186         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
11187         isa<ConstantSDNode>(Idx)) {
11188       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11189       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11190     }
11191   }
11192   return SDValue();
11193 }
11194
11195 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11196 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11197 // one of the above mentioned nodes. It has to be wrapped because otherwise
11198 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11199 // be used to form addressing mode. These wrapped nodes will be selected
11200 // into MOV32ri.
11201 SDValue
11202 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11203   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11204
11205   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11206   // global base reg.
11207   unsigned char OpFlag = 0;
11208   unsigned WrapperKind = X86ISD::Wrapper;
11209   CodeModel::Model M = DAG.getTarget().getCodeModel();
11210
11211   if (Subtarget->isPICStyleRIPRel() &&
11212       (M == CodeModel::Small || M == CodeModel::Kernel))
11213     WrapperKind = X86ISD::WrapperRIP;
11214   else if (Subtarget->isPICStyleGOT())
11215     OpFlag = X86II::MO_GOTOFF;
11216   else if (Subtarget->isPICStyleStubPIC())
11217     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11218
11219   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11220                                              CP->getAlignment(),
11221                                              CP->getOffset(), OpFlag);
11222   SDLoc DL(CP);
11223   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11224   // With PIC, the address is actually $g + Offset.
11225   if (OpFlag) {
11226     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11227                          DAG.getNode(X86ISD::GlobalBaseReg,
11228                                      SDLoc(), getPointerTy()),
11229                          Result);
11230   }
11231
11232   return Result;
11233 }
11234
11235 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11236   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11237
11238   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11239   // global base reg.
11240   unsigned char OpFlag = 0;
11241   unsigned WrapperKind = X86ISD::Wrapper;
11242   CodeModel::Model M = DAG.getTarget().getCodeModel();
11243
11244   if (Subtarget->isPICStyleRIPRel() &&
11245       (M == CodeModel::Small || M == CodeModel::Kernel))
11246     WrapperKind = X86ISD::WrapperRIP;
11247   else if (Subtarget->isPICStyleGOT())
11248     OpFlag = X86II::MO_GOTOFF;
11249   else if (Subtarget->isPICStyleStubPIC())
11250     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11251
11252   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11253                                           OpFlag);
11254   SDLoc DL(JT);
11255   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11256
11257   // With PIC, the address is actually $g + Offset.
11258   if (OpFlag)
11259     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11260                          DAG.getNode(X86ISD::GlobalBaseReg,
11261                                      SDLoc(), getPointerTy()),
11262                          Result);
11263
11264   return Result;
11265 }
11266
11267 SDValue
11268 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11269   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11270
11271   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11272   // global base reg.
11273   unsigned char OpFlag = 0;
11274   unsigned WrapperKind = X86ISD::Wrapper;
11275   CodeModel::Model M = DAG.getTarget().getCodeModel();
11276
11277   if (Subtarget->isPICStyleRIPRel() &&
11278       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11279     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11280       OpFlag = X86II::MO_GOTPCREL;
11281     WrapperKind = X86ISD::WrapperRIP;
11282   } else if (Subtarget->isPICStyleGOT()) {
11283     OpFlag = X86II::MO_GOT;
11284   } else if (Subtarget->isPICStyleStubPIC()) {
11285     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11286   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11287     OpFlag = X86II::MO_DARWIN_NONLAZY;
11288   }
11289
11290   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11291
11292   SDLoc DL(Op);
11293   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11294
11295   // With PIC, the address is actually $g + Offset.
11296   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11297       !Subtarget->is64Bit()) {
11298     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11299                          DAG.getNode(X86ISD::GlobalBaseReg,
11300                                      SDLoc(), getPointerTy()),
11301                          Result);
11302   }
11303
11304   // For symbols that require a load from a stub to get the address, emit the
11305   // load.
11306   if (isGlobalStubReference(OpFlag))
11307     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11308                          MachinePointerInfo::getGOT(), false, false, false, 0);
11309
11310   return Result;
11311 }
11312
11313 SDValue
11314 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11315   // Create the TargetBlockAddressAddress node.
11316   unsigned char OpFlags =
11317     Subtarget->ClassifyBlockAddressReference();
11318   CodeModel::Model M = DAG.getTarget().getCodeModel();
11319   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11320   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11321   SDLoc dl(Op);
11322   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11323                                              OpFlags);
11324
11325   if (Subtarget->isPICStyleRIPRel() &&
11326       (M == CodeModel::Small || M == CodeModel::Kernel))
11327     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11328   else
11329     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11330
11331   // With PIC, the address is actually $g + Offset.
11332   if (isGlobalRelativeToPICBase(OpFlags)) {
11333     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11334                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11335                          Result);
11336   }
11337
11338   return Result;
11339 }
11340
11341 SDValue
11342 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11343                                       int64_t Offset, SelectionDAG &DAG) const {
11344   // Create the TargetGlobalAddress node, folding in the constant
11345   // offset if it is legal.
11346   unsigned char OpFlags =
11347       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11348   CodeModel::Model M = DAG.getTarget().getCodeModel();
11349   SDValue Result;
11350   if (OpFlags == X86II::MO_NO_FLAG &&
11351       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11352     // A direct static reference to a global.
11353     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11354     Offset = 0;
11355   } else {
11356     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11357   }
11358
11359   if (Subtarget->isPICStyleRIPRel() &&
11360       (M == CodeModel::Small || M == CodeModel::Kernel))
11361     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11362   else
11363     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11364
11365   // With PIC, the address is actually $g + Offset.
11366   if (isGlobalRelativeToPICBase(OpFlags)) {
11367     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11368                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11369                          Result);
11370   }
11371
11372   // For globals that require a load from a stub to get the address, emit the
11373   // load.
11374   if (isGlobalStubReference(OpFlags))
11375     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11376                          MachinePointerInfo::getGOT(), false, false, false, 0);
11377
11378   // If there was a non-zero offset that we didn't fold, create an explicit
11379   // addition for it.
11380   if (Offset != 0)
11381     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11382                          DAG.getConstant(Offset, getPointerTy()));
11383
11384   return Result;
11385 }
11386
11387 SDValue
11388 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11389   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11390   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11391   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11392 }
11393
11394 static SDValue
11395 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11396            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11397            unsigned char OperandFlags, bool LocalDynamic = false) {
11398   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11399   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11400   SDLoc dl(GA);
11401   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11402                                            GA->getValueType(0),
11403                                            GA->getOffset(),
11404                                            OperandFlags);
11405
11406   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11407                                            : X86ISD::TLSADDR;
11408
11409   if (InFlag) {
11410     SDValue Ops[] = { Chain,  TGA, *InFlag };
11411     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11412   } else {
11413     SDValue Ops[]  = { Chain, TGA };
11414     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11415   }
11416
11417   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11418   MFI->setAdjustsStack(true);
11419
11420   SDValue Flag = Chain.getValue(1);
11421   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11422 }
11423
11424 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11425 static SDValue
11426 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11427                                 const EVT PtrVT) {
11428   SDValue InFlag;
11429   SDLoc dl(GA);  // ? function entry point might be better
11430   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11431                                    DAG.getNode(X86ISD::GlobalBaseReg,
11432                                                SDLoc(), PtrVT), InFlag);
11433   InFlag = Chain.getValue(1);
11434
11435   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11436 }
11437
11438 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11439 static SDValue
11440 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11441                                 const EVT PtrVT) {
11442   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11443                     X86::RAX, X86II::MO_TLSGD);
11444 }
11445
11446 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11447                                            SelectionDAG &DAG,
11448                                            const EVT PtrVT,
11449                                            bool is64Bit) {
11450   SDLoc dl(GA);
11451
11452   // Get the start address of the TLS block for this module.
11453   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11454       .getInfo<X86MachineFunctionInfo>();
11455   MFI->incNumLocalDynamicTLSAccesses();
11456
11457   SDValue Base;
11458   if (is64Bit) {
11459     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11460                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11461   } else {
11462     SDValue InFlag;
11463     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11464         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11465     InFlag = Chain.getValue(1);
11466     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11467                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11468   }
11469
11470   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11471   // of Base.
11472
11473   // Build x@dtpoff.
11474   unsigned char OperandFlags = X86II::MO_DTPOFF;
11475   unsigned WrapperKind = X86ISD::Wrapper;
11476   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11477                                            GA->getValueType(0),
11478                                            GA->getOffset(), OperandFlags);
11479   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11480
11481   // Add x@dtpoff with the base.
11482   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11483 }
11484
11485 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11486 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11487                                    const EVT PtrVT, TLSModel::Model model,
11488                                    bool is64Bit, bool isPIC) {
11489   SDLoc dl(GA);
11490
11491   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11492   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11493                                                          is64Bit ? 257 : 256));
11494
11495   SDValue ThreadPointer =
11496       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
11497                   MachinePointerInfo(Ptr), false, false, false, 0);
11498
11499   unsigned char OperandFlags = 0;
11500   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11501   // initialexec.
11502   unsigned WrapperKind = X86ISD::Wrapper;
11503   if (model == TLSModel::LocalExec) {
11504     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11505   } else if (model == TLSModel::InitialExec) {
11506     if (is64Bit) {
11507       OperandFlags = X86II::MO_GOTTPOFF;
11508       WrapperKind = X86ISD::WrapperRIP;
11509     } else {
11510       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11511     }
11512   } else {
11513     llvm_unreachable("Unexpected model");
11514   }
11515
11516   // emit "addl x@ntpoff,%eax" (local exec)
11517   // or "addl x@indntpoff,%eax" (initial exec)
11518   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11519   SDValue TGA =
11520       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11521                                  GA->getOffset(), OperandFlags);
11522   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11523
11524   if (model == TLSModel::InitialExec) {
11525     if (isPIC && !is64Bit) {
11526       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11527                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11528                            Offset);
11529     }
11530
11531     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11532                          MachinePointerInfo::getGOT(), false, false, false, 0);
11533   }
11534
11535   // The address of the thread local variable is the add of the thread
11536   // pointer with the offset of the variable.
11537   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11538 }
11539
11540 SDValue
11541 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11542
11543   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11544   const GlobalValue *GV = GA->getGlobal();
11545
11546   if (Subtarget->isTargetELF()) {
11547     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11548
11549     switch (model) {
11550       case TLSModel::GeneralDynamic:
11551         if (Subtarget->is64Bit())
11552           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11553         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11554       case TLSModel::LocalDynamic:
11555         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11556                                            Subtarget->is64Bit());
11557       case TLSModel::InitialExec:
11558       case TLSModel::LocalExec:
11559         return LowerToTLSExecModel(
11560             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11561             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11562     }
11563     llvm_unreachable("Unknown TLS model.");
11564   }
11565
11566   if (Subtarget->isTargetDarwin()) {
11567     // Darwin only has one model of TLS.  Lower to that.
11568     unsigned char OpFlag = 0;
11569     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11570                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11571
11572     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11573     // global base reg.
11574     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11575                  !Subtarget->is64Bit();
11576     if (PIC32)
11577       OpFlag = X86II::MO_TLVP_PIC_BASE;
11578     else
11579       OpFlag = X86II::MO_TLVP;
11580     SDLoc DL(Op);
11581     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11582                                                 GA->getValueType(0),
11583                                                 GA->getOffset(), OpFlag);
11584     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11585
11586     // With PIC32, the address is actually $g + Offset.
11587     if (PIC32)
11588       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11589                            DAG.getNode(X86ISD::GlobalBaseReg,
11590                                        SDLoc(), getPointerTy()),
11591                            Offset);
11592
11593     // Lowering the machine isd will make sure everything is in the right
11594     // location.
11595     SDValue Chain = DAG.getEntryNode();
11596     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11597     SDValue Args[] = { Chain, Offset };
11598     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11599
11600     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11601     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11602     MFI->setAdjustsStack(true);
11603
11604     // And our return value (tls address) is in the standard call return value
11605     // location.
11606     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11607     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11608                               Chain.getValue(1));
11609   }
11610
11611   if (Subtarget->isTargetKnownWindowsMSVC() ||
11612       Subtarget->isTargetWindowsGNU()) {
11613     // Just use the implicit TLS architecture
11614     // Need to generate someting similar to:
11615     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11616     //                                  ; from TEB
11617     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11618     //   mov     rcx, qword [rdx+rcx*8]
11619     //   mov     eax, .tls$:tlsvar
11620     //   [rax+rcx] contains the address
11621     // Windows 64bit: gs:0x58
11622     // Windows 32bit: fs:__tls_array
11623
11624     SDLoc dl(GA);
11625     SDValue Chain = DAG.getEntryNode();
11626
11627     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11628     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11629     // use its literal value of 0x2C.
11630     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11631                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11632                                                              256)
11633                                         : Type::getInt32PtrTy(*DAG.getContext(),
11634                                                               257));
11635
11636     SDValue TlsArray =
11637         Subtarget->is64Bit()
11638             ? DAG.getIntPtrConstant(0x58)
11639             : (Subtarget->isTargetWindowsGNU()
11640                    ? DAG.getIntPtrConstant(0x2C)
11641                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11642
11643     SDValue ThreadPointer =
11644         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11645                     MachinePointerInfo(Ptr), false, false, false, 0);
11646
11647     // Load the _tls_index variable
11648     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11649     if (Subtarget->is64Bit())
11650       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
11651                            IDX, MachinePointerInfo(), MVT::i32,
11652                            false, false, false, 0);
11653     else
11654       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11655                         false, false, false, 0);
11656
11657     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
11658                                     getPointerTy());
11659     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11660
11661     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11662     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11663                       false, false, false, 0);
11664
11665     // Get the offset of start of .tls section
11666     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11667                                              GA->getValueType(0),
11668                                              GA->getOffset(), X86II::MO_SECREL);
11669     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11670
11671     // The address of the thread local variable is the add of the thread
11672     // pointer with the offset of the variable.
11673     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11674   }
11675
11676   llvm_unreachable("TLS not implemented for this target.");
11677 }
11678
11679 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11680 /// and take a 2 x i32 value to shift plus a shift amount.
11681 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11682   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11683   MVT VT = Op.getSimpleValueType();
11684   unsigned VTBits = VT.getSizeInBits();
11685   SDLoc dl(Op);
11686   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11687   SDValue ShOpLo = Op.getOperand(0);
11688   SDValue ShOpHi = Op.getOperand(1);
11689   SDValue ShAmt  = Op.getOperand(2);
11690   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11691   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11692   // during isel.
11693   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11694                                   DAG.getConstant(VTBits - 1, MVT::i8));
11695   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11696                                      DAG.getConstant(VTBits - 1, MVT::i8))
11697                        : DAG.getConstant(0, VT);
11698
11699   SDValue Tmp2, Tmp3;
11700   if (Op.getOpcode() == ISD::SHL_PARTS) {
11701     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11702     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11703   } else {
11704     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11705     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11706   }
11707
11708   // If the shift amount is larger or equal than the width of a part we can't
11709   // rely on the results of shld/shrd. Insert a test and select the appropriate
11710   // values for large shift amounts.
11711   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11712                                 DAG.getConstant(VTBits, MVT::i8));
11713   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11714                              AndNode, DAG.getConstant(0, MVT::i8));
11715
11716   SDValue Hi, Lo;
11717   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11718   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11719   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11720
11721   if (Op.getOpcode() == ISD::SHL_PARTS) {
11722     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11723     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11724   } else {
11725     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11726     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11727   }
11728
11729   SDValue Ops[2] = { Lo, Hi };
11730   return DAG.getMergeValues(Ops, dl);
11731 }
11732
11733 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11734                                            SelectionDAG &DAG) const {
11735   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
11736
11737   if (SrcVT.isVector())
11738     return SDValue();
11739
11740   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11741          "Unknown SINT_TO_FP to lower!");
11742
11743   // These are really Legal; return the operand so the caller accepts it as
11744   // Legal.
11745   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11746     return Op;
11747   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11748       Subtarget->is64Bit()) {
11749     return Op;
11750   }
11751
11752   SDLoc dl(Op);
11753   unsigned Size = SrcVT.getSizeInBits()/8;
11754   MachineFunction &MF = DAG.getMachineFunction();
11755   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11756   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11757   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11758                                StackSlot,
11759                                MachinePointerInfo::getFixedStack(SSFI),
11760                                false, false, 0);
11761   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11762 }
11763
11764 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11765                                      SDValue StackSlot,
11766                                      SelectionDAG &DAG) const {
11767   // Build the FILD
11768   SDLoc DL(Op);
11769   SDVTList Tys;
11770   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11771   if (useSSE)
11772     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11773   else
11774     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11775
11776   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11777
11778   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11779   MachineMemOperand *MMO;
11780   if (FI) {
11781     int SSFI = FI->getIndex();
11782     MMO =
11783       DAG.getMachineFunction()
11784       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11785                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11786   } else {
11787     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11788     StackSlot = StackSlot.getOperand(1);
11789   }
11790   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11791   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11792                                            X86ISD::FILD, DL,
11793                                            Tys, Ops, SrcVT, MMO);
11794
11795   if (useSSE) {
11796     Chain = Result.getValue(1);
11797     SDValue InFlag = Result.getValue(2);
11798
11799     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11800     // shouldn't be necessary except that RFP cannot be live across
11801     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11802     MachineFunction &MF = DAG.getMachineFunction();
11803     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11804     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11805     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11806     Tys = DAG.getVTList(MVT::Other);
11807     SDValue Ops[] = {
11808       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11809     };
11810     MachineMemOperand *MMO =
11811       DAG.getMachineFunction()
11812       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11813                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11814
11815     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11816                                     Ops, Op.getValueType(), MMO);
11817     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11818                          MachinePointerInfo::getFixedStack(SSFI),
11819                          false, false, false, 0);
11820   }
11821
11822   return Result;
11823 }
11824
11825 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11826 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11827                                                SelectionDAG &DAG) const {
11828   // This algorithm is not obvious. Here it is what we're trying to output:
11829   /*
11830      movq       %rax,  %xmm0
11831      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11832      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11833      #ifdef __SSE3__
11834        haddpd   %xmm0, %xmm0
11835      #else
11836        pshufd   $0x4e, %xmm0, %xmm1
11837        addpd    %xmm1, %xmm0
11838      #endif
11839   */
11840
11841   SDLoc dl(Op);
11842   LLVMContext *Context = DAG.getContext();
11843
11844   // Build some magic constants.
11845   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11846   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11847   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11848
11849   SmallVector<Constant*,2> CV1;
11850   CV1.push_back(
11851     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11852                                       APInt(64, 0x4330000000000000ULL))));
11853   CV1.push_back(
11854     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11855                                       APInt(64, 0x4530000000000000ULL))));
11856   Constant *C1 = ConstantVector::get(CV1);
11857   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11858
11859   // Load the 64-bit value into an XMM register.
11860   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11861                             Op.getOperand(0));
11862   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11863                               MachinePointerInfo::getConstantPool(),
11864                               false, false, false, 16);
11865   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11866                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11867                               CLod0);
11868
11869   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11870                               MachinePointerInfo::getConstantPool(),
11871                               false, false, false, 16);
11872   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11873   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11874   SDValue Result;
11875
11876   if (Subtarget->hasSSE3()) {
11877     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11878     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11879   } else {
11880     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11881     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11882                                            S2F, 0x4E, DAG);
11883     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11884                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11885                          Sub);
11886   }
11887
11888   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11889                      DAG.getIntPtrConstant(0));
11890 }
11891
11892 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11893 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11894                                                SelectionDAG &DAG) const {
11895   SDLoc dl(Op);
11896   // FP constant to bias correct the final result.
11897   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11898                                    MVT::f64);
11899
11900   // Load the 32-bit value into an XMM register.
11901   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11902                              Op.getOperand(0));
11903
11904   // Zero out the upper parts of the register.
11905   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11906
11907   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11908                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11909                      DAG.getIntPtrConstant(0));
11910
11911   // Or the load with the bias.
11912   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11913                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11914                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11915                                                    MVT::v2f64, Load)),
11916                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11917                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11918                                                    MVT::v2f64, Bias)));
11919   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11920                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11921                    DAG.getIntPtrConstant(0));
11922
11923   // Subtract the bias.
11924   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11925
11926   // Handle final rounding.
11927   EVT DestVT = Op.getValueType();
11928
11929   if (DestVT.bitsLT(MVT::f64))
11930     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11931                        DAG.getIntPtrConstant(0));
11932   if (DestVT.bitsGT(MVT::f64))
11933     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11934
11935   // Handle final rounding.
11936   return Sub;
11937 }
11938
11939 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11940                                                SelectionDAG &DAG) const {
11941   SDValue N0 = Op.getOperand(0);
11942   MVT SVT = N0.getSimpleValueType();
11943   SDLoc dl(Op);
11944
11945   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11946           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11947          "Custom UINT_TO_FP is not supported!");
11948
11949   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11950   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11951                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11952 }
11953
11954 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11955                                            SelectionDAG &DAG) const {
11956   SDValue N0 = Op.getOperand(0);
11957   SDLoc dl(Op);
11958
11959   if (Op.getValueType().isVector())
11960     return lowerUINT_TO_FP_vec(Op, DAG);
11961
11962   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11963   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11964   // the optimization here.
11965   if (DAG.SignBitIsZero(N0))
11966     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11967
11968   MVT SrcVT = N0.getSimpleValueType();
11969   MVT DstVT = Op.getSimpleValueType();
11970   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11971     return LowerUINT_TO_FP_i64(Op, DAG);
11972   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11973     return LowerUINT_TO_FP_i32(Op, DAG);
11974   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11975     return SDValue();
11976
11977   // Make a 64-bit buffer, and use it to build an FILD.
11978   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11979   if (SrcVT == MVT::i32) {
11980     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11981     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11982                                      getPointerTy(), StackSlot, WordOff);
11983     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11984                                   StackSlot, MachinePointerInfo(),
11985                                   false, false, 0);
11986     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11987                                   OffsetSlot, MachinePointerInfo(),
11988                                   false, false, 0);
11989     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11990     return Fild;
11991   }
11992
11993   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11994   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11995                                StackSlot, MachinePointerInfo(),
11996                                false, false, 0);
11997   // For i64 source, we need to add the appropriate power of 2 if the input
11998   // was negative.  This is the same as the optimization in
11999   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12000   // we must be careful to do the computation in x87 extended precision, not
12001   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12002   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12003   MachineMemOperand *MMO =
12004     DAG.getMachineFunction()
12005     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12006                           MachineMemOperand::MOLoad, 8, 8);
12007
12008   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12009   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12010   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12011                                          MVT::i64, MMO);
12012
12013   APInt FF(32, 0x5F800000ULL);
12014
12015   // Check whether the sign bit is set.
12016   SDValue SignSet = DAG.getSetCC(dl,
12017                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
12018                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
12019                                  ISD::SETLT);
12020
12021   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12022   SDValue FudgePtr = DAG.getConstantPool(
12023                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
12024                                          getPointerTy());
12025
12026   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12027   SDValue Zero = DAG.getIntPtrConstant(0);
12028   SDValue Four = DAG.getIntPtrConstant(4);
12029   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12030                                Zero, Four);
12031   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
12032
12033   // Load the value out, extending it from f32 to f80.
12034   // FIXME: Avoid the extend by constructing the right constant pool?
12035   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12036                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12037                                  MVT::f32, false, false, false, 4);
12038   // Extend everything to 80 bits to force it to be done on x87.
12039   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12040   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
12041 }
12042
12043 std::pair<SDValue,SDValue>
12044 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12045                                     bool IsSigned, bool IsReplace) const {
12046   SDLoc DL(Op);
12047
12048   EVT DstTy = Op.getValueType();
12049
12050   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12051     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12052     DstTy = MVT::i64;
12053   }
12054
12055   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12056          DstTy.getSimpleVT() >= MVT::i16 &&
12057          "Unknown FP_TO_INT to lower!");
12058
12059   // These are really Legal.
12060   if (DstTy == MVT::i32 &&
12061       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12062     return std::make_pair(SDValue(), SDValue());
12063   if (Subtarget->is64Bit() &&
12064       DstTy == MVT::i64 &&
12065       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12066     return std::make_pair(SDValue(), SDValue());
12067
12068   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12069   // stack slot, or into the FTOL runtime function.
12070   MachineFunction &MF = DAG.getMachineFunction();
12071   unsigned MemSize = DstTy.getSizeInBits()/8;
12072   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12073   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12074
12075   unsigned Opc;
12076   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12077     Opc = X86ISD::WIN_FTOL;
12078   else
12079     switch (DstTy.getSimpleVT().SimpleTy) {
12080     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12081     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12082     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12083     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12084     }
12085
12086   SDValue Chain = DAG.getEntryNode();
12087   SDValue Value = Op.getOperand(0);
12088   EVT TheVT = Op.getOperand(0).getValueType();
12089   // FIXME This causes a redundant load/store if the SSE-class value is already
12090   // in memory, such as if it is on the callstack.
12091   if (isScalarFPTypeInSSEReg(TheVT)) {
12092     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12093     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12094                          MachinePointerInfo::getFixedStack(SSFI),
12095                          false, false, 0);
12096     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12097     SDValue Ops[] = {
12098       Chain, StackSlot, DAG.getValueType(TheVT)
12099     };
12100
12101     MachineMemOperand *MMO =
12102       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12103                               MachineMemOperand::MOLoad, MemSize, MemSize);
12104     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12105     Chain = Value.getValue(1);
12106     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12107     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12108   }
12109
12110   MachineMemOperand *MMO =
12111     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12112                             MachineMemOperand::MOStore, MemSize, MemSize);
12113
12114   if (Opc != X86ISD::WIN_FTOL) {
12115     // Build the FP_TO_INT*_IN_MEM
12116     SDValue Ops[] = { Chain, Value, StackSlot };
12117     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12118                                            Ops, DstTy, MMO);
12119     return std::make_pair(FIST, StackSlot);
12120   } else {
12121     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12122       DAG.getVTList(MVT::Other, MVT::Glue),
12123       Chain, Value);
12124     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12125       MVT::i32, ftol.getValue(1));
12126     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12127       MVT::i32, eax.getValue(2));
12128     SDValue Ops[] = { eax, edx };
12129     SDValue pair = IsReplace
12130       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12131       : DAG.getMergeValues(Ops, DL);
12132     return std::make_pair(pair, SDValue());
12133   }
12134 }
12135
12136 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12137                               const X86Subtarget *Subtarget) {
12138   MVT VT = Op->getSimpleValueType(0);
12139   SDValue In = Op->getOperand(0);
12140   MVT InVT = In.getSimpleValueType();
12141   SDLoc dl(Op);
12142
12143   // Optimize vectors in AVX mode:
12144   //
12145   //   v8i16 -> v8i32
12146   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12147   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12148   //   Concat upper and lower parts.
12149   //
12150   //   v4i32 -> v4i64
12151   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12152   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12153   //   Concat upper and lower parts.
12154   //
12155
12156   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12157       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12158       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12159     return SDValue();
12160
12161   if (Subtarget->hasInt256())
12162     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12163
12164   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12165   SDValue Undef = DAG.getUNDEF(InVT);
12166   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12167   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12168   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12169
12170   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12171                              VT.getVectorNumElements()/2);
12172
12173   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12174   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12175
12176   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12177 }
12178
12179 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12180                                         SelectionDAG &DAG) {
12181   MVT VT = Op->getSimpleValueType(0);
12182   SDValue In = Op->getOperand(0);
12183   MVT InVT = In.getSimpleValueType();
12184   SDLoc DL(Op);
12185   unsigned int NumElts = VT.getVectorNumElements();
12186   if (NumElts != 8 && NumElts != 16)
12187     return SDValue();
12188
12189   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12190     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12191
12192   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
12193   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12194   // Now we have only mask extension
12195   assert(InVT.getVectorElementType() == MVT::i1);
12196   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
12197   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12198   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12199   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12200   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12201                            MachinePointerInfo::getConstantPool(),
12202                            false, false, false, Alignment);
12203
12204   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
12205   if (VT.is512BitVector())
12206     return Brcst;
12207   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
12208 }
12209
12210 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12211                                SelectionDAG &DAG) {
12212   if (Subtarget->hasFp256()) {
12213     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12214     if (Res.getNode())
12215       return Res;
12216   }
12217
12218   return SDValue();
12219 }
12220
12221 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12222                                 SelectionDAG &DAG) {
12223   SDLoc DL(Op);
12224   MVT VT = Op.getSimpleValueType();
12225   SDValue In = Op.getOperand(0);
12226   MVT SVT = In.getSimpleValueType();
12227
12228   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12229     return LowerZERO_EXTEND_AVX512(Op, DAG);
12230
12231   if (Subtarget->hasFp256()) {
12232     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12233     if (Res.getNode())
12234       return Res;
12235   }
12236
12237   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12238          VT.getVectorNumElements() != SVT.getVectorNumElements());
12239   return SDValue();
12240 }
12241
12242 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12243   SDLoc DL(Op);
12244   MVT VT = Op.getSimpleValueType();
12245   SDValue In = Op.getOperand(0);
12246   MVT InVT = In.getSimpleValueType();
12247
12248   if (VT == MVT::i1) {
12249     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12250            "Invalid scalar TRUNCATE operation");
12251     if (InVT.getSizeInBits() >= 32)
12252       return SDValue();
12253     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12254     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12255   }
12256   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12257          "Invalid TRUNCATE operation");
12258
12259   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12260     if (VT.getVectorElementType().getSizeInBits() >=8)
12261       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12262
12263     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12264     unsigned NumElts = InVT.getVectorNumElements();
12265     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12266     if (InVT.getSizeInBits() < 512) {
12267       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12268       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12269       InVT = ExtVT;
12270     }
12271     
12272     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12273     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12274     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12275     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12276     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12277                            MachinePointerInfo::getConstantPool(),
12278                            false, false, false, Alignment);
12279     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12280     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12281     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12282   }
12283
12284   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12285     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12286     if (Subtarget->hasInt256()) {
12287       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12288       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
12289       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12290                                 ShufMask);
12291       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12292                          DAG.getIntPtrConstant(0));
12293     }
12294
12295     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12296                                DAG.getIntPtrConstant(0));
12297     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12298                                DAG.getIntPtrConstant(2));
12299     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12300     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12301     static const int ShufMask[] = {0, 2, 4, 6};
12302     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12303   }
12304
12305   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12306     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12307     if (Subtarget->hasInt256()) {
12308       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
12309
12310       SmallVector<SDValue,32> pshufbMask;
12311       for (unsigned i = 0; i < 2; ++i) {
12312         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
12313         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
12314         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
12315         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
12316         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
12317         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
12318         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
12319         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
12320         for (unsigned j = 0; j < 8; ++j)
12321           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
12322       }
12323       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12324       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12325       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
12326
12327       static const int ShufMask[] = {0,  2,  -1,  -1};
12328       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12329                                 &ShufMask[0]);
12330       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12331                        DAG.getIntPtrConstant(0));
12332       return DAG.getNode(ISD::BITCAST, DL, VT, In);
12333     }
12334
12335     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12336                                DAG.getIntPtrConstant(0));
12337
12338     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12339                                DAG.getIntPtrConstant(4));
12340
12341     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
12342     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
12343
12344     // The PSHUFB mask:
12345     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12346                                    -1, -1, -1, -1, -1, -1, -1, -1};
12347
12348     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12349     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12350     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12351
12352     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
12353     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
12354
12355     // The MOVLHPS Mask:
12356     static const int ShufMask2[] = {0, 1, 4, 5};
12357     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12358     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
12359   }
12360
12361   // Handle truncation of V256 to V128 using shuffles.
12362   if (!VT.is128BitVector() || !InVT.is256BitVector())
12363     return SDValue();
12364
12365   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12366
12367   unsigned NumElems = VT.getVectorNumElements();
12368   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12369
12370   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12371   // Prepare truncation shuffle mask
12372   for (unsigned i = 0; i != NumElems; ++i)
12373     MaskVec[i] = i * 2;
12374   SDValue V = DAG.getVectorShuffle(NVT, DL,
12375                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
12376                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12377   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12378                      DAG.getIntPtrConstant(0));
12379 }
12380
12381 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12382                                            SelectionDAG &DAG) const {
12383   assert(!Op.getSimpleValueType().isVector());
12384
12385   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12386     /*IsSigned=*/ true, /*IsReplace=*/ false);
12387   SDValue FIST = Vals.first, StackSlot = Vals.second;
12388   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12389   if (!FIST.getNode()) return Op;
12390
12391   if (StackSlot.getNode())
12392     // Load the result.
12393     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12394                        FIST, StackSlot, MachinePointerInfo(),
12395                        false, false, false, 0);
12396
12397   // The node is the result.
12398   return FIST;
12399 }
12400
12401 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12402                                            SelectionDAG &DAG) const {
12403   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12404     /*IsSigned=*/ false, /*IsReplace=*/ false);
12405   SDValue FIST = Vals.first, StackSlot = Vals.second;
12406   assert(FIST.getNode() && "Unexpected failure");
12407
12408   if (StackSlot.getNode())
12409     // Load the result.
12410     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12411                        FIST, StackSlot, MachinePointerInfo(),
12412                        false, false, false, 0);
12413
12414   // The node is the result.
12415   return FIST;
12416 }
12417
12418 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12419   SDLoc DL(Op);
12420   MVT VT = Op.getSimpleValueType();
12421   SDValue In = Op.getOperand(0);
12422   MVT SVT = In.getSimpleValueType();
12423
12424   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12425
12426   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12427                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12428                                  In, DAG.getUNDEF(SVT)));
12429 }
12430
12431 // The only differences between FABS and FNEG are the mask and the logic op.
12432 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12433   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12434          "Wrong opcode for lowering FABS or FNEG.");
12435
12436   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12437   SDLoc dl(Op);
12438   MVT VT = Op.getSimpleValueType();
12439   // Assume scalar op for initialization; update for vector if needed.
12440   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12441   // generate a 16-byte vector constant and logic op even for the scalar case.
12442   // Using a 16-byte mask allows folding the load of the mask with
12443   // the logic op, so it can save (~4 bytes) on code size.
12444   MVT EltVT = VT;
12445   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12446   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12447   // decide if we should generate a 16-byte constant mask when we only need 4 or
12448   // 8 bytes for the scalar case.
12449   if (VT.isVector()) {
12450     EltVT = VT.getVectorElementType();
12451     NumElts = VT.getVectorNumElements();
12452   }
12453   
12454   unsigned EltBits = EltVT.getSizeInBits();
12455   LLVMContext *Context = DAG.getContext();
12456   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12457   APInt MaskElt =
12458     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12459   Constant *C = ConstantInt::get(*Context, MaskElt);
12460   C = ConstantVector::getSplat(NumElts, C);
12461   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12462   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12463   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12464   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12465                              MachinePointerInfo::getConstantPool(),
12466                              false, false, false, Alignment);
12467
12468   if (VT.isVector()) {
12469     // For a vector, cast operands to a vector type, perform the logic op,
12470     // and cast the result back to the original value type.
12471     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12472     SDValue Op0Casted = DAG.getNode(ISD::BITCAST, dl, VecVT, Op.getOperand(0));
12473     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
12474     unsigned LogicOp = IsFABS ? ISD::AND : ISD::XOR;
12475     return DAG.getNode(ISD::BITCAST, dl, VT,
12476                        DAG.getNode(LogicOp, dl, VecVT, Op0Casted, MaskCasted));
12477   }
12478   // If not vector, then scalar.
12479   unsigned LogicOp = IsFABS ? X86ISD::FAND : X86ISD::FXOR;
12480   return DAG.getNode(LogicOp, dl, VT, Op.getOperand(0), Mask);
12481 }
12482
12483 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12484   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12485   LLVMContext *Context = DAG.getContext();
12486   SDValue Op0 = Op.getOperand(0);
12487   SDValue Op1 = Op.getOperand(1);
12488   SDLoc dl(Op);
12489   MVT VT = Op.getSimpleValueType();
12490   MVT SrcVT = Op1.getSimpleValueType();
12491
12492   // If second operand is smaller, extend it first.
12493   if (SrcVT.bitsLT(VT)) {
12494     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12495     SrcVT = VT;
12496   }
12497   // And if it is bigger, shrink it first.
12498   if (SrcVT.bitsGT(VT)) {
12499     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
12500     SrcVT = VT;
12501   }
12502
12503   // At this point the operands and the result should have the same
12504   // type, and that won't be f80 since that is not custom lowered.
12505
12506   // First get the sign bit of second operand.
12507   SmallVector<Constant*,4> CV;
12508   if (SrcVT == MVT::f64) {
12509     const fltSemantics &Sem = APFloat::IEEEdouble;
12510     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
12511     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12512   } else {
12513     const fltSemantics &Sem = APFloat::IEEEsingle;
12514     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
12515     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12516     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12517     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12518   }
12519   Constant *C = ConstantVector::get(CV);
12520   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12521   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12522                               MachinePointerInfo::getConstantPool(),
12523                               false, false, false, 16);
12524   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12525
12526   // Shift sign bit right or left if the two operands have different types.
12527   if (SrcVT.bitsGT(VT)) {
12528     // Op0 is MVT::f32, Op1 is MVT::f64.
12529     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
12530     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
12531                           DAG.getConstant(32, MVT::i32));
12532     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
12533     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
12534                           DAG.getIntPtrConstant(0));
12535   }
12536
12537   // Clear first operand sign bit.
12538   CV.clear();
12539   if (VT == MVT::f64) {
12540     const fltSemantics &Sem = APFloat::IEEEdouble;
12541     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12542                                                    APInt(64, ~(1ULL << 63)))));
12543     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
12544   } else {
12545     const fltSemantics &Sem = APFloat::IEEEsingle;
12546     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
12547                                                    APInt(32, ~(1U << 31)))));
12548     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12549     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12550     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
12551   }
12552   C = ConstantVector::get(CV);
12553   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12554   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12555                               MachinePointerInfo::getConstantPool(),
12556                               false, false, false, 16);
12557   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
12558
12559   // Or the value with the sign bit.
12560   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12561 }
12562
12563 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12564   SDValue N0 = Op.getOperand(0);
12565   SDLoc dl(Op);
12566   MVT VT = Op.getSimpleValueType();
12567
12568   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12569   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12570                                   DAG.getConstant(1, VT));
12571   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
12572 }
12573
12574 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
12575 //
12576 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12577                                       SelectionDAG &DAG) {
12578   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12579
12580   if (!Subtarget->hasSSE41())
12581     return SDValue();
12582
12583   if (!Op->hasOneUse())
12584     return SDValue();
12585
12586   SDNode *N = Op.getNode();
12587   SDLoc DL(N);
12588
12589   SmallVector<SDValue, 8> Opnds;
12590   DenseMap<SDValue, unsigned> VecInMap;
12591   SmallVector<SDValue, 8> VecIns;
12592   EVT VT = MVT::Other;
12593
12594   // Recognize a special case where a vector is casted into wide integer to
12595   // test all 0s.
12596   Opnds.push_back(N->getOperand(0));
12597   Opnds.push_back(N->getOperand(1));
12598
12599   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12600     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12601     // BFS traverse all OR'd operands.
12602     if (I->getOpcode() == ISD::OR) {
12603       Opnds.push_back(I->getOperand(0));
12604       Opnds.push_back(I->getOperand(1));
12605       // Re-evaluate the number of nodes to be traversed.
12606       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12607       continue;
12608     }
12609
12610     // Quit if a non-EXTRACT_VECTOR_ELT
12611     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12612       return SDValue();
12613
12614     // Quit if without a constant index.
12615     SDValue Idx = I->getOperand(1);
12616     if (!isa<ConstantSDNode>(Idx))
12617       return SDValue();
12618
12619     SDValue ExtractedFromVec = I->getOperand(0);
12620     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12621     if (M == VecInMap.end()) {
12622       VT = ExtractedFromVec.getValueType();
12623       // Quit if not 128/256-bit vector.
12624       if (!VT.is128BitVector() && !VT.is256BitVector())
12625         return SDValue();
12626       // Quit if not the same type.
12627       if (VecInMap.begin() != VecInMap.end() &&
12628           VT != VecInMap.begin()->first.getValueType())
12629         return SDValue();
12630       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12631       VecIns.push_back(ExtractedFromVec);
12632     }
12633     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12634   }
12635
12636   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12637          "Not extracted from 128-/256-bit vector.");
12638
12639   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12640
12641   for (DenseMap<SDValue, unsigned>::const_iterator
12642         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12643     // Quit if not all elements are used.
12644     if (I->second != FullMask)
12645       return SDValue();
12646   }
12647
12648   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12649
12650   // Cast all vectors into TestVT for PTEST.
12651   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12652     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
12653
12654   // If more than one full vectors are evaluated, OR them first before PTEST.
12655   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12656     // Each iteration will OR 2 nodes and append the result until there is only
12657     // 1 node left, i.e. the final OR'd value of all vectors.
12658     SDValue LHS = VecIns[Slot];
12659     SDValue RHS = VecIns[Slot + 1];
12660     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12661   }
12662
12663   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12664                      VecIns.back(), VecIns.back());
12665 }
12666
12667 /// \brief return true if \c Op has a use that doesn't just read flags.
12668 static bool hasNonFlagsUse(SDValue Op) {
12669   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12670        ++UI) {
12671     SDNode *User = *UI;
12672     unsigned UOpNo = UI.getOperandNo();
12673     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12674       // Look pass truncate.
12675       UOpNo = User->use_begin().getOperandNo();
12676       User = *User->use_begin();
12677     }
12678
12679     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12680         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12681       return true;
12682   }
12683   return false;
12684 }
12685
12686 /// Emit nodes that will be selected as "test Op0,Op0", or something
12687 /// equivalent.
12688 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12689                                     SelectionDAG &DAG) const {
12690   if (Op.getValueType() == MVT::i1)
12691     // KORTEST instruction should be selected
12692     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12693                        DAG.getConstant(0, Op.getValueType()));
12694
12695   // CF and OF aren't always set the way we want. Determine which
12696   // of these we need.
12697   bool NeedCF = false;
12698   bool NeedOF = false;
12699   switch (X86CC) {
12700   default: break;
12701   case X86::COND_A: case X86::COND_AE:
12702   case X86::COND_B: case X86::COND_BE:
12703     NeedCF = true;
12704     break;
12705   case X86::COND_G: case X86::COND_GE:
12706   case X86::COND_L: case X86::COND_LE:
12707   case X86::COND_O: case X86::COND_NO: {
12708     // Check if we really need to set the
12709     // Overflow flag. If NoSignedWrap is present
12710     // that is not actually needed.
12711     switch (Op->getOpcode()) {
12712     case ISD::ADD:
12713     case ISD::SUB:
12714     case ISD::MUL:
12715     case ISD::SHL: {
12716       const BinaryWithFlagsSDNode *BinNode =
12717           cast<BinaryWithFlagsSDNode>(Op.getNode());
12718       if (BinNode->hasNoSignedWrap())
12719         break;
12720     }
12721     default:
12722       NeedOF = true;
12723       break;
12724     }
12725     break;
12726   }
12727   }
12728   // See if we can use the EFLAGS value from the operand instead of
12729   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12730   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12731   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12732     // Emit a CMP with 0, which is the TEST pattern.
12733     //if (Op.getValueType() == MVT::i1)
12734     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12735     //                     DAG.getConstant(0, MVT::i1));
12736     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12737                        DAG.getConstant(0, Op.getValueType()));
12738   }
12739   unsigned Opcode = 0;
12740   unsigned NumOperands = 0;
12741
12742   // Truncate operations may prevent the merge of the SETCC instruction
12743   // and the arithmetic instruction before it. Attempt to truncate the operands
12744   // of the arithmetic instruction and use a reduced bit-width instruction.
12745   bool NeedTruncation = false;
12746   SDValue ArithOp = Op;
12747   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12748     SDValue Arith = Op->getOperand(0);
12749     // Both the trunc and the arithmetic op need to have one user each.
12750     if (Arith->hasOneUse())
12751       switch (Arith.getOpcode()) {
12752         default: break;
12753         case ISD::ADD:
12754         case ISD::SUB:
12755         case ISD::AND:
12756         case ISD::OR:
12757         case ISD::XOR: {
12758           NeedTruncation = true;
12759           ArithOp = Arith;
12760         }
12761       }
12762   }
12763
12764   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12765   // which may be the result of a CAST.  We use the variable 'Op', which is the
12766   // non-casted variable when we check for possible users.
12767   switch (ArithOp.getOpcode()) {
12768   case ISD::ADD:
12769     // Due to an isel shortcoming, be conservative if this add is likely to be
12770     // selected as part of a load-modify-store instruction. When the root node
12771     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12772     // uses of other nodes in the match, such as the ADD in this case. This
12773     // leads to the ADD being left around and reselected, with the result being
12774     // two adds in the output.  Alas, even if none our users are stores, that
12775     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12776     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12777     // climbing the DAG back to the root, and it doesn't seem to be worth the
12778     // effort.
12779     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12780          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12781       if (UI->getOpcode() != ISD::CopyToReg &&
12782           UI->getOpcode() != ISD::SETCC &&
12783           UI->getOpcode() != ISD::STORE)
12784         goto default_case;
12785
12786     if (ConstantSDNode *C =
12787         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12788       // An add of one will be selected as an INC.
12789       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12790         Opcode = X86ISD::INC;
12791         NumOperands = 1;
12792         break;
12793       }
12794
12795       // An add of negative one (subtract of one) will be selected as a DEC.
12796       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12797         Opcode = X86ISD::DEC;
12798         NumOperands = 1;
12799         break;
12800       }
12801     }
12802
12803     // Otherwise use a regular EFLAGS-setting add.
12804     Opcode = X86ISD::ADD;
12805     NumOperands = 2;
12806     break;
12807   case ISD::SHL:
12808   case ISD::SRL:
12809     // If we have a constant logical shift that's only used in a comparison
12810     // against zero turn it into an equivalent AND. This allows turning it into
12811     // a TEST instruction later.
12812     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12813         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12814       EVT VT = Op.getValueType();
12815       unsigned BitWidth = VT.getSizeInBits();
12816       unsigned ShAmt = Op->getConstantOperandVal(1);
12817       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12818         break;
12819       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12820                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12821                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12822       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12823         break;
12824       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12825                                 DAG.getConstant(Mask, VT));
12826       DAG.ReplaceAllUsesWith(Op, New);
12827       Op = New;
12828     }
12829     break;
12830
12831   case ISD::AND:
12832     // If the primary and result isn't used, don't bother using X86ISD::AND,
12833     // because a TEST instruction will be better.
12834     if (!hasNonFlagsUse(Op))
12835       break;
12836     // FALL THROUGH
12837   case ISD::SUB:
12838   case ISD::OR:
12839   case ISD::XOR:
12840     // Due to the ISEL shortcoming noted above, be conservative if this op is
12841     // likely to be selected as part of a load-modify-store instruction.
12842     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12843            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12844       if (UI->getOpcode() == ISD::STORE)
12845         goto default_case;
12846
12847     // Otherwise use a regular EFLAGS-setting instruction.
12848     switch (ArithOp.getOpcode()) {
12849     default: llvm_unreachable("unexpected operator!");
12850     case ISD::SUB: Opcode = X86ISD::SUB; break;
12851     case ISD::XOR: Opcode = X86ISD::XOR; break;
12852     case ISD::AND: Opcode = X86ISD::AND; break;
12853     case ISD::OR: {
12854       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12855         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12856         if (EFLAGS.getNode())
12857           return EFLAGS;
12858       }
12859       Opcode = X86ISD::OR;
12860       break;
12861     }
12862     }
12863
12864     NumOperands = 2;
12865     break;
12866   case X86ISD::ADD:
12867   case X86ISD::SUB:
12868   case X86ISD::INC:
12869   case X86ISD::DEC:
12870   case X86ISD::OR:
12871   case X86ISD::XOR:
12872   case X86ISD::AND:
12873     return SDValue(Op.getNode(), 1);
12874   default:
12875   default_case:
12876     break;
12877   }
12878
12879   // If we found that truncation is beneficial, perform the truncation and
12880   // update 'Op'.
12881   if (NeedTruncation) {
12882     EVT VT = Op.getValueType();
12883     SDValue WideVal = Op->getOperand(0);
12884     EVT WideVT = WideVal.getValueType();
12885     unsigned ConvertedOp = 0;
12886     // Use a target machine opcode to prevent further DAGCombine
12887     // optimizations that may separate the arithmetic operations
12888     // from the setcc node.
12889     switch (WideVal.getOpcode()) {
12890       default: break;
12891       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12892       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12893       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12894       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12895       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12896     }
12897
12898     if (ConvertedOp) {
12899       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12900       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12901         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12902         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12903         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12904       }
12905     }
12906   }
12907
12908   if (Opcode == 0)
12909     // Emit a CMP with 0, which is the TEST pattern.
12910     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12911                        DAG.getConstant(0, Op.getValueType()));
12912
12913   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12914   SmallVector<SDValue, 4> Ops;
12915   for (unsigned i = 0; i != NumOperands; ++i)
12916     Ops.push_back(Op.getOperand(i));
12917
12918   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12919   DAG.ReplaceAllUsesWith(Op, New);
12920   return SDValue(New.getNode(), 1);
12921 }
12922
12923 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12924 /// equivalent.
12925 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12926                                    SDLoc dl, SelectionDAG &DAG) const {
12927   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12928     if (C->getAPIntValue() == 0)
12929       return EmitTest(Op0, X86CC, dl, DAG);
12930
12931      if (Op0.getValueType() == MVT::i1)
12932        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12933   }
12934  
12935   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12936        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12937     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12938     // This avoids subregister aliasing issues. Keep the smaller reference 
12939     // if we're optimizing for size, however, as that'll allow better folding 
12940     // of memory operations.
12941     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12942         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12943              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12944         !Subtarget->isAtom()) {
12945       unsigned ExtendOp =
12946           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12947       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12948       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12949     }
12950     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12951     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12952     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12953                               Op0, Op1);
12954     return SDValue(Sub.getNode(), 1);
12955   }
12956   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12957 }
12958
12959 /// Convert a comparison if required by the subtarget.
12960 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12961                                                  SelectionDAG &DAG) const {
12962   // If the subtarget does not support the FUCOMI instruction, floating-point
12963   // comparisons have to be converted.
12964   if (Subtarget->hasCMov() ||
12965       Cmp.getOpcode() != X86ISD::CMP ||
12966       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12967       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12968     return Cmp;
12969
12970   // The instruction selector will select an FUCOM instruction instead of
12971   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12972   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12973   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12974   SDLoc dl(Cmp);
12975   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12976   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12977   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12978                             DAG.getConstant(8, MVT::i8));
12979   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12980   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12981 }
12982
12983 static bool isAllOnes(SDValue V) {
12984   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12985   return C && C->isAllOnesValue();
12986 }
12987
12988 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12989 /// if it's possible.
12990 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12991                                      SDLoc dl, SelectionDAG &DAG) const {
12992   SDValue Op0 = And.getOperand(0);
12993   SDValue Op1 = And.getOperand(1);
12994   if (Op0.getOpcode() == ISD::TRUNCATE)
12995     Op0 = Op0.getOperand(0);
12996   if (Op1.getOpcode() == ISD::TRUNCATE)
12997     Op1 = Op1.getOperand(0);
12998
12999   SDValue LHS, RHS;
13000   if (Op1.getOpcode() == ISD::SHL)
13001     std::swap(Op0, Op1);
13002   if (Op0.getOpcode() == ISD::SHL) {
13003     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13004       if (And00C->getZExtValue() == 1) {
13005         // If we looked past a truncate, check that it's only truncating away
13006         // known zeros.
13007         unsigned BitWidth = Op0.getValueSizeInBits();
13008         unsigned AndBitWidth = And.getValueSizeInBits();
13009         if (BitWidth > AndBitWidth) {
13010           APInt Zeros, Ones;
13011           DAG.computeKnownBits(Op0, Zeros, Ones);
13012           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13013             return SDValue();
13014         }
13015         LHS = Op1;
13016         RHS = Op0.getOperand(1);
13017       }
13018   } else if (Op1.getOpcode() == ISD::Constant) {
13019     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13020     uint64_t AndRHSVal = AndRHS->getZExtValue();
13021     SDValue AndLHS = Op0;
13022
13023     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13024       LHS = AndLHS.getOperand(0);
13025       RHS = AndLHS.getOperand(1);
13026     }
13027
13028     // Use BT if the immediate can't be encoded in a TEST instruction.
13029     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13030       LHS = AndLHS;
13031       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
13032     }
13033   }
13034
13035   if (LHS.getNode()) {
13036     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13037     // instruction.  Since the shift amount is in-range-or-undefined, we know
13038     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13039     // the encoding for the i16 version is larger than the i32 version.
13040     // Also promote i16 to i32 for performance / code size reason.
13041     if (LHS.getValueType() == MVT::i8 ||
13042         LHS.getValueType() == MVT::i16)
13043       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13044
13045     // If the operand types disagree, extend the shift amount to match.  Since
13046     // BT ignores high bits (like shifts) we can use anyextend.
13047     if (LHS.getValueType() != RHS.getValueType())
13048       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13049
13050     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13051     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13052     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13053                        DAG.getConstant(Cond, MVT::i8), BT);
13054   }
13055
13056   return SDValue();
13057 }
13058
13059 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13060 /// mask CMPs.
13061 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13062                               SDValue &Op1) {
13063   unsigned SSECC;
13064   bool Swap = false;
13065
13066   // SSE Condition code mapping:
13067   //  0 - EQ
13068   //  1 - LT
13069   //  2 - LE
13070   //  3 - UNORD
13071   //  4 - NEQ
13072   //  5 - NLT
13073   //  6 - NLE
13074   //  7 - ORD
13075   switch (SetCCOpcode) {
13076   default: llvm_unreachable("Unexpected SETCC condition");
13077   case ISD::SETOEQ:
13078   case ISD::SETEQ:  SSECC = 0; break;
13079   case ISD::SETOGT:
13080   case ISD::SETGT:  Swap = true; // Fallthrough
13081   case ISD::SETLT:
13082   case ISD::SETOLT: SSECC = 1; break;
13083   case ISD::SETOGE:
13084   case ISD::SETGE:  Swap = true; // Fallthrough
13085   case ISD::SETLE:
13086   case ISD::SETOLE: SSECC = 2; break;
13087   case ISD::SETUO:  SSECC = 3; break;
13088   case ISD::SETUNE:
13089   case ISD::SETNE:  SSECC = 4; break;
13090   case ISD::SETULE: Swap = true; // Fallthrough
13091   case ISD::SETUGE: SSECC = 5; break;
13092   case ISD::SETULT: Swap = true; // Fallthrough
13093   case ISD::SETUGT: SSECC = 6; break;
13094   case ISD::SETO:   SSECC = 7; break;
13095   case ISD::SETUEQ:
13096   case ISD::SETONE: SSECC = 8; break;
13097   }
13098   if (Swap)
13099     std::swap(Op0, Op1);
13100
13101   return SSECC;
13102 }
13103
13104 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13105 // ones, and then concatenate the result back.
13106 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13107   MVT VT = Op.getSimpleValueType();
13108
13109   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13110          "Unsupported value type for operation");
13111
13112   unsigned NumElems = VT.getVectorNumElements();
13113   SDLoc dl(Op);
13114   SDValue CC = Op.getOperand(2);
13115
13116   // Extract the LHS vectors
13117   SDValue LHS = Op.getOperand(0);
13118   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13119   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13120
13121   // Extract the RHS vectors
13122   SDValue RHS = Op.getOperand(1);
13123   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13124   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13125
13126   // Issue the operation on the smaller types and concatenate the result back
13127   MVT EltVT = VT.getVectorElementType();
13128   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13129   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13130                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13131                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13132 }
13133
13134 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13135                                      const X86Subtarget *Subtarget) {
13136   SDValue Op0 = Op.getOperand(0);
13137   SDValue Op1 = Op.getOperand(1);
13138   SDValue CC = Op.getOperand(2);
13139   MVT VT = Op.getSimpleValueType();
13140   SDLoc dl(Op);
13141
13142   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13143          Op.getValueType().getScalarType() == MVT::i1 &&
13144          "Cannot set masked compare for this operation");
13145
13146   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13147   unsigned  Opc = 0;
13148   bool Unsigned = false;
13149   bool Swap = false;
13150   unsigned SSECC;
13151   switch (SetCCOpcode) {
13152   default: llvm_unreachable("Unexpected SETCC condition");
13153   case ISD::SETNE:  SSECC = 4; break;
13154   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13155   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13156   case ISD::SETLT:  Swap = true; //fall-through
13157   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13158   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13159   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13160   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13161   case ISD::SETULE: Unsigned = true; //fall-through
13162   case ISD::SETLE:  SSECC = 2; break;
13163   }
13164
13165   if (Swap)
13166     std::swap(Op0, Op1);
13167   if (Opc)
13168     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13169   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13170   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13171                      DAG.getConstant(SSECC, MVT::i8));
13172 }
13173
13174 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13175 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13176 /// return an empty value.
13177 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13178 {
13179   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13180   if (!BV)
13181     return SDValue();
13182
13183   MVT VT = Op1.getSimpleValueType();
13184   MVT EVT = VT.getVectorElementType();
13185   unsigned n = VT.getVectorNumElements();
13186   SmallVector<SDValue, 8> ULTOp1;
13187
13188   for (unsigned i = 0; i < n; ++i) {
13189     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13190     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13191       return SDValue();
13192
13193     // Avoid underflow.
13194     APInt Val = Elt->getAPIntValue();
13195     if (Val == 0)
13196       return SDValue();
13197
13198     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13199   }
13200
13201   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13202 }
13203
13204 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13205                            SelectionDAG &DAG) {
13206   SDValue Op0 = Op.getOperand(0);
13207   SDValue Op1 = Op.getOperand(1);
13208   SDValue CC = Op.getOperand(2);
13209   MVT VT = Op.getSimpleValueType();
13210   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13211   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13212   SDLoc dl(Op);
13213
13214   if (isFP) {
13215 #ifndef NDEBUG
13216     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13217     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13218 #endif
13219
13220     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13221     unsigned Opc = X86ISD::CMPP;
13222     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13223       assert(VT.getVectorNumElements() <= 16);
13224       Opc = X86ISD::CMPM;
13225     }
13226     // In the two special cases we can't handle, emit two comparisons.
13227     if (SSECC == 8) {
13228       unsigned CC0, CC1;
13229       unsigned CombineOpc;
13230       if (SetCCOpcode == ISD::SETUEQ) {
13231         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13232       } else {
13233         assert(SetCCOpcode == ISD::SETONE);
13234         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13235       }
13236
13237       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13238                                  DAG.getConstant(CC0, MVT::i8));
13239       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13240                                  DAG.getConstant(CC1, MVT::i8));
13241       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13242     }
13243     // Handle all other FP comparisons here.
13244     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13245                        DAG.getConstant(SSECC, MVT::i8));
13246   }
13247
13248   // Break 256-bit integer vector compare into smaller ones.
13249   if (VT.is256BitVector() && !Subtarget->hasInt256())
13250     return Lower256IntVSETCC(Op, DAG);
13251
13252   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13253   EVT OpVT = Op1.getValueType();
13254   if (Subtarget->hasAVX512()) {
13255     if (Op1.getValueType().is512BitVector() ||
13256         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13257         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13258       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13259
13260     // In AVX-512 architecture setcc returns mask with i1 elements,
13261     // But there is no compare instruction for i8 and i16 elements in KNL.
13262     // We are not talking about 512-bit operands in this case, these
13263     // types are illegal.
13264     if (MaskResult &&
13265         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13266          OpVT.getVectorElementType().getSizeInBits() >= 8))
13267       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13268                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13269   }
13270
13271   // We are handling one of the integer comparisons here.  Since SSE only has
13272   // GT and EQ comparisons for integer, swapping operands and multiple
13273   // operations may be required for some comparisons.
13274   unsigned Opc;
13275   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13276   bool Subus = false;
13277
13278   switch (SetCCOpcode) {
13279   default: llvm_unreachable("Unexpected SETCC condition");
13280   case ISD::SETNE:  Invert = true;
13281   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13282   case ISD::SETLT:  Swap = true;
13283   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13284   case ISD::SETGE:  Swap = true;
13285   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13286                     Invert = true; break;
13287   case ISD::SETULT: Swap = true;
13288   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13289                     FlipSigns = true; break;
13290   case ISD::SETUGE: Swap = true;
13291   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13292                     FlipSigns = true; Invert = true; break;
13293   }
13294
13295   // Special case: Use min/max operations for SETULE/SETUGE
13296   MVT VET = VT.getVectorElementType();
13297   bool hasMinMax =
13298        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13299     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13300
13301   if (hasMinMax) {
13302     switch (SetCCOpcode) {
13303     default: break;
13304     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
13305     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
13306     }
13307
13308     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13309   }
13310
13311   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13312   if (!MinMax && hasSubus) {
13313     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13314     // Op0 u<= Op1:
13315     //   t = psubus Op0, Op1
13316     //   pcmpeq t, <0..0>
13317     switch (SetCCOpcode) {
13318     default: break;
13319     case ISD::SETULT: {
13320       // If the comparison is against a constant we can turn this into a
13321       // setule.  With psubus, setule does not require a swap.  This is
13322       // beneficial because the constant in the register is no longer
13323       // destructed as the destination so it can be hoisted out of a loop.
13324       // Only do this pre-AVX since vpcmp* is no longer destructive.
13325       if (Subtarget->hasAVX())
13326         break;
13327       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13328       if (ULEOp1.getNode()) {
13329         Op1 = ULEOp1;
13330         Subus = true; Invert = false; Swap = false;
13331       }
13332       break;
13333     }
13334     // Psubus is better than flip-sign because it requires no inversion.
13335     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13336     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13337     }
13338
13339     if (Subus) {
13340       Opc = X86ISD::SUBUS;
13341       FlipSigns = false;
13342     }
13343   }
13344
13345   if (Swap)
13346     std::swap(Op0, Op1);
13347
13348   // Check that the operation in question is available (most are plain SSE2,
13349   // but PCMPGTQ and PCMPEQQ have different requirements).
13350   if (VT == MVT::v2i64) {
13351     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13352       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13353
13354       // First cast everything to the right type.
13355       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13356       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13357
13358       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13359       // bits of the inputs before performing those operations. The lower
13360       // compare is always unsigned.
13361       SDValue SB;
13362       if (FlipSigns) {
13363         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
13364       } else {
13365         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
13366         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
13367         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13368                          Sign, Zero, Sign, Zero);
13369       }
13370       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13371       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13372
13373       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13374       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13375       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13376
13377       // Create masks for only the low parts/high parts of the 64 bit integers.
13378       static const int MaskHi[] = { 1, 1, 3, 3 };
13379       static const int MaskLo[] = { 0, 0, 2, 2 };
13380       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13381       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13382       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13383
13384       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13385       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13386
13387       if (Invert)
13388         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13389
13390       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13391     }
13392
13393     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13394       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13395       // pcmpeqd + pshufd + pand.
13396       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13397
13398       // First cast everything to the right type.
13399       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
13400       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
13401
13402       // Do the compare.
13403       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13404
13405       // Make sure the lower and upper halves are both all-ones.
13406       static const int Mask[] = { 1, 0, 3, 2 };
13407       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13408       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13409
13410       if (Invert)
13411         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13412
13413       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13414     }
13415   }
13416
13417   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13418   // bits of the inputs before performing those operations.
13419   if (FlipSigns) {
13420     EVT EltVT = VT.getVectorElementType();
13421     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
13422     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13423     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13424   }
13425
13426   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13427
13428   // If the logical-not of the result is required, perform that now.
13429   if (Invert)
13430     Result = DAG.getNOT(dl, Result, VT);
13431
13432   if (MinMax)
13433     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13434
13435   if (Subus)
13436     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13437                          getZeroVector(VT, Subtarget, DAG, dl));
13438
13439   return Result;
13440 }
13441
13442 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13443
13444   MVT VT = Op.getSimpleValueType();
13445
13446   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13447
13448   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13449          && "SetCC type must be 8-bit or 1-bit integer");
13450   SDValue Op0 = Op.getOperand(0);
13451   SDValue Op1 = Op.getOperand(1);
13452   SDLoc dl(Op);
13453   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13454
13455   // Optimize to BT if possible.
13456   // Lower (X & (1 << N)) == 0 to BT(X, N).
13457   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13458   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13459   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13460       Op1.getOpcode() == ISD::Constant &&
13461       cast<ConstantSDNode>(Op1)->isNullValue() &&
13462       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13463     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13464     if (NewSetCC.getNode())
13465       return NewSetCC;
13466   }
13467
13468   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13469   // these.
13470   if (Op1.getOpcode() == ISD::Constant &&
13471       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13472        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13473       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13474
13475     // If the input is a setcc, then reuse the input setcc or use a new one with
13476     // the inverted condition.
13477     if (Op0.getOpcode() == X86ISD::SETCC) {
13478       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13479       bool Invert = (CC == ISD::SETNE) ^
13480         cast<ConstantSDNode>(Op1)->isNullValue();
13481       if (!Invert)
13482         return Op0;
13483
13484       CCode = X86::GetOppositeBranchCondition(CCode);
13485       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13486                                   DAG.getConstant(CCode, MVT::i8),
13487                                   Op0.getOperand(1));
13488       if (VT == MVT::i1)
13489         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13490       return SetCC;
13491     }
13492   }
13493   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13494       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13495       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13496
13497     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13498     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
13499   }
13500
13501   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13502   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
13503   if (X86CC == X86::COND_INVALID)
13504     return SDValue();
13505
13506   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13507   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13508   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13509                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
13510   if (VT == MVT::i1)
13511     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13512   return SetCC;
13513 }
13514
13515 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13516 static bool isX86LogicalCmp(SDValue Op) {
13517   unsigned Opc = Op.getNode()->getOpcode();
13518   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13519       Opc == X86ISD::SAHF)
13520     return true;
13521   if (Op.getResNo() == 1 &&
13522       (Opc == X86ISD::ADD ||
13523        Opc == X86ISD::SUB ||
13524        Opc == X86ISD::ADC ||
13525        Opc == X86ISD::SBB ||
13526        Opc == X86ISD::SMUL ||
13527        Opc == X86ISD::UMUL ||
13528        Opc == X86ISD::INC ||
13529        Opc == X86ISD::DEC ||
13530        Opc == X86ISD::OR ||
13531        Opc == X86ISD::XOR ||
13532        Opc == X86ISD::AND))
13533     return true;
13534
13535   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13536     return true;
13537
13538   return false;
13539 }
13540
13541 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13542   if (V.getOpcode() != ISD::TRUNCATE)
13543     return false;
13544
13545   SDValue VOp0 = V.getOperand(0);
13546   unsigned InBits = VOp0.getValueSizeInBits();
13547   unsigned Bits = V.getValueSizeInBits();
13548   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13549 }
13550
13551 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13552   bool addTest = true;
13553   SDValue Cond  = Op.getOperand(0);
13554   SDValue Op1 = Op.getOperand(1);
13555   SDValue Op2 = Op.getOperand(2);
13556   SDLoc DL(Op);
13557   EVT VT = Op1.getValueType();
13558   SDValue CC;
13559
13560   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13561   // are available. Otherwise fp cmovs get lowered into a less efficient branch
13562   // sequence later on.
13563   if (Cond.getOpcode() == ISD::SETCC &&
13564       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13565        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13566       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13567     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13568     int SSECC = translateX86FSETCC(
13569         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13570
13571     if (SSECC != 8) {
13572       if (Subtarget->hasAVX512()) {
13573         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13574                                   DAG.getConstant(SSECC, MVT::i8));
13575         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13576       }
13577       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13578                                 DAG.getConstant(SSECC, MVT::i8));
13579       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13580       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13581       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13582     }
13583   }
13584
13585   if (Cond.getOpcode() == ISD::SETCC) {
13586     SDValue NewCond = LowerSETCC(Cond, DAG);
13587     if (NewCond.getNode())
13588       Cond = NewCond;
13589   }
13590
13591   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13592   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13593   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13594   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13595   if (Cond.getOpcode() == X86ISD::SETCC &&
13596       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13597       isZero(Cond.getOperand(1).getOperand(1))) {
13598     SDValue Cmp = Cond.getOperand(1);
13599
13600     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13601
13602     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13603         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13604       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13605
13606       SDValue CmpOp0 = Cmp.getOperand(0);
13607       // Apply further optimizations for special cases
13608       // (select (x != 0), -1, 0) -> neg & sbb
13609       // (select (x == 0), 0, -1) -> neg & sbb
13610       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13611         if (YC->isNullValue() &&
13612             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13613           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13614           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13615                                     DAG.getConstant(0, CmpOp0.getValueType()),
13616                                     CmpOp0);
13617           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13618                                     DAG.getConstant(X86::COND_B, MVT::i8),
13619                                     SDValue(Neg.getNode(), 1));
13620           return Res;
13621         }
13622
13623       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13624                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
13625       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13626
13627       SDValue Res =   // Res = 0 or -1.
13628         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13629                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
13630
13631       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13632         Res = DAG.getNOT(DL, Res, Res.getValueType());
13633
13634       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13635       if (!N2C || !N2C->isNullValue())
13636         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13637       return Res;
13638     }
13639   }
13640
13641   // Look past (and (setcc_carry (cmp ...)), 1).
13642   if (Cond.getOpcode() == ISD::AND &&
13643       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13644     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13645     if (C && C->getAPIntValue() == 1)
13646       Cond = Cond.getOperand(0);
13647   }
13648
13649   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13650   // setting operand in place of the X86ISD::SETCC.
13651   unsigned CondOpcode = Cond.getOpcode();
13652   if (CondOpcode == X86ISD::SETCC ||
13653       CondOpcode == X86ISD::SETCC_CARRY) {
13654     CC = Cond.getOperand(0);
13655
13656     SDValue Cmp = Cond.getOperand(1);
13657     unsigned Opc = Cmp.getOpcode();
13658     MVT VT = Op.getSimpleValueType();
13659
13660     bool IllegalFPCMov = false;
13661     if (VT.isFloatingPoint() && !VT.isVector() &&
13662         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13663       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13664
13665     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13666         Opc == X86ISD::BT) { // FIXME
13667       Cond = Cmp;
13668       addTest = false;
13669     }
13670   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13671              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13672              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13673               Cond.getOperand(0).getValueType() != MVT::i8)) {
13674     SDValue LHS = Cond.getOperand(0);
13675     SDValue RHS = Cond.getOperand(1);
13676     unsigned X86Opcode;
13677     unsigned X86Cond;
13678     SDVTList VTs;
13679     switch (CondOpcode) {
13680     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13681     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13682     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13683     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13684     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13685     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13686     default: llvm_unreachable("unexpected overflowing operator");
13687     }
13688     if (CondOpcode == ISD::UMULO)
13689       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13690                           MVT::i32);
13691     else
13692       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13693
13694     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13695
13696     if (CondOpcode == ISD::UMULO)
13697       Cond = X86Op.getValue(2);
13698     else
13699       Cond = X86Op.getValue(1);
13700
13701     CC = DAG.getConstant(X86Cond, MVT::i8);
13702     addTest = false;
13703   }
13704
13705   if (addTest) {
13706     // Look pass the truncate if the high bits are known zero.
13707     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13708         Cond = Cond.getOperand(0);
13709
13710     // We know the result of AND is compared against zero. Try to match
13711     // it to BT.
13712     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13713       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13714       if (NewSetCC.getNode()) {
13715         CC = NewSetCC.getOperand(0);
13716         Cond = NewSetCC.getOperand(1);
13717         addTest = false;
13718       }
13719     }
13720   }
13721
13722   if (addTest) {
13723     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13724     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13725   }
13726
13727   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13728   // a <  b ?  0 : -1 -> RES = setcc_carry
13729   // a >= b ? -1 :  0 -> RES = setcc_carry
13730   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13731   if (Cond.getOpcode() == X86ISD::SUB) {
13732     Cond = ConvertCmpIfNecessary(Cond, DAG);
13733     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13734
13735     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13736         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13737       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13738                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
13739       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13740         return DAG.getNOT(DL, Res, Res.getValueType());
13741       return Res;
13742     }
13743   }
13744
13745   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13746   // widen the cmov and push the truncate through. This avoids introducing a new
13747   // branch during isel and doesn't add any extensions.
13748   if (Op.getValueType() == MVT::i8 &&
13749       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13750     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13751     if (T1.getValueType() == T2.getValueType() &&
13752         // Blacklist CopyFromReg to avoid partial register stalls.
13753         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13754       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13755       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13756       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13757     }
13758   }
13759
13760   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13761   // condition is true.
13762   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13763   SDValue Ops[] = { Op2, Op1, CC, Cond };
13764   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13765 }
13766
13767 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
13768   MVT VT = Op->getSimpleValueType(0);
13769   SDValue In = Op->getOperand(0);
13770   MVT InVT = In.getSimpleValueType();
13771   SDLoc dl(Op);
13772
13773   unsigned int NumElts = VT.getVectorNumElements();
13774   if (NumElts != 8 && NumElts != 16)
13775     return SDValue();
13776
13777   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
13778     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13779
13780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13781   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13782
13783   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13784   Constant *C = ConstantInt::get(*DAG.getContext(),
13785     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13786
13787   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13788   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13789   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13790                           MachinePointerInfo::getConstantPool(),
13791                           false, false, false, Alignment);
13792   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13793   if (VT.is512BitVector())
13794     return Brcst;
13795   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13796 }
13797
13798 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13799                                 SelectionDAG &DAG) {
13800   MVT VT = Op->getSimpleValueType(0);
13801   SDValue In = Op->getOperand(0);
13802   MVT InVT = In.getSimpleValueType();
13803   SDLoc dl(Op);
13804
13805   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13806     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13807
13808   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13809       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13810       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13811     return SDValue();
13812
13813   if (Subtarget->hasInt256())
13814     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13815
13816   // Optimize vectors in AVX mode
13817   // Sign extend  v8i16 to v8i32 and
13818   //              v4i32 to v4i64
13819   //
13820   // Divide input vector into two parts
13821   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13822   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13823   // concat the vectors to original VT
13824
13825   unsigned NumElems = InVT.getVectorNumElements();
13826   SDValue Undef = DAG.getUNDEF(InVT);
13827
13828   SmallVector<int,8> ShufMask1(NumElems, -1);
13829   for (unsigned i = 0; i != NumElems/2; ++i)
13830     ShufMask1[i] = i;
13831
13832   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13833
13834   SmallVector<int,8> ShufMask2(NumElems, -1);
13835   for (unsigned i = 0; i != NumElems/2; ++i)
13836     ShufMask2[i] = i + NumElems/2;
13837
13838   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13839
13840   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13841                                 VT.getVectorNumElements()/2);
13842
13843   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13844   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13845
13846   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13847 }
13848
13849 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13850 // may emit an illegal shuffle but the expansion is still better than scalar
13851 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13852 // we'll emit a shuffle and a arithmetic shift.
13853 // TODO: It is possible to support ZExt by zeroing the undef values during
13854 // the shuffle phase or after the shuffle.
13855 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13856                                  SelectionDAG &DAG) {
13857   MVT RegVT = Op.getSimpleValueType();
13858   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13859   assert(RegVT.isInteger() &&
13860          "We only custom lower integer vector sext loads.");
13861
13862   // Nothing useful we can do without SSE2 shuffles.
13863   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13864
13865   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13866   SDLoc dl(Ld);
13867   EVT MemVT = Ld->getMemoryVT();
13868   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13869   unsigned RegSz = RegVT.getSizeInBits();
13870
13871   ISD::LoadExtType Ext = Ld->getExtensionType();
13872
13873   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13874          && "Only anyext and sext are currently implemented.");
13875   assert(MemVT != RegVT && "Cannot extend to the same type");
13876   assert(MemVT.isVector() && "Must load a vector from memory");
13877
13878   unsigned NumElems = RegVT.getVectorNumElements();
13879   unsigned MemSz = MemVT.getSizeInBits();
13880   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13881
13882   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13883     // The only way in which we have a legal 256-bit vector result but not the
13884     // integer 256-bit operations needed to directly lower a sextload is if we
13885     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13886     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13887     // correctly legalized. We do this late to allow the canonical form of
13888     // sextload to persist throughout the rest of the DAG combiner -- it wants
13889     // to fold together any extensions it can, and so will fuse a sign_extend
13890     // of an sextload into a sextload targeting a wider value.
13891     SDValue Load;
13892     if (MemSz == 128) {
13893       // Just switch this to a normal load.
13894       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13895                                        "it must be a legal 128-bit vector "
13896                                        "type!");
13897       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13898                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13899                   Ld->isInvariant(), Ld->getAlignment());
13900     } else {
13901       assert(MemSz < 128 &&
13902              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13903       // Do an sext load to a 128-bit vector type. We want to use the same
13904       // number of elements, but elements half as wide. This will end up being
13905       // recursively lowered by this routine, but will succeed as we definitely
13906       // have all the necessary features if we're using AVX1.
13907       EVT HalfEltVT =
13908           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13909       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13910       Load =
13911           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13912                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13913                          Ld->isNonTemporal(), Ld->isInvariant(),
13914                          Ld->getAlignment());
13915     }
13916
13917     // Replace chain users with the new chain.
13918     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13919     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13920
13921     // Finally, do a normal sign-extend to the desired register.
13922     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13923   }
13924
13925   // All sizes must be a power of two.
13926   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13927          "Non-power-of-two elements are not custom lowered!");
13928
13929   // Attempt to load the original value using scalar loads.
13930   // Find the largest scalar type that divides the total loaded size.
13931   MVT SclrLoadTy = MVT::i8;
13932   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13933        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13934     MVT Tp = (MVT::SimpleValueType)tp;
13935     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13936       SclrLoadTy = Tp;
13937     }
13938   }
13939
13940   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13941   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13942       (64 <= MemSz))
13943     SclrLoadTy = MVT::f64;
13944
13945   // Calculate the number of scalar loads that we need to perform
13946   // in order to load our vector from memory.
13947   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13948
13949   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13950          "Can only lower sext loads with a single scalar load!");
13951
13952   unsigned loadRegZize = RegSz;
13953   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13954     loadRegZize /= 2;
13955
13956   // Represent our vector as a sequence of elements which are the
13957   // largest scalar that we can load.
13958   EVT LoadUnitVecVT = EVT::getVectorVT(
13959       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13960
13961   // Represent the data using the same element type that is stored in
13962   // memory. In practice, we ''widen'' MemVT.
13963   EVT WideVecVT =
13964       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13965                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13966
13967   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13968          "Invalid vector type");
13969
13970   // We can't shuffle using an illegal type.
13971   assert(TLI.isTypeLegal(WideVecVT) &&
13972          "We only lower types that form legal widened vector types");
13973
13974   SmallVector<SDValue, 8> Chains;
13975   SDValue Ptr = Ld->getBasePtr();
13976   SDValue Increment =
13977       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13978   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13979
13980   for (unsigned i = 0; i < NumLoads; ++i) {
13981     // Perform a single load.
13982     SDValue ScalarLoad =
13983         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13984                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13985                     Ld->getAlignment());
13986     Chains.push_back(ScalarLoad.getValue(1));
13987     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13988     // another round of DAGCombining.
13989     if (i == 0)
13990       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13991     else
13992       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13993                         ScalarLoad, DAG.getIntPtrConstant(i));
13994
13995     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13996   }
13997
13998   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13999
14000   // Bitcast the loaded value to a vector of the original element type, in
14001   // the size of the target vector type.
14002   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14003   unsigned SizeRatio = RegSz / MemSz;
14004
14005   if (Ext == ISD::SEXTLOAD) {
14006     // If we have SSE4.1, we can directly emit a VSEXT node.
14007     if (Subtarget->hasSSE41()) {
14008       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14009       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14010       return Sext;
14011     }
14012
14013     // Otherwise we'll shuffle the small elements in the high bits of the
14014     // larger type and perform an arithmetic shift. If the shift is not legal
14015     // it's better to scalarize.
14016     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14017            "We can't implement a sext load without an arithmetic right shift!");
14018
14019     // Redistribute the loaded elements into the different locations.
14020     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14021     for (unsigned i = 0; i != NumElems; ++i)
14022       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14023
14024     SDValue Shuff = DAG.getVectorShuffle(
14025         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14026
14027     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14028
14029     // Build the arithmetic shift.
14030     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14031                    MemVT.getVectorElementType().getSizeInBits();
14032     Shuff =
14033         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
14034
14035     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14036     return Shuff;
14037   }
14038
14039   // Redistribute the loaded elements into the different locations.
14040   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14041   for (unsigned i = 0; i != NumElems; ++i)
14042     ShuffleVec[i * SizeRatio] = i;
14043
14044   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14045                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14046
14047   // Bitcast to the requested type.
14048   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14049   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14050   return Shuff;
14051 }
14052
14053 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14054 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14055 // from the AND / OR.
14056 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14057   Opc = Op.getOpcode();
14058   if (Opc != ISD::OR && Opc != ISD::AND)
14059     return false;
14060   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14061           Op.getOperand(0).hasOneUse() &&
14062           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14063           Op.getOperand(1).hasOneUse());
14064 }
14065
14066 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14067 // 1 and that the SETCC node has a single use.
14068 static bool isXor1OfSetCC(SDValue Op) {
14069   if (Op.getOpcode() != ISD::XOR)
14070     return false;
14071   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14072   if (N1C && N1C->getAPIntValue() == 1) {
14073     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14074       Op.getOperand(0).hasOneUse();
14075   }
14076   return false;
14077 }
14078
14079 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14080   bool addTest = true;
14081   SDValue Chain = Op.getOperand(0);
14082   SDValue Cond  = Op.getOperand(1);
14083   SDValue Dest  = Op.getOperand(2);
14084   SDLoc dl(Op);
14085   SDValue CC;
14086   bool Inverted = false;
14087
14088   if (Cond.getOpcode() == ISD::SETCC) {
14089     // Check for setcc([su]{add,sub,mul}o == 0).
14090     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14091         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14092         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14093         Cond.getOperand(0).getResNo() == 1 &&
14094         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14095          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14096          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14097          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14098          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14099          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14100       Inverted = true;
14101       Cond = Cond.getOperand(0);
14102     } else {
14103       SDValue NewCond = LowerSETCC(Cond, DAG);
14104       if (NewCond.getNode())
14105         Cond = NewCond;
14106     }
14107   }
14108 #if 0
14109   // FIXME: LowerXALUO doesn't handle these!!
14110   else if (Cond.getOpcode() == X86ISD::ADD  ||
14111            Cond.getOpcode() == X86ISD::SUB  ||
14112            Cond.getOpcode() == X86ISD::SMUL ||
14113            Cond.getOpcode() == X86ISD::UMUL)
14114     Cond = LowerXALUO(Cond, DAG);
14115 #endif
14116
14117   // Look pass (and (setcc_carry (cmp ...)), 1).
14118   if (Cond.getOpcode() == ISD::AND &&
14119       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14120     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14121     if (C && C->getAPIntValue() == 1)
14122       Cond = Cond.getOperand(0);
14123   }
14124
14125   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14126   // setting operand in place of the X86ISD::SETCC.
14127   unsigned CondOpcode = Cond.getOpcode();
14128   if (CondOpcode == X86ISD::SETCC ||
14129       CondOpcode == X86ISD::SETCC_CARRY) {
14130     CC = Cond.getOperand(0);
14131
14132     SDValue Cmp = Cond.getOperand(1);
14133     unsigned Opc = Cmp.getOpcode();
14134     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14135     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14136       Cond = Cmp;
14137       addTest = false;
14138     } else {
14139       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14140       default: break;
14141       case X86::COND_O:
14142       case X86::COND_B:
14143         // These can only come from an arithmetic instruction with overflow,
14144         // e.g. SADDO, UADDO.
14145         Cond = Cond.getNode()->getOperand(1);
14146         addTest = false;
14147         break;
14148       }
14149     }
14150   }
14151   CondOpcode = Cond.getOpcode();
14152   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14153       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14154       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14155        Cond.getOperand(0).getValueType() != MVT::i8)) {
14156     SDValue LHS = Cond.getOperand(0);
14157     SDValue RHS = Cond.getOperand(1);
14158     unsigned X86Opcode;
14159     unsigned X86Cond;
14160     SDVTList VTs;
14161     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14162     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14163     // X86ISD::INC).
14164     switch (CondOpcode) {
14165     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14166     case ISD::SADDO:
14167       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14168         if (C->isOne()) {
14169           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14170           break;
14171         }
14172       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14173     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14174     case ISD::SSUBO:
14175       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14176         if (C->isOne()) {
14177           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14178           break;
14179         }
14180       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14181     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14182     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14183     default: llvm_unreachable("unexpected overflowing operator");
14184     }
14185     if (Inverted)
14186       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14187     if (CondOpcode == ISD::UMULO)
14188       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14189                           MVT::i32);
14190     else
14191       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14192
14193     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14194
14195     if (CondOpcode == ISD::UMULO)
14196       Cond = X86Op.getValue(2);
14197     else
14198       Cond = X86Op.getValue(1);
14199
14200     CC = DAG.getConstant(X86Cond, MVT::i8);
14201     addTest = false;
14202   } else {
14203     unsigned CondOpc;
14204     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14205       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14206       if (CondOpc == ISD::OR) {
14207         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14208         // two branches instead of an explicit OR instruction with a
14209         // separate test.
14210         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14211             isX86LogicalCmp(Cmp)) {
14212           CC = Cond.getOperand(0).getOperand(0);
14213           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14214                               Chain, Dest, CC, Cmp);
14215           CC = Cond.getOperand(1).getOperand(0);
14216           Cond = Cmp;
14217           addTest = false;
14218         }
14219       } else { // ISD::AND
14220         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14221         // two branches instead of an explicit AND instruction with a
14222         // separate test. However, we only do this if this block doesn't
14223         // have a fall-through edge, because this requires an explicit
14224         // jmp when the condition is false.
14225         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14226             isX86LogicalCmp(Cmp) &&
14227             Op.getNode()->hasOneUse()) {
14228           X86::CondCode CCode =
14229             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14230           CCode = X86::GetOppositeBranchCondition(CCode);
14231           CC = DAG.getConstant(CCode, MVT::i8);
14232           SDNode *User = *Op.getNode()->use_begin();
14233           // Look for an unconditional branch following this conditional branch.
14234           // We need this because we need to reverse the successors in order
14235           // to implement FCMP_OEQ.
14236           if (User->getOpcode() == ISD::BR) {
14237             SDValue FalseBB = User->getOperand(1);
14238             SDNode *NewBR =
14239               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14240             assert(NewBR == User);
14241             (void)NewBR;
14242             Dest = FalseBB;
14243
14244             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14245                                 Chain, Dest, CC, Cmp);
14246             X86::CondCode CCode =
14247               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14248             CCode = X86::GetOppositeBranchCondition(CCode);
14249             CC = DAG.getConstant(CCode, MVT::i8);
14250             Cond = Cmp;
14251             addTest = false;
14252           }
14253         }
14254       }
14255     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14256       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14257       // It should be transformed during dag combiner except when the condition
14258       // is set by a arithmetics with overflow node.
14259       X86::CondCode CCode =
14260         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14261       CCode = X86::GetOppositeBranchCondition(CCode);
14262       CC = DAG.getConstant(CCode, MVT::i8);
14263       Cond = Cond.getOperand(0).getOperand(1);
14264       addTest = false;
14265     } else if (Cond.getOpcode() == ISD::SETCC &&
14266                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14267       // For FCMP_OEQ, we can emit
14268       // two branches instead of an explicit AND instruction with a
14269       // separate test. However, we only do this if this block doesn't
14270       // have a fall-through edge, because this requires an explicit
14271       // jmp when the condition is false.
14272       if (Op.getNode()->hasOneUse()) {
14273         SDNode *User = *Op.getNode()->use_begin();
14274         // Look for an unconditional branch following this conditional branch.
14275         // We need this because we need to reverse the successors in order
14276         // to implement FCMP_OEQ.
14277         if (User->getOpcode() == ISD::BR) {
14278           SDValue FalseBB = User->getOperand(1);
14279           SDNode *NewBR =
14280             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14281           assert(NewBR == User);
14282           (void)NewBR;
14283           Dest = FalseBB;
14284
14285           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14286                                     Cond.getOperand(0), Cond.getOperand(1));
14287           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14288           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14289           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14290                               Chain, Dest, CC, Cmp);
14291           CC = DAG.getConstant(X86::COND_P, MVT::i8);
14292           Cond = Cmp;
14293           addTest = false;
14294         }
14295       }
14296     } else if (Cond.getOpcode() == ISD::SETCC &&
14297                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14298       // For FCMP_UNE, we can emit
14299       // two branches instead of an explicit AND instruction with a
14300       // separate test. However, we only do this if this block doesn't
14301       // have a fall-through edge, because this requires an explicit
14302       // jmp when the condition is false.
14303       if (Op.getNode()->hasOneUse()) {
14304         SDNode *User = *Op.getNode()->use_begin();
14305         // Look for an unconditional branch following this conditional branch.
14306         // We need this because we need to reverse the successors in order
14307         // to implement FCMP_UNE.
14308         if (User->getOpcode() == ISD::BR) {
14309           SDValue FalseBB = User->getOperand(1);
14310           SDNode *NewBR =
14311             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14312           assert(NewBR == User);
14313           (void)NewBR;
14314
14315           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14316                                     Cond.getOperand(0), Cond.getOperand(1));
14317           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14318           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14319           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14320                               Chain, Dest, CC, Cmp);
14321           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
14322           Cond = Cmp;
14323           addTest = false;
14324           Dest = FalseBB;
14325         }
14326       }
14327     }
14328   }
14329
14330   if (addTest) {
14331     // Look pass the truncate if the high bits are known zero.
14332     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14333         Cond = Cond.getOperand(0);
14334
14335     // We know the result of AND is compared against zero. Try to match
14336     // it to BT.
14337     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14338       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14339       if (NewSetCC.getNode()) {
14340         CC = NewSetCC.getOperand(0);
14341         Cond = NewSetCC.getOperand(1);
14342         addTest = false;
14343       }
14344     }
14345   }
14346
14347   if (addTest) {
14348     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14349     CC = DAG.getConstant(X86Cond, MVT::i8);
14350     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14351   }
14352   Cond = ConvertCmpIfNecessary(Cond, DAG);
14353   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14354                      Chain, Dest, CC, Cond);
14355 }
14356
14357 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14358 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14359 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14360 // that the guard pages used by the OS virtual memory manager are allocated in
14361 // correct sequence.
14362 SDValue
14363 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14364                                            SelectionDAG &DAG) const {
14365   MachineFunction &MF = DAG.getMachineFunction();
14366   bool SplitStack = MF.shouldSplitStack();
14367   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
14368                SplitStack;
14369   SDLoc dl(Op);
14370
14371   if (!Lower) {
14372     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14373     SDNode* Node = Op.getNode();
14374
14375     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14376     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14377         " not tell us which reg is the stack pointer!");
14378     EVT VT = Node->getValueType(0);
14379     SDValue Tmp1 = SDValue(Node, 0);
14380     SDValue Tmp2 = SDValue(Node, 1);
14381     SDValue Tmp3 = Node->getOperand(2);
14382     SDValue Chain = Tmp1.getOperand(0);
14383
14384     // Chain the dynamic stack allocation so that it doesn't modify the stack
14385     // pointer when other instructions are using the stack.
14386     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
14387         SDLoc(Node));
14388
14389     SDValue Size = Tmp2.getOperand(1);
14390     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14391     Chain = SP.getValue(1);
14392     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14393     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
14394     unsigned StackAlign = TFI.getStackAlignment();
14395     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14396     if (Align > StackAlign)
14397       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14398           DAG.getConstant(-(uint64_t)Align, VT));
14399     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14400
14401     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
14402         DAG.getIntPtrConstant(0, true), SDValue(),
14403         SDLoc(Node));
14404
14405     SDValue Ops[2] = { Tmp1, Tmp2 };
14406     return DAG.getMergeValues(Ops, dl);
14407   }
14408
14409   // Get the inputs.
14410   SDValue Chain = Op.getOperand(0);
14411   SDValue Size  = Op.getOperand(1);
14412   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14413   EVT VT = Op.getNode()->getValueType(0);
14414
14415   bool Is64Bit = Subtarget->is64Bit();
14416   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
14417
14418   if (SplitStack) {
14419     MachineRegisterInfo &MRI = MF.getRegInfo();
14420
14421     if (Is64Bit) {
14422       // The 64 bit implementation of segmented stacks needs to clobber both r10
14423       // r11. This makes it impossible to use it along with nested parameters.
14424       const Function *F = MF.getFunction();
14425
14426       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14427            I != E; ++I)
14428         if (I->hasNestAttr())
14429           report_fatal_error("Cannot use segmented stacks with functions that "
14430                              "have nested arguments.");
14431     }
14432
14433     const TargetRegisterClass *AddrRegClass =
14434       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
14435     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14436     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14437     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14438                                 DAG.getRegister(Vreg, SPTy));
14439     SDValue Ops1[2] = { Value, Chain };
14440     return DAG.getMergeValues(Ops1, dl);
14441   } else {
14442     SDValue Flag;
14443     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
14444
14445     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14446     Flag = Chain.getValue(1);
14447     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14448
14449     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14450
14451     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
14452         DAG.getSubtarget().getRegisterInfo());
14453     unsigned SPReg = RegInfo->getStackRegister();
14454     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14455     Chain = SP.getValue(1);
14456
14457     if (Align) {
14458       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14459                        DAG.getConstant(-(uint64_t)Align, VT));
14460       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14461     }
14462
14463     SDValue Ops1[2] = { SP, Chain };
14464     return DAG.getMergeValues(Ops1, dl);
14465   }
14466 }
14467
14468 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14469   MachineFunction &MF = DAG.getMachineFunction();
14470   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14471
14472   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14473   SDLoc DL(Op);
14474
14475   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14476     // vastart just stores the address of the VarArgsFrameIndex slot into the
14477     // memory location argument.
14478     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14479                                    getPointerTy());
14480     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14481                         MachinePointerInfo(SV), false, false, 0);
14482   }
14483
14484   // __va_list_tag:
14485   //   gp_offset         (0 - 6 * 8)
14486   //   fp_offset         (48 - 48 + 8 * 16)
14487   //   overflow_arg_area (point to parameters coming in memory).
14488   //   reg_save_area
14489   SmallVector<SDValue, 8> MemOps;
14490   SDValue FIN = Op.getOperand(1);
14491   // Store gp_offset
14492   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14493                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14494                                                MVT::i32),
14495                                FIN, MachinePointerInfo(SV), false, false, 0);
14496   MemOps.push_back(Store);
14497
14498   // Store fp_offset
14499   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14500                     FIN, DAG.getIntPtrConstant(4));
14501   Store = DAG.getStore(Op.getOperand(0), DL,
14502                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
14503                                        MVT::i32),
14504                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14505   MemOps.push_back(Store);
14506
14507   // Store ptr to overflow_arg_area
14508   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14509                     FIN, DAG.getIntPtrConstant(4));
14510   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14511                                     getPointerTy());
14512   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14513                        MachinePointerInfo(SV, 8),
14514                        false, false, 0);
14515   MemOps.push_back(Store);
14516
14517   // Store ptr to reg_save_area.
14518   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14519                     FIN, DAG.getIntPtrConstant(8));
14520   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14521                                     getPointerTy());
14522   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14523                        MachinePointerInfo(SV, 16), false, false, 0);
14524   MemOps.push_back(Store);
14525   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14526 }
14527
14528 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14529   assert(Subtarget->is64Bit() &&
14530          "LowerVAARG only handles 64-bit va_arg!");
14531   assert((Subtarget->isTargetLinux() ||
14532           Subtarget->isTargetDarwin()) &&
14533           "Unhandled target in LowerVAARG");
14534   assert(Op.getNode()->getNumOperands() == 4);
14535   SDValue Chain = Op.getOperand(0);
14536   SDValue SrcPtr = Op.getOperand(1);
14537   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14538   unsigned Align = Op.getConstantOperandVal(3);
14539   SDLoc dl(Op);
14540
14541   EVT ArgVT = Op.getNode()->getValueType(0);
14542   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14543   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14544   uint8_t ArgMode;
14545
14546   // Decide which area this value should be read from.
14547   // TODO: Implement the AMD64 ABI in its entirety. This simple
14548   // selection mechanism works only for the basic types.
14549   if (ArgVT == MVT::f80) {
14550     llvm_unreachable("va_arg for f80 not yet implemented");
14551   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14552     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14553   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14554     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14555   } else {
14556     llvm_unreachable("Unhandled argument type in LowerVAARG");
14557   }
14558
14559   if (ArgMode == 2) {
14560     // Sanity Check: Make sure using fp_offset makes sense.
14561     assert(!DAG.getTarget().Options.UseSoftFloat &&
14562            !(DAG.getMachineFunction()
14563                 .getFunction()->getAttributes()
14564                 .hasAttribute(AttributeSet::FunctionIndex,
14565                               Attribute::NoImplicitFloat)) &&
14566            Subtarget->hasSSE1());
14567   }
14568
14569   // Insert VAARG_64 node into the DAG
14570   // VAARG_64 returns two values: Variable Argument Address, Chain
14571   SmallVector<SDValue, 11> InstOps;
14572   InstOps.push_back(Chain);
14573   InstOps.push_back(SrcPtr);
14574   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
14575   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
14576   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
14577   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14578   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14579                                           VTs, InstOps, MVT::i64,
14580                                           MachinePointerInfo(SV),
14581                                           /*Align=*/0,
14582                                           /*Volatile=*/false,
14583                                           /*ReadMem=*/true,
14584                                           /*WriteMem=*/true);
14585   Chain = VAARG.getValue(1);
14586
14587   // Load the next argument and return it
14588   return DAG.getLoad(ArgVT, dl,
14589                      Chain,
14590                      VAARG,
14591                      MachinePointerInfo(),
14592                      false, false, false, 0);
14593 }
14594
14595 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14596                            SelectionDAG &DAG) {
14597   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14598   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14599   SDValue Chain = Op.getOperand(0);
14600   SDValue DstPtr = Op.getOperand(1);
14601   SDValue SrcPtr = Op.getOperand(2);
14602   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14603   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14604   SDLoc DL(Op);
14605
14606   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14607                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
14608                        false,
14609                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14610 }
14611
14612 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14613 // amount is a constant. Takes immediate version of shift as input.
14614 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14615                                           SDValue SrcOp, uint64_t ShiftAmt,
14616                                           SelectionDAG &DAG) {
14617   MVT ElementType = VT.getVectorElementType();
14618
14619   // Fold this packed shift into its first operand if ShiftAmt is 0.
14620   if (ShiftAmt == 0)
14621     return SrcOp;
14622
14623   // Check for ShiftAmt >= element width
14624   if (ShiftAmt >= ElementType.getSizeInBits()) {
14625     if (Opc == X86ISD::VSRAI)
14626       ShiftAmt = ElementType.getSizeInBits() - 1;
14627     else
14628       return DAG.getConstant(0, VT);
14629   }
14630
14631   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14632          && "Unknown target vector shift-by-constant node");
14633
14634   // Fold this packed vector shift into a build vector if SrcOp is a
14635   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14636   if (VT == SrcOp.getSimpleValueType() &&
14637       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14638     SmallVector<SDValue, 8> Elts;
14639     unsigned NumElts = SrcOp->getNumOperands();
14640     ConstantSDNode *ND;
14641
14642     switch(Opc) {
14643     default: llvm_unreachable(nullptr);
14644     case X86ISD::VSHLI:
14645       for (unsigned i=0; i!=NumElts; ++i) {
14646         SDValue CurrentOp = SrcOp->getOperand(i);
14647         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14648           Elts.push_back(CurrentOp);
14649           continue;
14650         }
14651         ND = cast<ConstantSDNode>(CurrentOp);
14652         const APInt &C = ND->getAPIntValue();
14653         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
14654       }
14655       break;
14656     case X86ISD::VSRLI:
14657       for (unsigned i=0; i!=NumElts; ++i) {
14658         SDValue CurrentOp = SrcOp->getOperand(i);
14659         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14660           Elts.push_back(CurrentOp);
14661           continue;
14662         }
14663         ND = cast<ConstantSDNode>(CurrentOp);
14664         const APInt &C = ND->getAPIntValue();
14665         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
14666       }
14667       break;
14668     case X86ISD::VSRAI:
14669       for (unsigned i=0; i!=NumElts; ++i) {
14670         SDValue CurrentOp = SrcOp->getOperand(i);
14671         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14672           Elts.push_back(CurrentOp);
14673           continue;
14674         }
14675         ND = cast<ConstantSDNode>(CurrentOp);
14676         const APInt &C = ND->getAPIntValue();
14677         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
14678       }
14679       break;
14680     }
14681
14682     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14683   }
14684
14685   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
14686 }
14687
14688 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14689 // may or may not be a constant. Takes immediate version of shift as input.
14690 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14691                                    SDValue SrcOp, SDValue ShAmt,
14692                                    SelectionDAG &DAG) {
14693   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
14694
14695   // Catch shift-by-constant.
14696   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14697     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14698                                       CShAmt->getZExtValue(), DAG);
14699
14700   // Change opcode to non-immediate version
14701   switch (Opc) {
14702     default: llvm_unreachable("Unknown target vector shift node");
14703     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14704     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14705     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14706   }
14707
14708   // Need to build a vector containing shift amount
14709   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
14710   SDValue ShOps[4];
14711   ShOps[0] = ShAmt;
14712   ShOps[1] = DAG.getConstant(0, MVT::i32);
14713   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
14714   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
14715
14716   // The return type has to be a 128-bit type with the same element
14717   // type as the input type.
14718   MVT EltVT = VT.getVectorElementType();
14719   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14720
14721   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
14722   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14723 }
14724
14725 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
14726 /// necessary casting for \p Mask when lowering masking intrinsics.
14727 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14728                                     SDValue PreservedSrc, SelectionDAG &DAG) {
14729     EVT VT = Op.getValueType();
14730     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
14731                                   MVT::i1, VT.getVectorNumElements());
14732     SDLoc dl(Op);
14733
14734     assert(MaskVT.isSimple() && "invalid mask type");
14735     return DAG.getNode(ISD::VSELECT, dl, VT,
14736                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
14737                        Op, PreservedSrc);
14738 }
14739
14740 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
14741     switch (IntNo) {
14742     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14743     case Intrinsic::x86_fma_vfmadd_ps:
14744     case Intrinsic::x86_fma_vfmadd_pd:
14745     case Intrinsic::x86_fma_vfmadd_ps_256:
14746     case Intrinsic::x86_fma_vfmadd_pd_256:
14747     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
14748     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
14749       return X86ISD::FMADD;
14750     case Intrinsic::x86_fma_vfmsub_ps:
14751     case Intrinsic::x86_fma_vfmsub_pd:
14752     case Intrinsic::x86_fma_vfmsub_ps_256:
14753     case Intrinsic::x86_fma_vfmsub_pd_256:
14754     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
14755     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
14756       return X86ISD::FMSUB;
14757     case Intrinsic::x86_fma_vfnmadd_ps:
14758     case Intrinsic::x86_fma_vfnmadd_pd:
14759     case Intrinsic::x86_fma_vfnmadd_ps_256:
14760     case Intrinsic::x86_fma_vfnmadd_pd_256:
14761     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
14762     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
14763       return X86ISD::FNMADD;
14764     case Intrinsic::x86_fma_vfnmsub_ps:
14765     case Intrinsic::x86_fma_vfnmsub_pd:
14766     case Intrinsic::x86_fma_vfnmsub_ps_256:
14767     case Intrinsic::x86_fma_vfnmsub_pd_256:
14768     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
14769     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
14770       return X86ISD::FNMSUB;
14771     case Intrinsic::x86_fma_vfmaddsub_ps:
14772     case Intrinsic::x86_fma_vfmaddsub_pd:
14773     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14774     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14775     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
14776     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
14777       return X86ISD::FMADDSUB;
14778     case Intrinsic::x86_fma_vfmsubadd_ps:
14779     case Intrinsic::x86_fma_vfmsubadd_pd:
14780     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14781     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14782     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
14783     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
14784       return X86ISD::FMSUBADD;
14785     }
14786 }
14787
14788 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
14789   SDLoc dl(Op);
14790   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14791
14792   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
14793   if (IntrData) {
14794     switch(IntrData->Type) {
14795     case INTR_TYPE_1OP:
14796       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
14797     case INTR_TYPE_2OP:
14798       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14799         Op.getOperand(2));
14800     case INTR_TYPE_3OP:
14801       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
14802         Op.getOperand(2), Op.getOperand(3));
14803     case COMI: { // Comparison intrinsics
14804       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
14805       SDValue LHS = Op.getOperand(1);
14806       SDValue RHS = Op.getOperand(2);
14807       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14808       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14809       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
14810       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14811                                   DAG.getConstant(X86CC, MVT::i8), Cond);
14812       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14813     }
14814     case VSHIFT:
14815       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
14816                                  Op.getOperand(1), Op.getOperand(2), DAG);
14817     default:
14818       break;
14819     }
14820   }
14821
14822   switch (IntNo) {
14823   default: return SDValue();    // Don't custom lower most intrinsics.
14824
14825   // Arithmetic intrinsics.
14826   case Intrinsic::x86_sse2_pmulu_dq:
14827   case Intrinsic::x86_avx2_pmulu_dq:
14828     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14829                        Op.getOperand(1), Op.getOperand(2));
14830
14831   case Intrinsic::x86_sse41_pmuldq:
14832   case Intrinsic::x86_avx2_pmul_dq:
14833     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14834                        Op.getOperand(1), Op.getOperand(2));
14835
14836   case Intrinsic::x86_sse2_pmulhu_w:
14837   case Intrinsic::x86_avx2_pmulhu_w:
14838     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14839                        Op.getOperand(1), Op.getOperand(2));
14840
14841   case Intrinsic::x86_sse2_pmulh_w:
14842   case Intrinsic::x86_avx2_pmulh_w:
14843     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14844                        Op.getOperand(1), Op.getOperand(2));
14845
14846   // SSE/SSE2/AVX floating point max/min intrinsics.
14847   case Intrinsic::x86_sse_max_ps:
14848   case Intrinsic::x86_sse2_max_pd:
14849   case Intrinsic::x86_avx_max_ps_256:
14850   case Intrinsic::x86_avx_max_pd_256:
14851   case Intrinsic::x86_sse_min_ps:
14852   case Intrinsic::x86_sse2_min_pd:
14853   case Intrinsic::x86_avx_min_ps_256:
14854   case Intrinsic::x86_avx_min_pd_256: {
14855     unsigned Opcode;
14856     switch (IntNo) {
14857     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14858     case Intrinsic::x86_sse_max_ps:
14859     case Intrinsic::x86_sse2_max_pd:
14860     case Intrinsic::x86_avx_max_ps_256:
14861     case Intrinsic::x86_avx_max_pd_256:
14862       Opcode = X86ISD::FMAX;
14863       break;
14864     case Intrinsic::x86_sse_min_ps:
14865     case Intrinsic::x86_sse2_min_pd:
14866     case Intrinsic::x86_avx_min_ps_256:
14867     case Intrinsic::x86_avx_min_pd_256:
14868       Opcode = X86ISD::FMIN;
14869       break;
14870     }
14871     return DAG.getNode(Opcode, dl, Op.getValueType(),
14872                        Op.getOperand(1), Op.getOperand(2));
14873   }
14874
14875   // AVX2 variable shift intrinsics
14876   case Intrinsic::x86_avx2_psllv_d:
14877   case Intrinsic::x86_avx2_psllv_q:
14878   case Intrinsic::x86_avx2_psllv_d_256:
14879   case Intrinsic::x86_avx2_psllv_q_256:
14880   case Intrinsic::x86_avx2_psrlv_d:
14881   case Intrinsic::x86_avx2_psrlv_q:
14882   case Intrinsic::x86_avx2_psrlv_d_256:
14883   case Intrinsic::x86_avx2_psrlv_q_256:
14884   case Intrinsic::x86_avx2_psrav_d:
14885   case Intrinsic::x86_avx2_psrav_d_256: {
14886     unsigned Opcode;
14887     switch (IntNo) {
14888     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14889     case Intrinsic::x86_avx2_psllv_d:
14890     case Intrinsic::x86_avx2_psllv_q:
14891     case Intrinsic::x86_avx2_psllv_d_256:
14892     case Intrinsic::x86_avx2_psllv_q_256:
14893       Opcode = ISD::SHL;
14894       break;
14895     case Intrinsic::x86_avx2_psrlv_d:
14896     case Intrinsic::x86_avx2_psrlv_q:
14897     case Intrinsic::x86_avx2_psrlv_d_256:
14898     case Intrinsic::x86_avx2_psrlv_q_256:
14899       Opcode = ISD::SRL;
14900       break;
14901     case Intrinsic::x86_avx2_psrav_d:
14902     case Intrinsic::x86_avx2_psrav_d_256:
14903       Opcode = ISD::SRA;
14904       break;
14905     }
14906     return DAG.getNode(Opcode, dl, Op.getValueType(),
14907                        Op.getOperand(1), Op.getOperand(2));
14908   }
14909
14910   case Intrinsic::x86_sse2_packssdw_128:
14911   case Intrinsic::x86_sse2_packsswb_128:
14912   case Intrinsic::x86_avx2_packssdw:
14913   case Intrinsic::x86_avx2_packsswb:
14914     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14915                        Op.getOperand(1), Op.getOperand(2));
14916
14917   case Intrinsic::x86_sse2_packuswb_128:
14918   case Intrinsic::x86_sse41_packusdw:
14919   case Intrinsic::x86_avx2_packuswb:
14920   case Intrinsic::x86_avx2_packusdw:
14921     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14922                        Op.getOperand(1), Op.getOperand(2));
14923
14924   case Intrinsic::x86_ssse3_pshuf_b_128:
14925   case Intrinsic::x86_avx2_pshuf_b:
14926     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14927                        Op.getOperand(1), Op.getOperand(2));
14928
14929   case Intrinsic::x86_sse2_pshuf_d:
14930     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14931                        Op.getOperand(1), Op.getOperand(2));
14932
14933   case Intrinsic::x86_sse2_pshufl_w:
14934     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14935                        Op.getOperand(1), Op.getOperand(2));
14936
14937   case Intrinsic::x86_sse2_pshufh_w:
14938     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14939                        Op.getOperand(1), Op.getOperand(2));
14940
14941   case Intrinsic::x86_ssse3_psign_b_128:
14942   case Intrinsic::x86_ssse3_psign_w_128:
14943   case Intrinsic::x86_ssse3_psign_d_128:
14944   case Intrinsic::x86_avx2_psign_b:
14945   case Intrinsic::x86_avx2_psign_w:
14946   case Intrinsic::x86_avx2_psign_d:
14947     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14948                        Op.getOperand(1), Op.getOperand(2));
14949
14950   case Intrinsic::x86_avx2_permd:
14951   case Intrinsic::x86_avx2_permps:
14952     // Operands intentionally swapped. Mask is last operand to intrinsic,
14953     // but second operand for node/instruction.
14954     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14955                        Op.getOperand(2), Op.getOperand(1));
14956
14957   case Intrinsic::x86_avx512_mask_valign_q_512:
14958   case Intrinsic::x86_avx512_mask_valign_d_512:
14959     // Vector source operands are swapped.
14960     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
14961                                             Op.getValueType(), Op.getOperand(2),
14962                                             Op.getOperand(1),
14963                                             Op.getOperand(3)),
14964                                 Op.getOperand(5), Op.getOperand(4), DAG);
14965
14966   // ptest and testp intrinsics. The intrinsic these come from are designed to
14967   // return an integer value, not just an instruction so lower it to the ptest
14968   // or testp pattern and a setcc for the result.
14969   case Intrinsic::x86_sse41_ptestz:
14970   case Intrinsic::x86_sse41_ptestc:
14971   case Intrinsic::x86_sse41_ptestnzc:
14972   case Intrinsic::x86_avx_ptestz_256:
14973   case Intrinsic::x86_avx_ptestc_256:
14974   case Intrinsic::x86_avx_ptestnzc_256:
14975   case Intrinsic::x86_avx_vtestz_ps:
14976   case Intrinsic::x86_avx_vtestc_ps:
14977   case Intrinsic::x86_avx_vtestnzc_ps:
14978   case Intrinsic::x86_avx_vtestz_pd:
14979   case Intrinsic::x86_avx_vtestc_pd:
14980   case Intrinsic::x86_avx_vtestnzc_pd:
14981   case Intrinsic::x86_avx_vtestz_ps_256:
14982   case Intrinsic::x86_avx_vtestc_ps_256:
14983   case Intrinsic::x86_avx_vtestnzc_ps_256:
14984   case Intrinsic::x86_avx_vtestz_pd_256:
14985   case Intrinsic::x86_avx_vtestc_pd_256:
14986   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14987     bool IsTestPacked = false;
14988     unsigned X86CC;
14989     switch (IntNo) {
14990     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14991     case Intrinsic::x86_avx_vtestz_ps:
14992     case Intrinsic::x86_avx_vtestz_pd:
14993     case Intrinsic::x86_avx_vtestz_ps_256:
14994     case Intrinsic::x86_avx_vtestz_pd_256:
14995       IsTestPacked = true; // Fallthrough
14996     case Intrinsic::x86_sse41_ptestz:
14997     case Intrinsic::x86_avx_ptestz_256:
14998       // ZF = 1
14999       X86CC = X86::COND_E;
15000       break;
15001     case Intrinsic::x86_avx_vtestc_ps:
15002     case Intrinsic::x86_avx_vtestc_pd:
15003     case Intrinsic::x86_avx_vtestc_ps_256:
15004     case Intrinsic::x86_avx_vtestc_pd_256:
15005       IsTestPacked = true; // Fallthrough
15006     case Intrinsic::x86_sse41_ptestc:
15007     case Intrinsic::x86_avx_ptestc_256:
15008       // CF = 1
15009       X86CC = X86::COND_B;
15010       break;
15011     case Intrinsic::x86_avx_vtestnzc_ps:
15012     case Intrinsic::x86_avx_vtestnzc_pd:
15013     case Intrinsic::x86_avx_vtestnzc_ps_256:
15014     case Intrinsic::x86_avx_vtestnzc_pd_256:
15015       IsTestPacked = true; // Fallthrough
15016     case Intrinsic::x86_sse41_ptestnzc:
15017     case Intrinsic::x86_avx_ptestnzc_256:
15018       // ZF and CF = 0
15019       X86CC = X86::COND_A;
15020       break;
15021     }
15022
15023     SDValue LHS = Op.getOperand(1);
15024     SDValue RHS = Op.getOperand(2);
15025     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15026     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15027     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
15028     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15029     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15030   }
15031   case Intrinsic::x86_avx512_kortestz_w:
15032   case Intrinsic::x86_avx512_kortestc_w: {
15033     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15034     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15035     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15036     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
15037     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15038     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15039     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15040   }
15041
15042   case Intrinsic::x86_sse42_pcmpistria128:
15043   case Intrinsic::x86_sse42_pcmpestria128:
15044   case Intrinsic::x86_sse42_pcmpistric128:
15045   case Intrinsic::x86_sse42_pcmpestric128:
15046   case Intrinsic::x86_sse42_pcmpistrio128:
15047   case Intrinsic::x86_sse42_pcmpestrio128:
15048   case Intrinsic::x86_sse42_pcmpistris128:
15049   case Intrinsic::x86_sse42_pcmpestris128:
15050   case Intrinsic::x86_sse42_pcmpistriz128:
15051   case Intrinsic::x86_sse42_pcmpestriz128: {
15052     unsigned Opcode;
15053     unsigned X86CC;
15054     switch (IntNo) {
15055     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15056     case Intrinsic::x86_sse42_pcmpistria128:
15057       Opcode = X86ISD::PCMPISTRI;
15058       X86CC = X86::COND_A;
15059       break;
15060     case Intrinsic::x86_sse42_pcmpestria128:
15061       Opcode = X86ISD::PCMPESTRI;
15062       X86CC = X86::COND_A;
15063       break;
15064     case Intrinsic::x86_sse42_pcmpistric128:
15065       Opcode = X86ISD::PCMPISTRI;
15066       X86CC = X86::COND_B;
15067       break;
15068     case Intrinsic::x86_sse42_pcmpestric128:
15069       Opcode = X86ISD::PCMPESTRI;
15070       X86CC = X86::COND_B;
15071       break;
15072     case Intrinsic::x86_sse42_pcmpistrio128:
15073       Opcode = X86ISD::PCMPISTRI;
15074       X86CC = X86::COND_O;
15075       break;
15076     case Intrinsic::x86_sse42_pcmpestrio128:
15077       Opcode = X86ISD::PCMPESTRI;
15078       X86CC = X86::COND_O;
15079       break;
15080     case Intrinsic::x86_sse42_pcmpistris128:
15081       Opcode = X86ISD::PCMPISTRI;
15082       X86CC = X86::COND_S;
15083       break;
15084     case Intrinsic::x86_sse42_pcmpestris128:
15085       Opcode = X86ISD::PCMPESTRI;
15086       X86CC = X86::COND_S;
15087       break;
15088     case Intrinsic::x86_sse42_pcmpistriz128:
15089       Opcode = X86ISD::PCMPISTRI;
15090       X86CC = X86::COND_E;
15091       break;
15092     case Intrinsic::x86_sse42_pcmpestriz128:
15093       Opcode = X86ISD::PCMPESTRI;
15094       X86CC = X86::COND_E;
15095       break;
15096     }
15097     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15098     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15099     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15100     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15101                                 DAG.getConstant(X86CC, MVT::i8),
15102                                 SDValue(PCMP.getNode(), 1));
15103     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15104   }
15105
15106   case Intrinsic::x86_sse42_pcmpistri128:
15107   case Intrinsic::x86_sse42_pcmpestri128: {
15108     unsigned Opcode;
15109     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15110       Opcode = X86ISD::PCMPISTRI;
15111     else
15112       Opcode = X86ISD::PCMPESTRI;
15113
15114     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15115     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15116     return DAG.getNode(Opcode, dl, VTs, NewOps);
15117   }
15118
15119   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15120   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15121   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15122   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15123   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15124   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15125   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15126   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15127   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15128   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15129   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15130   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
15131     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
15132     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
15133       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
15134                                               dl, Op.getValueType(),
15135                                               Op.getOperand(1),
15136                                               Op.getOperand(2),
15137                                               Op.getOperand(3)),
15138                                   Op.getOperand(4), Op.getOperand(1), DAG);
15139     else
15140       return SDValue();
15141   }
15142
15143   case Intrinsic::x86_fma_vfmadd_ps:
15144   case Intrinsic::x86_fma_vfmadd_pd:
15145   case Intrinsic::x86_fma_vfmsub_ps:
15146   case Intrinsic::x86_fma_vfmsub_pd:
15147   case Intrinsic::x86_fma_vfnmadd_ps:
15148   case Intrinsic::x86_fma_vfnmadd_pd:
15149   case Intrinsic::x86_fma_vfnmsub_ps:
15150   case Intrinsic::x86_fma_vfnmsub_pd:
15151   case Intrinsic::x86_fma_vfmaddsub_ps:
15152   case Intrinsic::x86_fma_vfmaddsub_pd:
15153   case Intrinsic::x86_fma_vfmsubadd_ps:
15154   case Intrinsic::x86_fma_vfmsubadd_pd:
15155   case Intrinsic::x86_fma_vfmadd_ps_256:
15156   case Intrinsic::x86_fma_vfmadd_pd_256:
15157   case Intrinsic::x86_fma_vfmsub_ps_256:
15158   case Intrinsic::x86_fma_vfmsub_pd_256:
15159   case Intrinsic::x86_fma_vfnmadd_ps_256:
15160   case Intrinsic::x86_fma_vfnmadd_pd_256:
15161   case Intrinsic::x86_fma_vfnmsub_ps_256:
15162   case Intrinsic::x86_fma_vfnmsub_pd_256:
15163   case Intrinsic::x86_fma_vfmaddsub_ps_256:
15164   case Intrinsic::x86_fma_vfmaddsub_pd_256:
15165   case Intrinsic::x86_fma_vfmsubadd_ps_256:
15166   case Intrinsic::x86_fma_vfmsubadd_pd_256:
15167     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
15168                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
15169   }
15170 }
15171
15172 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15173                               SDValue Src, SDValue Mask, SDValue Base,
15174                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15175                               const X86Subtarget * Subtarget) {
15176   SDLoc dl(Op);
15177   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15178   assert(C && "Invalid scale type");
15179   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15180   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15181                              Index.getSimpleValueType().getVectorNumElements());
15182   SDValue MaskInReg;
15183   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15184   if (MaskC)
15185     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15186   else
15187     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15188   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15189   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15190   SDValue Segment = DAG.getRegister(0, MVT::i32);
15191   if (Src.getOpcode() == ISD::UNDEF)
15192     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15193   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15194   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15195   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15196   return DAG.getMergeValues(RetOps, dl);
15197 }
15198
15199 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15200                                SDValue Src, SDValue Mask, SDValue Base,
15201                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15202   SDLoc dl(Op);
15203   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15204   assert(C && "Invalid scale type");
15205   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15206   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15207   SDValue Segment = DAG.getRegister(0, MVT::i32);
15208   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15209                              Index.getSimpleValueType().getVectorNumElements());
15210   SDValue MaskInReg;
15211   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15212   if (MaskC)
15213     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15214   else
15215     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15216   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15217   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15218   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15219   return SDValue(Res, 1);
15220 }
15221
15222 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15223                                SDValue Mask, SDValue Base, SDValue Index,
15224                                SDValue ScaleOp, SDValue Chain) {
15225   SDLoc dl(Op);
15226   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15227   assert(C && "Invalid scale type");
15228   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15229   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15230   SDValue Segment = DAG.getRegister(0, MVT::i32);
15231   EVT MaskVT =
15232     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15233   SDValue MaskInReg;
15234   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15235   if (MaskC)
15236     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15237   else
15238     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15239   //SDVTList VTs = DAG.getVTList(MVT::Other);
15240   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15241   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15242   return SDValue(Res, 0);
15243 }
15244
15245 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15246 // read performance monitor counters (x86_rdpmc).
15247 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15248                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15249                               SmallVectorImpl<SDValue> &Results) {
15250   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15251   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15252   SDValue LO, HI;
15253
15254   // The ECX register is used to select the index of the performance counter
15255   // to read.
15256   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15257                                    N->getOperand(2));
15258   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15259
15260   // Reads the content of a 64-bit performance counter and returns it in the
15261   // registers EDX:EAX.
15262   if (Subtarget->is64Bit()) {
15263     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15264     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15265                             LO.getValue(2));
15266   } else {
15267     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15268     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15269                             LO.getValue(2));
15270   }
15271   Chain = HI.getValue(1);
15272
15273   if (Subtarget->is64Bit()) {
15274     // The EAX register is loaded with the low-order 32 bits. The EDX register
15275     // is loaded with the supported high-order bits of the counter.
15276     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15277                               DAG.getConstant(32, MVT::i8));
15278     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15279     Results.push_back(Chain);
15280     return;
15281   }
15282
15283   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15284   SDValue Ops[] = { LO, HI };
15285   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15286   Results.push_back(Pair);
15287   Results.push_back(Chain);
15288 }
15289
15290 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15291 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15292 // also used to custom lower READCYCLECOUNTER nodes.
15293 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15294                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15295                               SmallVectorImpl<SDValue> &Results) {
15296   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15297   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15298   SDValue LO, HI;
15299
15300   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15301   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15302   // and the EAX register is loaded with the low-order 32 bits.
15303   if (Subtarget->is64Bit()) {
15304     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15305     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15306                             LO.getValue(2));
15307   } else {
15308     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15309     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15310                             LO.getValue(2));
15311   }
15312   SDValue Chain = HI.getValue(1);
15313
15314   if (Opcode == X86ISD::RDTSCP_DAG) {
15315     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15316
15317     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15318     // the ECX register. Add 'ecx' explicitly to the chain.
15319     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15320                                      HI.getValue(2));
15321     // Explicitly store the content of ECX at the location passed in input
15322     // to the 'rdtscp' intrinsic.
15323     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15324                          MachinePointerInfo(), false, false, 0);
15325   }
15326
15327   if (Subtarget->is64Bit()) {
15328     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15329     // the EAX register is loaded with the low-order 32 bits.
15330     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15331                               DAG.getConstant(32, MVT::i8));
15332     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15333     Results.push_back(Chain);
15334     return;
15335   }
15336
15337   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15338   SDValue Ops[] = { LO, HI };
15339   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15340   Results.push_back(Pair);
15341   Results.push_back(Chain);
15342 }
15343
15344 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15345                                      SelectionDAG &DAG) {
15346   SmallVector<SDValue, 2> Results;
15347   SDLoc DL(Op);
15348   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15349                           Results);
15350   return DAG.getMergeValues(Results, DL);
15351 }
15352
15353
15354 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15355                                       SelectionDAG &DAG) {
15356   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15357
15358   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15359   if (!IntrData)
15360     return SDValue();
15361
15362   SDLoc dl(Op);
15363   switch(IntrData->Type) {
15364   default:
15365     llvm_unreachable("Unknown Intrinsic Type");
15366     break;    
15367   case RDSEED:
15368   case RDRAND: {
15369     // Emit the node with the right value type.
15370     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15371     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15372
15373     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15374     // Otherwise return the value from Rand, which is always 0, casted to i32.
15375     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15376                       DAG.getConstant(1, Op->getValueType(1)),
15377                       DAG.getConstant(X86::COND_B, MVT::i32),
15378                       SDValue(Result.getNode(), 1) };
15379     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15380                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15381                                   Ops);
15382
15383     // Return { result, isValid, chain }.
15384     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15385                        SDValue(Result.getNode(), 2));
15386   }
15387   case GATHER: {
15388   //gather(v1, mask, index, base, scale);
15389     SDValue Chain = Op.getOperand(0);
15390     SDValue Src   = Op.getOperand(2);
15391     SDValue Base  = Op.getOperand(3);
15392     SDValue Index = Op.getOperand(4);
15393     SDValue Mask  = Op.getOperand(5);
15394     SDValue Scale = Op.getOperand(6);
15395     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
15396                           Subtarget);
15397   }
15398   case SCATTER: {
15399   //scatter(base, mask, index, v1, scale);
15400     SDValue Chain = Op.getOperand(0);
15401     SDValue Base  = Op.getOperand(2);
15402     SDValue Mask  = Op.getOperand(3);
15403     SDValue Index = Op.getOperand(4);
15404     SDValue Src   = Op.getOperand(5);
15405     SDValue Scale = Op.getOperand(6);
15406     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
15407   }
15408   case PREFETCH: {
15409     SDValue Hint = Op.getOperand(6);
15410     unsigned HintVal;
15411     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
15412         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15413       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15414     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15415     SDValue Chain = Op.getOperand(0);
15416     SDValue Mask  = Op.getOperand(2);
15417     SDValue Index = Op.getOperand(3);
15418     SDValue Base  = Op.getOperand(4);
15419     SDValue Scale = Op.getOperand(5);
15420     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15421   }
15422   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15423   case RDTSC: {
15424     SmallVector<SDValue, 2> Results;
15425     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
15426     return DAG.getMergeValues(Results, dl);
15427   }
15428   // Read Performance Monitoring Counters.
15429   case RDPMC: {
15430     SmallVector<SDValue, 2> Results;
15431     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15432     return DAG.getMergeValues(Results, dl);
15433   }
15434   // XTEST intrinsics.
15435   case XTEST: {
15436     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15437     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15438     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15439                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15440                                 InTrans);
15441     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15442     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15443                        Ret, SDValue(InTrans.getNode(), 1));
15444   }
15445   // ADC/ADCX/SBB
15446   case ADX: {
15447     SmallVector<SDValue, 2> Results;
15448     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15449     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15450     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15451                                 DAG.getConstant(-1, MVT::i8));
15452     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15453                               Op.getOperand(4), GenCF.getValue(1));
15454     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15455                                  Op.getOperand(5), MachinePointerInfo(),
15456                                  false, false, 0);
15457     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15458                                 DAG.getConstant(X86::COND_B, MVT::i8),
15459                                 Res.getValue(1));
15460     Results.push_back(SetCC);
15461     Results.push_back(Store);
15462     return DAG.getMergeValues(Results, dl);
15463   }
15464   }
15465 }
15466
15467 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15468                                            SelectionDAG &DAG) const {
15469   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15470   MFI->setReturnAddressIsTaken(true);
15471
15472   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15473     return SDValue();
15474
15475   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15476   SDLoc dl(Op);
15477   EVT PtrVT = getPointerTy();
15478
15479   if (Depth > 0) {
15480     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15481     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15482         DAG.getSubtarget().getRegisterInfo());
15483     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15484     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15485                        DAG.getNode(ISD::ADD, dl, PtrVT,
15486                                    FrameAddr, Offset),
15487                        MachinePointerInfo(), false, false, false, 0);
15488   }
15489
15490   // Just load the return address.
15491   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15492   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15493                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15494 }
15495
15496 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15497   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15498   MFI->setFrameAddressIsTaken(true);
15499
15500   EVT VT = Op.getValueType();
15501   SDLoc dl(Op);  // FIXME probably not meaningful
15502   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15503   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15504       DAG.getSubtarget().getRegisterInfo());
15505   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15506   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15507           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15508          "Invalid Frame Register!");
15509   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15510   while (Depth--)
15511     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15512                             MachinePointerInfo(),
15513                             false, false, false, 0);
15514   return FrameAddr;
15515 }
15516
15517 // FIXME? Maybe this could be a TableGen attribute on some registers and
15518 // this table could be generated automatically from RegInfo.
15519 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15520                                               EVT VT) const {
15521   unsigned Reg = StringSwitch<unsigned>(RegName)
15522                        .Case("esp", X86::ESP)
15523                        .Case("rsp", X86::RSP)
15524                        .Default(0);
15525   if (Reg)
15526     return Reg;
15527   report_fatal_error("Invalid register name global variable");
15528 }
15529
15530 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15531                                                      SelectionDAG &DAG) const {
15532   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15533       DAG.getSubtarget().getRegisterInfo());
15534   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15535 }
15536
15537 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15538   SDValue Chain     = Op.getOperand(0);
15539   SDValue Offset    = Op.getOperand(1);
15540   SDValue Handler   = Op.getOperand(2);
15541   SDLoc dl      (Op);
15542
15543   EVT PtrVT = getPointerTy();
15544   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15545       DAG.getSubtarget().getRegisterInfo());
15546   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15547   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15548           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15549          "Invalid Frame Register!");
15550   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15551   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15552
15553   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15554                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15555   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15556   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15557                        false, false, 0);
15558   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15559
15560   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15561                      DAG.getRegister(StoreAddrReg, PtrVT));
15562 }
15563
15564 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15565                                                SelectionDAG &DAG) const {
15566   SDLoc DL(Op);
15567   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15568                      DAG.getVTList(MVT::i32, MVT::Other),
15569                      Op.getOperand(0), Op.getOperand(1));
15570 }
15571
15572 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15573                                                 SelectionDAG &DAG) const {
15574   SDLoc DL(Op);
15575   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15576                      Op.getOperand(0), Op.getOperand(1));
15577 }
15578
15579 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15580   return Op.getOperand(0);
15581 }
15582
15583 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15584                                                 SelectionDAG &DAG) const {
15585   SDValue Root = Op.getOperand(0);
15586   SDValue Trmp = Op.getOperand(1); // trampoline
15587   SDValue FPtr = Op.getOperand(2); // nested function
15588   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15589   SDLoc dl (Op);
15590
15591   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15592   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
15593
15594   if (Subtarget->is64Bit()) {
15595     SDValue OutChains[6];
15596
15597     // Large code-model.
15598     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15599     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15600
15601     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15602     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15603
15604     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15605
15606     // Load the pointer to the nested function into R11.
15607     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15608     SDValue Addr = Trmp;
15609     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15610                                 Addr, MachinePointerInfo(TrmpAddr),
15611                                 false, false, 0);
15612
15613     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15614                        DAG.getConstant(2, MVT::i64));
15615     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15616                                 MachinePointerInfo(TrmpAddr, 2),
15617                                 false, false, 2);
15618
15619     // Load the 'nest' parameter value into R10.
15620     // R10 is specified in X86CallingConv.td
15621     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15622     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15623                        DAG.getConstant(10, MVT::i64));
15624     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15625                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15626                                 false, false, 0);
15627
15628     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15629                        DAG.getConstant(12, MVT::i64));
15630     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15631                                 MachinePointerInfo(TrmpAddr, 12),
15632                                 false, false, 2);
15633
15634     // Jump to the nested function.
15635     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15636     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15637                        DAG.getConstant(20, MVT::i64));
15638     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15639                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15640                                 false, false, 0);
15641
15642     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15643     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15644                        DAG.getConstant(22, MVT::i64));
15645     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15646                                 MachinePointerInfo(TrmpAddr, 22),
15647                                 false, false, 0);
15648
15649     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15650   } else {
15651     const Function *Func =
15652       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15653     CallingConv::ID CC = Func->getCallingConv();
15654     unsigned NestReg;
15655
15656     switch (CC) {
15657     default:
15658       llvm_unreachable("Unsupported calling convention");
15659     case CallingConv::C:
15660     case CallingConv::X86_StdCall: {
15661       // Pass 'nest' parameter in ECX.
15662       // Must be kept in sync with X86CallingConv.td
15663       NestReg = X86::ECX;
15664
15665       // Check that ECX wasn't needed by an 'inreg' parameter.
15666       FunctionType *FTy = Func->getFunctionType();
15667       const AttributeSet &Attrs = Func->getAttributes();
15668
15669       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15670         unsigned InRegCount = 0;
15671         unsigned Idx = 1;
15672
15673         for (FunctionType::param_iterator I = FTy->param_begin(),
15674              E = FTy->param_end(); I != E; ++I, ++Idx)
15675           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15676             // FIXME: should only count parameters that are lowered to integers.
15677             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15678
15679         if (InRegCount > 2) {
15680           report_fatal_error("Nest register in use - reduce number of inreg"
15681                              " parameters!");
15682         }
15683       }
15684       break;
15685     }
15686     case CallingConv::X86_FastCall:
15687     case CallingConv::X86_ThisCall:
15688     case CallingConv::Fast:
15689       // Pass 'nest' parameter in EAX.
15690       // Must be kept in sync with X86CallingConv.td
15691       NestReg = X86::EAX;
15692       break;
15693     }
15694
15695     SDValue OutChains[4];
15696     SDValue Addr, Disp;
15697
15698     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15699                        DAG.getConstant(10, MVT::i32));
15700     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15701
15702     // This is storing the opcode for MOV32ri.
15703     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15704     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15705     OutChains[0] = DAG.getStore(Root, dl,
15706                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15707                                 Trmp, MachinePointerInfo(TrmpAddr),
15708                                 false, false, 0);
15709
15710     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15711                        DAG.getConstant(1, MVT::i32));
15712     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15713                                 MachinePointerInfo(TrmpAddr, 1),
15714                                 false, false, 1);
15715
15716     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15717     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15718                        DAG.getConstant(5, MVT::i32));
15719     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15720                                 MachinePointerInfo(TrmpAddr, 5),
15721                                 false, false, 1);
15722
15723     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15724                        DAG.getConstant(6, MVT::i32));
15725     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15726                                 MachinePointerInfo(TrmpAddr, 6),
15727                                 false, false, 1);
15728
15729     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15730   }
15731 }
15732
15733 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15734                                             SelectionDAG &DAG) const {
15735   /*
15736    The rounding mode is in bits 11:10 of FPSR, and has the following
15737    settings:
15738      00 Round to nearest
15739      01 Round to -inf
15740      10 Round to +inf
15741      11 Round to 0
15742
15743   FLT_ROUNDS, on the other hand, expects the following:
15744     -1 Undefined
15745      0 Round to 0
15746      1 Round to nearest
15747      2 Round to +inf
15748      3 Round to -inf
15749
15750   To perform the conversion, we do:
15751     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15752   */
15753
15754   MachineFunction &MF = DAG.getMachineFunction();
15755   const TargetMachine &TM = MF.getTarget();
15756   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15757   unsigned StackAlignment = TFI.getStackAlignment();
15758   MVT VT = Op.getSimpleValueType();
15759   SDLoc DL(Op);
15760
15761   // Save FP Control Word to stack slot
15762   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15763   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15764
15765   MachineMemOperand *MMO =
15766    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15767                            MachineMemOperand::MOStore, 2, 2);
15768
15769   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15770   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15771                                           DAG.getVTList(MVT::Other),
15772                                           Ops, MVT::i16, MMO);
15773
15774   // Load FP Control Word from stack slot
15775   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15776                             MachinePointerInfo(), false, false, false, 0);
15777
15778   // Transform as necessary
15779   SDValue CWD1 =
15780     DAG.getNode(ISD::SRL, DL, MVT::i16,
15781                 DAG.getNode(ISD::AND, DL, MVT::i16,
15782                             CWD, DAG.getConstant(0x800, MVT::i16)),
15783                 DAG.getConstant(11, MVT::i8));
15784   SDValue CWD2 =
15785     DAG.getNode(ISD::SRL, DL, MVT::i16,
15786                 DAG.getNode(ISD::AND, DL, MVT::i16,
15787                             CWD, DAG.getConstant(0x400, MVT::i16)),
15788                 DAG.getConstant(9, MVT::i8));
15789
15790   SDValue RetVal =
15791     DAG.getNode(ISD::AND, DL, MVT::i16,
15792                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15793                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15794                             DAG.getConstant(1, MVT::i16)),
15795                 DAG.getConstant(3, MVT::i16));
15796
15797   return DAG.getNode((VT.getSizeInBits() < 16 ?
15798                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15799 }
15800
15801 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15802   MVT VT = Op.getSimpleValueType();
15803   EVT OpVT = VT;
15804   unsigned NumBits = VT.getSizeInBits();
15805   SDLoc dl(Op);
15806
15807   Op = Op.getOperand(0);
15808   if (VT == MVT::i8) {
15809     // Zero extend to i32 since there is not an i8 bsr.
15810     OpVT = MVT::i32;
15811     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15812   }
15813
15814   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15815   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15816   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15817
15818   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15819   SDValue Ops[] = {
15820     Op,
15821     DAG.getConstant(NumBits+NumBits-1, OpVT),
15822     DAG.getConstant(X86::COND_E, MVT::i8),
15823     Op.getValue(1)
15824   };
15825   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15826
15827   // Finally xor with NumBits-1.
15828   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15829
15830   if (VT == MVT::i8)
15831     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15832   return Op;
15833 }
15834
15835 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15836   MVT VT = Op.getSimpleValueType();
15837   EVT OpVT = VT;
15838   unsigned NumBits = VT.getSizeInBits();
15839   SDLoc dl(Op);
15840
15841   Op = Op.getOperand(0);
15842   if (VT == MVT::i8) {
15843     // Zero extend to i32 since there is not an i8 bsr.
15844     OpVT = MVT::i32;
15845     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15846   }
15847
15848   // Issue a bsr (scan bits in reverse).
15849   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15850   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15851
15852   // And xor with NumBits-1.
15853   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15854
15855   if (VT == MVT::i8)
15856     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15857   return Op;
15858 }
15859
15860 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15861   MVT VT = Op.getSimpleValueType();
15862   unsigned NumBits = VT.getSizeInBits();
15863   SDLoc dl(Op);
15864   Op = Op.getOperand(0);
15865
15866   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15867   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15868   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15869
15870   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15871   SDValue Ops[] = {
15872     Op,
15873     DAG.getConstant(NumBits, VT),
15874     DAG.getConstant(X86::COND_E, MVT::i8),
15875     Op.getValue(1)
15876   };
15877   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15878 }
15879
15880 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15881 // ones, and then concatenate the result back.
15882 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15883   MVT VT = Op.getSimpleValueType();
15884
15885   assert(VT.is256BitVector() && VT.isInteger() &&
15886          "Unsupported value type for operation");
15887
15888   unsigned NumElems = VT.getVectorNumElements();
15889   SDLoc dl(Op);
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   // Extract the RHS vectors
15897   SDValue RHS = Op.getOperand(1);
15898   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15899   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15900
15901   MVT EltVT = VT.getVectorElementType();
15902   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15903
15904   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15905                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15906                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15907 }
15908
15909 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15910   assert(Op.getSimpleValueType().is256BitVector() &&
15911          Op.getSimpleValueType().isInteger() &&
15912          "Only handle AVX 256-bit vector integer operation");
15913   return Lower256IntArith(Op, DAG);
15914 }
15915
15916 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15917   assert(Op.getSimpleValueType().is256BitVector() &&
15918          Op.getSimpleValueType().isInteger() &&
15919          "Only handle AVX 256-bit vector integer operation");
15920   return Lower256IntArith(Op, DAG);
15921 }
15922
15923 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15924                         SelectionDAG &DAG) {
15925   SDLoc dl(Op);
15926   MVT VT = Op.getSimpleValueType();
15927
15928   // Decompose 256-bit ops into smaller 128-bit ops.
15929   if (VT.is256BitVector() && !Subtarget->hasInt256())
15930     return Lower256IntArith(Op, DAG);
15931
15932   SDValue A = Op.getOperand(0);
15933   SDValue B = Op.getOperand(1);
15934
15935   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15936   if (VT == MVT::v4i32) {
15937     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15938            "Should not custom lower when pmuldq is available!");
15939
15940     // Extract the odd parts.
15941     static const int UnpackMask[] = { 1, -1, 3, -1 };
15942     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15943     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15944
15945     // Multiply the even parts.
15946     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15947     // Now multiply odd parts.
15948     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15949
15950     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15951     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15952
15953     // Merge the two vectors back together with a shuffle. This expands into 2
15954     // shuffles.
15955     static const int ShufMask[] = { 0, 4, 2, 6 };
15956     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15957   }
15958
15959   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15960          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15961
15962   //  Ahi = psrlqi(a, 32);
15963   //  Bhi = psrlqi(b, 32);
15964   //
15965   //  AloBlo = pmuludq(a, b);
15966   //  AloBhi = pmuludq(a, Bhi);
15967   //  AhiBlo = pmuludq(Ahi, b);
15968
15969   //  AloBhi = psllqi(AloBhi, 32);
15970   //  AhiBlo = psllqi(AhiBlo, 32);
15971   //  return AloBlo + AloBhi + AhiBlo;
15972
15973   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15974   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15975
15976   // Bit cast to 32-bit vectors for MULUDQ
15977   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15978                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15979   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15980   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15981   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15982   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15983
15984   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15985   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15986   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15987
15988   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15989   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15990
15991   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15992   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15993 }
15994
15995 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15996   assert(Subtarget->isTargetWin64() && "Unexpected target");
15997   EVT VT = Op.getValueType();
15998   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15999          "Unexpected return type for lowering");
16000
16001   RTLIB::Libcall LC;
16002   bool isSigned;
16003   switch (Op->getOpcode()) {
16004   default: llvm_unreachable("Unexpected request for libcall!");
16005   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16006   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16007   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16008   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16009   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16010   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16011   }
16012
16013   SDLoc dl(Op);
16014   SDValue InChain = DAG.getEntryNode();
16015
16016   TargetLowering::ArgListTy Args;
16017   TargetLowering::ArgListEntry Entry;
16018   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16019     EVT ArgVT = Op->getOperand(i).getValueType();
16020     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16021            "Unexpected argument type for lowering");
16022     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16023     Entry.Node = StackPtr;
16024     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16025                            false, false, 16);
16026     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16027     Entry.Ty = PointerType::get(ArgTy,0);
16028     Entry.isSExt = false;
16029     Entry.isZExt = false;
16030     Args.push_back(Entry);
16031   }
16032
16033   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16034                                          getPointerTy());
16035
16036   TargetLowering::CallLoweringInfo CLI(DAG);
16037   CLI.setDebugLoc(dl).setChain(InChain)
16038     .setCallee(getLibcallCallingConv(LC),
16039                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16040                Callee, std::move(Args), 0)
16041     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16042
16043   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16044   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16045 }
16046
16047 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16048                              SelectionDAG &DAG) {
16049   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16050   EVT VT = Op0.getValueType();
16051   SDLoc dl(Op);
16052
16053   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16054          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16055
16056   // PMULxD operations multiply each even value (starting at 0) of LHS with
16057   // the related value of RHS and produce a widen result.
16058   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16059   // => <2 x i64> <ae|cg>
16060   //
16061   // In other word, to have all the results, we need to perform two PMULxD:
16062   // 1. one with the even values.
16063   // 2. one with the odd values.
16064   // To achieve #2, with need to place the odd values at an even position.
16065   //
16066   // Place the odd value at an even position (basically, shift all values 1
16067   // step to the left):
16068   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16069   // <a|b|c|d> => <b|undef|d|undef>
16070   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16071   // <e|f|g|h> => <f|undef|h|undef>
16072   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16073
16074   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16075   // ints.
16076   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16077   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16078   unsigned Opcode =
16079       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16080   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16081   // => <2 x i64> <ae|cg>
16082   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16083                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16084   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16085   // => <2 x i64> <bf|dh>
16086   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16087                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16088
16089   // Shuffle it back into the right order.
16090   SDValue Highs, Lows;
16091   if (VT == MVT::v8i32) {
16092     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16093     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16094     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16095     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16096   } else {
16097     const int HighMask[] = {1, 5, 3, 7};
16098     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16099     const int LowMask[] = {0, 4, 2, 6};
16100     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16101   }
16102
16103   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16104   // unsigned multiply.
16105   if (IsSigned && !Subtarget->hasSSE41()) {
16106     SDValue ShAmt =
16107         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16108     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16109                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16110     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16111                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16112
16113     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16114     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16115   }
16116
16117   // The first result of MUL_LOHI is actually the low value, followed by the
16118   // high value.
16119   SDValue Ops[] = {Lows, Highs};
16120   return DAG.getMergeValues(Ops, dl);
16121 }
16122
16123 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16124                                          const X86Subtarget *Subtarget) {
16125   MVT VT = Op.getSimpleValueType();
16126   SDLoc dl(Op);
16127   SDValue R = Op.getOperand(0);
16128   SDValue Amt = Op.getOperand(1);
16129
16130   // Optimize shl/srl/sra with constant shift amount.
16131   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16132     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16133       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16134
16135       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16136           (Subtarget->hasInt256() &&
16137            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16138           (Subtarget->hasAVX512() &&
16139            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16140         if (Op.getOpcode() == ISD::SHL)
16141           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16142                                             DAG);
16143         if (Op.getOpcode() == ISD::SRL)
16144           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16145                                             DAG);
16146         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16147           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16148                                             DAG);
16149       }
16150
16151       if (VT == MVT::v16i8) {
16152         if (Op.getOpcode() == ISD::SHL) {
16153           // Make a large shift.
16154           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16155                                                    MVT::v8i16, R, ShiftAmt,
16156                                                    DAG);
16157           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16158           // Zero out the rightmost bits.
16159           SmallVector<SDValue, 16> V(16,
16160                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16161                                                      MVT::i8));
16162           return DAG.getNode(ISD::AND, dl, VT, SHL,
16163                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16164         }
16165         if (Op.getOpcode() == ISD::SRL) {
16166           // Make a large shift.
16167           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16168                                                    MVT::v8i16, R, ShiftAmt,
16169                                                    DAG);
16170           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16171           // Zero out the leftmost bits.
16172           SmallVector<SDValue, 16> V(16,
16173                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16174                                                      MVT::i8));
16175           return DAG.getNode(ISD::AND, dl, VT, SRL,
16176                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16177         }
16178         if (Op.getOpcode() == ISD::SRA) {
16179           if (ShiftAmt == 7) {
16180             // R s>> 7  ===  R s< 0
16181             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16182             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16183           }
16184
16185           // R s>> a === ((R u>> a) ^ m) - m
16186           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16187           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16188                                                          MVT::i8));
16189           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16190           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16191           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16192           return Res;
16193         }
16194         llvm_unreachable("Unknown shift opcode.");
16195       }
16196
16197       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16198         if (Op.getOpcode() == ISD::SHL) {
16199           // Make a large shift.
16200           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16201                                                    MVT::v16i16, R, ShiftAmt,
16202                                                    DAG);
16203           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16204           // Zero out the rightmost bits.
16205           SmallVector<SDValue, 32> V(32,
16206                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16207                                                      MVT::i8));
16208           return DAG.getNode(ISD::AND, dl, VT, SHL,
16209                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16210         }
16211         if (Op.getOpcode() == ISD::SRL) {
16212           // Make a large shift.
16213           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16214                                                    MVT::v16i16, R, ShiftAmt,
16215                                                    DAG);
16216           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16217           // Zero out the leftmost bits.
16218           SmallVector<SDValue, 32> V(32,
16219                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16220                                                      MVT::i8));
16221           return DAG.getNode(ISD::AND, dl, VT, SRL,
16222                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16223         }
16224         if (Op.getOpcode() == ISD::SRA) {
16225           if (ShiftAmt == 7) {
16226             // R s>> 7  ===  R s< 0
16227             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16228             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16229           }
16230
16231           // R s>> a === ((R u>> a) ^ m) - m
16232           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16233           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16234                                                          MVT::i8));
16235           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16236           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16237           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16238           return Res;
16239         }
16240         llvm_unreachable("Unknown shift opcode.");
16241       }
16242     }
16243   }
16244
16245   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16246   if (!Subtarget->is64Bit() &&
16247       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16248       Amt.getOpcode() == ISD::BITCAST &&
16249       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16250     Amt = Amt.getOperand(0);
16251     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16252                      VT.getVectorNumElements();
16253     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16254     uint64_t ShiftAmt = 0;
16255     for (unsigned i = 0; i != Ratio; ++i) {
16256       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16257       if (!C)
16258         return SDValue();
16259       // 6 == Log2(64)
16260       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16261     }
16262     // Check remaining shift amounts.
16263     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16264       uint64_t ShAmt = 0;
16265       for (unsigned j = 0; j != Ratio; ++j) {
16266         ConstantSDNode *C =
16267           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16268         if (!C)
16269           return SDValue();
16270         // 6 == Log2(64)
16271         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16272       }
16273       if (ShAmt != ShiftAmt)
16274         return SDValue();
16275     }
16276     switch (Op.getOpcode()) {
16277     default:
16278       llvm_unreachable("Unknown shift opcode!");
16279     case ISD::SHL:
16280       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16281                                         DAG);
16282     case ISD::SRL:
16283       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16284                                         DAG);
16285     case ISD::SRA:
16286       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16287                                         DAG);
16288     }
16289   }
16290
16291   return SDValue();
16292 }
16293
16294 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16295                                         const X86Subtarget* Subtarget) {
16296   MVT VT = Op.getSimpleValueType();
16297   SDLoc dl(Op);
16298   SDValue R = Op.getOperand(0);
16299   SDValue Amt = Op.getOperand(1);
16300
16301   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
16302       VT == MVT::v4i32 || VT == MVT::v8i16 ||
16303       (Subtarget->hasInt256() &&
16304        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
16305         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16306        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16307     SDValue BaseShAmt;
16308     EVT EltVT = VT.getVectorElementType();
16309
16310     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16311       unsigned NumElts = VT.getVectorNumElements();
16312       unsigned i, j;
16313       for (i = 0; i != NumElts; ++i) {
16314         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
16315           continue;
16316         break;
16317       }
16318       for (j = i; j != NumElts; ++j) {
16319         SDValue Arg = Amt.getOperand(j);
16320         if (Arg.getOpcode() == ISD::UNDEF) continue;
16321         if (Arg != Amt.getOperand(i))
16322           break;
16323       }
16324       if (i != NumElts && j == NumElts)
16325         BaseShAmt = Amt.getOperand(i);
16326     } else {
16327       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16328         Amt = Amt.getOperand(0);
16329       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
16330                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
16331         SDValue InVec = Amt.getOperand(0);
16332         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16333           unsigned NumElts = InVec.getValueType().getVectorNumElements();
16334           unsigned i = 0;
16335           for (; i != NumElts; ++i) {
16336             SDValue Arg = InVec.getOperand(i);
16337             if (Arg.getOpcode() == ISD::UNDEF) continue;
16338             BaseShAmt = Arg;
16339             break;
16340           }
16341         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16342            if (ConstantSDNode *C =
16343                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16344              unsigned SplatIdx =
16345                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
16346              if (C->getZExtValue() == SplatIdx)
16347                BaseShAmt = InVec.getOperand(1);
16348            }
16349         }
16350         if (!BaseShAmt.getNode())
16351           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
16352                                   DAG.getIntPtrConstant(0));
16353       }
16354     }
16355
16356     if (BaseShAmt.getNode()) {
16357       if (EltVT.bitsGT(MVT::i32))
16358         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
16359       else if (EltVT.bitsLT(MVT::i32))
16360         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16361
16362       switch (Op.getOpcode()) {
16363       default:
16364         llvm_unreachable("Unknown shift opcode!");
16365       case ISD::SHL:
16366         switch (VT.SimpleTy) {
16367         default: return SDValue();
16368         case MVT::v2i64:
16369         case MVT::v4i32:
16370         case MVT::v8i16:
16371         case MVT::v4i64:
16372         case MVT::v8i32:
16373         case MVT::v16i16:
16374         case MVT::v16i32:
16375         case MVT::v8i64:
16376           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
16377         }
16378       case ISD::SRA:
16379         switch (VT.SimpleTy) {
16380         default: return SDValue();
16381         case MVT::v4i32:
16382         case MVT::v8i16:
16383         case MVT::v8i32:
16384         case MVT::v16i16:
16385         case MVT::v16i32:
16386         case MVT::v8i64:
16387           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
16388         }
16389       case ISD::SRL:
16390         switch (VT.SimpleTy) {
16391         default: return SDValue();
16392         case MVT::v2i64:
16393         case MVT::v4i32:
16394         case MVT::v8i16:
16395         case MVT::v4i64:
16396         case MVT::v8i32:
16397         case MVT::v16i16:
16398         case MVT::v16i32:
16399         case MVT::v8i64:
16400           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
16401         }
16402       }
16403     }
16404   }
16405
16406   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16407   if (!Subtarget->is64Bit() &&
16408       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
16409       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
16410       Amt.getOpcode() == ISD::BITCAST &&
16411       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16412     Amt = Amt.getOperand(0);
16413     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16414                      VT.getVectorNumElements();
16415     std::vector<SDValue> Vals(Ratio);
16416     for (unsigned i = 0; i != Ratio; ++i)
16417       Vals[i] = Amt.getOperand(i);
16418     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16419       for (unsigned j = 0; j != Ratio; ++j)
16420         if (Vals[j] != Amt.getOperand(i + j))
16421           return SDValue();
16422     }
16423     switch (Op.getOpcode()) {
16424     default:
16425       llvm_unreachable("Unknown shift opcode!");
16426     case ISD::SHL:
16427       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
16428     case ISD::SRL:
16429       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16430     case ISD::SRA:
16431       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16432     }
16433   }
16434
16435   return SDValue();
16436 }
16437
16438 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16439                           SelectionDAG &DAG) {
16440   MVT VT = Op.getSimpleValueType();
16441   SDLoc dl(Op);
16442   SDValue R = Op.getOperand(0);
16443   SDValue Amt = Op.getOperand(1);
16444   SDValue V;
16445
16446   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16447   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16448
16449   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16450   if (V.getNode())
16451     return V;
16452
16453   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16454   if (V.getNode())
16455       return V;
16456
16457   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16458     return Op;
16459   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16460   if (Subtarget->hasInt256()) {
16461     if (Op.getOpcode() == ISD::SRL &&
16462         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16463          VT == MVT::v4i64 || VT == MVT::v8i32))
16464       return Op;
16465     if (Op.getOpcode() == ISD::SHL &&
16466         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16467          VT == MVT::v4i64 || VT == MVT::v8i32))
16468       return Op;
16469     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16470       return Op;
16471   }
16472
16473   // If possible, lower this packed shift into a vector multiply instead of
16474   // expanding it into a sequence of scalar shifts.
16475   // Do this only if the vector shift count is a constant build_vector.
16476   if (Op.getOpcode() == ISD::SHL && 
16477       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16478        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16479       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16480     SmallVector<SDValue, 8> Elts;
16481     EVT SVT = VT.getScalarType();
16482     unsigned SVTBits = SVT.getSizeInBits();
16483     const APInt &One = APInt(SVTBits, 1);
16484     unsigned NumElems = VT.getVectorNumElements();
16485
16486     for (unsigned i=0; i !=NumElems; ++i) {
16487       SDValue Op = Amt->getOperand(i);
16488       if (Op->getOpcode() == ISD::UNDEF) {
16489         Elts.push_back(Op);
16490         continue;
16491       }
16492
16493       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16494       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16495       uint64_t ShAmt = C.getZExtValue();
16496       if (ShAmt >= SVTBits) {
16497         Elts.push_back(DAG.getUNDEF(SVT));
16498         continue;
16499       }
16500       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16501     }
16502     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16503     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16504   }
16505
16506   // Lower SHL with variable shift amount.
16507   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16508     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16509
16510     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16511     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16512     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16513     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16514   }
16515
16516   // If possible, lower this shift as a sequence of two shifts by
16517   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16518   // Example:
16519   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16520   //
16521   // Could be rewritten as:
16522   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16523   //
16524   // The advantage is that the two shifts from the example would be
16525   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16526   // the vector shift into four scalar shifts plus four pairs of vector
16527   // insert/extract.
16528   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16529       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16530     unsigned TargetOpcode = X86ISD::MOVSS;
16531     bool CanBeSimplified;
16532     // The splat value for the first packed shift (the 'X' from the example).
16533     SDValue Amt1 = Amt->getOperand(0);
16534     // The splat value for the second packed shift (the 'Y' from the example).
16535     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16536                                         Amt->getOperand(2);
16537
16538     // See if it is possible to replace this node with a sequence of
16539     // two shifts followed by a MOVSS/MOVSD
16540     if (VT == MVT::v4i32) {
16541       // Check if it is legal to use a MOVSS.
16542       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16543                         Amt2 == Amt->getOperand(3);
16544       if (!CanBeSimplified) {
16545         // Otherwise, check if we can still simplify this node using a MOVSD.
16546         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16547                           Amt->getOperand(2) == Amt->getOperand(3);
16548         TargetOpcode = X86ISD::MOVSD;
16549         Amt2 = Amt->getOperand(2);
16550       }
16551     } else {
16552       // Do similar checks for the case where the machine value type
16553       // is MVT::v8i16.
16554       CanBeSimplified = Amt1 == Amt->getOperand(1);
16555       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16556         CanBeSimplified = Amt2 == Amt->getOperand(i);
16557
16558       if (!CanBeSimplified) {
16559         TargetOpcode = X86ISD::MOVSD;
16560         CanBeSimplified = true;
16561         Amt2 = Amt->getOperand(4);
16562         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16563           CanBeSimplified = Amt1 == Amt->getOperand(i);
16564         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16565           CanBeSimplified = Amt2 == Amt->getOperand(j);
16566       }
16567     }
16568     
16569     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16570         isa<ConstantSDNode>(Amt2)) {
16571       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16572       EVT CastVT = MVT::v4i32;
16573       SDValue Splat1 = 
16574         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16575       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16576       SDValue Splat2 = 
16577         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16578       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16579       if (TargetOpcode == X86ISD::MOVSD)
16580         CastVT = MVT::v2i64;
16581       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16582       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16583       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16584                                             BitCast1, DAG);
16585       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16586     }
16587   }
16588
16589   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16590     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16591
16592     // a = a << 5;
16593     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16594     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16595
16596     // Turn 'a' into a mask suitable for VSELECT
16597     SDValue VSelM = DAG.getConstant(0x80, VT);
16598     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16599     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16600
16601     SDValue CM1 = DAG.getConstant(0x0f, VT);
16602     SDValue CM2 = DAG.getConstant(0x3f, VT);
16603
16604     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16605     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16606     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16607     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16608     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16609
16610     // a += a
16611     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16612     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16613     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16614
16615     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16616     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16617     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16618     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16619     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16620
16621     // a += a
16622     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16623     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16624     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16625
16626     // return VSELECT(r, r+r, a);
16627     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16628                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16629     return R;
16630   }
16631
16632   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16633   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16634   // solution better.
16635   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16636     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16637     unsigned ExtOpc =
16638         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16639     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16640     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16641     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16642                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16643     }
16644
16645   // Decompose 256-bit shifts into smaller 128-bit shifts.
16646   if (VT.is256BitVector()) {
16647     unsigned NumElems = VT.getVectorNumElements();
16648     MVT EltVT = VT.getVectorElementType();
16649     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16650
16651     // Extract the two vectors
16652     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16653     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16654
16655     // Recreate the shift amount vectors
16656     SDValue Amt1, Amt2;
16657     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16658       // Constant shift amount
16659       SmallVector<SDValue, 4> Amt1Csts;
16660       SmallVector<SDValue, 4> Amt2Csts;
16661       for (unsigned i = 0; i != NumElems/2; ++i)
16662         Amt1Csts.push_back(Amt->getOperand(i));
16663       for (unsigned i = NumElems/2; i != NumElems; ++i)
16664         Amt2Csts.push_back(Amt->getOperand(i));
16665
16666       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16667       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16668     } else {
16669       // Variable shift amount
16670       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16671       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16672     }
16673
16674     // Issue new vector shifts for the smaller types
16675     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16676     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16677
16678     // Concatenate the result back
16679     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16680   }
16681
16682   return SDValue();
16683 }
16684
16685 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16686   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16687   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16688   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16689   // has only one use.
16690   SDNode *N = Op.getNode();
16691   SDValue LHS = N->getOperand(0);
16692   SDValue RHS = N->getOperand(1);
16693   unsigned BaseOp = 0;
16694   unsigned Cond = 0;
16695   SDLoc DL(Op);
16696   switch (Op.getOpcode()) {
16697   default: llvm_unreachable("Unknown ovf instruction!");
16698   case ISD::SADDO:
16699     // A subtract of one will be selected as a INC. Note that INC doesn't
16700     // set CF, so we can't do this for UADDO.
16701     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16702       if (C->isOne()) {
16703         BaseOp = X86ISD::INC;
16704         Cond = X86::COND_O;
16705         break;
16706       }
16707     BaseOp = X86ISD::ADD;
16708     Cond = X86::COND_O;
16709     break;
16710   case ISD::UADDO:
16711     BaseOp = X86ISD::ADD;
16712     Cond = X86::COND_B;
16713     break;
16714   case ISD::SSUBO:
16715     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16716     // set CF, so we can't do this for USUBO.
16717     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16718       if (C->isOne()) {
16719         BaseOp = X86ISD::DEC;
16720         Cond = X86::COND_O;
16721         break;
16722       }
16723     BaseOp = X86ISD::SUB;
16724     Cond = X86::COND_O;
16725     break;
16726   case ISD::USUBO:
16727     BaseOp = X86ISD::SUB;
16728     Cond = X86::COND_B;
16729     break;
16730   case ISD::SMULO:
16731     BaseOp = X86ISD::SMUL;
16732     Cond = X86::COND_O;
16733     break;
16734   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16735     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16736                                  MVT::i32);
16737     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16738
16739     SDValue SetCC =
16740       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16741                   DAG.getConstant(X86::COND_O, MVT::i32),
16742                   SDValue(Sum.getNode(), 2));
16743
16744     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16745   }
16746   }
16747
16748   // Also sets EFLAGS.
16749   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16750   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16751
16752   SDValue SetCC =
16753     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16754                 DAG.getConstant(Cond, MVT::i32),
16755                 SDValue(Sum.getNode(), 1));
16756
16757   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16758 }
16759
16760 // Sign extension of the low part of vector elements. This may be used either
16761 // when sign extend instructions are not available or if the vector element
16762 // sizes already match the sign-extended size. If the vector elements are in
16763 // their pre-extended size and sign extend instructions are available, that will
16764 // be handled by LowerSIGN_EXTEND.
16765 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16766                                                   SelectionDAG &DAG) const {
16767   SDLoc dl(Op);
16768   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16769   MVT VT = Op.getSimpleValueType();
16770
16771   if (!Subtarget->hasSSE2() || !VT.isVector())
16772     return SDValue();
16773
16774   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16775                       ExtraVT.getScalarType().getSizeInBits();
16776
16777   switch (VT.SimpleTy) {
16778     default: return SDValue();
16779     case MVT::v8i32:
16780     case MVT::v16i16:
16781       if (!Subtarget->hasFp256())
16782         return SDValue();
16783       if (!Subtarget->hasInt256()) {
16784         // needs to be split
16785         unsigned NumElems = VT.getVectorNumElements();
16786
16787         // Extract the LHS vectors
16788         SDValue LHS = Op.getOperand(0);
16789         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16790         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16791
16792         MVT EltVT = VT.getVectorElementType();
16793         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16794
16795         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16796         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16797         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16798                                    ExtraNumElems/2);
16799         SDValue Extra = DAG.getValueType(ExtraVT);
16800
16801         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16802         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16803
16804         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16805       }
16806       // fall through
16807     case MVT::v4i32:
16808     case MVT::v8i16: {
16809       SDValue Op0 = Op.getOperand(0);
16810
16811       // This is a sign extension of some low part of vector elements without
16812       // changing the size of the vector elements themselves:
16813       // Shift-Left + Shift-Right-Algebraic.
16814       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
16815                                                BitsDiff, DAG);
16816       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
16817                                         DAG);
16818     }
16819   }
16820 }
16821
16822 /// Returns true if the operand type is exactly twice the native width, and
16823 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
16824 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
16825 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
16826 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
16827   const X86Subtarget &Subtarget =
16828       getTargetMachine().getSubtarget<X86Subtarget>();
16829   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
16830
16831   if (OpWidth == 64)
16832     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
16833   else if (OpWidth == 128)
16834     return Subtarget.hasCmpxchg16b();
16835   else
16836     return false;
16837 }
16838
16839 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
16840   return needsCmpXchgNb(SI->getValueOperand()->getType());
16841 }
16842
16843 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *SI) const {
16844   return false; // FIXME, currently these are expanded separately in this file.
16845 }
16846
16847 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
16848   const X86Subtarget &Subtarget =
16849       getTargetMachine().getSubtarget<X86Subtarget>();
16850   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
16851   const Type *MemType = AI->getType();
16852
16853   // If the operand is too big, we must see if cmpxchg8/16b is available
16854   // and default to library calls otherwise.
16855   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
16856     return needsCmpXchgNb(MemType);
16857
16858   AtomicRMWInst::BinOp Op = AI->getOperation();
16859   switch (Op) {
16860   default:
16861     llvm_unreachable("Unknown atomic operation");
16862   case AtomicRMWInst::Xchg:
16863   case AtomicRMWInst::Add:
16864   case AtomicRMWInst::Sub:
16865     // It's better to use xadd, xsub or xchg for these in all cases.
16866     return false;
16867   case AtomicRMWInst::Or:
16868   case AtomicRMWInst::And:
16869   case AtomicRMWInst::Xor:
16870     // If the atomicrmw's result isn't actually used, we can just add a "lock"
16871     // prefix to a normal instruction for these operations.
16872     return !AI->use_empty();
16873   case AtomicRMWInst::Nand:
16874   case AtomicRMWInst::Max:
16875   case AtomicRMWInst::Min:
16876   case AtomicRMWInst::UMax:
16877   case AtomicRMWInst::UMin:
16878     // These always require a non-trivial set of data operations on x86. We must
16879     // use a cmpxchg loop.
16880     return true;
16881   }
16882 }
16883
16884 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16885                                  SelectionDAG &DAG) {
16886   SDLoc dl(Op);
16887   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16888     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16889   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16890     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16891
16892   // The only fence that needs an instruction is a sequentially-consistent
16893   // cross-thread fence.
16894   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16895     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16896     // no-sse2). There isn't any reason to disable it if the target processor
16897     // supports it.
16898     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16899       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16900
16901     SDValue Chain = Op.getOperand(0);
16902     SDValue Zero = DAG.getConstant(0, MVT::i32);
16903     SDValue Ops[] = {
16904       DAG.getRegister(X86::ESP, MVT::i32), // Base
16905       DAG.getTargetConstant(1, MVT::i8),   // Scale
16906       DAG.getRegister(0, MVT::i32),        // Index
16907       DAG.getTargetConstant(0, MVT::i32),  // Disp
16908       DAG.getRegister(0, MVT::i32),        // Segment.
16909       Zero,
16910       Chain
16911     };
16912     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16913     return SDValue(Res, 0);
16914   }
16915
16916   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16917   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16918 }
16919
16920 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16921                              SelectionDAG &DAG) {
16922   MVT T = Op.getSimpleValueType();
16923   SDLoc DL(Op);
16924   unsigned Reg = 0;
16925   unsigned size = 0;
16926   switch(T.SimpleTy) {
16927   default: llvm_unreachable("Invalid value type!");
16928   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16929   case MVT::i16: Reg = X86::AX;  size = 2; break;
16930   case MVT::i32: Reg = X86::EAX; size = 4; break;
16931   case MVT::i64:
16932     assert(Subtarget->is64Bit() && "Node not type legal!");
16933     Reg = X86::RAX; size = 8;
16934     break;
16935   }
16936   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16937                                   Op.getOperand(2), SDValue());
16938   SDValue Ops[] = { cpIn.getValue(0),
16939                     Op.getOperand(1),
16940                     Op.getOperand(3),
16941                     DAG.getTargetConstant(size, MVT::i8),
16942                     cpIn.getValue(1) };
16943   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16944   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16945   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16946                                            Ops, T, MMO);
16947
16948   SDValue cpOut =
16949     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16950   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16951                                       MVT::i32, cpOut.getValue(2));
16952   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16953                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16954
16955   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16956   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16957   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16958   return SDValue();
16959 }
16960
16961 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16962                             SelectionDAG &DAG) {
16963   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16964   MVT DstVT = Op.getSimpleValueType();
16965
16966   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16967     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16968     if (DstVT != MVT::f64)
16969       // This conversion needs to be expanded.
16970       return SDValue();
16971
16972     SDValue InVec = Op->getOperand(0);
16973     SDLoc dl(Op);
16974     unsigned NumElts = SrcVT.getVectorNumElements();
16975     EVT SVT = SrcVT.getVectorElementType();
16976
16977     // Widen the vector in input in the case of MVT::v2i32.
16978     // Example: from MVT::v2i32 to MVT::v4i32.
16979     SmallVector<SDValue, 16> Elts;
16980     for (unsigned i = 0, e = NumElts; i != e; ++i)
16981       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16982                                  DAG.getIntPtrConstant(i)));
16983
16984     // Explicitly mark the extra elements as Undef.
16985     SDValue Undef = DAG.getUNDEF(SVT);
16986     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16987       Elts.push_back(Undef);
16988
16989     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16990     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16991     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16992     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16993                        DAG.getIntPtrConstant(0));
16994   }
16995
16996   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16997          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16998   assert((DstVT == MVT::i64 ||
16999           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17000          "Unexpected custom BITCAST");
17001   // i64 <=> MMX conversions are Legal.
17002   if (SrcVT==MVT::i64 && DstVT.isVector())
17003     return Op;
17004   if (DstVT==MVT::i64 && SrcVT.isVector())
17005     return Op;
17006   // MMX <=> MMX conversions are Legal.
17007   if (SrcVT.isVector() && DstVT.isVector())
17008     return Op;
17009   // All other conversions need to be expanded.
17010   return SDValue();
17011 }
17012
17013 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17014   SDNode *Node = Op.getNode();
17015   SDLoc dl(Node);
17016   EVT T = Node->getValueType(0);
17017   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17018                               DAG.getConstant(0, T), Node->getOperand(2));
17019   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17020                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17021                        Node->getOperand(0),
17022                        Node->getOperand(1), negOp,
17023                        cast<AtomicSDNode>(Node)->getMemOperand(),
17024                        cast<AtomicSDNode>(Node)->getOrdering(),
17025                        cast<AtomicSDNode>(Node)->getSynchScope());
17026 }
17027
17028 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17029   SDNode *Node = Op.getNode();
17030   SDLoc dl(Node);
17031   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17032
17033   // Convert seq_cst store -> xchg
17034   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17035   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17036   //        (The only way to get a 16-byte store is cmpxchg16b)
17037   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17038   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17039       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17040     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17041                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17042                                  Node->getOperand(0),
17043                                  Node->getOperand(1), Node->getOperand(2),
17044                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17045                                  cast<AtomicSDNode>(Node)->getOrdering(),
17046                                  cast<AtomicSDNode>(Node)->getSynchScope());
17047     return Swap.getValue(1);
17048   }
17049   // Other atomic stores have a simple pattern.
17050   return Op;
17051 }
17052
17053 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17054   EVT VT = Op.getNode()->getSimpleValueType(0);
17055
17056   // Let legalize expand this if it isn't a legal type yet.
17057   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17058     return SDValue();
17059
17060   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17061
17062   unsigned Opc;
17063   bool ExtraOp = false;
17064   switch (Op.getOpcode()) {
17065   default: llvm_unreachable("Invalid code");
17066   case ISD::ADDC: Opc = X86ISD::ADD; break;
17067   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17068   case ISD::SUBC: Opc = X86ISD::SUB; break;
17069   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17070   }
17071
17072   if (!ExtraOp)
17073     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17074                        Op.getOperand(1));
17075   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17076                      Op.getOperand(1), Op.getOperand(2));
17077 }
17078
17079 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17080                             SelectionDAG &DAG) {
17081   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17082
17083   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17084   // which returns the values as { float, float } (in XMM0) or
17085   // { double, double } (which is returned in XMM0, XMM1).
17086   SDLoc dl(Op);
17087   SDValue Arg = Op.getOperand(0);
17088   EVT ArgVT = Arg.getValueType();
17089   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17090
17091   TargetLowering::ArgListTy Args;
17092   TargetLowering::ArgListEntry Entry;
17093
17094   Entry.Node = Arg;
17095   Entry.Ty = ArgTy;
17096   Entry.isSExt = false;
17097   Entry.isZExt = false;
17098   Args.push_back(Entry);
17099
17100   bool isF64 = ArgVT == MVT::f64;
17101   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17102   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17103   // the results are returned via SRet in memory.
17104   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17105   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17106   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17107
17108   Type *RetTy = isF64
17109     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
17110     : (Type*)VectorType::get(ArgTy, 4);
17111
17112   TargetLowering::CallLoweringInfo CLI(DAG);
17113   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17114     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17115
17116   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17117
17118   if (isF64)
17119     // Returned in xmm0 and xmm1.
17120     return CallResult.first;
17121
17122   // Returned in bits 0:31 and 32:64 xmm0.
17123   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17124                                CallResult.first, DAG.getIntPtrConstant(0));
17125   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17126                                CallResult.first, DAG.getIntPtrConstant(1));
17127   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17128   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17129 }
17130
17131 /// LowerOperation - Provide custom lowering hooks for some operations.
17132 ///
17133 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17134   switch (Op.getOpcode()) {
17135   default: llvm_unreachable("Should not custom lower this!");
17136   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
17137   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17138   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17139     return LowerCMP_SWAP(Op, Subtarget, DAG);
17140   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17141   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17142   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17143   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
17144   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
17145   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17146   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17147   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17148   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17149   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17150   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17151   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17152   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17153   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17154   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17155   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17156   case ISD::SHL_PARTS:
17157   case ISD::SRA_PARTS:
17158   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17159   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17160   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17161   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17162   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17163   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17164   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17165   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17166   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17167   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17168   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17169   case ISD::FABS:
17170   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17171   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17172   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17173   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17174   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17175   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17176   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17177   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17178   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17179   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17180   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
17181   case ISD::INTRINSIC_VOID:
17182   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17183   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17184   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17185   case ISD::FRAME_TO_ARGS_OFFSET:
17186                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17187   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17188   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17189   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17190   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17191   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17192   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17193   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17194   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17195   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17196   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17197   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17198   case ISD::UMUL_LOHI:
17199   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17200   case ISD::SRA:
17201   case ISD::SRL:
17202   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17203   case ISD::SADDO:
17204   case ISD::UADDO:
17205   case ISD::SSUBO:
17206   case ISD::USUBO:
17207   case ISD::SMULO:
17208   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17209   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17210   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17211   case ISD::ADDC:
17212   case ISD::ADDE:
17213   case ISD::SUBC:
17214   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17215   case ISD::ADD:                return LowerADD(Op, DAG);
17216   case ISD::SUB:                return LowerSUB(Op, DAG);
17217   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17218   }
17219 }
17220
17221 static void ReplaceATOMIC_LOAD(SDNode *Node,
17222                                SmallVectorImpl<SDValue> &Results,
17223                                SelectionDAG &DAG) {
17224   SDLoc dl(Node);
17225   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17226
17227   // Convert wide load -> cmpxchg8b/cmpxchg16b
17228   // FIXME: On 32-bit, load -> fild or movq would be more efficient
17229   //        (The only way to get a 16-byte load is cmpxchg16b)
17230   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
17231   SDValue Zero = DAG.getConstant(0, VT);
17232   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
17233   SDValue Swap =
17234       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
17235                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
17236                            cast<AtomicSDNode>(Node)->getMemOperand(),
17237                            cast<AtomicSDNode>(Node)->getOrdering(),
17238                            cast<AtomicSDNode>(Node)->getOrdering(),
17239                            cast<AtomicSDNode>(Node)->getSynchScope());
17240   Results.push_back(Swap.getValue(0));
17241   Results.push_back(Swap.getValue(2));
17242 }
17243
17244 /// ReplaceNodeResults - Replace a node with an illegal result type
17245 /// with a new node built out of custom code.
17246 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17247                                            SmallVectorImpl<SDValue>&Results,
17248                                            SelectionDAG &DAG) const {
17249   SDLoc dl(N);
17250   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17251   switch (N->getOpcode()) {
17252   default:
17253     llvm_unreachable("Do not know how to custom type legalize this operation!");
17254   case ISD::SIGN_EXTEND_INREG:
17255   case ISD::ADDC:
17256   case ISD::ADDE:
17257   case ISD::SUBC:
17258   case ISD::SUBE:
17259     // We don't want to expand or promote these.
17260     return;
17261   case ISD::SDIV:
17262   case ISD::UDIV:
17263   case ISD::SREM:
17264   case ISD::UREM:
17265   case ISD::SDIVREM:
17266   case ISD::UDIVREM: {
17267     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17268     Results.push_back(V);
17269     return;
17270   }
17271   case ISD::FP_TO_SINT:
17272   case ISD::FP_TO_UINT: {
17273     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17274
17275     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17276       return;
17277
17278     std::pair<SDValue,SDValue> Vals =
17279         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17280     SDValue FIST = Vals.first, StackSlot = Vals.second;
17281     if (FIST.getNode()) {
17282       EVT VT = N->getValueType(0);
17283       // Return a load from the stack slot.
17284       if (StackSlot.getNode())
17285         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17286                                       MachinePointerInfo(),
17287                                       false, false, false, 0));
17288       else
17289         Results.push_back(FIST);
17290     }
17291     return;
17292   }
17293   case ISD::UINT_TO_FP: {
17294     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17295     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17296         N->getValueType(0) != MVT::v2f32)
17297       return;
17298     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17299                                  N->getOperand(0));
17300     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17301                                      MVT::f64);
17302     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17303     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
17304                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
17305     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
17306     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
17307     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
17308     return;
17309   }
17310   case ISD::FP_ROUND: {
17311     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
17312         return;
17313     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
17314     Results.push_back(V);
17315     return;
17316   }
17317   case ISD::INTRINSIC_W_CHAIN: {
17318     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
17319     switch (IntNo) {
17320     default : llvm_unreachable("Do not know how to custom type "
17321                                "legalize this intrinsic operation!");
17322     case Intrinsic::x86_rdtsc:
17323       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17324                                      Results);
17325     case Intrinsic::x86_rdtscp:
17326       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
17327                                      Results);
17328     case Intrinsic::x86_rdpmc:
17329       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
17330     }
17331   }
17332   case ISD::READCYCLECOUNTER: {
17333     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
17334                                    Results);
17335   }
17336   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
17337     EVT T = N->getValueType(0);
17338     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
17339     bool Regs64bit = T == MVT::i128;
17340     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
17341     SDValue cpInL, cpInH;
17342     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17343                         DAG.getConstant(0, HalfT));
17344     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
17345                         DAG.getConstant(1, HalfT));
17346     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
17347                              Regs64bit ? X86::RAX : X86::EAX,
17348                              cpInL, SDValue());
17349     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
17350                              Regs64bit ? X86::RDX : X86::EDX,
17351                              cpInH, cpInL.getValue(1));
17352     SDValue swapInL, swapInH;
17353     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17354                           DAG.getConstant(0, HalfT));
17355     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
17356                           DAG.getConstant(1, HalfT));
17357     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
17358                                Regs64bit ? X86::RBX : X86::EBX,
17359                                swapInL, cpInH.getValue(1));
17360     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
17361                                Regs64bit ? X86::RCX : X86::ECX,
17362                                swapInH, swapInL.getValue(1));
17363     SDValue Ops[] = { swapInH.getValue(0),
17364                       N->getOperand(1),
17365                       swapInH.getValue(1) };
17366     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17367     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
17368     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
17369                                   X86ISD::LCMPXCHG8_DAG;
17370     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
17371     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
17372                                         Regs64bit ? X86::RAX : X86::EAX,
17373                                         HalfT, Result.getValue(1));
17374     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
17375                                         Regs64bit ? X86::RDX : X86::EDX,
17376                                         HalfT, cpOutL.getValue(2));
17377     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
17378
17379     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
17380                                         MVT::i32, cpOutH.getValue(2));
17381     SDValue Success =
17382         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
17383                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17384     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
17385
17386     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
17387     Results.push_back(Success);
17388     Results.push_back(EFLAGS.getValue(1));
17389     return;
17390   }
17391   case ISD::ATOMIC_SWAP:
17392   case ISD::ATOMIC_LOAD_ADD:
17393   case ISD::ATOMIC_LOAD_SUB:
17394   case ISD::ATOMIC_LOAD_AND:
17395   case ISD::ATOMIC_LOAD_OR:
17396   case ISD::ATOMIC_LOAD_XOR:
17397   case ISD::ATOMIC_LOAD_NAND:
17398   case ISD::ATOMIC_LOAD_MIN:
17399   case ISD::ATOMIC_LOAD_MAX:
17400   case ISD::ATOMIC_LOAD_UMIN:
17401   case ISD::ATOMIC_LOAD_UMAX:
17402     // Delegate to generic TypeLegalization. Situations we can really handle
17403     // should have already been dealt with by AtomicExpandPass.cpp.
17404     break;
17405   case ISD::ATOMIC_LOAD: {
17406     ReplaceATOMIC_LOAD(N, Results, DAG);
17407     return;
17408   }
17409   case ISD::BITCAST: {
17410     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17411     EVT DstVT = N->getValueType(0);
17412     EVT SrcVT = N->getOperand(0)->getValueType(0);
17413
17414     if (SrcVT != MVT::f64 ||
17415         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
17416       return;
17417
17418     unsigned NumElts = DstVT.getVectorNumElements();
17419     EVT SVT = DstVT.getVectorElementType();
17420     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17421     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
17422                                    MVT::v2f64, N->getOperand(0));
17423     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
17424
17425     if (ExperimentalVectorWideningLegalization) {
17426       // If we are legalizing vectors by widening, we already have the desired
17427       // legal vector type, just return it.
17428       Results.push_back(ToVecInt);
17429       return;
17430     }
17431
17432     SmallVector<SDValue, 8> Elts;
17433     for (unsigned i = 0, e = NumElts; i != e; ++i)
17434       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
17435                                    ToVecInt, DAG.getIntPtrConstant(i)));
17436
17437     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
17438   }
17439   }
17440 }
17441
17442 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
17443   switch (Opcode) {
17444   default: return nullptr;
17445   case X86ISD::BSF:                return "X86ISD::BSF";
17446   case X86ISD::BSR:                return "X86ISD::BSR";
17447   case X86ISD::SHLD:               return "X86ISD::SHLD";
17448   case X86ISD::SHRD:               return "X86ISD::SHRD";
17449   case X86ISD::FAND:               return "X86ISD::FAND";
17450   case X86ISD::FANDN:              return "X86ISD::FANDN";
17451   case X86ISD::FOR:                return "X86ISD::FOR";
17452   case X86ISD::FXOR:               return "X86ISD::FXOR";
17453   case X86ISD::FSRL:               return "X86ISD::FSRL";
17454   case X86ISD::FILD:               return "X86ISD::FILD";
17455   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
17456   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
17457   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
17458   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
17459   case X86ISD::FLD:                return "X86ISD::FLD";
17460   case X86ISD::FST:                return "X86ISD::FST";
17461   case X86ISD::CALL:               return "X86ISD::CALL";
17462   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
17463   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
17464   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
17465   case X86ISD::BT:                 return "X86ISD::BT";
17466   case X86ISD::CMP:                return "X86ISD::CMP";
17467   case X86ISD::COMI:               return "X86ISD::COMI";
17468   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
17469   case X86ISD::CMPM:               return "X86ISD::CMPM";
17470   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
17471   case X86ISD::SETCC:              return "X86ISD::SETCC";
17472   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
17473   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
17474   case X86ISD::CMOV:               return "X86ISD::CMOV";
17475   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
17476   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
17477   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17478   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17479   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17480   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17481   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17482   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17483   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17484   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17485   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17486   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17487   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17488   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17489   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17490   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17491   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17492   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17493   case X86ISD::HADD:               return "X86ISD::HADD";
17494   case X86ISD::HSUB:               return "X86ISD::HSUB";
17495   case X86ISD::FHADD:              return "X86ISD::FHADD";
17496   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17497   case X86ISD::UMAX:               return "X86ISD::UMAX";
17498   case X86ISD::UMIN:               return "X86ISD::UMIN";
17499   case X86ISD::SMAX:               return "X86ISD::SMAX";
17500   case X86ISD::SMIN:               return "X86ISD::SMIN";
17501   case X86ISD::FMAX:               return "X86ISD::FMAX";
17502   case X86ISD::FMIN:               return "X86ISD::FMIN";
17503   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17504   case X86ISD::FMINC:              return "X86ISD::FMINC";
17505   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17506   case X86ISD::FRCP:               return "X86ISD::FRCP";
17507   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17508   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17509   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17510   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17511   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17512   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17513   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17514   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17515   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17516   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17517   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17518   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17519   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17520   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17521   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17522   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17523   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17524   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17525   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17526   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17527   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17528   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17529   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17530   case X86ISD::VSHL:               return "X86ISD::VSHL";
17531   case X86ISD::VSRL:               return "X86ISD::VSRL";
17532   case X86ISD::VSRA:               return "X86ISD::VSRA";
17533   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17534   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17535   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17536   case X86ISD::CMPP:               return "X86ISD::CMPP";
17537   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17538   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17539   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17540   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17541   case X86ISD::ADD:                return "X86ISD::ADD";
17542   case X86ISD::SUB:                return "X86ISD::SUB";
17543   case X86ISD::ADC:                return "X86ISD::ADC";
17544   case X86ISD::SBB:                return "X86ISD::SBB";
17545   case X86ISD::SMUL:               return "X86ISD::SMUL";
17546   case X86ISD::UMUL:               return "X86ISD::UMUL";
17547   case X86ISD::INC:                return "X86ISD::INC";
17548   case X86ISD::DEC:                return "X86ISD::DEC";
17549   case X86ISD::OR:                 return "X86ISD::OR";
17550   case X86ISD::XOR:                return "X86ISD::XOR";
17551   case X86ISD::AND:                return "X86ISD::AND";
17552   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17553   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17554   case X86ISD::PTEST:              return "X86ISD::PTEST";
17555   case X86ISD::TESTP:              return "X86ISD::TESTP";
17556   case X86ISD::TESTM:              return "X86ISD::TESTM";
17557   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17558   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17559   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17560   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17561   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17562   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
17563   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17564   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17565   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17566   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17567   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17568   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17569   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17570   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17571   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17572   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17573   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17574   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17575   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17576   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17577   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17578   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17579   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17580   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17581   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17582   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17583   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17584   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17585   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17586   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17587   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17588   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17589   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17590   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17591   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17592   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17593   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17594   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17595   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17596   case X86ISD::SAHF:               return "X86ISD::SAHF";
17597   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17598   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17599   case X86ISD::FMADD:              return "X86ISD::FMADD";
17600   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17601   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17602   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17603   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17604   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17605   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17606   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17607   case X86ISD::XTEST:              return "X86ISD::XTEST";
17608   }
17609 }
17610
17611 // isLegalAddressingMode - Return true if the addressing mode represented
17612 // by AM is legal for this target, for a load/store of the specified type.
17613 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17614                                               Type *Ty) const {
17615   // X86 supports extremely general addressing modes.
17616   CodeModel::Model M = getTargetMachine().getCodeModel();
17617   Reloc::Model R = getTargetMachine().getRelocationModel();
17618
17619   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17620   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17621     return false;
17622
17623   if (AM.BaseGV) {
17624     unsigned GVFlags =
17625       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17626
17627     // If a reference to this global requires an extra load, we can't fold it.
17628     if (isGlobalStubReference(GVFlags))
17629       return false;
17630
17631     // If BaseGV requires a register for the PIC base, we cannot also have a
17632     // BaseReg specified.
17633     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17634       return false;
17635
17636     // If lower 4G is not available, then we must use rip-relative addressing.
17637     if ((M != CodeModel::Small || R != Reloc::Static) &&
17638         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17639       return false;
17640   }
17641
17642   switch (AM.Scale) {
17643   case 0:
17644   case 1:
17645   case 2:
17646   case 4:
17647   case 8:
17648     // These scales always work.
17649     break;
17650   case 3:
17651   case 5:
17652   case 9:
17653     // These scales are formed with basereg+scalereg.  Only accept if there is
17654     // no basereg yet.
17655     if (AM.HasBaseReg)
17656       return false;
17657     break;
17658   default:  // Other stuff never works.
17659     return false;
17660   }
17661
17662   return true;
17663 }
17664
17665 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17666   unsigned Bits = Ty->getScalarSizeInBits();
17667
17668   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17669   // particularly cheaper than those without.
17670   if (Bits == 8)
17671     return false;
17672
17673   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17674   // variable shifts just as cheap as scalar ones.
17675   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17676     return false;
17677
17678   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17679   // fully general vector.
17680   return true;
17681 }
17682
17683 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17684   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17685     return false;
17686   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17687   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17688   return NumBits1 > NumBits2;
17689 }
17690
17691 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17692   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17693     return false;
17694
17695   if (!isTypeLegal(EVT::getEVT(Ty1)))
17696     return false;
17697
17698   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17699
17700   // Assuming the caller doesn't have a zeroext or signext return parameter,
17701   // truncation all the way down to i1 is valid.
17702   return true;
17703 }
17704
17705 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17706   return isInt<32>(Imm);
17707 }
17708
17709 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17710   // Can also use sub to handle negated immediates.
17711   return isInt<32>(Imm);
17712 }
17713
17714 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17715   if (!VT1.isInteger() || !VT2.isInteger())
17716     return false;
17717   unsigned NumBits1 = VT1.getSizeInBits();
17718   unsigned NumBits2 = VT2.getSizeInBits();
17719   return NumBits1 > NumBits2;
17720 }
17721
17722 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17723   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17724   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17725 }
17726
17727 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17728   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17729   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17730 }
17731
17732 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17733   EVT VT1 = Val.getValueType();
17734   if (isZExtFree(VT1, VT2))
17735     return true;
17736
17737   if (Val.getOpcode() != ISD::LOAD)
17738     return false;
17739
17740   if (!VT1.isSimple() || !VT1.isInteger() ||
17741       !VT2.isSimple() || !VT2.isInteger())
17742     return false;
17743
17744   switch (VT1.getSimpleVT().SimpleTy) {
17745   default: break;
17746   case MVT::i8:
17747   case MVT::i16:
17748   case MVT::i32:
17749     // X86 has 8, 16, and 32-bit zero-extending loads.
17750     return true;
17751   }
17752
17753   return false;
17754 }
17755
17756 bool
17757 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17758   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17759     return false;
17760
17761   VT = VT.getScalarType();
17762
17763   if (!VT.isSimple())
17764     return false;
17765
17766   switch (VT.getSimpleVT().SimpleTy) {
17767   case MVT::f32:
17768   case MVT::f64:
17769     return true;
17770   default:
17771     break;
17772   }
17773
17774   return false;
17775 }
17776
17777 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17778   // i16 instructions are longer (0x66 prefix) and potentially slower.
17779   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17780 }
17781
17782 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17783 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17784 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17785 /// are assumed to be legal.
17786 bool
17787 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17788                                       EVT VT) const {
17789   if (!VT.isSimple())
17790     return false;
17791
17792   MVT SVT = VT.getSimpleVT();
17793
17794   // Very little shuffling can be done for 64-bit vectors right now.
17795   if (VT.getSizeInBits() == 64)
17796     return false;
17797
17798   // If this is a single-input shuffle with no 128 bit lane crossings we can
17799   // lower it into pshufb.
17800   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17801       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17802     bool isLegal = true;
17803     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17804       if (M[I] >= (int)SVT.getVectorNumElements() ||
17805           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17806         isLegal = false;
17807         break;
17808       }
17809     }
17810     if (isLegal)
17811       return true;
17812   }
17813
17814   // FIXME: blends, shifts.
17815   return (SVT.getVectorNumElements() == 2 ||
17816           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17817           isMOVLMask(M, SVT) ||
17818           isMOVHLPSMask(M, SVT) ||
17819           isSHUFPMask(M, SVT) ||
17820           isPSHUFDMask(M, SVT) ||
17821           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17822           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17823           isPALIGNRMask(M, SVT, Subtarget) ||
17824           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17825           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17826           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17827           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17828           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17829 }
17830
17831 bool
17832 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17833                                           EVT VT) const {
17834   if (!VT.isSimple())
17835     return false;
17836
17837   MVT SVT = VT.getSimpleVT();
17838   unsigned NumElts = SVT.getVectorNumElements();
17839   // FIXME: This collection of masks seems suspect.
17840   if (NumElts == 2)
17841     return true;
17842   if (NumElts == 4 && SVT.is128BitVector()) {
17843     return (isMOVLMask(Mask, SVT)  ||
17844             isCommutedMOVLMask(Mask, SVT, true) ||
17845             isSHUFPMask(Mask, SVT) ||
17846             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17847   }
17848   return false;
17849 }
17850
17851 //===----------------------------------------------------------------------===//
17852 //                           X86 Scheduler Hooks
17853 //===----------------------------------------------------------------------===//
17854
17855 /// Utility function to emit xbegin specifying the start of an RTM region.
17856 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17857                                      const TargetInstrInfo *TII) {
17858   DebugLoc DL = MI->getDebugLoc();
17859
17860   const BasicBlock *BB = MBB->getBasicBlock();
17861   MachineFunction::iterator I = MBB;
17862   ++I;
17863
17864   // For the v = xbegin(), we generate
17865   //
17866   // thisMBB:
17867   //  xbegin sinkMBB
17868   //
17869   // mainMBB:
17870   //  eax = -1
17871   //
17872   // sinkMBB:
17873   //  v = eax
17874
17875   MachineBasicBlock *thisMBB = MBB;
17876   MachineFunction *MF = MBB->getParent();
17877   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17878   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17879   MF->insert(I, mainMBB);
17880   MF->insert(I, sinkMBB);
17881
17882   // Transfer the remainder of BB and its successor edges to sinkMBB.
17883   sinkMBB->splice(sinkMBB->begin(), MBB,
17884                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17885   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17886
17887   // thisMBB:
17888   //  xbegin sinkMBB
17889   //  # fallthrough to mainMBB
17890   //  # abortion to sinkMBB
17891   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17892   thisMBB->addSuccessor(mainMBB);
17893   thisMBB->addSuccessor(sinkMBB);
17894
17895   // mainMBB:
17896   //  EAX = -1
17897   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17898   mainMBB->addSuccessor(sinkMBB);
17899
17900   // sinkMBB:
17901   // EAX is live into the sinkMBB
17902   sinkMBB->addLiveIn(X86::EAX);
17903   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17904           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17905     .addReg(X86::EAX);
17906
17907   MI->eraseFromParent();
17908   return sinkMBB;
17909 }
17910
17911 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17912 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17913 // in the .td file.
17914 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17915                                        const TargetInstrInfo *TII) {
17916   unsigned Opc;
17917   switch (MI->getOpcode()) {
17918   default: llvm_unreachable("illegal opcode!");
17919   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17920   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17921   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17922   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17923   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17924   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17925   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17926   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17927   }
17928
17929   DebugLoc dl = MI->getDebugLoc();
17930   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17931
17932   unsigned NumArgs = MI->getNumOperands();
17933   for (unsigned i = 1; i < NumArgs; ++i) {
17934     MachineOperand &Op = MI->getOperand(i);
17935     if (!(Op.isReg() && Op.isImplicit()))
17936       MIB.addOperand(Op);
17937   }
17938   if (MI->hasOneMemOperand())
17939     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17940
17941   BuildMI(*BB, MI, dl,
17942     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17943     .addReg(X86::XMM0);
17944
17945   MI->eraseFromParent();
17946   return BB;
17947 }
17948
17949 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17950 // defs in an instruction pattern
17951 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17952                                        const TargetInstrInfo *TII) {
17953   unsigned Opc;
17954   switch (MI->getOpcode()) {
17955   default: llvm_unreachable("illegal opcode!");
17956   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17957   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17958   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17959   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17960   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17961   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17962   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17963   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17964   }
17965
17966   DebugLoc dl = MI->getDebugLoc();
17967   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17968
17969   unsigned NumArgs = MI->getNumOperands(); // remove the results
17970   for (unsigned i = 1; i < NumArgs; ++i) {
17971     MachineOperand &Op = MI->getOperand(i);
17972     if (!(Op.isReg() && Op.isImplicit()))
17973       MIB.addOperand(Op);
17974   }
17975   if (MI->hasOneMemOperand())
17976     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17977
17978   BuildMI(*BB, MI, dl,
17979     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17980     .addReg(X86::ECX);
17981
17982   MI->eraseFromParent();
17983   return BB;
17984 }
17985
17986 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17987                                        const TargetInstrInfo *TII,
17988                                        const X86Subtarget* Subtarget) {
17989   DebugLoc dl = MI->getDebugLoc();
17990
17991   // Address into RAX/EAX, other two args into ECX, EDX.
17992   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17993   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17994   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17995   for (int i = 0; i < X86::AddrNumOperands; ++i)
17996     MIB.addOperand(MI->getOperand(i));
17997
17998   unsigned ValOps = X86::AddrNumOperands;
17999   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18000     .addReg(MI->getOperand(ValOps).getReg());
18001   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18002     .addReg(MI->getOperand(ValOps+1).getReg());
18003
18004   // The instruction doesn't actually take any operands though.
18005   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18006
18007   MI->eraseFromParent(); // The pseudo is gone now.
18008   return BB;
18009 }
18010
18011 MachineBasicBlock *
18012 X86TargetLowering::EmitVAARG64WithCustomInserter(
18013                    MachineInstr *MI,
18014                    MachineBasicBlock *MBB) const {
18015   // Emit va_arg instruction on X86-64.
18016
18017   // Operands to this pseudo-instruction:
18018   // 0  ) Output        : destination address (reg)
18019   // 1-5) Input         : va_list address (addr, i64mem)
18020   // 6  ) ArgSize       : Size (in bytes) of vararg type
18021   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18022   // 8  ) Align         : Alignment of type
18023   // 9  ) EFLAGS (implicit-def)
18024
18025   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18026   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
18027
18028   unsigned DestReg = MI->getOperand(0).getReg();
18029   MachineOperand &Base = MI->getOperand(1);
18030   MachineOperand &Scale = MI->getOperand(2);
18031   MachineOperand &Index = MI->getOperand(3);
18032   MachineOperand &Disp = MI->getOperand(4);
18033   MachineOperand &Segment = MI->getOperand(5);
18034   unsigned ArgSize = MI->getOperand(6).getImm();
18035   unsigned ArgMode = MI->getOperand(7).getImm();
18036   unsigned Align = MI->getOperand(8).getImm();
18037
18038   // Memory Reference
18039   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18040   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18041   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18042
18043   // Machine Information
18044   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18045   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18046   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18047   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18048   DebugLoc DL = MI->getDebugLoc();
18049
18050   // struct va_list {
18051   //   i32   gp_offset
18052   //   i32   fp_offset
18053   //   i64   overflow_area (address)
18054   //   i64   reg_save_area (address)
18055   // }
18056   // sizeof(va_list) = 24
18057   // alignment(va_list) = 8
18058
18059   unsigned TotalNumIntRegs = 6;
18060   unsigned TotalNumXMMRegs = 8;
18061   bool UseGPOffset = (ArgMode == 1);
18062   bool UseFPOffset = (ArgMode == 2);
18063   unsigned MaxOffset = TotalNumIntRegs * 8 +
18064                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18065
18066   /* Align ArgSize to a multiple of 8 */
18067   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18068   bool NeedsAlign = (Align > 8);
18069
18070   MachineBasicBlock *thisMBB = MBB;
18071   MachineBasicBlock *overflowMBB;
18072   MachineBasicBlock *offsetMBB;
18073   MachineBasicBlock *endMBB;
18074
18075   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18076   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18077   unsigned OffsetReg = 0;
18078
18079   if (!UseGPOffset && !UseFPOffset) {
18080     // If we only pull from the overflow region, we don't create a branch.
18081     // We don't need to alter control flow.
18082     OffsetDestReg = 0; // unused
18083     OverflowDestReg = DestReg;
18084
18085     offsetMBB = nullptr;
18086     overflowMBB = thisMBB;
18087     endMBB = thisMBB;
18088   } else {
18089     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18090     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18091     // If not, pull from overflow_area. (branch to overflowMBB)
18092     //
18093     //       thisMBB
18094     //         |     .
18095     //         |        .
18096     //     offsetMBB   overflowMBB
18097     //         |        .
18098     //         |     .
18099     //        endMBB
18100
18101     // Registers for the PHI in endMBB
18102     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18103     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18104
18105     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18106     MachineFunction *MF = MBB->getParent();
18107     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18108     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18109     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18110
18111     MachineFunction::iterator MBBIter = MBB;
18112     ++MBBIter;
18113
18114     // Insert the new basic blocks
18115     MF->insert(MBBIter, offsetMBB);
18116     MF->insert(MBBIter, overflowMBB);
18117     MF->insert(MBBIter, endMBB);
18118
18119     // Transfer the remainder of MBB and its successor edges to endMBB.
18120     endMBB->splice(endMBB->begin(), thisMBB,
18121                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18122     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18123
18124     // Make offsetMBB and overflowMBB successors of thisMBB
18125     thisMBB->addSuccessor(offsetMBB);
18126     thisMBB->addSuccessor(overflowMBB);
18127
18128     // endMBB is a successor of both offsetMBB and overflowMBB
18129     offsetMBB->addSuccessor(endMBB);
18130     overflowMBB->addSuccessor(endMBB);
18131
18132     // Load the offset value into a register
18133     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18134     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18135       .addOperand(Base)
18136       .addOperand(Scale)
18137       .addOperand(Index)
18138       .addDisp(Disp, UseFPOffset ? 4 : 0)
18139       .addOperand(Segment)
18140       .setMemRefs(MMOBegin, MMOEnd);
18141
18142     // Check if there is enough room left to pull this argument.
18143     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18144       .addReg(OffsetReg)
18145       .addImm(MaxOffset + 8 - ArgSizeA8);
18146
18147     // Branch to "overflowMBB" if offset >= max
18148     // Fall through to "offsetMBB" otherwise
18149     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18150       .addMBB(overflowMBB);
18151   }
18152
18153   // In offsetMBB, emit code to use the reg_save_area.
18154   if (offsetMBB) {
18155     assert(OffsetReg != 0);
18156
18157     // Read the reg_save_area address.
18158     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18159     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18160       .addOperand(Base)
18161       .addOperand(Scale)
18162       .addOperand(Index)
18163       .addDisp(Disp, 16)
18164       .addOperand(Segment)
18165       .setMemRefs(MMOBegin, MMOEnd);
18166
18167     // Zero-extend the offset
18168     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18169       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18170         .addImm(0)
18171         .addReg(OffsetReg)
18172         .addImm(X86::sub_32bit);
18173
18174     // Add the offset to the reg_save_area to get the final address.
18175     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18176       .addReg(OffsetReg64)
18177       .addReg(RegSaveReg);
18178
18179     // Compute the offset for the next argument
18180     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18181     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18182       .addReg(OffsetReg)
18183       .addImm(UseFPOffset ? 16 : 8);
18184
18185     // Store it back into the va_list.
18186     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18187       .addOperand(Base)
18188       .addOperand(Scale)
18189       .addOperand(Index)
18190       .addDisp(Disp, UseFPOffset ? 4 : 0)
18191       .addOperand(Segment)
18192       .addReg(NextOffsetReg)
18193       .setMemRefs(MMOBegin, MMOEnd);
18194
18195     // Jump to endMBB
18196     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
18197       .addMBB(endMBB);
18198   }
18199
18200   //
18201   // Emit code to use overflow area
18202   //
18203
18204   // Load the overflow_area address into a register.
18205   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18206   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18207     .addOperand(Base)
18208     .addOperand(Scale)
18209     .addOperand(Index)
18210     .addDisp(Disp, 8)
18211     .addOperand(Segment)
18212     .setMemRefs(MMOBegin, MMOEnd);
18213
18214   // If we need to align it, do so. Otherwise, just copy the address
18215   // to OverflowDestReg.
18216   if (NeedsAlign) {
18217     // Align the overflow address
18218     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18219     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18220
18221     // aligned_addr = (addr + (align-1)) & ~(align-1)
18222     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18223       .addReg(OverflowAddrReg)
18224       .addImm(Align-1);
18225
18226     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18227       .addReg(TmpReg)
18228       .addImm(~(uint64_t)(Align-1));
18229   } else {
18230     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18231       .addReg(OverflowAddrReg);
18232   }
18233
18234   // Compute the next overflow address after this argument.
18235   // (the overflow address should be kept 8-byte aligned)
18236   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18237   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18238     .addReg(OverflowDestReg)
18239     .addImm(ArgSizeA8);
18240
18241   // Store the new overflow address.
18242   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18243     .addOperand(Base)
18244     .addOperand(Scale)
18245     .addOperand(Index)
18246     .addDisp(Disp, 8)
18247     .addOperand(Segment)
18248     .addReg(NextAddrReg)
18249     .setMemRefs(MMOBegin, MMOEnd);
18250
18251   // If we branched, emit the PHI to the front of endMBB.
18252   if (offsetMBB) {
18253     BuildMI(*endMBB, endMBB->begin(), DL,
18254             TII->get(X86::PHI), DestReg)
18255       .addReg(OffsetDestReg).addMBB(offsetMBB)
18256       .addReg(OverflowDestReg).addMBB(overflowMBB);
18257   }
18258
18259   // Erase the pseudo instruction
18260   MI->eraseFromParent();
18261
18262   return endMBB;
18263 }
18264
18265 MachineBasicBlock *
18266 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18267                                                  MachineInstr *MI,
18268                                                  MachineBasicBlock *MBB) const {
18269   // Emit code to save XMM registers to the stack. The ABI says that the
18270   // number of registers to save is given in %al, so it's theoretically
18271   // possible to do an indirect jump trick to avoid saving all of them,
18272   // however this code takes a simpler approach and just executes all
18273   // of the stores if %al is non-zero. It's less code, and it's probably
18274   // easier on the hardware branch predictor, and stores aren't all that
18275   // expensive anyway.
18276
18277   // Create the new basic blocks. One block contains all the XMM stores,
18278   // and one block is the final destination regardless of whether any
18279   // stores were performed.
18280   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18281   MachineFunction *F = MBB->getParent();
18282   MachineFunction::iterator MBBIter = MBB;
18283   ++MBBIter;
18284   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18285   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18286   F->insert(MBBIter, XMMSaveMBB);
18287   F->insert(MBBIter, EndMBB);
18288
18289   // Transfer the remainder of MBB and its successor edges to EndMBB.
18290   EndMBB->splice(EndMBB->begin(), MBB,
18291                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18292   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18293
18294   // The original block will now fall through to the XMM save block.
18295   MBB->addSuccessor(XMMSaveMBB);
18296   // The XMMSaveMBB will fall through to the end block.
18297   XMMSaveMBB->addSuccessor(EndMBB);
18298
18299   // Now add the instructions.
18300   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18301   DebugLoc DL = MI->getDebugLoc();
18302
18303   unsigned CountReg = MI->getOperand(0).getReg();
18304   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18305   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
18306
18307   if (!Subtarget->isTargetWin64()) {
18308     // If %al is 0, branch around the XMM save block.
18309     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
18310     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
18311     MBB->addSuccessor(EndMBB);
18312   }
18313
18314   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
18315   // that was just emitted, but clearly shouldn't be "saved".
18316   assert((MI->getNumOperands() <= 3 ||
18317           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
18318           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
18319          && "Expected last argument to be EFLAGS");
18320   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
18321   // In the XMM save block, save all the XMM argument registers.
18322   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
18323     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
18324     MachineMemOperand *MMO =
18325       F->getMachineMemOperand(
18326           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
18327         MachineMemOperand::MOStore,
18328         /*Size=*/16, /*Align=*/16);
18329     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
18330       .addFrameIndex(RegSaveFrameIndex)
18331       .addImm(/*Scale=*/1)
18332       .addReg(/*IndexReg=*/0)
18333       .addImm(/*Disp=*/Offset)
18334       .addReg(/*Segment=*/0)
18335       .addReg(MI->getOperand(i).getReg())
18336       .addMemOperand(MMO);
18337   }
18338
18339   MI->eraseFromParent();   // The pseudo instruction is gone now.
18340
18341   return EndMBB;
18342 }
18343
18344 // The EFLAGS operand of SelectItr might be missing a kill marker
18345 // because there were multiple uses of EFLAGS, and ISel didn't know
18346 // which to mark. Figure out whether SelectItr should have had a
18347 // kill marker, and set it if it should. Returns the correct kill
18348 // marker value.
18349 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
18350                                      MachineBasicBlock* BB,
18351                                      const TargetRegisterInfo* TRI) {
18352   // Scan forward through BB for a use/def of EFLAGS.
18353   MachineBasicBlock::iterator miI(std::next(SelectItr));
18354   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
18355     const MachineInstr& mi = *miI;
18356     if (mi.readsRegister(X86::EFLAGS))
18357       return false;
18358     if (mi.definesRegister(X86::EFLAGS))
18359       break; // Should have kill-flag - update below.
18360   }
18361
18362   // If we hit the end of the block, check whether EFLAGS is live into a
18363   // successor.
18364   if (miI == BB->end()) {
18365     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
18366                                           sEnd = BB->succ_end();
18367          sItr != sEnd; ++sItr) {
18368       MachineBasicBlock* succ = *sItr;
18369       if (succ->isLiveIn(X86::EFLAGS))
18370         return false;
18371     }
18372   }
18373
18374   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
18375   // out. SelectMI should have a kill flag on EFLAGS.
18376   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
18377   return true;
18378 }
18379
18380 MachineBasicBlock *
18381 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
18382                                      MachineBasicBlock *BB) const {
18383   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18384   DebugLoc DL = MI->getDebugLoc();
18385
18386   // To "insert" a SELECT_CC instruction, we actually have to insert the
18387   // diamond control-flow pattern.  The incoming instruction knows the
18388   // destination vreg to set, the condition code register to branch on, the
18389   // true/false values to select between, and a branch opcode to use.
18390   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18391   MachineFunction::iterator It = BB;
18392   ++It;
18393
18394   //  thisMBB:
18395   //  ...
18396   //   TrueVal = ...
18397   //   cmpTY ccX, r1, r2
18398   //   bCC copy1MBB
18399   //   fallthrough --> copy0MBB
18400   MachineBasicBlock *thisMBB = BB;
18401   MachineFunction *F = BB->getParent();
18402   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
18403   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
18404   F->insert(It, copy0MBB);
18405   F->insert(It, sinkMBB);
18406
18407   // If the EFLAGS register isn't dead in the terminator, then claim that it's
18408   // live into the sink and copy blocks.
18409   const TargetRegisterInfo *TRI =
18410       BB->getParent()->getSubtarget().getRegisterInfo();
18411   if (!MI->killsRegister(X86::EFLAGS) &&
18412       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
18413     copy0MBB->addLiveIn(X86::EFLAGS);
18414     sinkMBB->addLiveIn(X86::EFLAGS);
18415   }
18416
18417   // Transfer the remainder of BB and its successor edges to sinkMBB.
18418   sinkMBB->splice(sinkMBB->begin(), BB,
18419                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
18420   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
18421
18422   // Add the true and fallthrough blocks as its successors.
18423   BB->addSuccessor(copy0MBB);
18424   BB->addSuccessor(sinkMBB);
18425
18426   // Create the conditional branch instruction.
18427   unsigned Opc =
18428     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
18429   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
18430
18431   //  copy0MBB:
18432   //   %FalseValue = ...
18433   //   # fallthrough to sinkMBB
18434   copy0MBB->addSuccessor(sinkMBB);
18435
18436   //  sinkMBB:
18437   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
18438   //  ...
18439   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18440           TII->get(X86::PHI), MI->getOperand(0).getReg())
18441     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
18442     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
18443
18444   MI->eraseFromParent();   // The pseudo instruction is gone now.
18445   return sinkMBB;
18446 }
18447
18448 MachineBasicBlock *
18449 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
18450                                         bool Is64Bit) const {
18451   MachineFunction *MF = BB->getParent();
18452   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18453   DebugLoc DL = MI->getDebugLoc();
18454   const BasicBlock *LLVM_BB = BB->getBasicBlock();
18455
18456   assert(MF->shouldSplitStack());
18457
18458   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
18459   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
18460
18461   // BB:
18462   //  ... [Till the alloca]
18463   // If stacklet is not large enough, jump to mallocMBB
18464   //
18465   // bumpMBB:
18466   //  Allocate by subtracting from RSP
18467   //  Jump to continueMBB
18468   //
18469   // mallocMBB:
18470   //  Allocate by call to runtime
18471   //
18472   // continueMBB:
18473   //  ...
18474   //  [rest of original BB]
18475   //
18476
18477   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18478   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18479   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18480
18481   MachineRegisterInfo &MRI = MF->getRegInfo();
18482   const TargetRegisterClass *AddrRegClass =
18483     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18484
18485   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18486     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18487     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18488     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18489     sizeVReg = MI->getOperand(1).getReg(),
18490     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18491
18492   MachineFunction::iterator MBBIter = BB;
18493   ++MBBIter;
18494
18495   MF->insert(MBBIter, bumpMBB);
18496   MF->insert(MBBIter, mallocMBB);
18497   MF->insert(MBBIter, continueMBB);
18498
18499   continueMBB->splice(continueMBB->begin(), BB,
18500                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18501   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18502
18503   // Add code to the main basic block to check if the stack limit has been hit,
18504   // and if so, jump to mallocMBB otherwise to bumpMBB.
18505   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18506   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18507     .addReg(tmpSPVReg).addReg(sizeVReg);
18508   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18509     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18510     .addReg(SPLimitVReg);
18511   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18512
18513   // bumpMBB simply decreases the stack pointer, since we know the current
18514   // stacklet has enough space.
18515   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18516     .addReg(SPLimitVReg);
18517   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18518     .addReg(SPLimitVReg);
18519   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18520
18521   // Calls into a routine in libgcc to allocate more space from the heap.
18522   const uint32_t *RegMask = MF->getTarget()
18523                                 .getSubtargetImpl()
18524                                 ->getRegisterInfo()
18525                                 ->getCallPreservedMask(CallingConv::C);
18526   if (Is64Bit) {
18527     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18528       .addReg(sizeVReg);
18529     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18530       .addExternalSymbol("__morestack_allocate_stack_space")
18531       .addRegMask(RegMask)
18532       .addReg(X86::RDI, RegState::Implicit)
18533       .addReg(X86::RAX, RegState::ImplicitDefine);
18534   } else {
18535     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18536       .addImm(12);
18537     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18538     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18539       .addExternalSymbol("__morestack_allocate_stack_space")
18540       .addRegMask(RegMask)
18541       .addReg(X86::EAX, RegState::ImplicitDefine);
18542   }
18543
18544   if (!Is64Bit)
18545     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18546       .addImm(16);
18547
18548   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18549     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18550   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18551
18552   // Set up the CFG correctly.
18553   BB->addSuccessor(bumpMBB);
18554   BB->addSuccessor(mallocMBB);
18555   mallocMBB->addSuccessor(continueMBB);
18556   bumpMBB->addSuccessor(continueMBB);
18557
18558   // Take care of the PHI nodes.
18559   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18560           MI->getOperand(0).getReg())
18561     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18562     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18563
18564   // Delete the original pseudo instruction.
18565   MI->eraseFromParent();
18566
18567   // And we're done.
18568   return continueMBB;
18569 }
18570
18571 MachineBasicBlock *
18572 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18573                                         MachineBasicBlock *BB) const {
18574   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
18575   DebugLoc DL = MI->getDebugLoc();
18576
18577   assert(!Subtarget->isTargetMacho());
18578
18579   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18580   // non-trivial part is impdef of ESP.
18581
18582   if (Subtarget->isTargetWin64()) {
18583     if (Subtarget->isTargetCygMing()) {
18584       // ___chkstk(Mingw64):
18585       // Clobbers R10, R11, RAX and EFLAGS.
18586       // Updates RSP.
18587       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18588         .addExternalSymbol("___chkstk")
18589         .addReg(X86::RAX, RegState::Implicit)
18590         .addReg(X86::RSP, RegState::Implicit)
18591         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18592         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18593         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18594     } else {
18595       // __chkstk(MSVCRT): does not update stack pointer.
18596       // Clobbers R10, R11 and EFLAGS.
18597       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18598         .addExternalSymbol("__chkstk")
18599         .addReg(X86::RAX, RegState::Implicit)
18600         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18601       // RAX has the offset to be subtracted from RSP.
18602       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18603         .addReg(X86::RSP)
18604         .addReg(X86::RAX);
18605     }
18606   } else {
18607     const char *StackProbeSymbol =
18608       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18609
18610     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18611       .addExternalSymbol(StackProbeSymbol)
18612       .addReg(X86::EAX, RegState::Implicit)
18613       .addReg(X86::ESP, RegState::Implicit)
18614       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18615       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18616       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18617   }
18618
18619   MI->eraseFromParent();   // The pseudo instruction is gone now.
18620   return BB;
18621 }
18622
18623 MachineBasicBlock *
18624 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18625                                       MachineBasicBlock *BB) const {
18626   // This is pretty easy.  We're taking the value that we received from
18627   // our load from the relocation, sticking it in either RDI (x86-64)
18628   // or EAX and doing an indirect call.  The return value will then
18629   // be in the normal return register.
18630   MachineFunction *F = BB->getParent();
18631   const X86InstrInfo *TII =
18632       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
18633   DebugLoc DL = MI->getDebugLoc();
18634
18635   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18636   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18637
18638   // Get a register mask for the lowered call.
18639   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18640   // proper register mask.
18641   const uint32_t *RegMask = F->getTarget()
18642                                 .getSubtargetImpl()
18643                                 ->getRegisterInfo()
18644                                 ->getCallPreservedMask(CallingConv::C);
18645   if (Subtarget->is64Bit()) {
18646     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18647                                       TII->get(X86::MOV64rm), X86::RDI)
18648     .addReg(X86::RIP)
18649     .addImm(0).addReg(0)
18650     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18651                       MI->getOperand(3).getTargetFlags())
18652     .addReg(0);
18653     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18654     addDirectMem(MIB, X86::RDI);
18655     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18656   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18657     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18658                                       TII->get(X86::MOV32rm), X86::EAX)
18659     .addReg(0)
18660     .addImm(0).addReg(0)
18661     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18662                       MI->getOperand(3).getTargetFlags())
18663     .addReg(0);
18664     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18665     addDirectMem(MIB, X86::EAX);
18666     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18667   } else {
18668     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18669                                       TII->get(X86::MOV32rm), X86::EAX)
18670     .addReg(TII->getGlobalBaseReg(F))
18671     .addImm(0).addReg(0)
18672     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18673                       MI->getOperand(3).getTargetFlags())
18674     .addReg(0);
18675     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18676     addDirectMem(MIB, X86::EAX);
18677     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18678   }
18679
18680   MI->eraseFromParent(); // The pseudo instruction is gone now.
18681   return BB;
18682 }
18683
18684 MachineBasicBlock *
18685 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18686                                     MachineBasicBlock *MBB) const {
18687   DebugLoc DL = MI->getDebugLoc();
18688   MachineFunction *MF = MBB->getParent();
18689   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18690   MachineRegisterInfo &MRI = MF->getRegInfo();
18691
18692   const BasicBlock *BB = MBB->getBasicBlock();
18693   MachineFunction::iterator I = MBB;
18694   ++I;
18695
18696   // Memory Reference
18697   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18698   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18699
18700   unsigned DstReg;
18701   unsigned MemOpndSlot = 0;
18702
18703   unsigned CurOp = 0;
18704
18705   DstReg = MI->getOperand(CurOp++).getReg();
18706   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18707   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18708   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18709   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18710
18711   MemOpndSlot = CurOp;
18712
18713   MVT PVT = getPointerTy();
18714   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18715          "Invalid Pointer Size!");
18716
18717   // For v = setjmp(buf), we generate
18718   //
18719   // thisMBB:
18720   //  buf[LabelOffset] = restoreMBB
18721   //  SjLjSetup restoreMBB
18722   //
18723   // mainMBB:
18724   //  v_main = 0
18725   //
18726   // sinkMBB:
18727   //  v = phi(main, restore)
18728   //
18729   // restoreMBB:
18730   //  v_restore = 1
18731
18732   MachineBasicBlock *thisMBB = MBB;
18733   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18734   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18735   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18736   MF->insert(I, mainMBB);
18737   MF->insert(I, sinkMBB);
18738   MF->push_back(restoreMBB);
18739
18740   MachineInstrBuilder MIB;
18741
18742   // Transfer the remainder of BB and its successor edges to sinkMBB.
18743   sinkMBB->splice(sinkMBB->begin(), MBB,
18744                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18745   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18746
18747   // thisMBB:
18748   unsigned PtrStoreOpc = 0;
18749   unsigned LabelReg = 0;
18750   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18751   Reloc::Model RM = MF->getTarget().getRelocationModel();
18752   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18753                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18754
18755   // Prepare IP either in reg or imm.
18756   if (!UseImmLabel) {
18757     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18758     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18759     LabelReg = MRI.createVirtualRegister(PtrRC);
18760     if (Subtarget->is64Bit()) {
18761       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18762               .addReg(X86::RIP)
18763               .addImm(0)
18764               .addReg(0)
18765               .addMBB(restoreMBB)
18766               .addReg(0);
18767     } else {
18768       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18769       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18770               .addReg(XII->getGlobalBaseReg(MF))
18771               .addImm(0)
18772               .addReg(0)
18773               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18774               .addReg(0);
18775     }
18776   } else
18777     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18778   // Store IP
18779   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18780   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18781     if (i == X86::AddrDisp)
18782       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18783     else
18784       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18785   }
18786   if (!UseImmLabel)
18787     MIB.addReg(LabelReg);
18788   else
18789     MIB.addMBB(restoreMBB);
18790   MIB.setMemRefs(MMOBegin, MMOEnd);
18791   // Setup
18792   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18793           .addMBB(restoreMBB);
18794
18795   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18796       MF->getSubtarget().getRegisterInfo());
18797   MIB.addRegMask(RegInfo->getNoPreservedMask());
18798   thisMBB->addSuccessor(mainMBB);
18799   thisMBB->addSuccessor(restoreMBB);
18800
18801   // mainMBB:
18802   //  EAX = 0
18803   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18804   mainMBB->addSuccessor(sinkMBB);
18805
18806   // sinkMBB:
18807   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18808           TII->get(X86::PHI), DstReg)
18809     .addReg(mainDstReg).addMBB(mainMBB)
18810     .addReg(restoreDstReg).addMBB(restoreMBB);
18811
18812   // restoreMBB:
18813   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18814   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18815   restoreMBB->addSuccessor(sinkMBB);
18816
18817   MI->eraseFromParent();
18818   return sinkMBB;
18819 }
18820
18821 MachineBasicBlock *
18822 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18823                                      MachineBasicBlock *MBB) const {
18824   DebugLoc DL = MI->getDebugLoc();
18825   MachineFunction *MF = MBB->getParent();
18826   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
18827   MachineRegisterInfo &MRI = MF->getRegInfo();
18828
18829   // Memory Reference
18830   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18831   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18832
18833   MVT PVT = getPointerTy();
18834   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18835          "Invalid Pointer Size!");
18836
18837   const TargetRegisterClass *RC =
18838     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18839   unsigned Tmp = MRI.createVirtualRegister(RC);
18840   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18841   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18842       MF->getSubtarget().getRegisterInfo());
18843   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18844   unsigned SP = RegInfo->getStackRegister();
18845
18846   MachineInstrBuilder MIB;
18847
18848   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18849   const int64_t SPOffset = 2 * PVT.getStoreSize();
18850
18851   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18852   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18853
18854   // Reload FP
18855   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18856   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18857     MIB.addOperand(MI->getOperand(i));
18858   MIB.setMemRefs(MMOBegin, MMOEnd);
18859   // Reload IP
18860   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18861   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18862     if (i == X86::AddrDisp)
18863       MIB.addDisp(MI->getOperand(i), LabelOffset);
18864     else
18865       MIB.addOperand(MI->getOperand(i));
18866   }
18867   MIB.setMemRefs(MMOBegin, MMOEnd);
18868   // Reload SP
18869   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18870   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18871     if (i == X86::AddrDisp)
18872       MIB.addDisp(MI->getOperand(i), SPOffset);
18873     else
18874       MIB.addOperand(MI->getOperand(i));
18875   }
18876   MIB.setMemRefs(MMOBegin, MMOEnd);
18877   // Jump
18878   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18879
18880   MI->eraseFromParent();
18881   return MBB;
18882 }
18883
18884 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18885 // accumulator loops. Writing back to the accumulator allows the coalescer
18886 // to remove extra copies in the loop.   
18887 MachineBasicBlock *
18888 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18889                                  MachineBasicBlock *MBB) const {
18890   MachineOperand &AddendOp = MI->getOperand(3);
18891
18892   // Bail out early if the addend isn't a register - we can't switch these.
18893   if (!AddendOp.isReg())
18894     return MBB;
18895
18896   MachineFunction &MF = *MBB->getParent();
18897   MachineRegisterInfo &MRI = MF.getRegInfo();
18898
18899   // Check whether the addend is defined by a PHI:
18900   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18901   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18902   if (!AddendDef.isPHI())
18903     return MBB;
18904
18905   // Look for the following pattern:
18906   // loop:
18907   //   %addend = phi [%entry, 0], [%loop, %result]
18908   //   ...
18909   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18910
18911   // Replace with:
18912   //   loop:
18913   //   %addend = phi [%entry, 0], [%loop, %result]
18914   //   ...
18915   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18916
18917   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18918     assert(AddendDef.getOperand(i).isReg());
18919     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18920     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18921     if (&PHISrcInst == MI) {
18922       // Found a matching instruction.
18923       unsigned NewFMAOpc = 0;
18924       switch (MI->getOpcode()) {
18925         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18926         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18927         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18928         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18929         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18930         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18931         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18932         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18933         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18934         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18935         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18936         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18937         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18938         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18939         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18940         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18941         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18942         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18943         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18944         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18945         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18946         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18947         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18948         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18949         default: llvm_unreachable("Unrecognized FMA variant.");
18950       }
18951
18952       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
18953       MachineInstrBuilder MIB =
18954         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18955         .addOperand(MI->getOperand(0))
18956         .addOperand(MI->getOperand(3))
18957         .addOperand(MI->getOperand(2))
18958         .addOperand(MI->getOperand(1));
18959       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18960       MI->eraseFromParent();
18961     }
18962   }
18963
18964   return MBB;
18965 }
18966
18967 MachineBasicBlock *
18968 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18969                                                MachineBasicBlock *BB) const {
18970   switch (MI->getOpcode()) {
18971   default: llvm_unreachable("Unexpected instr type to insert");
18972   case X86::TAILJMPd64:
18973   case X86::TAILJMPr64:
18974   case X86::TAILJMPm64:
18975     llvm_unreachable("TAILJMP64 would not be touched here.");
18976   case X86::TCRETURNdi64:
18977   case X86::TCRETURNri64:
18978   case X86::TCRETURNmi64:
18979     return BB;
18980   case X86::WIN_ALLOCA:
18981     return EmitLoweredWinAlloca(MI, BB);
18982   case X86::SEG_ALLOCA_32:
18983     return EmitLoweredSegAlloca(MI, BB, false);
18984   case X86::SEG_ALLOCA_64:
18985     return EmitLoweredSegAlloca(MI, BB, true);
18986   case X86::TLSCall_32:
18987   case X86::TLSCall_64:
18988     return EmitLoweredTLSCall(MI, BB);
18989   case X86::CMOV_GR8:
18990   case X86::CMOV_FR32:
18991   case X86::CMOV_FR64:
18992   case X86::CMOV_V4F32:
18993   case X86::CMOV_V2F64:
18994   case X86::CMOV_V2I64:
18995   case X86::CMOV_V8F32:
18996   case X86::CMOV_V4F64:
18997   case X86::CMOV_V4I64:
18998   case X86::CMOV_V16F32:
18999   case X86::CMOV_V8F64:
19000   case X86::CMOV_V8I64:
19001   case X86::CMOV_GR16:
19002   case X86::CMOV_GR32:
19003   case X86::CMOV_RFP32:
19004   case X86::CMOV_RFP64:
19005   case X86::CMOV_RFP80:
19006     return EmitLoweredSelect(MI, BB);
19007
19008   case X86::FP32_TO_INT16_IN_MEM:
19009   case X86::FP32_TO_INT32_IN_MEM:
19010   case X86::FP32_TO_INT64_IN_MEM:
19011   case X86::FP64_TO_INT16_IN_MEM:
19012   case X86::FP64_TO_INT32_IN_MEM:
19013   case X86::FP64_TO_INT64_IN_MEM:
19014   case X86::FP80_TO_INT16_IN_MEM:
19015   case X86::FP80_TO_INT32_IN_MEM:
19016   case X86::FP80_TO_INT64_IN_MEM: {
19017     MachineFunction *F = BB->getParent();
19018     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
19019     DebugLoc DL = MI->getDebugLoc();
19020
19021     // Change the floating point control register to use "round towards zero"
19022     // mode when truncating to an integer value.
19023     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19024     addFrameReference(BuildMI(*BB, MI, DL,
19025                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19026
19027     // Load the old value of the high byte of the control word...
19028     unsigned OldCW =
19029       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19030     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19031                       CWFrameIdx);
19032
19033     // Set the high part to be round to zero...
19034     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19035       .addImm(0xC7F);
19036
19037     // Reload the modified control word now...
19038     addFrameReference(BuildMI(*BB, MI, DL,
19039                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19040
19041     // Restore the memory image of control word to original value
19042     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19043       .addReg(OldCW);
19044
19045     // Get the X86 opcode to use.
19046     unsigned Opc;
19047     switch (MI->getOpcode()) {
19048     default: llvm_unreachable("illegal opcode!");
19049     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19050     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19051     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19052     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19053     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19054     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19055     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19056     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19057     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19058     }
19059
19060     X86AddressMode AM;
19061     MachineOperand &Op = MI->getOperand(0);
19062     if (Op.isReg()) {
19063       AM.BaseType = X86AddressMode::RegBase;
19064       AM.Base.Reg = Op.getReg();
19065     } else {
19066       AM.BaseType = X86AddressMode::FrameIndexBase;
19067       AM.Base.FrameIndex = Op.getIndex();
19068     }
19069     Op = MI->getOperand(1);
19070     if (Op.isImm())
19071       AM.Scale = Op.getImm();
19072     Op = MI->getOperand(2);
19073     if (Op.isImm())
19074       AM.IndexReg = Op.getImm();
19075     Op = MI->getOperand(3);
19076     if (Op.isGlobal()) {
19077       AM.GV = Op.getGlobal();
19078     } else {
19079       AM.Disp = Op.getImm();
19080     }
19081     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19082                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19083
19084     // Reload the original control word now.
19085     addFrameReference(BuildMI(*BB, MI, DL,
19086                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19087
19088     MI->eraseFromParent();   // The pseudo instruction is gone now.
19089     return BB;
19090   }
19091     // String/text processing lowering.
19092   case X86::PCMPISTRM128REG:
19093   case X86::VPCMPISTRM128REG:
19094   case X86::PCMPISTRM128MEM:
19095   case X86::VPCMPISTRM128MEM:
19096   case X86::PCMPESTRM128REG:
19097   case X86::VPCMPESTRM128REG:
19098   case X86::PCMPESTRM128MEM:
19099   case X86::VPCMPESTRM128MEM:
19100     assert(Subtarget->hasSSE42() &&
19101            "Target must have SSE4.2 or AVX features enabled");
19102     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19103
19104   // String/text processing lowering.
19105   case X86::PCMPISTRIREG:
19106   case X86::VPCMPISTRIREG:
19107   case X86::PCMPISTRIMEM:
19108   case X86::VPCMPISTRIMEM:
19109   case X86::PCMPESTRIREG:
19110   case X86::VPCMPESTRIREG:
19111   case X86::PCMPESTRIMEM:
19112   case X86::VPCMPESTRIMEM:
19113     assert(Subtarget->hasSSE42() &&
19114            "Target must have SSE4.2 or AVX features enabled");
19115     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19116
19117   // Thread synchronization.
19118   case X86::MONITOR:
19119     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
19120                        Subtarget);
19121
19122   // xbegin
19123   case X86::XBEGIN:
19124     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19125
19126   case X86::VASTART_SAVE_XMM_REGS:
19127     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19128
19129   case X86::VAARG_64:
19130     return EmitVAARG64WithCustomInserter(MI, BB);
19131
19132   case X86::EH_SjLj_SetJmp32:
19133   case X86::EH_SjLj_SetJmp64:
19134     return emitEHSjLjSetJmp(MI, BB);
19135
19136   case X86::EH_SjLj_LongJmp32:
19137   case X86::EH_SjLj_LongJmp64:
19138     return emitEHSjLjLongJmp(MI, BB);
19139
19140   case TargetOpcode::STACKMAP:
19141   case TargetOpcode::PATCHPOINT:
19142     return emitPatchPoint(MI, BB);
19143
19144   case X86::VFMADDPDr213r:
19145   case X86::VFMADDPSr213r:
19146   case X86::VFMADDSDr213r:
19147   case X86::VFMADDSSr213r:
19148   case X86::VFMSUBPDr213r:
19149   case X86::VFMSUBPSr213r:
19150   case X86::VFMSUBSDr213r:
19151   case X86::VFMSUBSSr213r:
19152   case X86::VFNMADDPDr213r:
19153   case X86::VFNMADDPSr213r:
19154   case X86::VFNMADDSDr213r:
19155   case X86::VFNMADDSSr213r:
19156   case X86::VFNMSUBPDr213r:
19157   case X86::VFNMSUBPSr213r:
19158   case X86::VFNMSUBSDr213r:
19159   case X86::VFNMSUBSSr213r:
19160   case X86::VFMADDPDr213rY:
19161   case X86::VFMADDPSr213rY:
19162   case X86::VFMSUBPDr213rY:
19163   case X86::VFMSUBPSr213rY:
19164   case X86::VFNMADDPDr213rY:
19165   case X86::VFNMADDPSr213rY:
19166   case X86::VFNMSUBPDr213rY:
19167   case X86::VFNMSUBPSr213rY:
19168     return emitFMA3Instr(MI, BB);
19169   }
19170 }
19171
19172 //===----------------------------------------------------------------------===//
19173 //                           X86 Optimization Hooks
19174 //===----------------------------------------------------------------------===//
19175
19176 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19177                                                       APInt &KnownZero,
19178                                                       APInt &KnownOne,
19179                                                       const SelectionDAG &DAG,
19180                                                       unsigned Depth) const {
19181   unsigned BitWidth = KnownZero.getBitWidth();
19182   unsigned Opc = Op.getOpcode();
19183   assert((Opc >= ISD::BUILTIN_OP_END ||
19184           Opc == ISD::INTRINSIC_WO_CHAIN ||
19185           Opc == ISD::INTRINSIC_W_CHAIN ||
19186           Opc == ISD::INTRINSIC_VOID) &&
19187          "Should use MaskedValueIsZero if you don't know whether Op"
19188          " is a target node!");
19189
19190   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19191   switch (Opc) {
19192   default: break;
19193   case X86ISD::ADD:
19194   case X86ISD::SUB:
19195   case X86ISD::ADC:
19196   case X86ISD::SBB:
19197   case X86ISD::SMUL:
19198   case X86ISD::UMUL:
19199   case X86ISD::INC:
19200   case X86ISD::DEC:
19201   case X86ISD::OR:
19202   case X86ISD::XOR:
19203   case X86ISD::AND:
19204     // These nodes' second result is a boolean.
19205     if (Op.getResNo() == 0)
19206       break;
19207     // Fallthrough
19208   case X86ISD::SETCC:
19209     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19210     break;
19211   case ISD::INTRINSIC_WO_CHAIN: {
19212     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19213     unsigned NumLoBits = 0;
19214     switch (IntId) {
19215     default: break;
19216     case Intrinsic::x86_sse_movmsk_ps:
19217     case Intrinsic::x86_avx_movmsk_ps_256:
19218     case Intrinsic::x86_sse2_movmsk_pd:
19219     case Intrinsic::x86_avx_movmsk_pd_256:
19220     case Intrinsic::x86_mmx_pmovmskb:
19221     case Intrinsic::x86_sse2_pmovmskb_128:
19222     case Intrinsic::x86_avx2_pmovmskb: {
19223       // High bits of movmskp{s|d}, pmovmskb are known zero.
19224       switch (IntId) {
19225         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19226         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19227         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19228         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19229         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19230         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19231         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19232         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19233       }
19234       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19235       break;
19236     }
19237     }
19238     break;
19239   }
19240   }
19241 }
19242
19243 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19244   SDValue Op,
19245   const SelectionDAG &,
19246   unsigned Depth) const {
19247   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19248   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19249     return Op.getValueType().getScalarType().getSizeInBits();
19250
19251   // Fallback case.
19252   return 1;
19253 }
19254
19255 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19256 /// node is a GlobalAddress + offset.
19257 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19258                                        const GlobalValue* &GA,
19259                                        int64_t &Offset) const {
19260   if (N->getOpcode() == X86ISD::Wrapper) {
19261     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19262       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19263       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19264       return true;
19265     }
19266   }
19267   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19268 }
19269
19270 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19271 /// same as extracting the high 128-bit part of 256-bit vector and then
19272 /// inserting the result into the low part of a new 256-bit vector
19273 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19274   EVT VT = SVOp->getValueType(0);
19275   unsigned NumElems = VT.getVectorNumElements();
19276
19277   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19278   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19279     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19280         SVOp->getMaskElt(j) >= 0)
19281       return false;
19282
19283   return true;
19284 }
19285
19286 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19287 /// same as extracting the low 128-bit part of 256-bit vector and then
19288 /// inserting the result into the high part of a new 256-bit vector
19289 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19290   EVT VT = SVOp->getValueType(0);
19291   unsigned NumElems = VT.getVectorNumElements();
19292
19293   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19294   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19295     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19296         SVOp->getMaskElt(j) >= 0)
19297       return false;
19298
19299   return true;
19300 }
19301
19302 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
19303 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
19304                                         TargetLowering::DAGCombinerInfo &DCI,
19305                                         const X86Subtarget* Subtarget) {
19306   SDLoc dl(N);
19307   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19308   SDValue V1 = SVOp->getOperand(0);
19309   SDValue V2 = SVOp->getOperand(1);
19310   EVT VT = SVOp->getValueType(0);
19311   unsigned NumElems = VT.getVectorNumElements();
19312
19313   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
19314       V2.getOpcode() == ISD::CONCAT_VECTORS) {
19315     //
19316     //                   0,0,0,...
19317     //                      |
19318     //    V      UNDEF    BUILD_VECTOR    UNDEF
19319     //     \      /           \           /
19320     //  CONCAT_VECTOR         CONCAT_VECTOR
19321     //         \                  /
19322     //          \                /
19323     //          RESULT: V + zero extended
19324     //
19325     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
19326         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
19327         V1.getOperand(1).getOpcode() != ISD::UNDEF)
19328       return SDValue();
19329
19330     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
19331       return SDValue();
19332
19333     // To match the shuffle mask, the first half of the mask should
19334     // be exactly the first vector, and all the rest a splat with the
19335     // first element of the second one.
19336     for (unsigned i = 0; i != NumElems/2; ++i)
19337       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
19338           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
19339         return SDValue();
19340
19341     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
19342     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
19343       if (Ld->hasNUsesOfValue(1, 0)) {
19344         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
19345         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
19346         SDValue ResNode =
19347           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
19348                                   Ld->getMemoryVT(),
19349                                   Ld->getPointerInfo(),
19350                                   Ld->getAlignment(),
19351                                   false/*isVolatile*/, true/*ReadMem*/,
19352                                   false/*WriteMem*/);
19353
19354         // Make sure the newly-created LOAD is in the same position as Ld in
19355         // terms of dependency. We create a TokenFactor for Ld and ResNode,
19356         // and update uses of Ld's output chain to use the TokenFactor.
19357         if (Ld->hasAnyUseOfValue(1)) {
19358           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19359                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
19360           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
19361           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
19362                                  SDValue(ResNode.getNode(), 1));
19363         }
19364
19365         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
19366       }
19367     }
19368
19369     // Emit a zeroed vector and insert the desired subvector on its
19370     // first half.
19371     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
19372     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
19373     return DCI.CombineTo(N, InsV);
19374   }
19375
19376   //===--------------------------------------------------------------------===//
19377   // Combine some shuffles into subvector extracts and inserts:
19378   //
19379
19380   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19381   if (isShuffleHigh128VectorInsertLow(SVOp)) {
19382     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
19383     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
19384     return DCI.CombineTo(N, InsV);
19385   }
19386
19387   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19388   if (isShuffleLow128VectorInsertHigh(SVOp)) {
19389     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
19390     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
19391     return DCI.CombineTo(N, InsV);
19392   }
19393
19394   return SDValue();
19395 }
19396
19397 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
19398 /// possible.
19399 ///
19400 /// This is the leaf of the recursive combinine below. When we have found some
19401 /// chain of single-use x86 shuffle instructions and accumulated the combined
19402 /// shuffle mask represented by them, this will try to pattern match that mask
19403 /// into either a single instruction if there is a special purpose instruction
19404 /// for this operation, or into a PSHUFB instruction which is a fully general
19405 /// instruction but should only be used to replace chains over a certain depth.
19406 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
19407                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
19408                                    TargetLowering::DAGCombinerInfo &DCI,
19409                                    const X86Subtarget *Subtarget) {
19410   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
19411
19412   // Find the operand that enters the chain. Note that multiple uses are OK
19413   // here, we're not going to remove the operand we find.
19414   SDValue Input = Op.getOperand(0);
19415   while (Input.getOpcode() == ISD::BITCAST)
19416     Input = Input.getOperand(0);
19417
19418   MVT VT = Input.getSimpleValueType();
19419   MVT RootVT = Root.getSimpleValueType();
19420   SDLoc DL(Root);
19421
19422   // Just remove no-op shuffle masks.
19423   if (Mask.size() == 1) {
19424     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
19425                   /*AddTo*/ true);
19426     return true;
19427   }
19428
19429   // Use the float domain if the operand type is a floating point type.
19430   bool FloatDomain = VT.isFloatingPoint();
19431
19432   // For floating point shuffles, we don't have free copies in the shuffle
19433   // instructions or the ability to load as part of the instruction, so
19434   // canonicalize their shuffles to UNPCK or MOV variants.
19435   //
19436   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
19437   // vectors because it can have a load folded into it that UNPCK cannot. This
19438   // doesn't preclude something switching to the shorter encoding post-RA.
19439   if (FloatDomain) {
19440     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
19441       bool Lo = Mask.equals(0, 0);
19442       unsigned Shuffle;
19443       MVT ShuffleVT;
19444       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
19445       // is no slower than UNPCKLPD but has the option to fold the input operand
19446       // into even an unaligned memory load.
19447       if (Lo && Subtarget->hasSSE3()) {
19448         Shuffle = X86ISD::MOVDDUP;
19449         ShuffleVT = MVT::v2f64;
19450       } else {
19451         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
19452         // than the UNPCK variants.
19453         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
19454         ShuffleVT = MVT::v4f32;
19455       }
19456       if (Depth == 1 && Root->getOpcode() == Shuffle)
19457         return false; // Nothing to do!
19458       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19459       DCI.AddToWorklist(Op.getNode());
19460       if (Shuffle == X86ISD::MOVDDUP)
19461         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19462       else
19463         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19464       DCI.AddToWorklist(Op.getNode());
19465       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19466                     /*AddTo*/ true);
19467       return true;
19468     }
19469     if (Subtarget->hasSSE3() &&
19470         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
19471       bool Lo = Mask.equals(0, 0, 2, 2);
19472       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
19473       MVT ShuffleVT = MVT::v4f32;
19474       if (Depth == 1 && Root->getOpcode() == Shuffle)
19475         return false; // Nothing to do!
19476       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19477       DCI.AddToWorklist(Op.getNode());
19478       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
19479       DCI.AddToWorklist(Op.getNode());
19480       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19481                     /*AddTo*/ true);
19482       return true;
19483     }
19484     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
19485       bool Lo = Mask.equals(0, 0, 1, 1);
19486       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19487       MVT ShuffleVT = MVT::v4f32;
19488       if (Depth == 1 && Root->getOpcode() == Shuffle)
19489         return false; // Nothing to do!
19490       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19491       DCI.AddToWorklist(Op.getNode());
19492       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19493       DCI.AddToWorklist(Op.getNode());
19494       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19495                     /*AddTo*/ true);
19496       return true;
19497     }
19498   }
19499
19500   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
19501   // variants as none of these have single-instruction variants that are
19502   // superior to the UNPCK formulation.
19503   if (!FloatDomain &&
19504       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19505        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19506        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19507        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19508                    15))) {
19509     bool Lo = Mask[0] == 0;
19510     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19511     if (Depth == 1 && Root->getOpcode() == Shuffle)
19512       return false; // Nothing to do!
19513     MVT ShuffleVT;
19514     switch (Mask.size()) {
19515     case 8:
19516       ShuffleVT = MVT::v8i16;
19517       break;
19518     case 16:
19519       ShuffleVT = MVT::v16i8;
19520       break;
19521     default:
19522       llvm_unreachable("Impossible mask size!");
19523     };
19524     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19525     DCI.AddToWorklist(Op.getNode());
19526     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19527     DCI.AddToWorklist(Op.getNode());
19528     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19529                   /*AddTo*/ true);
19530     return true;
19531   }
19532
19533   // Don't try to re-form single instruction chains under any circumstances now
19534   // that we've done encoding canonicalization for them.
19535   if (Depth < 2)
19536     return false;
19537
19538   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19539   // can replace them with a single PSHUFB instruction profitably. Intel's
19540   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19541   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19542   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19543     SmallVector<SDValue, 16> PSHUFBMask;
19544     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19545     int Ratio = 16 / Mask.size();
19546     for (unsigned i = 0; i < 16; ++i) {
19547       int M = Mask[i / Ratio] != SM_SentinelZero
19548                   ? Ratio * Mask[i / Ratio] + i % Ratio
19549                   : 255;
19550       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19551     }
19552     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19553     DCI.AddToWorklist(Op.getNode());
19554     SDValue PSHUFBMaskOp =
19555         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19556     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19557     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19558     DCI.AddToWorklist(Op.getNode());
19559     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19560                   /*AddTo*/ true);
19561     return true;
19562   }
19563
19564   // Failed to find any combines.
19565   return false;
19566 }
19567
19568 /// \brief Fully generic combining of x86 shuffle instructions.
19569 ///
19570 /// This should be the last combine run over the x86 shuffle instructions. Once
19571 /// they have been fully optimized, this will recursively consider all chains
19572 /// of single-use shuffle instructions, build a generic model of the cumulative
19573 /// shuffle operation, and check for simpler instructions which implement this
19574 /// operation. We use this primarily for two purposes:
19575 ///
19576 /// 1) Collapse generic shuffles to specialized single instructions when
19577 ///    equivalent. In most cases, this is just an encoding size win, but
19578 ///    sometimes we will collapse multiple generic shuffles into a single
19579 ///    special-purpose shuffle.
19580 /// 2) Look for sequences of shuffle instructions with 3 or more total
19581 ///    instructions, and replace them with the slightly more expensive SSSE3
19582 ///    PSHUFB instruction if available. We do this as the last combining step
19583 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19584 ///    a suitable short sequence of other instructions. The PHUFB will either
19585 ///    use a register or have to read from memory and so is slightly (but only
19586 ///    slightly) more expensive than the other shuffle instructions.
19587 ///
19588 /// Because this is inherently a quadratic operation (for each shuffle in
19589 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19590 /// This should never be an issue in practice as the shuffle lowering doesn't
19591 /// produce sequences of more than 8 instructions.
19592 ///
19593 /// FIXME: We will currently miss some cases where the redundant shuffling
19594 /// would simplify under the threshold for PSHUFB formation because of
19595 /// combine-ordering. To fix this, we should do the redundant instruction
19596 /// combining in this recursive walk.
19597 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19598                                           ArrayRef<int> RootMask,
19599                                           int Depth, bool HasPSHUFB,
19600                                           SelectionDAG &DAG,
19601                                           TargetLowering::DAGCombinerInfo &DCI,
19602                                           const X86Subtarget *Subtarget) {
19603   // Bound the depth of our recursive combine because this is ultimately
19604   // quadratic in nature.
19605   if (Depth > 8)
19606     return false;
19607
19608   // Directly rip through bitcasts to find the underlying operand.
19609   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19610     Op = Op.getOperand(0);
19611
19612   MVT VT = Op.getSimpleValueType();
19613   if (!VT.isVector())
19614     return false; // Bail if we hit a non-vector.
19615   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19616   // version should be added.
19617   if (VT.getSizeInBits() != 128)
19618     return false;
19619
19620   assert(Root.getSimpleValueType().isVector() &&
19621          "Shuffles operate on vector types!");
19622   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19623          "Can only combine shuffles of the same vector register size.");
19624
19625   if (!isTargetShuffle(Op.getOpcode()))
19626     return false;
19627   SmallVector<int, 16> OpMask;
19628   bool IsUnary;
19629   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19630   // We only can combine unary shuffles which we can decode the mask for.
19631   if (!HaveMask || !IsUnary)
19632     return false;
19633
19634   assert(VT.getVectorNumElements() == OpMask.size() &&
19635          "Different mask size from vector size!");
19636   assert(((RootMask.size() > OpMask.size() &&
19637            RootMask.size() % OpMask.size() == 0) ||
19638           (OpMask.size() > RootMask.size() &&
19639            OpMask.size() % RootMask.size() == 0) ||
19640           OpMask.size() == RootMask.size()) &&
19641          "The smaller number of elements must divide the larger.");
19642   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
19643   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
19644   assert(((RootRatio == 1 && OpRatio == 1) ||
19645           (RootRatio == 1) != (OpRatio == 1)) &&
19646          "Must not have a ratio for both incoming and op masks!");
19647
19648   SmallVector<int, 16> Mask;
19649   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
19650
19651   // Merge this shuffle operation's mask into our accumulated mask. Note that
19652   // this shuffle's mask will be the first applied to the input, followed by the
19653   // root mask to get us all the way to the root value arrangement. The reason
19654   // for this order is that we are recursing up the operation chain.
19655   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
19656     int RootIdx = i / RootRatio;
19657     if (RootMask[RootIdx] == SM_SentinelZero) {
19658       // This is a zero-ed lane, we're done.
19659       Mask.push_back(SM_SentinelZero);
19660       continue;
19661     }
19662
19663     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
19664     int OpIdx = RootMaskedIdx / OpRatio;
19665     if (OpMask[OpIdx] == SM_SentinelZero) {
19666       // The incoming lanes are zero, it doesn't matter which ones we are using.
19667       Mask.push_back(SM_SentinelZero);
19668       continue;
19669     }
19670
19671     // Ok, we have non-zero lanes, map them through.
19672     Mask.push_back(OpMask[OpIdx] * OpRatio +
19673                    RootMaskedIdx % OpRatio);
19674   }
19675
19676   // See if we can recurse into the operand to combine more things.
19677   switch (Op.getOpcode()) {
19678     case X86ISD::PSHUFB:
19679       HasPSHUFB = true;
19680     case X86ISD::PSHUFD:
19681     case X86ISD::PSHUFHW:
19682     case X86ISD::PSHUFLW:
19683       if (Op.getOperand(0).hasOneUse() &&
19684           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19685                                         HasPSHUFB, DAG, DCI, Subtarget))
19686         return true;
19687       break;
19688
19689     case X86ISD::UNPCKL:
19690     case X86ISD::UNPCKH:
19691       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19692       // We can't check for single use, we have to check that this shuffle is the only user.
19693       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19694           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19695                                         HasPSHUFB, DAG, DCI, Subtarget))
19696           return true;
19697       break;
19698   }
19699
19700   // Minor canonicalization of the accumulated shuffle mask to make it easier
19701   // to match below. All this does is detect masks with squential pairs of
19702   // elements, and shrink them to the half-width mask. It does this in a loop
19703   // so it will reduce the size of the mask to the minimal width mask which
19704   // performs an equivalent shuffle.
19705   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
19706     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
19707       Mask[i] = Mask[2 * i] / 2;
19708     Mask.resize(Mask.size() / 2);
19709   }
19710
19711   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19712                                 Subtarget);
19713 }
19714
19715 /// \brief Get the PSHUF-style mask from PSHUF node.
19716 ///
19717 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19718 /// PSHUF-style masks that can be reused with such instructions.
19719 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19720   SmallVector<int, 4> Mask;
19721   bool IsUnary;
19722   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19723   (void)HaveMask;
19724   assert(HaveMask);
19725
19726   switch (N.getOpcode()) {
19727   case X86ISD::PSHUFD:
19728     return Mask;
19729   case X86ISD::PSHUFLW:
19730     Mask.resize(4);
19731     return Mask;
19732   case X86ISD::PSHUFHW:
19733     Mask.erase(Mask.begin(), Mask.begin() + 4);
19734     for (int &M : Mask)
19735       M -= 4;
19736     return Mask;
19737   default:
19738     llvm_unreachable("No valid shuffle instruction found!");
19739   }
19740 }
19741
19742 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19743 ///
19744 /// We walk up the chain and look for a combinable shuffle, skipping over
19745 /// shuffles that we could hoist this shuffle's transformation past without
19746 /// altering anything.
19747 static SDValue
19748 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19749                              SelectionDAG &DAG,
19750                              TargetLowering::DAGCombinerInfo &DCI) {
19751   assert(N.getOpcode() == X86ISD::PSHUFD &&
19752          "Called with something other than an x86 128-bit half shuffle!");
19753   SDLoc DL(N);
19754
19755   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
19756   // of the shuffles in the chain so that we can form a fresh chain to replace
19757   // this one.
19758   SmallVector<SDValue, 8> Chain;
19759   SDValue V = N.getOperand(0);
19760   for (; V.hasOneUse(); V = V.getOperand(0)) {
19761     switch (V.getOpcode()) {
19762     default:
19763       return SDValue(); // Nothing combined!
19764
19765     case ISD::BITCAST:
19766       // Skip bitcasts as we always know the type for the target specific
19767       // instructions.
19768       continue;
19769
19770     case X86ISD::PSHUFD:
19771       // Found another dword shuffle.
19772       break;
19773
19774     case X86ISD::PSHUFLW:
19775       // Check that the low words (being shuffled) are the identity in the
19776       // dword shuffle, and the high words are self-contained.
19777       if (Mask[0] != 0 || Mask[1] != 1 ||
19778           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19779         return SDValue();
19780
19781       Chain.push_back(V);
19782       continue;
19783
19784     case X86ISD::PSHUFHW:
19785       // Check that the high words (being shuffled) are the identity in the
19786       // dword shuffle, and the low words are self-contained.
19787       if (Mask[2] != 2 || Mask[3] != 3 ||
19788           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19789         return SDValue();
19790
19791       Chain.push_back(V);
19792       continue;
19793
19794     case X86ISD::UNPCKL:
19795     case X86ISD::UNPCKH:
19796       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19797       // shuffle into a preceding word shuffle.
19798       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19799         return SDValue();
19800
19801       // Search for a half-shuffle which we can combine with.
19802       unsigned CombineOp =
19803           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19804       if (V.getOperand(0) != V.getOperand(1) ||
19805           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19806         return SDValue();
19807       Chain.push_back(V);
19808       V = V.getOperand(0);
19809       do {
19810         switch (V.getOpcode()) {
19811         default:
19812           return SDValue(); // Nothing to combine.
19813
19814         case X86ISD::PSHUFLW:
19815         case X86ISD::PSHUFHW:
19816           if (V.getOpcode() == CombineOp)
19817             break;
19818
19819           Chain.push_back(V);
19820
19821           // Fallthrough!
19822         case ISD::BITCAST:
19823           V = V.getOperand(0);
19824           continue;
19825         }
19826         break;
19827       } while (V.hasOneUse());
19828       break;
19829     }
19830     // Break out of the loop if we break out of the switch.
19831     break;
19832   }
19833
19834   if (!V.hasOneUse())
19835     // We fell out of the loop without finding a viable combining instruction.
19836     return SDValue();
19837
19838   // Merge this node's mask and our incoming mask.
19839   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19840   for (int &M : Mask)
19841     M = VMask[M];
19842   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19843                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19844
19845   // Rebuild the chain around this new shuffle.
19846   while (!Chain.empty()) {
19847     SDValue W = Chain.pop_back_val();
19848
19849     if (V.getValueType() != W.getOperand(0).getValueType())
19850       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
19851
19852     switch (W.getOpcode()) {
19853     default:
19854       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
19855
19856     case X86ISD::UNPCKL:
19857     case X86ISD::UNPCKH:
19858       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
19859       break;
19860
19861     case X86ISD::PSHUFD:
19862     case X86ISD::PSHUFLW:
19863     case X86ISD::PSHUFHW:
19864       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
19865       break;
19866     }
19867   }
19868   if (V.getValueType() != N.getValueType())
19869     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
19870
19871   // Return the new chain to replace N.
19872   return V;
19873 }
19874
19875 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19876 ///
19877 /// We walk up the chain, skipping shuffles of the other half and looking
19878 /// through shuffles which switch halves trying to find a shuffle of the same
19879 /// pair of dwords.
19880 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19881                                         SelectionDAG &DAG,
19882                                         TargetLowering::DAGCombinerInfo &DCI) {
19883   assert(
19884       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19885       "Called with something other than an x86 128-bit half shuffle!");
19886   SDLoc DL(N);
19887   unsigned CombineOpcode = N.getOpcode();
19888
19889   // Walk up a single-use chain looking for a combinable shuffle.
19890   SDValue V = N.getOperand(0);
19891   for (; V.hasOneUse(); V = V.getOperand(0)) {
19892     switch (V.getOpcode()) {
19893     default:
19894       return false; // Nothing combined!
19895
19896     case ISD::BITCAST:
19897       // Skip bitcasts as we always know the type for the target specific
19898       // instructions.
19899       continue;
19900
19901     case X86ISD::PSHUFLW:
19902     case X86ISD::PSHUFHW:
19903       if (V.getOpcode() == CombineOpcode)
19904         break;
19905
19906       // Other-half shuffles are no-ops.
19907       continue;
19908     }
19909     // Break out of the loop if we break out of the switch.
19910     break;
19911   }
19912
19913   if (!V.hasOneUse())
19914     // We fell out of the loop without finding a viable combining instruction.
19915     return false;
19916
19917   // Combine away the bottom node as its shuffle will be accumulated into
19918   // a preceding shuffle.
19919   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19920
19921   // Record the old value.
19922   SDValue Old = V;
19923
19924   // Merge this node's mask and our incoming mask (adjusted to account for all
19925   // the pshufd instructions encountered).
19926   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19927   for (int &M : Mask)
19928     M = VMask[M];
19929   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19930                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19931
19932   // Check that the shuffles didn't cancel each other out. If not, we need to
19933   // combine to the new one.
19934   if (Old != V)
19935     // Replace the combinable shuffle with the combined one, updating all users
19936     // so that we re-evaluate the chain here.
19937     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19938
19939   return true;
19940 }
19941
19942 /// \brief Try to combine x86 target specific shuffles.
19943 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19944                                            TargetLowering::DAGCombinerInfo &DCI,
19945                                            const X86Subtarget *Subtarget) {
19946   SDLoc DL(N);
19947   MVT VT = N.getSimpleValueType();
19948   SmallVector<int, 4> Mask;
19949
19950   switch (N.getOpcode()) {
19951   case X86ISD::PSHUFD:
19952   case X86ISD::PSHUFLW:
19953   case X86ISD::PSHUFHW:
19954     Mask = getPSHUFShuffleMask(N);
19955     assert(Mask.size() == 4);
19956     break;
19957   default:
19958     return SDValue();
19959   }
19960
19961   // Nuke no-op shuffles that show up after combining.
19962   if (isNoopShuffleMask(Mask))
19963     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19964
19965   // Look for simplifications involving one or two shuffle instructions.
19966   SDValue V = N.getOperand(0);
19967   switch (N.getOpcode()) {
19968   default:
19969     break;
19970   case X86ISD::PSHUFLW:
19971   case X86ISD::PSHUFHW:
19972     assert(VT == MVT::v8i16);
19973     (void)VT;
19974
19975     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19976       return SDValue(); // We combined away this shuffle, so we're done.
19977
19978     // See if this reduces to a PSHUFD which is no more expensive and can
19979     // combine with more operations.
19980     if (canWidenShuffleElements(Mask)) {
19981       int DMask[] = {-1, -1, -1, -1};
19982       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19983       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19984       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19985       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19986       DCI.AddToWorklist(V.getNode());
19987       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19988                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19989       DCI.AddToWorklist(V.getNode());
19990       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19991     }
19992
19993     // Look for shuffle patterns which can be implemented as a single unpack.
19994     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19995     // only works when we have a PSHUFD followed by two half-shuffles.
19996     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19997         (V.getOpcode() == X86ISD::PSHUFLW ||
19998          V.getOpcode() == X86ISD::PSHUFHW) &&
19999         V.getOpcode() != N.getOpcode() &&
20000         V.hasOneUse()) {
20001       SDValue D = V.getOperand(0);
20002       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20003         D = D.getOperand(0);
20004       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20005         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20006         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20007         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20008         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20009         int WordMask[8];
20010         for (int i = 0; i < 4; ++i) {
20011           WordMask[i + NOffset] = Mask[i] + NOffset;
20012           WordMask[i + VOffset] = VMask[i] + VOffset;
20013         }
20014         // Map the word mask through the DWord mask.
20015         int MappedMask[8];
20016         for (int i = 0; i < 8; ++i)
20017           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20018         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
20019         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
20020         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
20021                        std::begin(UnpackLoMask)) ||
20022             std::equal(std::begin(MappedMask), std::end(MappedMask),
20023                        std::begin(UnpackHiMask))) {
20024           // We can replace all three shuffles with an unpack.
20025           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
20026           DCI.AddToWorklist(V.getNode());
20027           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20028                                                 : X86ISD::UNPCKH,
20029                              DL, MVT::v8i16, V, V);
20030         }
20031       }
20032     }
20033
20034     break;
20035
20036   case X86ISD::PSHUFD:
20037     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20038       return NewN;
20039
20040     break;
20041   }
20042
20043   return SDValue();
20044 }
20045
20046 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20047 ///
20048 /// We combine this directly on the abstract vector shuffle nodes so it is
20049 /// easier to generically match. We also insert dummy vector shuffle nodes for
20050 /// the operands which explicitly discard the lanes which are unused by this
20051 /// operation to try to flow through the rest of the combiner the fact that
20052 /// they're unused.
20053 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20054   SDLoc DL(N);
20055   EVT VT = N->getValueType(0);
20056
20057   // We only handle target-independent shuffles.
20058   // FIXME: It would be easy and harmless to use the target shuffle mask
20059   // extraction tool to support more.
20060   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20061     return SDValue();
20062
20063   auto *SVN = cast<ShuffleVectorSDNode>(N);
20064   ArrayRef<int> Mask = SVN->getMask();
20065   SDValue V1 = N->getOperand(0);
20066   SDValue V2 = N->getOperand(1);
20067
20068   // We require the first shuffle operand to be the SUB node, and the second to
20069   // be the ADD node.
20070   // FIXME: We should support the commuted patterns.
20071   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20072     return SDValue();
20073
20074   // If there are other uses of these operations we can't fold them.
20075   if (!V1->hasOneUse() || !V2->hasOneUse())
20076     return SDValue();
20077
20078   // Ensure that both operations have the same operands. Note that we can
20079   // commute the FADD operands.
20080   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20081   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20082       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20083     return SDValue();
20084
20085   // We're looking for blends between FADD and FSUB nodes. We insist on these
20086   // nodes being lined up in a specific expected pattern.
20087   if (!(isShuffleEquivalent(Mask, 0, 3) ||
20088         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
20089         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
20090     return SDValue();
20091
20092   // Only specific types are legal at this point, assert so we notice if and
20093   // when these change.
20094   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20095           VT == MVT::v4f64) &&
20096          "Unknown vector type encountered!");
20097
20098   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20099 }
20100
20101 /// PerformShuffleCombine - Performs several different shuffle combines.
20102 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20103                                      TargetLowering::DAGCombinerInfo &DCI,
20104                                      const X86Subtarget *Subtarget) {
20105   SDLoc dl(N);
20106   SDValue N0 = N->getOperand(0);
20107   SDValue N1 = N->getOperand(1);
20108   EVT VT = N->getValueType(0);
20109
20110   // Don't create instructions with illegal types after legalize types has run.
20111   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20112   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20113     return SDValue();
20114
20115   // If we have legalized the vector types, look for blends of FADD and FSUB
20116   // nodes that we can fuse into an ADDSUB node.
20117   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20118     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20119       return AddSub;
20120
20121   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20122   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20123       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20124     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20125
20126   // During Type Legalization, when promoting illegal vector types,
20127   // the backend might introduce new shuffle dag nodes and bitcasts.
20128   //
20129   // This code performs the following transformation:
20130   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20131   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20132   //
20133   // We do this only if both the bitcast and the BINOP dag nodes have
20134   // one use. Also, perform this transformation only if the new binary
20135   // operation is legal. This is to avoid introducing dag nodes that
20136   // potentially need to be further expanded (or custom lowered) into a
20137   // less optimal sequence of dag nodes.
20138   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20139       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20140       N0.getOpcode() == ISD::BITCAST) {
20141     SDValue BC0 = N0.getOperand(0);
20142     EVT SVT = BC0.getValueType();
20143     unsigned Opcode = BC0.getOpcode();
20144     unsigned NumElts = VT.getVectorNumElements();
20145     
20146     if (BC0.hasOneUse() && SVT.isVector() &&
20147         SVT.getVectorNumElements() * 2 == NumElts &&
20148         TLI.isOperationLegal(Opcode, VT)) {
20149       bool CanFold = false;
20150       switch (Opcode) {
20151       default : break;
20152       case ISD::ADD :
20153       case ISD::FADD :
20154       case ISD::SUB :
20155       case ISD::FSUB :
20156       case ISD::MUL :
20157       case ISD::FMUL :
20158         CanFold = true;
20159       }
20160
20161       unsigned SVTNumElts = SVT.getVectorNumElements();
20162       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20163       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20164         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20165       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20166         CanFold = SVOp->getMaskElt(i) < 0;
20167
20168       if (CanFold) {
20169         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20170         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20171         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20172         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20173       }
20174     }
20175   }
20176
20177   // Only handle 128 wide vector from here on.
20178   if (!VT.is128BitVector())
20179     return SDValue();
20180
20181   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20182   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20183   // consecutive, non-overlapping, and in the right order.
20184   SmallVector<SDValue, 16> Elts;
20185   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20186     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20187
20188   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20189   if (LD.getNode())
20190     return LD;
20191
20192   if (isTargetShuffle(N->getOpcode())) {
20193     SDValue Shuffle =
20194         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20195     if (Shuffle.getNode())
20196       return Shuffle;
20197
20198     // Try recursively combining arbitrary sequences of x86 shuffle
20199     // instructions into higher-order shuffles. We do this after combining
20200     // specific PSHUF instruction sequences into their minimal form so that we
20201     // can evaluate how many specialized shuffle instructions are involved in
20202     // a particular chain.
20203     SmallVector<int, 1> NonceMask; // Just a placeholder.
20204     NonceMask.push_back(0);
20205     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20206                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20207                                       DCI, Subtarget))
20208       return SDValue(); // This routine will use CombineTo to replace N.
20209   }
20210
20211   return SDValue();
20212 }
20213
20214 /// PerformTruncateCombine - Converts truncate operation to
20215 /// a sequence of vector shuffle operations.
20216 /// It is possible when we truncate 256-bit vector to 128-bit vector
20217 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20218                                       TargetLowering::DAGCombinerInfo &DCI,
20219                                       const X86Subtarget *Subtarget)  {
20220   return SDValue();
20221 }
20222
20223 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20224 /// specific shuffle of a load can be folded into a single element load.
20225 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20226 /// shuffles have been customed lowered so we need to handle those here.
20227 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20228                                          TargetLowering::DAGCombinerInfo &DCI) {
20229   if (DCI.isBeforeLegalizeOps())
20230     return SDValue();
20231
20232   SDValue InVec = N->getOperand(0);
20233   SDValue EltNo = N->getOperand(1);
20234
20235   if (!isa<ConstantSDNode>(EltNo))
20236     return SDValue();
20237
20238   EVT VT = InVec.getValueType();
20239
20240   if (InVec.getOpcode() == ISD::BITCAST) {
20241     // Don't duplicate a load with other uses.
20242     if (!InVec.hasOneUse())
20243       return SDValue();
20244     EVT BCVT = InVec.getOperand(0).getValueType();
20245     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
20246       return SDValue();
20247     InVec = InVec.getOperand(0);
20248   }
20249
20250   if (!isTargetShuffle(InVec.getOpcode()))
20251     return SDValue();
20252
20253   // Don't duplicate a load with other uses.
20254   if (!InVec.hasOneUse())
20255     return SDValue();
20256
20257   SmallVector<int, 16> ShuffleMask;
20258   bool UnaryShuffle;
20259   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
20260                             UnaryShuffle))
20261     return SDValue();
20262
20263   // Select the input vector, guarding against out of range extract vector.
20264   unsigned NumElems = VT.getVectorNumElements();
20265   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20266   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20267   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20268                                          : InVec.getOperand(1);
20269
20270   // If inputs to shuffle are the same for both ops, then allow 2 uses
20271   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20272
20273   if (LdNode.getOpcode() == ISD::BITCAST) {
20274     // Don't duplicate a load with other uses.
20275     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20276       return SDValue();
20277
20278     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20279     LdNode = LdNode.getOperand(0);
20280   }
20281
20282   if (!ISD::isNormalLoad(LdNode.getNode()))
20283     return SDValue();
20284
20285   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20286
20287   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20288     return SDValue();
20289
20290   EVT EltVT = N->getValueType(0);
20291   // If there's a bitcast before the shuffle, check if the load type and
20292   // alignment is valid.
20293   unsigned Align = LN0->getAlignment();
20294   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20295   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
20296       EltVT.getTypeForEVT(*DAG.getContext()));
20297
20298   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
20299     return SDValue();
20300
20301   // All checks match so transform back to vector_shuffle so that DAG combiner
20302   // can finish the job
20303   SDLoc dl(N);
20304
20305   // Create shuffle node taking into account the case that its a unary shuffle
20306   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
20307   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
20308                                  InVec.getOperand(0), Shuffle,
20309                                  &ShuffleMask[0]);
20310   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
20311   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
20312                      EltNo);
20313 }
20314
20315 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
20316 /// generation and convert it from being a bunch of shuffles and extracts
20317 /// to a simple store and scalar loads to extract the elements.
20318 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
20319                                          TargetLowering::DAGCombinerInfo &DCI) {
20320   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
20321   if (NewOp.getNode())
20322     return NewOp;
20323
20324   SDValue InputVector = N->getOperand(0);
20325
20326   // Detect whether we are trying to convert from mmx to i32 and the bitcast
20327   // from mmx to v2i32 has a single usage.
20328   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
20329       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
20330       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
20331     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
20332                        N->getValueType(0),
20333                        InputVector.getNode()->getOperand(0));
20334
20335   // Only operate on vectors of 4 elements, where the alternative shuffling
20336   // gets to be more expensive.
20337   if (InputVector.getValueType() != MVT::v4i32)
20338     return SDValue();
20339
20340   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
20341   // single use which is a sign-extend or zero-extend, and all elements are
20342   // used.
20343   SmallVector<SDNode *, 4> Uses;
20344   unsigned ExtractedElements = 0;
20345   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
20346        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
20347     if (UI.getUse().getResNo() != InputVector.getResNo())
20348       return SDValue();
20349
20350     SDNode *Extract = *UI;
20351     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
20352       return SDValue();
20353
20354     if (Extract->getValueType(0) != MVT::i32)
20355       return SDValue();
20356     if (!Extract->hasOneUse())
20357       return SDValue();
20358     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
20359         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
20360       return SDValue();
20361     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
20362       return SDValue();
20363
20364     // Record which element was extracted.
20365     ExtractedElements |=
20366       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
20367
20368     Uses.push_back(Extract);
20369   }
20370
20371   // If not all the elements were used, this may not be worthwhile.
20372   if (ExtractedElements != 15)
20373     return SDValue();
20374
20375   // Ok, we've now decided to do the transformation.
20376   SDLoc dl(InputVector);
20377
20378   // Store the value to a temporary stack slot.
20379   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
20380   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
20381                             MachinePointerInfo(), false, false, 0);
20382
20383   // Replace each use (extract) with a load of the appropriate element.
20384   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
20385        UE = Uses.end(); UI != UE; ++UI) {
20386     SDNode *Extract = *UI;
20387
20388     // cOMpute the element's address.
20389     SDValue Idx = Extract->getOperand(1);
20390     unsigned EltSize =
20391         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
20392     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
20393     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20394     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
20395
20396     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
20397                                      StackPtr, OffsetVal);
20398
20399     // Load the scalar.
20400     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
20401                                      ScalarAddr, MachinePointerInfo(),
20402                                      false, false, false, 0);
20403
20404     // Replace the exact with the load.
20405     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
20406   }
20407
20408   // The replacement was made in place; don't return anything.
20409   return SDValue();
20410 }
20411
20412 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
20413 static std::pair<unsigned, bool>
20414 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
20415                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
20416   if (!VT.isVector())
20417     return std::make_pair(0, false);
20418
20419   bool NeedSplit = false;
20420   switch (VT.getSimpleVT().SimpleTy) {
20421   default: return std::make_pair(0, false);
20422   case MVT::v32i8:
20423   case MVT::v16i16:
20424   case MVT::v8i32:
20425     if (!Subtarget->hasAVX2())
20426       NeedSplit = true;
20427     if (!Subtarget->hasAVX())
20428       return std::make_pair(0, false);
20429     break;
20430   case MVT::v16i8:
20431   case MVT::v8i16:
20432   case MVT::v4i32:
20433     if (!Subtarget->hasSSE2())
20434       return std::make_pair(0, false);
20435   }
20436
20437   // SSE2 has only a small subset of the operations.
20438   bool hasUnsigned = Subtarget->hasSSE41() ||
20439                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
20440   bool hasSigned = Subtarget->hasSSE41() ||
20441                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
20442
20443   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20444
20445   unsigned Opc = 0;
20446   // Check for x CC y ? x : y.
20447   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20448       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20449     switch (CC) {
20450     default: break;
20451     case ISD::SETULT:
20452     case ISD::SETULE:
20453       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20454     case ISD::SETUGT:
20455     case ISD::SETUGE:
20456       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20457     case ISD::SETLT:
20458     case ISD::SETLE:
20459       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20460     case ISD::SETGT:
20461     case ISD::SETGE:
20462       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20463     }
20464   // Check for x CC y ? y : x -- a min/max with reversed arms.
20465   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20466              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20467     switch (CC) {
20468     default: break;
20469     case ISD::SETULT:
20470     case ISD::SETULE:
20471       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
20472     case ISD::SETUGT:
20473     case ISD::SETUGE:
20474       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
20475     case ISD::SETLT:
20476     case ISD::SETLE:
20477       Opc = hasSigned ? X86ISD::SMAX : 0; break;
20478     case ISD::SETGT:
20479     case ISD::SETGE:
20480       Opc = hasSigned ? X86ISD::SMIN : 0; break;
20481     }
20482   }
20483
20484   return std::make_pair(Opc, NeedSplit);
20485 }
20486
20487 static SDValue
20488 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
20489                                       const X86Subtarget *Subtarget) {
20490   SDLoc dl(N);
20491   SDValue Cond = N->getOperand(0);
20492   SDValue LHS = N->getOperand(1);
20493   SDValue RHS = N->getOperand(2);
20494
20495   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
20496     SDValue CondSrc = Cond->getOperand(0);
20497     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
20498       Cond = CondSrc->getOperand(0);
20499   }
20500
20501   MVT VT = N->getSimpleValueType(0);
20502   MVT EltVT = VT.getVectorElementType();
20503   unsigned NumElems = VT.getVectorNumElements();
20504   // There is no blend with immediate in AVX-512.
20505   if (VT.is512BitVector())
20506     return SDValue();
20507
20508   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
20509     return SDValue();
20510   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
20511     return SDValue();
20512
20513   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
20514     return SDValue();
20515
20516   // A vselect where all conditions and data are constants can be optimized into
20517   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
20518   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
20519       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
20520     return SDValue();
20521
20522   unsigned MaskValue = 0;
20523   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
20524     return SDValue();
20525
20526   SmallVector<int, 8> ShuffleMask(NumElems, -1);
20527   for (unsigned i = 0; i < NumElems; ++i) {
20528     // Be sure we emit undef where we can.
20529     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
20530       ShuffleMask[i] = -1;
20531     else
20532       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
20533   }
20534
20535   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
20536 }
20537
20538 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
20539 /// nodes.
20540 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
20541                                     TargetLowering::DAGCombinerInfo &DCI,
20542                                     const X86Subtarget *Subtarget) {
20543   SDLoc DL(N);
20544   SDValue Cond = N->getOperand(0);
20545   // Get the LHS/RHS of the select.
20546   SDValue LHS = N->getOperand(1);
20547   SDValue RHS = N->getOperand(2);
20548   EVT VT = LHS.getValueType();
20549   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20550
20551   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
20552   // instructions match the semantics of the common C idiom x<y?x:y but not
20553   // x<=y?x:y, because of how they handle negative zero (which can be
20554   // ignored in unsafe-math mode).
20555   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
20556       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
20557       (Subtarget->hasSSE2() ||
20558        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
20559     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20560
20561     unsigned Opcode = 0;
20562     // Check for x CC y ? x : y.
20563     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20564         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20565       switch (CC) {
20566       default: break;
20567       case ISD::SETULT:
20568         // Converting this to a min would handle NaNs incorrectly, and swapping
20569         // the operands would cause it to handle comparisons between positive
20570         // and negative zero incorrectly.
20571         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20572           if (!DAG.getTarget().Options.UnsafeFPMath &&
20573               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20574             break;
20575           std::swap(LHS, RHS);
20576         }
20577         Opcode = X86ISD::FMIN;
20578         break;
20579       case ISD::SETOLE:
20580         // Converting this to a min would handle comparisons between positive
20581         // and negative zero incorrectly.
20582         if (!DAG.getTarget().Options.UnsafeFPMath &&
20583             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20584           break;
20585         Opcode = X86ISD::FMIN;
20586         break;
20587       case ISD::SETULE:
20588         // Converting this to a min would handle both negative zeros and NaNs
20589         // incorrectly, but we can swap the operands to fix both.
20590         std::swap(LHS, RHS);
20591       case ISD::SETOLT:
20592       case ISD::SETLT:
20593       case ISD::SETLE:
20594         Opcode = X86ISD::FMIN;
20595         break;
20596
20597       case ISD::SETOGE:
20598         // Converting this to a max would handle comparisons between positive
20599         // and negative zero incorrectly.
20600         if (!DAG.getTarget().Options.UnsafeFPMath &&
20601             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20602           break;
20603         Opcode = X86ISD::FMAX;
20604         break;
20605       case ISD::SETUGT:
20606         // Converting this to a max would handle NaNs incorrectly, and swapping
20607         // the operands would cause it to handle comparisons between positive
20608         // and negative zero incorrectly.
20609         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20610           if (!DAG.getTarget().Options.UnsafeFPMath &&
20611               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20612             break;
20613           std::swap(LHS, RHS);
20614         }
20615         Opcode = X86ISD::FMAX;
20616         break;
20617       case ISD::SETUGE:
20618         // Converting this to a max would handle both negative zeros and NaNs
20619         // incorrectly, but we can swap the operands to fix both.
20620         std::swap(LHS, RHS);
20621       case ISD::SETOGT:
20622       case ISD::SETGT:
20623       case ISD::SETGE:
20624         Opcode = X86ISD::FMAX;
20625         break;
20626       }
20627     // Check for x CC y ? y : x -- a min/max with reversed arms.
20628     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20629                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20630       switch (CC) {
20631       default: break;
20632       case ISD::SETOGE:
20633         // Converting this to a min would handle comparisons between positive
20634         // and negative zero incorrectly, and swapping the operands would
20635         // cause it to handle NaNs incorrectly.
20636         if (!DAG.getTarget().Options.UnsafeFPMath &&
20637             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20638           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20639             break;
20640           std::swap(LHS, RHS);
20641         }
20642         Opcode = X86ISD::FMIN;
20643         break;
20644       case ISD::SETUGT:
20645         // Converting this to a min would handle NaNs incorrectly.
20646         if (!DAG.getTarget().Options.UnsafeFPMath &&
20647             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20648           break;
20649         Opcode = X86ISD::FMIN;
20650         break;
20651       case ISD::SETUGE:
20652         // Converting this to a min would handle both negative zeros and NaNs
20653         // incorrectly, but we can swap the operands to fix both.
20654         std::swap(LHS, RHS);
20655       case ISD::SETOGT:
20656       case ISD::SETGT:
20657       case ISD::SETGE:
20658         Opcode = X86ISD::FMIN;
20659         break;
20660
20661       case ISD::SETULT:
20662         // Converting this to a max would handle NaNs incorrectly.
20663         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20664           break;
20665         Opcode = X86ISD::FMAX;
20666         break;
20667       case ISD::SETOLE:
20668         // Converting this to a max would handle comparisons between positive
20669         // and negative zero incorrectly, and swapping the operands would
20670         // cause it to handle NaNs incorrectly.
20671         if (!DAG.getTarget().Options.UnsafeFPMath &&
20672             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20673           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20674             break;
20675           std::swap(LHS, RHS);
20676         }
20677         Opcode = X86ISD::FMAX;
20678         break;
20679       case ISD::SETULE:
20680         // Converting this to a max would handle both negative zeros and NaNs
20681         // incorrectly, but we can swap the operands to fix both.
20682         std::swap(LHS, RHS);
20683       case ISD::SETOLT:
20684       case ISD::SETLT:
20685       case ISD::SETLE:
20686         Opcode = X86ISD::FMAX;
20687         break;
20688       }
20689     }
20690
20691     if (Opcode)
20692       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20693   }
20694
20695   EVT CondVT = Cond.getValueType();
20696   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20697       CondVT.getVectorElementType() == MVT::i1) {
20698     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20699     // lowering on KNL. In this case we convert it to
20700     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20701     // The same situation for all 128 and 256-bit vectors of i8 and i16.
20702     // Since SKX these selects have a proper lowering.
20703     EVT OpVT = LHS.getValueType();
20704     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20705         (OpVT.getVectorElementType() == MVT::i8 ||
20706          OpVT.getVectorElementType() == MVT::i16) &&
20707         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
20708       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20709       DCI.AddToWorklist(Cond.getNode());
20710       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20711     }
20712   }
20713   // If this is a select between two integer constants, try to do some
20714   // optimizations.
20715   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20716     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20717       // Don't do this for crazy integer types.
20718       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20719         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20720         // so that TrueC (the true value) is larger than FalseC.
20721         bool NeedsCondInvert = false;
20722
20723         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20724             // Efficiently invertible.
20725             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20726              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20727               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20728           NeedsCondInvert = true;
20729           std::swap(TrueC, FalseC);
20730         }
20731
20732         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20733         if (FalseC->getAPIntValue() == 0 &&
20734             TrueC->getAPIntValue().isPowerOf2()) {
20735           if (NeedsCondInvert) // Invert the condition if needed.
20736             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20737                                DAG.getConstant(1, Cond.getValueType()));
20738
20739           // Zero extend the condition if needed.
20740           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20741
20742           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20743           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20744                              DAG.getConstant(ShAmt, MVT::i8));
20745         }
20746
20747         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20748         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20749           if (NeedsCondInvert) // Invert the condition if needed.
20750             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20751                                DAG.getConstant(1, Cond.getValueType()));
20752
20753           // Zero extend the condition if needed.
20754           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20755                              FalseC->getValueType(0), Cond);
20756           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20757                              SDValue(FalseC, 0));
20758         }
20759
20760         // Optimize cases that will turn into an LEA instruction.  This requires
20761         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20762         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20763           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20764           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20765
20766           bool isFastMultiplier = false;
20767           if (Diff < 10) {
20768             switch ((unsigned char)Diff) {
20769               default: break;
20770               case 1:  // result = add base, cond
20771               case 2:  // result = lea base(    , cond*2)
20772               case 3:  // result = lea base(cond, cond*2)
20773               case 4:  // result = lea base(    , cond*4)
20774               case 5:  // result = lea base(cond, cond*4)
20775               case 8:  // result = lea base(    , cond*8)
20776               case 9:  // result = lea base(cond, cond*8)
20777                 isFastMultiplier = true;
20778                 break;
20779             }
20780           }
20781
20782           if (isFastMultiplier) {
20783             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20784             if (NeedsCondInvert) // Invert the condition if needed.
20785               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20786                                  DAG.getConstant(1, Cond.getValueType()));
20787
20788             // Zero extend the condition if needed.
20789             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20790                                Cond);
20791             // Scale the condition by the difference.
20792             if (Diff != 1)
20793               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20794                                  DAG.getConstant(Diff, Cond.getValueType()));
20795
20796             // Add the base if non-zero.
20797             if (FalseC->getAPIntValue() != 0)
20798               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20799                                  SDValue(FalseC, 0));
20800             return Cond;
20801           }
20802         }
20803       }
20804   }
20805
20806   // Canonicalize max and min:
20807   // (x > y) ? x : y -> (x >= y) ? x : y
20808   // (x < y) ? x : y -> (x <= y) ? x : y
20809   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20810   // the need for an extra compare
20811   // against zero. e.g.
20812   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20813   // subl   %esi, %edi
20814   // testl  %edi, %edi
20815   // movl   $0, %eax
20816   // cmovgl %edi, %eax
20817   // =>
20818   // xorl   %eax, %eax
20819   // subl   %esi, $edi
20820   // cmovsl %eax, %edi
20821   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20822       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20823       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20824     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20825     switch (CC) {
20826     default: break;
20827     case ISD::SETLT:
20828     case ISD::SETGT: {
20829       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20830       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20831                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20832       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20833     }
20834     }
20835   }
20836
20837   // Early exit check
20838   if (!TLI.isTypeLegal(VT))
20839     return SDValue();
20840
20841   // Match VSELECTs into subs with unsigned saturation.
20842   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20843       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20844       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20845        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20846     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20847
20848     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20849     // left side invert the predicate to simplify logic below.
20850     SDValue Other;
20851     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20852       Other = RHS;
20853       CC = ISD::getSetCCInverse(CC, true);
20854     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20855       Other = LHS;
20856     }
20857
20858     if (Other.getNode() && Other->getNumOperands() == 2 &&
20859         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20860       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20861       SDValue CondRHS = Cond->getOperand(1);
20862
20863       // Look for a general sub with unsigned saturation first.
20864       // x >= y ? x-y : 0 --> subus x, y
20865       // x >  y ? x-y : 0 --> subus x, y
20866       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20867           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20868         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20869
20870       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20871         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20872           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20873             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20874               // If the RHS is a constant we have to reverse the const
20875               // canonicalization.
20876               // x > C-1 ? x+-C : 0 --> subus x, C
20877               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20878                   CondRHSConst->getAPIntValue() ==
20879                       (-OpRHSConst->getAPIntValue() - 1))
20880                 return DAG.getNode(
20881                     X86ISD::SUBUS, DL, VT, OpLHS,
20882                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20883
20884           // Another special case: If C was a sign bit, the sub has been
20885           // canonicalized into a xor.
20886           // FIXME: Would it be better to use computeKnownBits to determine
20887           //        whether it's safe to decanonicalize the xor?
20888           // x s< 0 ? x^C : 0 --> subus x, C
20889           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20890               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20891               OpRHSConst->getAPIntValue().isSignBit())
20892             // Note that we have to rebuild the RHS constant here to ensure we
20893             // don't rely on particular values of undef lanes.
20894             return DAG.getNode(
20895                 X86ISD::SUBUS, DL, VT, OpLHS,
20896                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20897         }
20898     }
20899   }
20900
20901   // Try to match a min/max vector operation.
20902   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20903     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20904     unsigned Opc = ret.first;
20905     bool NeedSplit = ret.second;
20906
20907     if (Opc && NeedSplit) {
20908       unsigned NumElems = VT.getVectorNumElements();
20909       // Extract the LHS vectors
20910       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20911       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20912
20913       // Extract the RHS vectors
20914       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20915       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20916
20917       // Create min/max for each subvector
20918       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20919       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20920
20921       // Merge the result
20922       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20923     } else if (Opc)
20924       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20925   }
20926
20927   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20928   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20929       // Check if SETCC has already been promoted
20930       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20931       // Check that condition value type matches vselect operand type
20932       CondVT == VT) { 
20933
20934     assert(Cond.getValueType().isVector() &&
20935            "vector select expects a vector selector!");
20936
20937     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20938     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20939
20940     if (!TValIsAllOnes && !FValIsAllZeros) {
20941       // Try invert the condition if true value is not all 1s and false value
20942       // is not all 0s.
20943       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20944       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20945
20946       if (TValIsAllZeros || FValIsAllOnes) {
20947         SDValue CC = Cond.getOperand(2);
20948         ISD::CondCode NewCC =
20949           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20950                                Cond.getOperand(0).getValueType().isInteger());
20951         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20952         std::swap(LHS, RHS);
20953         TValIsAllOnes = FValIsAllOnes;
20954         FValIsAllZeros = TValIsAllZeros;
20955       }
20956     }
20957
20958     if (TValIsAllOnes || FValIsAllZeros) {
20959       SDValue Ret;
20960
20961       if (TValIsAllOnes && FValIsAllZeros)
20962         Ret = Cond;
20963       else if (TValIsAllOnes)
20964         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20965                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20966       else if (FValIsAllZeros)
20967         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20968                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20969
20970       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20971     }
20972   }
20973
20974   // Try to fold this VSELECT into a MOVSS/MOVSD
20975   if (N->getOpcode() == ISD::VSELECT &&
20976       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20977     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20978         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20979       bool CanFold = false;
20980       unsigned NumElems = Cond.getNumOperands();
20981       SDValue A = LHS;
20982       SDValue B = RHS;
20983       
20984       if (isZero(Cond.getOperand(0))) {
20985         CanFold = true;
20986
20987         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20988         // fold (vselect <0,-1> -> (movsd A, B)
20989         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20990           CanFold = isAllOnes(Cond.getOperand(i));
20991       } else if (isAllOnes(Cond.getOperand(0))) {
20992         CanFold = true;
20993         std::swap(A, B);
20994
20995         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20996         // fold (vselect <-1,0> -> (movsd B, A)
20997         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20998           CanFold = isZero(Cond.getOperand(i));
20999       }
21000
21001       if (CanFold) {
21002         if (VT == MVT::v4i32 || VT == MVT::v4f32)
21003           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
21004         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
21005       }
21006
21007       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
21008         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
21009         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
21010         //                             (v2i64 (bitcast B)))))
21011         //
21012         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
21013         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
21014         //                             (v2f64 (bitcast B)))))
21015         //
21016         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
21017         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
21018         //                             (v2i64 (bitcast A)))))
21019         //
21020         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
21021         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
21022         //                             (v2f64 (bitcast A)))))
21023
21024         CanFold = (isZero(Cond.getOperand(0)) &&
21025                    isZero(Cond.getOperand(1)) &&
21026                    isAllOnes(Cond.getOperand(2)) &&
21027                    isAllOnes(Cond.getOperand(3)));
21028
21029         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
21030             isAllOnes(Cond.getOperand(1)) &&
21031             isZero(Cond.getOperand(2)) &&
21032             isZero(Cond.getOperand(3))) {
21033           CanFold = true;
21034           std::swap(LHS, RHS);
21035         }
21036
21037         if (CanFold) {
21038           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
21039           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
21040           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
21041           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
21042                                                 NewB, DAG);
21043           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
21044         }
21045       }
21046     }
21047   }
21048
21049   // If we know that this node is legal then we know that it is going to be
21050   // matched by one of the SSE/AVX BLEND instructions. These instructions only
21051   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
21052   // to simplify previous instructions.
21053   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21054       !DCI.isBeforeLegalize() &&
21055       // We explicitly check against v8i16 and v16i16 because, although
21056       // they're marked as Custom, they might only be legal when Cond is a
21057       // build_vector of constants. This will be taken care in a later
21058       // condition.
21059       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
21060        VT != MVT::v8i16)) {
21061     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21062
21063     // Don't optimize vector selects that map to mask-registers.
21064     if (BitWidth == 1)
21065       return SDValue();
21066
21067     // Check all uses of that condition operand to check whether it will be
21068     // consumed by non-BLEND instructions, which may depend on all bits are set
21069     // properly.
21070     for (SDNode::use_iterator I = Cond->use_begin(),
21071                               E = Cond->use_end(); I != E; ++I)
21072       if (I->getOpcode() != ISD::VSELECT)
21073         // TODO: Add other opcodes eventually lowered into BLEND.
21074         return SDValue();
21075
21076     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21077     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21078
21079     APInt KnownZero, KnownOne;
21080     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21081                                           DCI.isBeforeLegalizeOps());
21082     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21083         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
21084       DCI.CommitTargetLoweringOpt(TLO);
21085   }
21086
21087   // We should generate an X86ISD::BLENDI from a vselect if its argument
21088   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21089   // constants. This specific pattern gets generated when we split a
21090   // selector for a 512 bit vector in a machine without AVX512 (but with
21091   // 256-bit vectors), during legalization:
21092   //
21093   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21094   //
21095   // Iff we find this pattern and the build_vectors are built from
21096   // constants, we translate the vselect into a shuffle_vector that we
21097   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21098   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
21099     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21100     if (Shuffle.getNode())
21101       return Shuffle;
21102   }
21103
21104   return SDValue();
21105 }
21106
21107 // Check whether a boolean test is testing a boolean value generated by
21108 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21109 // code.
21110 //
21111 // Simplify the following patterns:
21112 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21113 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21114 // to (Op EFLAGS Cond)
21115 //
21116 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21117 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21118 // to (Op EFLAGS !Cond)
21119 //
21120 // where Op could be BRCOND or CMOV.
21121 //
21122 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21123   // Quit if not CMP and SUB with its value result used.
21124   if (Cmp.getOpcode() != X86ISD::CMP &&
21125       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21126       return SDValue();
21127
21128   // Quit if not used as a boolean value.
21129   if (CC != X86::COND_E && CC != X86::COND_NE)
21130     return SDValue();
21131
21132   // Check CMP operands. One of them should be 0 or 1 and the other should be
21133   // an SetCC or extended from it.
21134   SDValue Op1 = Cmp.getOperand(0);
21135   SDValue Op2 = Cmp.getOperand(1);
21136
21137   SDValue SetCC;
21138   const ConstantSDNode* C = nullptr;
21139   bool needOppositeCond = (CC == X86::COND_E);
21140   bool checkAgainstTrue = false; // Is it a comparison against 1?
21141
21142   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21143     SetCC = Op2;
21144   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21145     SetCC = Op1;
21146   else // Quit if all operands are not constants.
21147     return SDValue();
21148
21149   if (C->getZExtValue() == 1) {
21150     needOppositeCond = !needOppositeCond;
21151     checkAgainstTrue = true;
21152   } else if (C->getZExtValue() != 0)
21153     // Quit if the constant is neither 0 or 1.
21154     return SDValue();
21155
21156   bool truncatedToBoolWithAnd = false;
21157   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21158   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21159          SetCC.getOpcode() == ISD::TRUNCATE ||
21160          SetCC.getOpcode() == ISD::AND) {
21161     if (SetCC.getOpcode() == ISD::AND) {
21162       int OpIdx = -1;
21163       ConstantSDNode *CS;
21164       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21165           CS->getZExtValue() == 1)
21166         OpIdx = 1;
21167       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21168           CS->getZExtValue() == 1)
21169         OpIdx = 0;
21170       if (OpIdx == -1)
21171         break;
21172       SetCC = SetCC.getOperand(OpIdx);
21173       truncatedToBoolWithAnd = true;
21174     } else
21175       SetCC = SetCC.getOperand(0);
21176   }
21177
21178   switch (SetCC.getOpcode()) {
21179   case X86ISD::SETCC_CARRY:
21180     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21181     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21182     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21183     // truncated to i1 using 'and'.
21184     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21185       break;
21186     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21187            "Invalid use of SETCC_CARRY!");
21188     // FALL THROUGH
21189   case X86ISD::SETCC:
21190     // Set the condition code or opposite one if necessary.
21191     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21192     if (needOppositeCond)
21193       CC = X86::GetOppositeBranchCondition(CC);
21194     return SetCC.getOperand(1);
21195   case X86ISD::CMOV: {
21196     // Check whether false/true value has canonical one, i.e. 0 or 1.
21197     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21198     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21199     // Quit if true value is not a constant.
21200     if (!TVal)
21201       return SDValue();
21202     // Quit if false value is not a constant.
21203     if (!FVal) {
21204       SDValue Op = SetCC.getOperand(0);
21205       // Skip 'zext' or 'trunc' node.
21206       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21207           Op.getOpcode() == ISD::TRUNCATE)
21208         Op = Op.getOperand(0);
21209       // A special case for rdrand/rdseed, where 0 is set if false cond is
21210       // found.
21211       if ((Op.getOpcode() != X86ISD::RDRAND &&
21212            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21213         return SDValue();
21214     }
21215     // Quit if false value is not the constant 0 or 1.
21216     bool FValIsFalse = true;
21217     if (FVal && FVal->getZExtValue() != 0) {
21218       if (FVal->getZExtValue() != 1)
21219         return SDValue();
21220       // If FVal is 1, opposite cond is needed.
21221       needOppositeCond = !needOppositeCond;
21222       FValIsFalse = false;
21223     }
21224     // Quit if TVal is not the constant opposite of FVal.
21225     if (FValIsFalse && TVal->getZExtValue() != 1)
21226       return SDValue();
21227     if (!FValIsFalse && TVal->getZExtValue() != 0)
21228       return SDValue();
21229     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21230     if (needOppositeCond)
21231       CC = X86::GetOppositeBranchCondition(CC);
21232     return SetCC.getOperand(3);
21233   }
21234   }
21235
21236   return SDValue();
21237 }
21238
21239 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21240 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21241                                   TargetLowering::DAGCombinerInfo &DCI,
21242                                   const X86Subtarget *Subtarget) {
21243   SDLoc DL(N);
21244
21245   // If the flag operand isn't dead, don't touch this CMOV.
21246   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21247     return SDValue();
21248
21249   SDValue FalseOp = N->getOperand(0);
21250   SDValue TrueOp = N->getOperand(1);
21251   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21252   SDValue Cond = N->getOperand(3);
21253
21254   if (CC == X86::COND_E || CC == X86::COND_NE) {
21255     switch (Cond.getOpcode()) {
21256     default: break;
21257     case X86ISD::BSR:
21258     case X86ISD::BSF:
21259       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21260       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21261         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21262     }
21263   }
21264
21265   SDValue Flags;
21266
21267   Flags = checkBoolTestSetCCCombine(Cond, CC);
21268   if (Flags.getNode() &&
21269       // Extra check as FCMOV only supports a subset of X86 cond.
21270       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21271     SDValue Ops[] = { FalseOp, TrueOp,
21272                       DAG.getConstant(CC, MVT::i8), Flags };
21273     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21274   }
21275
21276   // If this is a select between two integer constants, try to do some
21277   // optimizations.  Note that the operands are ordered the opposite of SELECT
21278   // operands.
21279   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21280     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21281       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21282       // larger than FalseC (the false value).
21283       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21284         CC = X86::GetOppositeBranchCondition(CC);
21285         std::swap(TrueC, FalseC);
21286         std::swap(TrueOp, FalseOp);
21287       }
21288
21289       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21290       // This is efficient for any integer data type (including i8/i16) and
21291       // shift amount.
21292       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
21293         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21294                            DAG.getConstant(CC, MVT::i8), Cond);
21295
21296         // Zero extend the condition if needed.
21297         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
21298
21299         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21300         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
21301                            DAG.getConstant(ShAmt, MVT::i8));
21302         if (N->getNumValues() == 2)  // Dead flag value?
21303           return DCI.CombineTo(N, Cond, SDValue());
21304         return Cond;
21305       }
21306
21307       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
21308       // for any integer data type, including i8/i16.
21309       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21310         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21311                            DAG.getConstant(CC, MVT::i8), Cond);
21312
21313         // Zero extend the condition if needed.
21314         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21315                            FalseC->getValueType(0), Cond);
21316         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21317                            SDValue(FalseC, 0));
21318
21319         if (N->getNumValues() == 2)  // Dead flag value?
21320           return DCI.CombineTo(N, Cond, SDValue());
21321         return Cond;
21322       }
21323
21324       // Optimize cases that will turn into an LEA instruction.  This requires
21325       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21326       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21327         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21328         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21329
21330         bool isFastMultiplier = false;
21331         if (Diff < 10) {
21332           switch ((unsigned char)Diff) {
21333           default: break;
21334           case 1:  // result = add base, cond
21335           case 2:  // result = lea base(    , cond*2)
21336           case 3:  // result = lea base(cond, cond*2)
21337           case 4:  // result = lea base(    , cond*4)
21338           case 5:  // result = lea base(cond, cond*4)
21339           case 8:  // result = lea base(    , cond*8)
21340           case 9:  // result = lea base(cond, cond*8)
21341             isFastMultiplier = true;
21342             break;
21343           }
21344         }
21345
21346         if (isFastMultiplier) {
21347           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21348           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
21349                              DAG.getConstant(CC, MVT::i8), Cond);
21350           // Zero extend the condition if needed.
21351           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21352                              Cond);
21353           // Scale the condition by the difference.
21354           if (Diff != 1)
21355             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21356                                DAG.getConstant(Diff, Cond.getValueType()));
21357
21358           // Add the base if non-zero.
21359           if (FalseC->getAPIntValue() != 0)
21360             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21361                                SDValue(FalseC, 0));
21362           if (N->getNumValues() == 2)  // Dead flag value?
21363             return DCI.CombineTo(N, Cond, SDValue());
21364           return Cond;
21365         }
21366       }
21367     }
21368   }
21369
21370   // Handle these cases:
21371   //   (select (x != c), e, c) -> select (x != c), e, x),
21372   //   (select (x == c), c, e) -> select (x == c), x, e)
21373   // where the c is an integer constant, and the "select" is the combination
21374   // of CMOV and CMP.
21375   //
21376   // The rationale for this change is that the conditional-move from a constant
21377   // needs two instructions, however, conditional-move from a register needs
21378   // only one instruction.
21379   //
21380   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
21381   //  some instruction-combining opportunities. This opt needs to be
21382   //  postponed as late as possible.
21383   //
21384   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
21385     // the DCI.xxxx conditions are provided to postpone the optimization as
21386     // late as possible.
21387
21388     ConstantSDNode *CmpAgainst = nullptr;
21389     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
21390         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
21391         !isa<ConstantSDNode>(Cond.getOperand(0))) {
21392
21393       if (CC == X86::COND_NE &&
21394           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
21395         CC = X86::GetOppositeBranchCondition(CC);
21396         std::swap(TrueOp, FalseOp);
21397       }
21398
21399       if (CC == X86::COND_E &&
21400           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
21401         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
21402                           DAG.getConstant(CC, MVT::i8), Cond };
21403         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
21404       }
21405     }
21406   }
21407
21408   return SDValue();
21409 }
21410
21411 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
21412                                                 const X86Subtarget *Subtarget) {
21413   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
21414   switch (IntNo) {
21415   default: return SDValue();
21416   // SSE/AVX/AVX2 blend intrinsics.
21417   case Intrinsic::x86_avx2_pblendvb:
21418   case Intrinsic::x86_avx2_pblendw:
21419   case Intrinsic::x86_avx2_pblendd_128:
21420   case Intrinsic::x86_avx2_pblendd_256:
21421     // Don't try to simplify this intrinsic if we don't have AVX2.
21422     if (!Subtarget->hasAVX2())
21423       return SDValue();
21424     // FALL-THROUGH
21425   case Intrinsic::x86_avx_blend_pd_256:
21426   case Intrinsic::x86_avx_blend_ps_256:
21427   case Intrinsic::x86_avx_blendv_pd_256:
21428   case Intrinsic::x86_avx_blendv_ps_256:
21429     // Don't try to simplify this intrinsic if we don't have AVX.
21430     if (!Subtarget->hasAVX())
21431       return SDValue();
21432     // FALL-THROUGH
21433   case Intrinsic::x86_sse41_pblendw:
21434   case Intrinsic::x86_sse41_blendpd:
21435   case Intrinsic::x86_sse41_blendps:
21436   case Intrinsic::x86_sse41_blendvps:
21437   case Intrinsic::x86_sse41_blendvpd:
21438   case Intrinsic::x86_sse41_pblendvb: {
21439     SDValue Op0 = N->getOperand(1);
21440     SDValue Op1 = N->getOperand(2);
21441     SDValue Mask = N->getOperand(3);
21442
21443     // Don't try to simplify this intrinsic if we don't have SSE4.1.
21444     if (!Subtarget->hasSSE41())
21445       return SDValue();
21446
21447     // fold (blend A, A, Mask) -> A
21448     if (Op0 == Op1)
21449       return Op0;
21450     // fold (blend A, B, allZeros) -> A
21451     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
21452       return Op0;
21453     // fold (blend A, B, allOnes) -> B
21454     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
21455       return Op1;
21456     
21457     // Simplify the case where the mask is a constant i32 value.
21458     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
21459       if (C->isNullValue())
21460         return Op0;
21461       if (C->isAllOnesValue())
21462         return Op1;
21463     }
21464
21465     return SDValue();
21466   }
21467
21468   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
21469   case Intrinsic::x86_sse2_psrai_w:
21470   case Intrinsic::x86_sse2_psrai_d:
21471   case Intrinsic::x86_avx2_psrai_w:
21472   case Intrinsic::x86_avx2_psrai_d:
21473   case Intrinsic::x86_sse2_psra_w:
21474   case Intrinsic::x86_sse2_psra_d:
21475   case Intrinsic::x86_avx2_psra_w:
21476   case Intrinsic::x86_avx2_psra_d: {
21477     SDValue Op0 = N->getOperand(1);
21478     SDValue Op1 = N->getOperand(2);
21479     EVT VT = Op0.getValueType();
21480     assert(VT.isVector() && "Expected a vector type!");
21481
21482     if (isa<BuildVectorSDNode>(Op1))
21483       Op1 = Op1.getOperand(0);
21484
21485     if (!isa<ConstantSDNode>(Op1))
21486       return SDValue();
21487
21488     EVT SVT = VT.getVectorElementType();
21489     unsigned SVTBits = SVT.getSizeInBits();
21490
21491     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
21492     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
21493     uint64_t ShAmt = C.getZExtValue();
21494
21495     // Don't try to convert this shift into a ISD::SRA if the shift
21496     // count is bigger than or equal to the element size.
21497     if (ShAmt >= SVTBits)
21498       return SDValue();
21499
21500     // Trivial case: if the shift count is zero, then fold this
21501     // into the first operand.
21502     if (ShAmt == 0)
21503       return Op0;
21504
21505     // Replace this packed shift intrinsic with a target independent
21506     // shift dag node.
21507     SDValue Splat = DAG.getConstant(C, VT);
21508     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
21509   }
21510   }
21511 }
21512
21513 /// PerformMulCombine - Optimize a single multiply with constant into two
21514 /// in order to implement it with two cheaper instructions, e.g.
21515 /// LEA + SHL, LEA + LEA.
21516 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
21517                                  TargetLowering::DAGCombinerInfo &DCI) {
21518   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
21519     return SDValue();
21520
21521   EVT VT = N->getValueType(0);
21522   if (VT != MVT::i64)
21523     return SDValue();
21524
21525   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
21526   if (!C)
21527     return SDValue();
21528   uint64_t MulAmt = C->getZExtValue();
21529   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
21530     return SDValue();
21531
21532   uint64_t MulAmt1 = 0;
21533   uint64_t MulAmt2 = 0;
21534   if ((MulAmt % 9) == 0) {
21535     MulAmt1 = 9;
21536     MulAmt2 = MulAmt / 9;
21537   } else if ((MulAmt % 5) == 0) {
21538     MulAmt1 = 5;
21539     MulAmt2 = MulAmt / 5;
21540   } else if ((MulAmt % 3) == 0) {
21541     MulAmt1 = 3;
21542     MulAmt2 = MulAmt / 3;
21543   }
21544   if (MulAmt2 &&
21545       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
21546     SDLoc DL(N);
21547
21548     if (isPowerOf2_64(MulAmt2) &&
21549         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
21550       // If second multiplifer is pow2, issue it first. We want the multiply by
21551       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
21552       // is an add.
21553       std::swap(MulAmt1, MulAmt2);
21554
21555     SDValue NewMul;
21556     if (isPowerOf2_64(MulAmt1))
21557       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
21558                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
21559     else
21560       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
21561                            DAG.getConstant(MulAmt1, VT));
21562
21563     if (isPowerOf2_64(MulAmt2))
21564       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
21565                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
21566     else
21567       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
21568                            DAG.getConstant(MulAmt2, VT));
21569
21570     // Do not add new nodes to DAG combiner worklist.
21571     DCI.CombineTo(N, NewMul, false);
21572   }
21573   return SDValue();
21574 }
21575
21576 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
21577   SDValue N0 = N->getOperand(0);
21578   SDValue N1 = N->getOperand(1);
21579   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
21580   EVT VT = N0.getValueType();
21581
21582   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
21583   // since the result of setcc_c is all zero's or all ones.
21584   if (VT.isInteger() && !VT.isVector() &&
21585       N1C && N0.getOpcode() == ISD::AND &&
21586       N0.getOperand(1).getOpcode() == ISD::Constant) {
21587     SDValue N00 = N0.getOperand(0);
21588     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21589         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21590           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21591          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21592       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21593       APInt ShAmt = N1C->getAPIntValue();
21594       Mask = Mask.shl(ShAmt);
21595       if (Mask != 0)
21596         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21597                            N00, DAG.getConstant(Mask, VT));
21598     }
21599   }
21600
21601   // Hardware support for vector shifts is sparse which makes us scalarize the
21602   // vector operations in many cases. Also, on sandybridge ADD is faster than
21603   // shl.
21604   // (shl V, 1) -> add V,V
21605   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21606     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21607       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21608       // We shift all of the values by one. In many cases we do not have
21609       // hardware support for this operation. This is better expressed as an ADD
21610       // of two values.
21611       if (N1SplatC->getZExtValue() == 1)
21612         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21613     }
21614
21615   return SDValue();
21616 }
21617
21618 /// \brief Returns a vector of 0s if the node in input is a vector logical
21619 /// shift by a constant amount which is known to be bigger than or equal
21620 /// to the vector element size in bits.
21621 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21622                                       const X86Subtarget *Subtarget) {
21623   EVT VT = N->getValueType(0);
21624
21625   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21626       (!Subtarget->hasInt256() ||
21627        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21628     return SDValue();
21629
21630   SDValue Amt = N->getOperand(1);
21631   SDLoc DL(N);
21632   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21633     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21634       APInt ShiftAmt = AmtSplat->getAPIntValue();
21635       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21636
21637       // SSE2/AVX2 logical shifts always return a vector of 0s
21638       // if the shift amount is bigger than or equal to
21639       // the element size. The constant shift amount will be
21640       // encoded as a 8-bit immediate.
21641       if (ShiftAmt.trunc(8).uge(MaxAmount))
21642         return getZeroVector(VT, Subtarget, DAG, DL);
21643     }
21644
21645   return SDValue();
21646 }
21647
21648 /// PerformShiftCombine - Combine shifts.
21649 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21650                                    TargetLowering::DAGCombinerInfo &DCI,
21651                                    const X86Subtarget *Subtarget) {
21652   if (N->getOpcode() == ISD::SHL) {
21653     SDValue V = PerformSHLCombine(N, DAG);
21654     if (V.getNode()) return V;
21655   }
21656
21657   if (N->getOpcode() != ISD::SRA) {
21658     // Try to fold this logical shift into a zero vector.
21659     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21660     if (V.getNode()) return V;
21661   }
21662
21663   return SDValue();
21664 }
21665
21666 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21667 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21668 // and friends.  Likewise for OR -> CMPNEQSS.
21669 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21670                             TargetLowering::DAGCombinerInfo &DCI,
21671                             const X86Subtarget *Subtarget) {
21672   unsigned opcode;
21673
21674   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21675   // we're requiring SSE2 for both.
21676   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21677     SDValue N0 = N->getOperand(0);
21678     SDValue N1 = N->getOperand(1);
21679     SDValue CMP0 = N0->getOperand(1);
21680     SDValue CMP1 = N1->getOperand(1);
21681     SDLoc DL(N);
21682
21683     // The SETCCs should both refer to the same CMP.
21684     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21685       return SDValue();
21686
21687     SDValue CMP00 = CMP0->getOperand(0);
21688     SDValue CMP01 = CMP0->getOperand(1);
21689     EVT     VT    = CMP00.getValueType();
21690
21691     if (VT == MVT::f32 || VT == MVT::f64) {
21692       bool ExpectingFlags = false;
21693       // Check for any users that want flags:
21694       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21695            !ExpectingFlags && UI != UE; ++UI)
21696         switch (UI->getOpcode()) {
21697         default:
21698         case ISD::BR_CC:
21699         case ISD::BRCOND:
21700         case ISD::SELECT:
21701           ExpectingFlags = true;
21702           break;
21703         case ISD::CopyToReg:
21704         case ISD::SIGN_EXTEND:
21705         case ISD::ZERO_EXTEND:
21706         case ISD::ANY_EXTEND:
21707           break;
21708         }
21709
21710       if (!ExpectingFlags) {
21711         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21712         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21713
21714         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21715           X86::CondCode tmp = cc0;
21716           cc0 = cc1;
21717           cc1 = tmp;
21718         }
21719
21720         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21721             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21722           // FIXME: need symbolic constants for these magic numbers.
21723           // See X86ATTInstPrinter.cpp:printSSECC().
21724           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21725           if (Subtarget->hasAVX512()) {
21726             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21727                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21728             if (N->getValueType(0) != MVT::i1)
21729               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21730                                  FSetCC);
21731             return FSetCC;
21732           }
21733           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21734                                               CMP00.getValueType(), CMP00, CMP01,
21735                                               DAG.getConstant(x86cc, MVT::i8));
21736
21737           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21738           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21739
21740           if (is64BitFP && !Subtarget->is64Bit()) {
21741             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21742             // 64-bit integer, since that's not a legal type. Since
21743             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21744             // bits, but can do this little dance to extract the lowest 32 bits
21745             // and work with those going forward.
21746             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21747                                            OnesOrZeroesF);
21748             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21749                                            Vector64);
21750             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21751                                         Vector32, DAG.getIntPtrConstant(0));
21752             IntVT = MVT::i32;
21753           }
21754
21755           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21756           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21757                                       DAG.getConstant(1, IntVT));
21758           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21759           return OneBitOfTruth;
21760         }
21761       }
21762     }
21763   }
21764   return SDValue();
21765 }
21766
21767 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21768 /// so it can be folded inside ANDNP.
21769 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21770   EVT VT = N->getValueType(0);
21771
21772   // Match direct AllOnes for 128 and 256-bit vectors
21773   if (ISD::isBuildVectorAllOnes(N))
21774     return true;
21775
21776   // Look through a bit convert.
21777   if (N->getOpcode() == ISD::BITCAST)
21778     N = N->getOperand(0).getNode();
21779
21780   // Sometimes the operand may come from a insert_subvector building a 256-bit
21781   // allones vector
21782   if (VT.is256BitVector() &&
21783       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21784     SDValue V1 = N->getOperand(0);
21785     SDValue V2 = N->getOperand(1);
21786
21787     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21788         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21789         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21790         ISD::isBuildVectorAllOnes(V2.getNode()))
21791       return true;
21792   }
21793
21794   return false;
21795 }
21796
21797 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21798 // register. In most cases we actually compare or select YMM-sized registers
21799 // and mixing the two types creates horrible code. This method optimizes
21800 // some of the transition sequences.
21801 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21802                                  TargetLowering::DAGCombinerInfo &DCI,
21803                                  const X86Subtarget *Subtarget) {
21804   EVT VT = N->getValueType(0);
21805   if (!VT.is256BitVector())
21806     return SDValue();
21807
21808   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21809           N->getOpcode() == ISD::ZERO_EXTEND ||
21810           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21811
21812   SDValue Narrow = N->getOperand(0);
21813   EVT NarrowVT = Narrow->getValueType(0);
21814   if (!NarrowVT.is128BitVector())
21815     return SDValue();
21816
21817   if (Narrow->getOpcode() != ISD::XOR &&
21818       Narrow->getOpcode() != ISD::AND &&
21819       Narrow->getOpcode() != ISD::OR)
21820     return SDValue();
21821
21822   SDValue N0  = Narrow->getOperand(0);
21823   SDValue N1  = Narrow->getOperand(1);
21824   SDLoc DL(Narrow);
21825
21826   // The Left side has to be a trunc.
21827   if (N0.getOpcode() != ISD::TRUNCATE)
21828     return SDValue();
21829
21830   // The type of the truncated inputs.
21831   EVT WideVT = N0->getOperand(0)->getValueType(0);
21832   if (WideVT != VT)
21833     return SDValue();
21834
21835   // The right side has to be a 'trunc' or a constant vector.
21836   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21837   ConstantSDNode *RHSConstSplat = nullptr;
21838   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21839     RHSConstSplat = RHSBV->getConstantSplatNode();
21840   if (!RHSTrunc && !RHSConstSplat)
21841     return SDValue();
21842
21843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21844
21845   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21846     return SDValue();
21847
21848   // Set N0 and N1 to hold the inputs to the new wide operation.
21849   N0 = N0->getOperand(0);
21850   if (RHSConstSplat) {
21851     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21852                      SDValue(RHSConstSplat, 0));
21853     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21854     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21855   } else if (RHSTrunc) {
21856     N1 = N1->getOperand(0);
21857   }
21858
21859   // Generate the wide operation.
21860   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21861   unsigned Opcode = N->getOpcode();
21862   switch (Opcode) {
21863   case ISD::ANY_EXTEND:
21864     return Op;
21865   case ISD::ZERO_EXTEND: {
21866     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21867     APInt Mask = APInt::getAllOnesValue(InBits);
21868     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21869     return DAG.getNode(ISD::AND, DL, VT,
21870                        Op, DAG.getConstant(Mask, VT));
21871   }
21872   case ISD::SIGN_EXTEND:
21873     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21874                        Op, DAG.getValueType(NarrowVT));
21875   default:
21876     llvm_unreachable("Unexpected opcode");
21877   }
21878 }
21879
21880 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21881                                  TargetLowering::DAGCombinerInfo &DCI,
21882                                  const X86Subtarget *Subtarget) {
21883   EVT VT = N->getValueType(0);
21884   if (DCI.isBeforeLegalizeOps())
21885     return SDValue();
21886
21887   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21888   if (R.getNode())
21889     return R;
21890
21891   // Create BEXTR instructions
21892   // BEXTR is ((X >> imm) & (2**size-1))
21893   if (VT == MVT::i32 || VT == MVT::i64) {
21894     SDValue N0 = N->getOperand(0);
21895     SDValue N1 = N->getOperand(1);
21896     SDLoc DL(N);
21897
21898     // Check for BEXTR.
21899     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21900         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21901       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21902       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21903       if (MaskNode && ShiftNode) {
21904         uint64_t Mask = MaskNode->getZExtValue();
21905         uint64_t Shift = ShiftNode->getZExtValue();
21906         if (isMask_64(Mask)) {
21907           uint64_t MaskSize = CountPopulation_64(Mask);
21908           if (Shift + MaskSize <= VT.getSizeInBits())
21909             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21910                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21911         }
21912       }
21913     } // BEXTR
21914
21915     return SDValue();
21916   }
21917
21918   // Want to form ANDNP nodes:
21919   // 1) In the hopes of then easily combining them with OR and AND nodes
21920   //    to form PBLEND/PSIGN.
21921   // 2) To match ANDN packed intrinsics
21922   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21923     return SDValue();
21924
21925   SDValue N0 = N->getOperand(0);
21926   SDValue N1 = N->getOperand(1);
21927   SDLoc DL(N);
21928
21929   // Check LHS for vnot
21930   if (N0.getOpcode() == ISD::XOR &&
21931       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21932       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21933     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21934
21935   // Check RHS for vnot
21936   if (N1.getOpcode() == ISD::XOR &&
21937       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21938       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21939     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21940
21941   return SDValue();
21942 }
21943
21944 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21945                                 TargetLowering::DAGCombinerInfo &DCI,
21946                                 const X86Subtarget *Subtarget) {
21947   if (DCI.isBeforeLegalizeOps())
21948     return SDValue();
21949
21950   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21951   if (R.getNode())
21952     return R;
21953
21954   SDValue N0 = N->getOperand(0);
21955   SDValue N1 = N->getOperand(1);
21956   EVT VT = N->getValueType(0);
21957
21958   // look for psign/blend
21959   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21960     if (!Subtarget->hasSSSE3() ||
21961         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21962       return SDValue();
21963
21964     // Canonicalize pandn to RHS
21965     if (N0.getOpcode() == X86ISD::ANDNP)
21966       std::swap(N0, N1);
21967     // or (and (m, y), (pandn m, x))
21968     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21969       SDValue Mask = N1.getOperand(0);
21970       SDValue X    = N1.getOperand(1);
21971       SDValue Y;
21972       if (N0.getOperand(0) == Mask)
21973         Y = N0.getOperand(1);
21974       if (N0.getOperand(1) == Mask)
21975         Y = N0.getOperand(0);
21976
21977       // Check to see if the mask appeared in both the AND and ANDNP and
21978       if (!Y.getNode())
21979         return SDValue();
21980
21981       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21982       // Look through mask bitcast.
21983       if (Mask.getOpcode() == ISD::BITCAST)
21984         Mask = Mask.getOperand(0);
21985       if (X.getOpcode() == ISD::BITCAST)
21986         X = X.getOperand(0);
21987       if (Y.getOpcode() == ISD::BITCAST)
21988         Y = Y.getOperand(0);
21989
21990       EVT MaskVT = Mask.getValueType();
21991
21992       // Validate that the Mask operand is a vector sra node.
21993       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21994       // there is no psrai.b
21995       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21996       unsigned SraAmt = ~0;
21997       if (Mask.getOpcode() == ISD::SRA) {
21998         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21999           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22000             SraAmt = AmtConst->getZExtValue();
22001       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22002         SDValue SraC = Mask.getOperand(1);
22003         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22004       }
22005       if ((SraAmt + 1) != EltBits)
22006         return SDValue();
22007
22008       SDLoc DL(N);
22009
22010       // Now we know we at least have a plendvb with the mask val.  See if
22011       // we can form a psignb/w/d.
22012       // psign = x.type == y.type == mask.type && y = sub(0, x);
22013       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22014           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22015           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22016         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22017                "Unsupported VT for PSIGN");
22018         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22019         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22020       }
22021       // PBLENDVB only available on SSE 4.1
22022       if (!Subtarget->hasSSE41())
22023         return SDValue();
22024
22025       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22026
22027       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22028       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22029       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22030       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22031       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22032     }
22033   }
22034
22035   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22036     return SDValue();
22037
22038   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22039   MachineFunction &MF = DAG.getMachineFunction();
22040   bool OptForSize = MF.getFunction()->getAttributes().
22041     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
22042
22043   // SHLD/SHRD instructions have lower register pressure, but on some
22044   // platforms they have higher latency than the equivalent
22045   // series of shifts/or that would otherwise be generated.
22046   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22047   // have higher latencies and we are not optimizing for size.
22048   if (!OptForSize && Subtarget->isSHLDSlow())
22049     return SDValue();
22050
22051   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22052     std::swap(N0, N1);
22053   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22054     return SDValue();
22055   if (!N0.hasOneUse() || !N1.hasOneUse())
22056     return SDValue();
22057
22058   SDValue ShAmt0 = N0.getOperand(1);
22059   if (ShAmt0.getValueType() != MVT::i8)
22060     return SDValue();
22061   SDValue ShAmt1 = N1.getOperand(1);
22062   if (ShAmt1.getValueType() != MVT::i8)
22063     return SDValue();
22064   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22065     ShAmt0 = ShAmt0.getOperand(0);
22066   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22067     ShAmt1 = ShAmt1.getOperand(0);
22068
22069   SDLoc DL(N);
22070   unsigned Opc = X86ISD::SHLD;
22071   SDValue Op0 = N0.getOperand(0);
22072   SDValue Op1 = N1.getOperand(0);
22073   if (ShAmt0.getOpcode() == ISD::SUB) {
22074     Opc = X86ISD::SHRD;
22075     std::swap(Op0, Op1);
22076     std::swap(ShAmt0, ShAmt1);
22077   }
22078
22079   unsigned Bits = VT.getSizeInBits();
22080   if (ShAmt1.getOpcode() == ISD::SUB) {
22081     SDValue Sum = ShAmt1.getOperand(0);
22082     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22083       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22084       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22085         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22086       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22087         return DAG.getNode(Opc, DL, VT,
22088                            Op0, Op1,
22089                            DAG.getNode(ISD::TRUNCATE, DL,
22090                                        MVT::i8, ShAmt0));
22091     }
22092   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22093     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22094     if (ShAmt0C &&
22095         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22096       return DAG.getNode(Opc, DL, VT,
22097                          N0.getOperand(0), N1.getOperand(0),
22098                          DAG.getNode(ISD::TRUNCATE, DL,
22099                                        MVT::i8, ShAmt0));
22100   }
22101
22102   return SDValue();
22103 }
22104
22105 // Generate NEG and CMOV for integer abs.
22106 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22107   EVT VT = N->getValueType(0);
22108
22109   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22110   // 8-bit integer abs to NEG and CMOV.
22111   if (VT.isInteger() && VT.getSizeInBits() == 8)
22112     return SDValue();
22113
22114   SDValue N0 = N->getOperand(0);
22115   SDValue N1 = N->getOperand(1);
22116   SDLoc DL(N);
22117
22118   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22119   // and change it to SUB and CMOV.
22120   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22121       N0.getOpcode() == ISD::ADD &&
22122       N0.getOperand(1) == N1 &&
22123       N1.getOpcode() == ISD::SRA &&
22124       N1.getOperand(0) == N0.getOperand(0))
22125     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22126       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22127         // Generate SUB & CMOV.
22128         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22129                                   DAG.getConstant(0, VT), N0.getOperand(0));
22130
22131         SDValue Ops[] = { N0.getOperand(0), Neg,
22132                           DAG.getConstant(X86::COND_GE, MVT::i8),
22133                           SDValue(Neg.getNode(), 1) };
22134         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22135       }
22136   return SDValue();
22137 }
22138
22139 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22140 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22141                                  TargetLowering::DAGCombinerInfo &DCI,
22142                                  const X86Subtarget *Subtarget) {
22143   if (DCI.isBeforeLegalizeOps())
22144     return SDValue();
22145
22146   if (Subtarget->hasCMov()) {
22147     SDValue RV = performIntegerAbsCombine(N, DAG);
22148     if (RV.getNode())
22149       return RV;
22150   }
22151
22152   return SDValue();
22153 }
22154
22155 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22156 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22157                                   TargetLowering::DAGCombinerInfo &DCI,
22158                                   const X86Subtarget *Subtarget) {
22159   LoadSDNode *Ld = cast<LoadSDNode>(N);
22160   EVT RegVT = Ld->getValueType(0);
22161   EVT MemVT = Ld->getMemoryVT();
22162   SDLoc dl(Ld);
22163   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22164
22165   // On Sandybridge unaligned 256bit loads are inefficient.
22166   ISD::LoadExtType Ext = Ld->getExtensionType();
22167   unsigned Alignment = Ld->getAlignment();
22168   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22169   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
22170       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22171     unsigned NumElems = RegVT.getVectorNumElements();
22172     if (NumElems < 2)
22173       return SDValue();
22174
22175     SDValue Ptr = Ld->getBasePtr();
22176     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22177
22178     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22179                                   NumElems/2);
22180     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22181                                 Ld->getPointerInfo(), Ld->isVolatile(),
22182                                 Ld->isNonTemporal(), Ld->isInvariant(),
22183                                 Alignment);
22184     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22185     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22186                                 Ld->getPointerInfo(), Ld->isVolatile(),
22187                                 Ld->isNonTemporal(), Ld->isInvariant(),
22188                                 std::min(16U, Alignment));
22189     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22190                              Load1.getValue(1),
22191                              Load2.getValue(1));
22192
22193     SDValue NewVec = DAG.getUNDEF(RegVT);
22194     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22195     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22196     return DCI.CombineTo(N, NewVec, TF, true);
22197   }
22198
22199   return SDValue();
22200 }
22201
22202 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22203 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22204                                    const X86Subtarget *Subtarget) {
22205   StoreSDNode *St = cast<StoreSDNode>(N);
22206   EVT VT = St->getValue().getValueType();
22207   EVT StVT = St->getMemoryVT();
22208   SDLoc dl(St);
22209   SDValue StoredVal = St->getOperand(1);
22210   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22211
22212   // If we are saving a concatenation of two XMM registers, perform two stores.
22213   // On Sandy Bridge, 256-bit memory operations are executed by two
22214   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
22215   // memory  operation.
22216   unsigned Alignment = St->getAlignment();
22217   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22218   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
22219       StVT == VT && !IsAligned) {
22220     unsigned NumElems = VT.getVectorNumElements();
22221     if (NumElems < 2)
22222       return SDValue();
22223
22224     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22225     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22226
22227     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22228     SDValue Ptr0 = St->getBasePtr();
22229     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22230
22231     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22232                                 St->getPointerInfo(), St->isVolatile(),
22233                                 St->isNonTemporal(), Alignment);
22234     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22235                                 St->getPointerInfo(), St->isVolatile(),
22236                                 St->isNonTemporal(),
22237                                 std::min(16U, Alignment));
22238     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22239   }
22240
22241   // Optimize trunc store (of multiple scalars) to shuffle and store.
22242   // First, pack all of the elements in one place. Next, store to memory
22243   // in fewer chunks.
22244   if (St->isTruncatingStore() && VT.isVector()) {
22245     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22246     unsigned NumElems = VT.getVectorNumElements();
22247     assert(StVT != VT && "Cannot truncate to the same type");
22248     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22249     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22250
22251     // From, To sizes and ElemCount must be pow of two
22252     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22253     // We are going to use the original vector elt for storing.
22254     // Accumulated smaller vector elements must be a multiple of the store size.
22255     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22256
22257     unsigned SizeRatio  = FromSz / ToSz;
22258
22259     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22260
22261     // Create a type on which we perform the shuffle
22262     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22263             StVT.getScalarType(), NumElems*SizeRatio);
22264
22265     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22266
22267     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22268     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22269     for (unsigned i = 0; i != NumElems; ++i)
22270       ShuffleVec[i] = i * SizeRatio;
22271
22272     // Can't shuffle using an illegal type.
22273     if (!TLI.isTypeLegal(WideVecVT))
22274       return SDValue();
22275
22276     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22277                                          DAG.getUNDEF(WideVecVT),
22278                                          &ShuffleVec[0]);
22279     // At this point all of the data is stored at the bottom of the
22280     // register. We now need to save it to mem.
22281
22282     // Find the largest store unit
22283     MVT StoreType = MVT::i8;
22284     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
22285          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
22286       MVT Tp = (MVT::SimpleValueType)tp;
22287       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22288         StoreType = Tp;
22289     }
22290
22291     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
22292     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
22293         (64 <= NumElems * ToSz))
22294       StoreType = MVT::f64;
22295
22296     // Bitcast the original vector into a vector of store-size units
22297     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
22298             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
22299     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
22300     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
22301     SmallVector<SDValue, 8> Chains;
22302     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
22303                                         TLI.getPointerTy());
22304     SDValue Ptr = St->getBasePtr();
22305
22306     // Perform one or more big stores into memory.
22307     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
22308       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
22309                                    StoreType, ShuffWide,
22310                                    DAG.getIntPtrConstant(i));
22311       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
22312                                 St->getPointerInfo(), St->isVolatile(),
22313                                 St->isNonTemporal(), St->getAlignment());
22314       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22315       Chains.push_back(Ch);
22316     }
22317
22318     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
22319   }
22320
22321   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
22322   // the FP state in cases where an emms may be missing.
22323   // A preferable solution to the general problem is to figure out the right
22324   // places to insert EMMS.  This qualifies as a quick hack.
22325
22326   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
22327   if (VT.getSizeInBits() != 64)
22328     return SDValue();
22329
22330   const Function *F = DAG.getMachineFunction().getFunction();
22331   bool NoImplicitFloatOps = F->getAttributes().
22332     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
22333   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
22334                      && Subtarget->hasSSE2();
22335   if ((VT.isVector() ||
22336        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
22337       isa<LoadSDNode>(St->getValue()) &&
22338       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
22339       St->getChain().hasOneUse() && !St->isVolatile()) {
22340     SDNode* LdVal = St->getValue().getNode();
22341     LoadSDNode *Ld = nullptr;
22342     int TokenFactorIndex = -1;
22343     SmallVector<SDValue, 8> Ops;
22344     SDNode* ChainVal = St->getChain().getNode();
22345     // Must be a store of a load.  We currently handle two cases:  the load
22346     // is a direct child, and it's under an intervening TokenFactor.  It is
22347     // possible to dig deeper under nested TokenFactors.
22348     if (ChainVal == LdVal)
22349       Ld = cast<LoadSDNode>(St->getChain());
22350     else if (St->getValue().hasOneUse() &&
22351              ChainVal->getOpcode() == ISD::TokenFactor) {
22352       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
22353         if (ChainVal->getOperand(i).getNode() == LdVal) {
22354           TokenFactorIndex = i;
22355           Ld = cast<LoadSDNode>(St->getValue());
22356         } else
22357           Ops.push_back(ChainVal->getOperand(i));
22358       }
22359     }
22360
22361     if (!Ld || !ISD::isNormalLoad(Ld))
22362       return SDValue();
22363
22364     // If this is not the MMX case, i.e. we are just turning i64 load/store
22365     // into f64 load/store, avoid the transformation if there are multiple
22366     // uses of the loaded value.
22367     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
22368       return SDValue();
22369
22370     SDLoc LdDL(Ld);
22371     SDLoc StDL(N);
22372     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
22373     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
22374     // pair instead.
22375     if (Subtarget->is64Bit() || F64IsLegal) {
22376       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
22377       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
22378                                   Ld->getPointerInfo(), Ld->isVolatile(),
22379                                   Ld->isNonTemporal(), Ld->isInvariant(),
22380                                   Ld->getAlignment());
22381       SDValue NewChain = NewLd.getValue(1);
22382       if (TokenFactorIndex != -1) {
22383         Ops.push_back(NewChain);
22384         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22385       }
22386       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
22387                           St->getPointerInfo(),
22388                           St->isVolatile(), St->isNonTemporal(),
22389                           St->getAlignment());
22390     }
22391
22392     // Otherwise, lower to two pairs of 32-bit loads / stores.
22393     SDValue LoAddr = Ld->getBasePtr();
22394     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
22395                                  DAG.getConstant(4, MVT::i32));
22396
22397     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
22398                                Ld->getPointerInfo(),
22399                                Ld->isVolatile(), Ld->isNonTemporal(),
22400                                Ld->isInvariant(), Ld->getAlignment());
22401     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
22402                                Ld->getPointerInfo().getWithOffset(4),
22403                                Ld->isVolatile(), Ld->isNonTemporal(),
22404                                Ld->isInvariant(),
22405                                MinAlign(Ld->getAlignment(), 4));
22406
22407     SDValue NewChain = LoLd.getValue(1);
22408     if (TokenFactorIndex != -1) {
22409       Ops.push_back(LoLd);
22410       Ops.push_back(HiLd);
22411       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
22412     }
22413
22414     LoAddr = St->getBasePtr();
22415     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
22416                          DAG.getConstant(4, MVT::i32));
22417
22418     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
22419                                 St->getPointerInfo(),
22420                                 St->isVolatile(), St->isNonTemporal(),
22421                                 St->getAlignment());
22422     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
22423                                 St->getPointerInfo().getWithOffset(4),
22424                                 St->isVolatile(),
22425                                 St->isNonTemporal(),
22426                                 MinAlign(St->getAlignment(), 4));
22427     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
22428   }
22429   return SDValue();
22430 }
22431
22432 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
22433 /// and return the operands for the horizontal operation in LHS and RHS.  A
22434 /// horizontal operation performs the binary operation on successive elements
22435 /// of its first operand, then on successive elements of its second operand,
22436 /// returning the resulting values in a vector.  For example, if
22437 ///   A = < float a0, float a1, float a2, float a3 >
22438 /// and
22439 ///   B = < float b0, float b1, float b2, float b3 >
22440 /// then the result of doing a horizontal operation on A and B is
22441 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
22442 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
22443 /// A horizontal-op B, for some already available A and B, and if so then LHS is
22444 /// set to A, RHS to B, and the routine returns 'true'.
22445 /// Note that the binary operation should have the property that if one of the
22446 /// operands is UNDEF then the result is UNDEF.
22447 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
22448   // Look for the following pattern: if
22449   //   A = < float a0, float a1, float a2, float a3 >
22450   //   B = < float b0, float b1, float b2, float b3 >
22451   // and
22452   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
22453   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
22454   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
22455   // which is A horizontal-op B.
22456
22457   // At least one of the operands should be a vector shuffle.
22458   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
22459       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
22460     return false;
22461
22462   MVT VT = LHS.getSimpleValueType();
22463
22464   assert((VT.is128BitVector() || VT.is256BitVector()) &&
22465          "Unsupported vector type for horizontal add/sub");
22466
22467   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
22468   // operate independently on 128-bit lanes.
22469   unsigned NumElts = VT.getVectorNumElements();
22470   unsigned NumLanes = VT.getSizeInBits()/128;
22471   unsigned NumLaneElts = NumElts / NumLanes;
22472   assert((NumLaneElts % 2 == 0) &&
22473          "Vector type should have an even number of elements in each lane");
22474   unsigned HalfLaneElts = NumLaneElts/2;
22475
22476   // View LHS in the form
22477   //   LHS = VECTOR_SHUFFLE A, B, LMask
22478   // If LHS is not a shuffle then pretend it is the shuffle
22479   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
22480   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
22481   // type VT.
22482   SDValue A, B;
22483   SmallVector<int, 16> LMask(NumElts);
22484   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22485     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
22486       A = LHS.getOperand(0);
22487     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
22488       B = LHS.getOperand(1);
22489     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
22490     std::copy(Mask.begin(), Mask.end(), LMask.begin());
22491   } else {
22492     if (LHS.getOpcode() != ISD::UNDEF)
22493       A = LHS;
22494     for (unsigned i = 0; i != NumElts; ++i)
22495       LMask[i] = i;
22496   }
22497
22498   // Likewise, view RHS in the form
22499   //   RHS = VECTOR_SHUFFLE C, D, RMask
22500   SDValue C, D;
22501   SmallVector<int, 16> RMask(NumElts);
22502   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
22503     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
22504       C = RHS.getOperand(0);
22505     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
22506       D = RHS.getOperand(1);
22507     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
22508     std::copy(Mask.begin(), Mask.end(), RMask.begin());
22509   } else {
22510     if (RHS.getOpcode() != ISD::UNDEF)
22511       C = RHS;
22512     for (unsigned i = 0; i != NumElts; ++i)
22513       RMask[i] = i;
22514   }
22515
22516   // Check that the shuffles are both shuffling the same vectors.
22517   if (!(A == C && B == D) && !(A == D && B == C))
22518     return false;
22519
22520   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
22521   if (!A.getNode() && !B.getNode())
22522     return false;
22523
22524   // If A and B occur in reverse order in RHS, then "swap" them (which means
22525   // rewriting the mask).
22526   if (A != C)
22527     CommuteVectorShuffleMask(RMask, NumElts);
22528
22529   // At this point LHS and RHS are equivalent to
22530   //   LHS = VECTOR_SHUFFLE A, B, LMask
22531   //   RHS = VECTOR_SHUFFLE A, B, RMask
22532   // Check that the masks correspond to performing a horizontal operation.
22533   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
22534     for (unsigned i = 0; i != NumLaneElts; ++i) {
22535       int LIdx = LMask[i+l], RIdx = RMask[i+l];
22536
22537       // Ignore any UNDEF components.
22538       if (LIdx < 0 || RIdx < 0 ||
22539           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
22540           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
22541         continue;
22542
22543       // Check that successive elements are being operated on.  If not, this is
22544       // not a horizontal operation.
22545       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
22546       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
22547       if (!(LIdx == Index && RIdx == Index + 1) &&
22548           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
22549         return false;
22550     }
22551   }
22552
22553   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
22554   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
22555   return true;
22556 }
22557
22558 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
22559 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
22560                                   const X86Subtarget *Subtarget) {
22561   EVT VT = N->getValueType(0);
22562   SDValue LHS = N->getOperand(0);
22563   SDValue RHS = N->getOperand(1);
22564
22565   // Try to synthesize horizontal adds from adds of shuffles.
22566   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22567        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22568       isHorizontalBinOp(LHS, RHS, true))
22569     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
22570   return SDValue();
22571 }
22572
22573 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
22574 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
22575                                   const X86Subtarget *Subtarget) {
22576   EVT VT = N->getValueType(0);
22577   SDValue LHS = N->getOperand(0);
22578   SDValue RHS = N->getOperand(1);
22579
22580   // Try to synthesize horizontal subs from subs of shuffles.
22581   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
22582        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
22583       isHorizontalBinOp(LHS, RHS, false))
22584     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
22585   return SDValue();
22586 }
22587
22588 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22589 /// X86ISD::FXOR nodes.
22590 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22591   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22592   // F[X]OR(0.0, x) -> x
22593   // F[X]OR(x, 0.0) -> x
22594   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22595     if (C->getValueAPF().isPosZero())
22596       return N->getOperand(1);
22597   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22598     if (C->getValueAPF().isPosZero())
22599       return N->getOperand(0);
22600   return SDValue();
22601 }
22602
22603 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22604 /// X86ISD::FMAX nodes.
22605 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22606   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22607
22608   // Only perform optimizations if UnsafeMath is used.
22609   if (!DAG.getTarget().Options.UnsafeFPMath)
22610     return SDValue();
22611
22612   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22613   // into FMINC and FMAXC, which are Commutative operations.
22614   unsigned NewOp = 0;
22615   switch (N->getOpcode()) {
22616     default: llvm_unreachable("unknown opcode");
22617     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22618     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22619   }
22620
22621   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22622                      N->getOperand(0), N->getOperand(1));
22623 }
22624
22625 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22626 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22627   // FAND(0.0, x) -> 0.0
22628   // FAND(x, 0.0) -> 0.0
22629   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22630     if (C->getValueAPF().isPosZero())
22631       return N->getOperand(0);
22632   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22633     if (C->getValueAPF().isPosZero())
22634       return N->getOperand(1);
22635   return SDValue();
22636 }
22637
22638 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22639 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22640   // FANDN(x, 0.0) -> 0.0
22641   // FANDN(0.0, x) -> x
22642   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22643     if (C->getValueAPF().isPosZero())
22644       return N->getOperand(1);
22645   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22646     if (C->getValueAPF().isPosZero())
22647       return N->getOperand(1);
22648   return SDValue();
22649 }
22650
22651 static SDValue PerformBTCombine(SDNode *N,
22652                                 SelectionDAG &DAG,
22653                                 TargetLowering::DAGCombinerInfo &DCI) {
22654   // BT ignores high bits in the bit index operand.
22655   SDValue Op1 = N->getOperand(1);
22656   if (Op1.hasOneUse()) {
22657     unsigned BitWidth = Op1.getValueSizeInBits();
22658     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22659     APInt KnownZero, KnownOne;
22660     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22661                                           !DCI.isBeforeLegalizeOps());
22662     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22663     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22664         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22665       DCI.CommitTargetLoweringOpt(TLO);
22666   }
22667   return SDValue();
22668 }
22669
22670 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22671   SDValue Op = N->getOperand(0);
22672   if (Op.getOpcode() == ISD::BITCAST)
22673     Op = Op.getOperand(0);
22674   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22675   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22676       VT.getVectorElementType().getSizeInBits() ==
22677       OpVT.getVectorElementType().getSizeInBits()) {
22678     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22679   }
22680   return SDValue();
22681 }
22682
22683 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22684                                                const X86Subtarget *Subtarget) {
22685   EVT VT = N->getValueType(0);
22686   if (!VT.isVector())
22687     return SDValue();
22688
22689   SDValue N0 = N->getOperand(0);
22690   SDValue N1 = N->getOperand(1);
22691   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22692   SDLoc dl(N);
22693
22694   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22695   // both SSE and AVX2 since there is no sign-extended shift right
22696   // operation on a vector with 64-bit elements.
22697   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22698   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22699   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22700       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22701     SDValue N00 = N0.getOperand(0);
22702
22703     // EXTLOAD has a better solution on AVX2,
22704     // it may be replaced with X86ISD::VSEXT node.
22705     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22706       if (!ISD::isNormalLoad(N00.getNode()))
22707         return SDValue();
22708
22709     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22710         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22711                                   N00, N1);
22712       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22713     }
22714   }
22715   return SDValue();
22716 }
22717
22718 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22719                                   TargetLowering::DAGCombinerInfo &DCI,
22720                                   const X86Subtarget *Subtarget) {
22721   if (!DCI.isBeforeLegalizeOps())
22722     return SDValue();
22723
22724   if (!Subtarget->hasFp256())
22725     return SDValue();
22726
22727   EVT VT = N->getValueType(0);
22728   if (VT.isVector() && VT.getSizeInBits() == 256) {
22729     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22730     if (R.getNode())
22731       return R;
22732   }
22733
22734   return SDValue();
22735 }
22736
22737 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22738                                  const X86Subtarget* Subtarget) {
22739   SDLoc dl(N);
22740   EVT VT = N->getValueType(0);
22741
22742   // Let legalize expand this if it isn't a legal type yet.
22743   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22744     return SDValue();
22745
22746   EVT ScalarVT = VT.getScalarType();
22747   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22748       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22749     return SDValue();
22750
22751   SDValue A = N->getOperand(0);
22752   SDValue B = N->getOperand(1);
22753   SDValue C = N->getOperand(2);
22754
22755   bool NegA = (A.getOpcode() == ISD::FNEG);
22756   bool NegB = (B.getOpcode() == ISD::FNEG);
22757   bool NegC = (C.getOpcode() == ISD::FNEG);
22758
22759   // Negative multiplication when NegA xor NegB
22760   bool NegMul = (NegA != NegB);
22761   if (NegA)
22762     A = A.getOperand(0);
22763   if (NegB)
22764     B = B.getOperand(0);
22765   if (NegC)
22766     C = C.getOperand(0);
22767
22768   unsigned Opcode;
22769   if (!NegMul)
22770     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22771   else
22772     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22773
22774   return DAG.getNode(Opcode, dl, VT, A, B, C);
22775 }
22776
22777 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22778                                   TargetLowering::DAGCombinerInfo &DCI,
22779                                   const X86Subtarget *Subtarget) {
22780   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22781   //           (and (i32 x86isd::setcc_carry), 1)
22782   // This eliminates the zext. This transformation is necessary because
22783   // ISD::SETCC is always legalized to i8.
22784   SDLoc dl(N);
22785   SDValue N0 = N->getOperand(0);
22786   EVT VT = N->getValueType(0);
22787
22788   if (N0.getOpcode() == ISD::AND &&
22789       N0.hasOneUse() &&
22790       N0.getOperand(0).hasOneUse()) {
22791     SDValue N00 = N0.getOperand(0);
22792     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22793       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22794       if (!C || C->getZExtValue() != 1)
22795         return SDValue();
22796       return DAG.getNode(ISD::AND, dl, VT,
22797                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22798                                      N00.getOperand(0), N00.getOperand(1)),
22799                          DAG.getConstant(1, VT));
22800     }
22801   }
22802
22803   if (N0.getOpcode() == ISD::TRUNCATE &&
22804       N0.hasOneUse() &&
22805       N0.getOperand(0).hasOneUse()) {
22806     SDValue N00 = N0.getOperand(0);
22807     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22808       return DAG.getNode(ISD::AND, dl, VT,
22809                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22810                                      N00.getOperand(0), N00.getOperand(1)),
22811                          DAG.getConstant(1, VT));
22812     }
22813   }
22814   if (VT.is256BitVector()) {
22815     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22816     if (R.getNode())
22817       return R;
22818   }
22819
22820   return SDValue();
22821 }
22822
22823 // Optimize x == -y --> x+y == 0
22824 //          x != -y --> x+y != 0
22825 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22826                                       const X86Subtarget* Subtarget) {
22827   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22828   SDValue LHS = N->getOperand(0);
22829   SDValue RHS = N->getOperand(1);
22830   EVT VT = N->getValueType(0);
22831   SDLoc DL(N);
22832
22833   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22834     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22835       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22836         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22837                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22838         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22839                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22840       }
22841   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22842     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22843       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22844         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22845                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22846         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22847                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22848       }
22849
22850   if (VT.getScalarType() == MVT::i1) {
22851     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22852       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22853     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22854     if (!IsSEXT0 && !IsVZero0)
22855       return SDValue();
22856     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22857       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22858     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22859
22860     if (!IsSEXT1 && !IsVZero1)
22861       return SDValue();
22862
22863     if (IsSEXT0 && IsVZero1) {
22864       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22865       if (CC == ISD::SETEQ)
22866         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22867       return LHS.getOperand(0);
22868     }
22869     if (IsSEXT1 && IsVZero0) {
22870       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22871       if (CC == ISD::SETEQ)
22872         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22873       return RHS.getOperand(0);
22874     }
22875   }
22876
22877   return SDValue();
22878 }
22879
22880 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22881                                       const X86Subtarget *Subtarget) {
22882   SDLoc dl(N);
22883   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22884   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22885          "X86insertps is only defined for v4x32");
22886
22887   SDValue Ld = N->getOperand(1);
22888   if (MayFoldLoad(Ld)) {
22889     // Extract the countS bits from the immediate so we can get the proper
22890     // address when narrowing the vector load to a specific element.
22891     // When the second source op is a memory address, interps doesn't use
22892     // countS and just gets an f32 from that address.
22893     unsigned DestIndex =
22894         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22895     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22896   } else
22897     return SDValue();
22898
22899   // Create this as a scalar to vector to match the instruction pattern.
22900   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22901   // countS bits are ignored when loading from memory on insertps, which
22902   // means we don't need to explicitly set them to 0.
22903   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22904                      LoadScalarToVector, N->getOperand(2));
22905 }
22906
22907 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22908 // as "sbb reg,reg", since it can be extended without zext and produces
22909 // an all-ones bit which is more useful than 0/1 in some cases.
22910 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22911                                MVT VT) {
22912   if (VT == MVT::i8)
22913     return DAG.getNode(ISD::AND, DL, VT,
22914                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22915                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22916                        DAG.getConstant(1, VT));
22917   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22918   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22919                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22920                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22921 }
22922
22923 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22924 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22925                                    TargetLowering::DAGCombinerInfo &DCI,
22926                                    const X86Subtarget *Subtarget) {
22927   SDLoc DL(N);
22928   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22929   SDValue EFLAGS = N->getOperand(1);
22930
22931   if (CC == X86::COND_A) {
22932     // Try to convert COND_A into COND_B in an attempt to facilitate
22933     // materializing "setb reg".
22934     //
22935     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22936     // cannot take an immediate as its first operand.
22937     //
22938     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22939         EFLAGS.getValueType().isInteger() &&
22940         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22941       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22942                                    EFLAGS.getNode()->getVTList(),
22943                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22944       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22945       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22946     }
22947   }
22948
22949   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22950   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22951   // cases.
22952   if (CC == X86::COND_B)
22953     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22954
22955   SDValue Flags;
22956
22957   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22958   if (Flags.getNode()) {
22959     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22960     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22961   }
22962
22963   return SDValue();
22964 }
22965
22966 // Optimize branch condition evaluation.
22967 //
22968 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22969                                     TargetLowering::DAGCombinerInfo &DCI,
22970                                     const X86Subtarget *Subtarget) {
22971   SDLoc DL(N);
22972   SDValue Chain = N->getOperand(0);
22973   SDValue Dest = N->getOperand(1);
22974   SDValue EFLAGS = N->getOperand(3);
22975   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22976
22977   SDValue Flags;
22978
22979   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22980   if (Flags.getNode()) {
22981     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22982     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22983                        Flags);
22984   }
22985
22986   return SDValue();
22987 }
22988
22989 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22990                                                          SelectionDAG &DAG) {
22991   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22992   // optimize away operation when it's from a constant.
22993   //
22994   // The general transformation is:
22995   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22996   //       AND(VECTOR_CMP(x,y), constant2)
22997   //    constant2 = UNARYOP(constant)
22998
22999   // Early exit if this isn't a vector operation, the operand of the
23000   // unary operation isn't a bitwise AND, or if the sizes of the operations
23001   // aren't the same.
23002   EVT VT = N->getValueType(0);
23003   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23004       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23005       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23006     return SDValue();
23007
23008   // Now check that the other operand of the AND is a constant. We could
23009   // make the transformation for non-constant splats as well, but it's unclear
23010   // that would be a benefit as it would not eliminate any operations, just
23011   // perform one more step in scalar code before moving to the vector unit.
23012   if (BuildVectorSDNode *BV =
23013           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23014     // Bail out if the vector isn't a constant.
23015     if (!BV->isConstant())
23016       return SDValue();
23017
23018     // Everything checks out. Build up the new and improved node.
23019     SDLoc DL(N);
23020     EVT IntVT = BV->getValueType(0);
23021     // Create a new constant of the appropriate type for the transformed
23022     // DAG.
23023     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23024     // The AND node needs bitcasts to/from an integer vector type around it.
23025     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23026     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23027                                  N->getOperand(0)->getOperand(0), MaskConst);
23028     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23029     return Res;
23030   }
23031
23032   return SDValue();
23033 }
23034
23035 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23036                                         const X86TargetLowering *XTLI) {
23037   // First try to optimize away the conversion entirely when it's
23038   // conditionally from a constant. Vectors only.
23039   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23040   if (Res != SDValue())
23041     return Res;
23042
23043   // Now move on to more general possibilities.
23044   SDValue Op0 = N->getOperand(0);
23045   EVT InVT = Op0->getValueType(0);
23046
23047   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23048   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23049     SDLoc dl(N);
23050     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23051     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23052     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23053   }
23054
23055   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23056   // a 32-bit target where SSE doesn't support i64->FP operations.
23057   if (Op0.getOpcode() == ISD::LOAD) {
23058     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23059     EVT VT = Ld->getValueType(0);
23060     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23061         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23062         !XTLI->getSubtarget()->is64Bit() &&
23063         VT == MVT::i64) {
23064       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
23065                                           Ld->getChain(), Op0, DAG);
23066       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23067       return FILDChain;
23068     }
23069   }
23070   return SDValue();
23071 }
23072
23073 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23074 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23075                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23076   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23077   // the result is either zero or one (depending on the input carry bit).
23078   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23079   if (X86::isZeroNode(N->getOperand(0)) &&
23080       X86::isZeroNode(N->getOperand(1)) &&
23081       // We don't have a good way to replace an EFLAGS use, so only do this when
23082       // dead right now.
23083       SDValue(N, 1).use_empty()) {
23084     SDLoc DL(N);
23085     EVT VT = N->getValueType(0);
23086     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23087     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23088                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23089                                            DAG.getConstant(X86::COND_B,MVT::i8),
23090                                            N->getOperand(2)),
23091                                DAG.getConstant(1, VT));
23092     return DCI.CombineTo(N, Res1, CarryOut);
23093   }
23094
23095   return SDValue();
23096 }
23097
23098 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23099 //      (add Y, (setne X, 0)) -> sbb -1, Y
23100 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23101 //      (sub (setne X, 0), Y) -> adc -1, Y
23102 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23103   SDLoc DL(N);
23104
23105   // Look through ZExts.
23106   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23107   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23108     return SDValue();
23109
23110   SDValue SetCC = Ext.getOperand(0);
23111   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23112     return SDValue();
23113
23114   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23115   if (CC != X86::COND_E && CC != X86::COND_NE)
23116     return SDValue();
23117
23118   SDValue Cmp = SetCC.getOperand(1);
23119   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23120       !X86::isZeroNode(Cmp.getOperand(1)) ||
23121       !Cmp.getOperand(0).getValueType().isInteger())
23122     return SDValue();
23123
23124   SDValue CmpOp0 = Cmp.getOperand(0);
23125   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23126                                DAG.getConstant(1, CmpOp0.getValueType()));
23127
23128   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23129   if (CC == X86::COND_NE)
23130     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23131                        DL, OtherVal.getValueType(), OtherVal,
23132                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23133   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23134                      DL, OtherVal.getValueType(), OtherVal,
23135                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23136 }
23137
23138 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23139 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23140                                  const X86Subtarget *Subtarget) {
23141   EVT VT = N->getValueType(0);
23142   SDValue Op0 = N->getOperand(0);
23143   SDValue Op1 = N->getOperand(1);
23144
23145   // Try to synthesize horizontal adds from adds of shuffles.
23146   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23147        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23148       isHorizontalBinOp(Op0, Op1, true))
23149     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23150
23151   return OptimizeConditionalInDecrement(N, DAG);
23152 }
23153
23154 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23155                                  const X86Subtarget *Subtarget) {
23156   SDValue Op0 = N->getOperand(0);
23157   SDValue Op1 = N->getOperand(1);
23158
23159   // X86 can't encode an immediate LHS of a sub. See if we can push the
23160   // negation into a preceding instruction.
23161   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23162     // If the RHS of the sub is a XOR with one use and a constant, invert the
23163     // immediate. Then add one to the LHS of the sub so we can turn
23164     // X-Y -> X+~Y+1, saving one register.
23165     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23166         isa<ConstantSDNode>(Op1.getOperand(1))) {
23167       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23168       EVT VT = Op0.getValueType();
23169       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23170                                    Op1.getOperand(0),
23171                                    DAG.getConstant(~XorC, VT));
23172       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23173                          DAG.getConstant(C->getAPIntValue()+1, VT));
23174     }
23175   }
23176
23177   // Try to synthesize horizontal adds from adds of shuffles.
23178   EVT VT = N->getValueType(0);
23179   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23180        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23181       isHorizontalBinOp(Op0, Op1, true))
23182     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23183
23184   return OptimizeConditionalInDecrement(N, DAG);
23185 }
23186
23187 /// performVZEXTCombine - Performs build vector combines
23188 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23189                                         TargetLowering::DAGCombinerInfo &DCI,
23190                                         const X86Subtarget *Subtarget) {
23191   // (vzext (bitcast (vzext (x)) -> (vzext x)
23192   SDValue In = N->getOperand(0);
23193   while (In.getOpcode() == ISD::BITCAST)
23194     In = In.getOperand(0);
23195
23196   if (In.getOpcode() != X86ISD::VZEXT)
23197     return SDValue();
23198
23199   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
23200                      In.getOperand(0));
23201 }
23202
23203 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23204                                              DAGCombinerInfo &DCI) const {
23205   SelectionDAG &DAG = DCI.DAG;
23206   switch (N->getOpcode()) {
23207   default: break;
23208   case ISD::EXTRACT_VECTOR_ELT:
23209     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23210   case ISD::VSELECT:
23211   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23212   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23213   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23214   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23215   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23216   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23217   case ISD::SHL:
23218   case ISD::SRA:
23219   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23220   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23221   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23222   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23223   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23224   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23225   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
23226   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23227   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23228   case X86ISD::FXOR:
23229   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23230   case X86ISD::FMIN:
23231   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23232   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23233   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23234   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23235   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23236   case ISD::ANY_EXTEND:
23237   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23238   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23239   case ISD::SIGN_EXTEND_INREG:
23240     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23241   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23242   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23243   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23244   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23245   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23246   case X86ISD::SHUFP:       // Handle all target specific shuffles
23247   case X86ISD::PALIGNR:
23248   case X86ISD::UNPCKH:
23249   case X86ISD::UNPCKL:
23250   case X86ISD::MOVHLPS:
23251   case X86ISD::MOVLHPS:
23252   case X86ISD::PSHUFB:
23253   case X86ISD::PSHUFD:
23254   case X86ISD::PSHUFHW:
23255   case X86ISD::PSHUFLW:
23256   case X86ISD::MOVSS:
23257   case X86ISD::MOVSD:
23258   case X86ISD::VPERMILP:
23259   case X86ISD::VPERM2X128:
23260   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23261   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23262   case ISD::INTRINSIC_WO_CHAIN:
23263     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23264   case X86ISD::INSERTPS:
23265     return PerformINSERTPSCombine(N, DAG, Subtarget);
23266   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23267   }
23268
23269   return SDValue();
23270 }
23271
23272 /// isTypeDesirableForOp - Return true if the target has native support for
23273 /// the specified value type and it is 'desirable' to use the type for the
23274 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23275 /// instruction encodings are longer and some i16 instructions are slow.
23276 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23277   if (!isTypeLegal(VT))
23278     return false;
23279   if (VT != MVT::i16)
23280     return true;
23281
23282   switch (Opc) {
23283   default:
23284     return true;
23285   case ISD::LOAD:
23286   case ISD::SIGN_EXTEND:
23287   case ISD::ZERO_EXTEND:
23288   case ISD::ANY_EXTEND:
23289   case ISD::SHL:
23290   case ISD::SRL:
23291   case ISD::SUB:
23292   case ISD::ADD:
23293   case ISD::MUL:
23294   case ISD::AND:
23295   case ISD::OR:
23296   case ISD::XOR:
23297     return false;
23298   }
23299 }
23300
23301 /// IsDesirableToPromoteOp - This method query the target whether it is
23302 /// beneficial for dag combiner to promote the specified node. If true, it
23303 /// should return the desired promotion type by reference.
23304 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
23305   EVT VT = Op.getValueType();
23306   if (VT != MVT::i16)
23307     return false;
23308
23309   bool Promote = false;
23310   bool Commute = false;
23311   switch (Op.getOpcode()) {
23312   default: break;
23313   case ISD::LOAD: {
23314     LoadSDNode *LD = cast<LoadSDNode>(Op);
23315     // If the non-extending load has a single use and it's not live out, then it
23316     // might be folded.
23317     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
23318                                                      Op.hasOneUse()*/) {
23319       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
23320              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
23321         // The only case where we'd want to promote LOAD (rather then it being
23322         // promoted as an operand is when it's only use is liveout.
23323         if (UI->getOpcode() != ISD::CopyToReg)
23324           return false;
23325       }
23326     }
23327     Promote = true;
23328     break;
23329   }
23330   case ISD::SIGN_EXTEND:
23331   case ISD::ZERO_EXTEND:
23332   case ISD::ANY_EXTEND:
23333     Promote = true;
23334     break;
23335   case ISD::SHL:
23336   case ISD::SRL: {
23337     SDValue N0 = Op.getOperand(0);
23338     // Look out for (store (shl (load), x)).
23339     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
23340       return false;
23341     Promote = true;
23342     break;
23343   }
23344   case ISD::ADD:
23345   case ISD::MUL:
23346   case ISD::AND:
23347   case ISD::OR:
23348   case ISD::XOR:
23349     Commute = true;
23350     // fallthrough
23351   case ISD::SUB: {
23352     SDValue N0 = Op.getOperand(0);
23353     SDValue N1 = Op.getOperand(1);
23354     if (!Commute && MayFoldLoad(N1))
23355       return false;
23356     // Avoid disabling potential load folding opportunities.
23357     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
23358       return false;
23359     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
23360       return false;
23361     Promote = true;
23362   }
23363   }
23364
23365   PVT = MVT::i32;
23366   return Promote;
23367 }
23368
23369 //===----------------------------------------------------------------------===//
23370 //                           X86 Inline Assembly Support
23371 //===----------------------------------------------------------------------===//
23372
23373 namespace {
23374   // Helper to match a string separated by whitespace.
23375   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
23376     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
23377
23378     for (unsigned i = 0, e = args.size(); i != e; ++i) {
23379       StringRef piece(*args[i]);
23380       if (!s.startswith(piece)) // Check if the piece matches.
23381         return false;
23382
23383       s = s.substr(piece.size());
23384       StringRef::size_type pos = s.find_first_not_of(" \t");
23385       if (pos == 0) // We matched a prefix.
23386         return false;
23387
23388       s = s.substr(pos);
23389     }
23390
23391     return s.empty();
23392   }
23393   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
23394 }
23395
23396 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
23397
23398   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
23399     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
23400         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
23401         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
23402
23403       if (AsmPieces.size() == 3)
23404         return true;
23405       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
23406         return true;
23407     }
23408   }
23409   return false;
23410 }
23411
23412 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
23413   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
23414
23415   std::string AsmStr = IA->getAsmString();
23416
23417   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
23418   if (!Ty || Ty->getBitWidth() % 16 != 0)
23419     return false;
23420
23421   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
23422   SmallVector<StringRef, 4> AsmPieces;
23423   SplitString(AsmStr, AsmPieces, ";\n");
23424
23425   switch (AsmPieces.size()) {
23426   default: return false;
23427   case 1:
23428     // FIXME: this should verify that we are targeting a 486 or better.  If not,
23429     // we will turn this bswap into something that will be lowered to logical
23430     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
23431     // lower so don't worry about this.
23432     // bswap $0
23433     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
23434         matchAsm(AsmPieces[0], "bswapl", "$0") ||
23435         matchAsm(AsmPieces[0], "bswapq", "$0") ||
23436         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
23437         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
23438         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
23439       // No need to check constraints, nothing other than the equivalent of
23440       // "=r,0" would be valid here.
23441       return IntrinsicLowering::LowerToByteSwap(CI);
23442     }
23443
23444     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
23445     if (CI->getType()->isIntegerTy(16) &&
23446         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23447         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
23448          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
23449       AsmPieces.clear();
23450       const std::string &ConstraintsStr = IA->getConstraintString();
23451       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23452       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23453       if (clobbersFlagRegisters(AsmPieces))
23454         return IntrinsicLowering::LowerToByteSwap(CI);
23455     }
23456     break;
23457   case 3:
23458     if (CI->getType()->isIntegerTy(32) &&
23459         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
23460         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
23461         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
23462         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
23463       AsmPieces.clear();
23464       const std::string &ConstraintsStr = IA->getConstraintString();
23465       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
23466       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
23467       if (clobbersFlagRegisters(AsmPieces))
23468         return IntrinsicLowering::LowerToByteSwap(CI);
23469     }
23470
23471     if (CI->getType()->isIntegerTy(64)) {
23472       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
23473       if (Constraints.size() >= 2 &&
23474           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
23475           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
23476         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
23477         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
23478             matchAsm(AsmPieces[1], "bswap", "%edx") &&
23479             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
23480           return IntrinsicLowering::LowerToByteSwap(CI);
23481       }
23482     }
23483     break;
23484   }
23485   return false;
23486 }
23487
23488 /// getConstraintType - Given a constraint letter, return the type of
23489 /// constraint it is for this target.
23490 X86TargetLowering::ConstraintType
23491 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
23492   if (Constraint.size() == 1) {
23493     switch (Constraint[0]) {
23494     case 'R':
23495     case 'q':
23496     case 'Q':
23497     case 'f':
23498     case 't':
23499     case 'u':
23500     case 'y':
23501     case 'x':
23502     case 'Y':
23503     case 'l':
23504       return C_RegisterClass;
23505     case 'a':
23506     case 'b':
23507     case 'c':
23508     case 'd':
23509     case 'S':
23510     case 'D':
23511     case 'A':
23512       return C_Register;
23513     case 'I':
23514     case 'J':
23515     case 'K':
23516     case 'L':
23517     case 'M':
23518     case 'N':
23519     case 'G':
23520     case 'C':
23521     case 'e':
23522     case 'Z':
23523       return C_Other;
23524     default:
23525       break;
23526     }
23527   }
23528   return TargetLowering::getConstraintType(Constraint);
23529 }
23530
23531 /// Examine constraint type and operand type and determine a weight value.
23532 /// This object must already have been set up with the operand type
23533 /// and the current alternative constraint selected.
23534 TargetLowering::ConstraintWeight
23535   X86TargetLowering::getSingleConstraintMatchWeight(
23536     AsmOperandInfo &info, const char *constraint) const {
23537   ConstraintWeight weight = CW_Invalid;
23538   Value *CallOperandVal = info.CallOperandVal;
23539     // If we don't have a value, we can't do a match,
23540     // but allow it at the lowest weight.
23541   if (!CallOperandVal)
23542     return CW_Default;
23543   Type *type = CallOperandVal->getType();
23544   // Look at the constraint type.
23545   switch (*constraint) {
23546   default:
23547     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
23548   case 'R':
23549   case 'q':
23550   case 'Q':
23551   case 'a':
23552   case 'b':
23553   case 'c':
23554   case 'd':
23555   case 'S':
23556   case 'D':
23557   case 'A':
23558     if (CallOperandVal->getType()->isIntegerTy())
23559       weight = CW_SpecificReg;
23560     break;
23561   case 'f':
23562   case 't':
23563   case 'u':
23564     if (type->isFloatingPointTy())
23565       weight = CW_SpecificReg;
23566     break;
23567   case 'y':
23568     if (type->isX86_MMXTy() && Subtarget->hasMMX())
23569       weight = CW_SpecificReg;
23570     break;
23571   case 'x':
23572   case 'Y':
23573     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
23574         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
23575       weight = CW_Register;
23576     break;
23577   case 'I':
23578     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
23579       if (C->getZExtValue() <= 31)
23580         weight = CW_Constant;
23581     }
23582     break;
23583   case 'J':
23584     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23585       if (C->getZExtValue() <= 63)
23586         weight = CW_Constant;
23587     }
23588     break;
23589   case 'K':
23590     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23591       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23592         weight = CW_Constant;
23593     }
23594     break;
23595   case 'L':
23596     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23597       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23598         weight = CW_Constant;
23599     }
23600     break;
23601   case 'M':
23602     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23603       if (C->getZExtValue() <= 3)
23604         weight = CW_Constant;
23605     }
23606     break;
23607   case 'N':
23608     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23609       if (C->getZExtValue() <= 0xff)
23610         weight = CW_Constant;
23611     }
23612     break;
23613   case 'G':
23614   case 'C':
23615     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23616       weight = CW_Constant;
23617     }
23618     break;
23619   case 'e':
23620     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23621       if ((C->getSExtValue() >= -0x80000000LL) &&
23622           (C->getSExtValue() <= 0x7fffffffLL))
23623         weight = CW_Constant;
23624     }
23625     break;
23626   case 'Z':
23627     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23628       if (C->getZExtValue() <= 0xffffffff)
23629         weight = CW_Constant;
23630     }
23631     break;
23632   }
23633   return weight;
23634 }
23635
23636 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23637 /// with another that has more specific requirements based on the type of the
23638 /// corresponding operand.
23639 const char *X86TargetLowering::
23640 LowerXConstraint(EVT ConstraintVT) const {
23641   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23642   // 'f' like normal targets.
23643   if (ConstraintVT.isFloatingPoint()) {
23644     if (Subtarget->hasSSE2())
23645       return "Y";
23646     if (Subtarget->hasSSE1())
23647       return "x";
23648   }
23649
23650   return TargetLowering::LowerXConstraint(ConstraintVT);
23651 }
23652
23653 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23654 /// vector.  If it is invalid, don't add anything to Ops.
23655 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23656                                                      std::string &Constraint,
23657                                                      std::vector<SDValue>&Ops,
23658                                                      SelectionDAG &DAG) const {
23659   SDValue Result;
23660
23661   // Only support length 1 constraints for now.
23662   if (Constraint.length() > 1) return;
23663
23664   char ConstraintLetter = Constraint[0];
23665   switch (ConstraintLetter) {
23666   default: break;
23667   case 'I':
23668     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23669       if (C->getZExtValue() <= 31) {
23670         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23671         break;
23672       }
23673     }
23674     return;
23675   case 'J':
23676     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23677       if (C->getZExtValue() <= 63) {
23678         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23679         break;
23680       }
23681     }
23682     return;
23683   case 'K':
23684     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23685       if (isInt<8>(C->getSExtValue())) {
23686         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23687         break;
23688       }
23689     }
23690     return;
23691   case 'N':
23692     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23693       if (C->getZExtValue() <= 255) {
23694         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23695         break;
23696       }
23697     }
23698     return;
23699   case 'e': {
23700     // 32-bit signed value
23701     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23702       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23703                                            C->getSExtValue())) {
23704         // Widen to 64 bits here to get it sign extended.
23705         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23706         break;
23707       }
23708     // FIXME gcc accepts some relocatable values here too, but only in certain
23709     // memory models; it's complicated.
23710     }
23711     return;
23712   }
23713   case 'Z': {
23714     // 32-bit unsigned value
23715     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23716       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23717                                            C->getZExtValue())) {
23718         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23719         break;
23720       }
23721     }
23722     // FIXME gcc accepts some relocatable values here too, but only in certain
23723     // memory models; it's complicated.
23724     return;
23725   }
23726   case 'i': {
23727     // Literal immediates are always ok.
23728     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23729       // Widen to 64 bits here to get it sign extended.
23730       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23731       break;
23732     }
23733
23734     // In any sort of PIC mode addresses need to be computed at runtime by
23735     // adding in a register or some sort of table lookup.  These can't
23736     // be used as immediates.
23737     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23738       return;
23739
23740     // If we are in non-pic codegen mode, we allow the address of a global (with
23741     // an optional displacement) to be used with 'i'.
23742     GlobalAddressSDNode *GA = nullptr;
23743     int64_t Offset = 0;
23744
23745     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23746     while (1) {
23747       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23748         Offset += GA->getOffset();
23749         break;
23750       } else if (Op.getOpcode() == ISD::ADD) {
23751         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23752           Offset += C->getZExtValue();
23753           Op = Op.getOperand(0);
23754           continue;
23755         }
23756       } else if (Op.getOpcode() == ISD::SUB) {
23757         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23758           Offset += -C->getZExtValue();
23759           Op = Op.getOperand(0);
23760           continue;
23761         }
23762       }
23763
23764       // Otherwise, this isn't something we can handle, reject it.
23765       return;
23766     }
23767
23768     const GlobalValue *GV = GA->getGlobal();
23769     // If we require an extra load to get this address, as in PIC mode, we
23770     // can't accept it.
23771     if (isGlobalStubReference(
23772             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23773       return;
23774
23775     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23776                                         GA->getValueType(0), Offset);
23777     break;
23778   }
23779   }
23780
23781   if (Result.getNode()) {
23782     Ops.push_back(Result);
23783     return;
23784   }
23785   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23786 }
23787
23788 std::pair<unsigned, const TargetRegisterClass*>
23789 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23790                                                 MVT VT) const {
23791   // First, see if this is a constraint that directly corresponds to an LLVM
23792   // register class.
23793   if (Constraint.size() == 1) {
23794     // GCC Constraint Letters
23795     switch (Constraint[0]) {
23796     default: break;
23797       // TODO: Slight differences here in allocation order and leaving
23798       // RIP in the class. Do they matter any more here than they do
23799       // in the normal allocation?
23800     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23801       if (Subtarget->is64Bit()) {
23802         if (VT == MVT::i32 || VT == MVT::f32)
23803           return std::make_pair(0U, &X86::GR32RegClass);
23804         if (VT == MVT::i16)
23805           return std::make_pair(0U, &X86::GR16RegClass);
23806         if (VT == MVT::i8 || VT == MVT::i1)
23807           return std::make_pair(0U, &X86::GR8RegClass);
23808         if (VT == MVT::i64 || VT == MVT::f64)
23809           return std::make_pair(0U, &X86::GR64RegClass);
23810         break;
23811       }
23812       // 32-bit fallthrough
23813     case 'Q':   // Q_REGS
23814       if (VT == MVT::i32 || VT == MVT::f32)
23815         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23816       if (VT == MVT::i16)
23817         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23818       if (VT == MVT::i8 || VT == MVT::i1)
23819         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23820       if (VT == MVT::i64)
23821         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23822       break;
23823     case 'r':   // GENERAL_REGS
23824     case 'l':   // INDEX_REGS
23825       if (VT == MVT::i8 || VT == MVT::i1)
23826         return std::make_pair(0U, &X86::GR8RegClass);
23827       if (VT == MVT::i16)
23828         return std::make_pair(0U, &X86::GR16RegClass);
23829       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23830         return std::make_pair(0U, &X86::GR32RegClass);
23831       return std::make_pair(0U, &X86::GR64RegClass);
23832     case 'R':   // LEGACY_REGS
23833       if (VT == MVT::i8 || VT == MVT::i1)
23834         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23835       if (VT == MVT::i16)
23836         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23837       if (VT == MVT::i32 || !Subtarget->is64Bit())
23838         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23839       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23840     case 'f':  // FP Stack registers.
23841       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23842       // value to the correct fpstack register class.
23843       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23844         return std::make_pair(0U, &X86::RFP32RegClass);
23845       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23846         return std::make_pair(0U, &X86::RFP64RegClass);
23847       return std::make_pair(0U, &X86::RFP80RegClass);
23848     case 'y':   // MMX_REGS if MMX allowed.
23849       if (!Subtarget->hasMMX()) break;
23850       return std::make_pair(0U, &X86::VR64RegClass);
23851     case 'Y':   // SSE_REGS if SSE2 allowed
23852       if (!Subtarget->hasSSE2()) break;
23853       // FALL THROUGH.
23854     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23855       if (!Subtarget->hasSSE1()) break;
23856
23857       switch (VT.SimpleTy) {
23858       default: break;
23859       // Scalar SSE types.
23860       case MVT::f32:
23861       case MVT::i32:
23862         return std::make_pair(0U, &X86::FR32RegClass);
23863       case MVT::f64:
23864       case MVT::i64:
23865         return std::make_pair(0U, &X86::FR64RegClass);
23866       // Vector types.
23867       case MVT::v16i8:
23868       case MVT::v8i16:
23869       case MVT::v4i32:
23870       case MVT::v2i64:
23871       case MVT::v4f32:
23872       case MVT::v2f64:
23873         return std::make_pair(0U, &X86::VR128RegClass);
23874       // AVX types.
23875       case MVT::v32i8:
23876       case MVT::v16i16:
23877       case MVT::v8i32:
23878       case MVT::v4i64:
23879       case MVT::v8f32:
23880       case MVT::v4f64:
23881         return std::make_pair(0U, &X86::VR256RegClass);
23882       case MVT::v8f64:
23883       case MVT::v16f32:
23884       case MVT::v16i32:
23885       case MVT::v8i64:
23886         return std::make_pair(0U, &X86::VR512RegClass);
23887       }
23888       break;
23889     }
23890   }
23891
23892   // Use the default implementation in TargetLowering to convert the register
23893   // constraint into a member of a register class.
23894   std::pair<unsigned, const TargetRegisterClass*> Res;
23895   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23896
23897   // Not found as a standard register?
23898   if (!Res.second) {
23899     // Map st(0) -> st(7) -> ST0
23900     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23901         tolower(Constraint[1]) == 's' &&
23902         tolower(Constraint[2]) == 't' &&
23903         Constraint[3] == '(' &&
23904         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23905         Constraint[5] == ')' &&
23906         Constraint[6] == '}') {
23907
23908       Res.first = X86::FP0+Constraint[4]-'0';
23909       Res.second = &X86::RFP80RegClass;
23910       return Res;
23911     }
23912
23913     // GCC allows "st(0)" to be called just plain "st".
23914     if (StringRef("{st}").equals_lower(Constraint)) {
23915       Res.first = X86::FP0;
23916       Res.second = &X86::RFP80RegClass;
23917       return Res;
23918     }
23919
23920     // flags -> EFLAGS
23921     if (StringRef("{flags}").equals_lower(Constraint)) {
23922       Res.first = X86::EFLAGS;
23923       Res.second = &X86::CCRRegClass;
23924       return Res;
23925     }
23926
23927     // 'A' means EAX + EDX.
23928     if (Constraint == "A") {
23929       Res.first = X86::EAX;
23930       Res.second = &X86::GR32_ADRegClass;
23931       return Res;
23932     }
23933     return Res;
23934   }
23935
23936   // Otherwise, check to see if this is a register class of the wrong value
23937   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23938   // turn into {ax},{dx}.
23939   if (Res.second->hasType(VT))
23940     return Res;   // Correct type already, nothing to do.
23941
23942   // All of the single-register GCC register classes map their values onto
23943   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23944   // really want an 8-bit or 32-bit register, map to the appropriate register
23945   // class and return the appropriate register.
23946   if (Res.second == &X86::GR16RegClass) {
23947     if (VT == MVT::i8 || VT == MVT::i1) {
23948       unsigned DestReg = 0;
23949       switch (Res.first) {
23950       default: break;
23951       case X86::AX: DestReg = X86::AL; break;
23952       case X86::DX: DestReg = X86::DL; break;
23953       case X86::CX: DestReg = X86::CL; break;
23954       case X86::BX: DestReg = X86::BL; break;
23955       }
23956       if (DestReg) {
23957         Res.first = DestReg;
23958         Res.second = &X86::GR8RegClass;
23959       }
23960     } else if (VT == MVT::i32 || VT == MVT::f32) {
23961       unsigned DestReg = 0;
23962       switch (Res.first) {
23963       default: break;
23964       case X86::AX: DestReg = X86::EAX; break;
23965       case X86::DX: DestReg = X86::EDX; break;
23966       case X86::CX: DestReg = X86::ECX; break;
23967       case X86::BX: DestReg = X86::EBX; break;
23968       case X86::SI: DestReg = X86::ESI; break;
23969       case X86::DI: DestReg = X86::EDI; break;
23970       case X86::BP: DestReg = X86::EBP; break;
23971       case X86::SP: DestReg = X86::ESP; break;
23972       }
23973       if (DestReg) {
23974         Res.first = DestReg;
23975         Res.second = &X86::GR32RegClass;
23976       }
23977     } else if (VT == MVT::i64 || VT == MVT::f64) {
23978       unsigned DestReg = 0;
23979       switch (Res.first) {
23980       default: break;
23981       case X86::AX: DestReg = X86::RAX; break;
23982       case X86::DX: DestReg = X86::RDX; break;
23983       case X86::CX: DestReg = X86::RCX; break;
23984       case X86::BX: DestReg = X86::RBX; break;
23985       case X86::SI: DestReg = X86::RSI; break;
23986       case X86::DI: DestReg = X86::RDI; break;
23987       case X86::BP: DestReg = X86::RBP; break;
23988       case X86::SP: DestReg = X86::RSP; break;
23989       }
23990       if (DestReg) {
23991         Res.first = DestReg;
23992         Res.second = &X86::GR64RegClass;
23993       }
23994     }
23995   } else if (Res.second == &X86::FR32RegClass ||
23996              Res.second == &X86::FR64RegClass ||
23997              Res.second == &X86::VR128RegClass ||
23998              Res.second == &X86::VR256RegClass ||
23999              Res.second == &X86::FR32XRegClass ||
24000              Res.second == &X86::FR64XRegClass ||
24001              Res.second == &X86::VR128XRegClass ||
24002              Res.second == &X86::VR256XRegClass ||
24003              Res.second == &X86::VR512RegClass) {
24004     // Handle references to XMM physical registers that got mapped into the
24005     // wrong class.  This can happen with constraints like {xmm0} where the
24006     // target independent register mapper will just pick the first match it can
24007     // find, ignoring the required type.
24008
24009     if (VT == MVT::f32 || VT == MVT::i32)
24010       Res.second = &X86::FR32RegClass;
24011     else if (VT == MVT::f64 || VT == MVT::i64)
24012       Res.second = &X86::FR64RegClass;
24013     else if (X86::VR128RegClass.hasType(VT))
24014       Res.second = &X86::VR128RegClass;
24015     else if (X86::VR256RegClass.hasType(VT))
24016       Res.second = &X86::VR256RegClass;
24017     else if (X86::VR512RegClass.hasType(VT))
24018       Res.second = &X86::VR512RegClass;
24019   }
24020
24021   return Res;
24022 }
24023
24024 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24025                                             Type *Ty) const {
24026   // Scaling factors are not free at all.
24027   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24028   // will take 2 allocations in the out of order engine instead of 1
24029   // for plain addressing mode, i.e. inst (reg1).
24030   // E.g.,
24031   // vaddps (%rsi,%drx), %ymm0, %ymm1
24032   // Requires two allocations (one for the load, one for the computation)
24033   // whereas:
24034   // vaddps (%rsi), %ymm0, %ymm1
24035   // Requires just 1 allocation, i.e., freeing allocations for other operations
24036   // and having less micro operations to execute.
24037   //
24038   // For some X86 architectures, this is even worse because for instance for
24039   // stores, the complex addressing mode forces the instruction to use the
24040   // "load" ports instead of the dedicated "store" port.
24041   // E.g., on Haswell:
24042   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24043   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
24044   if (isLegalAddressingMode(AM, Ty))
24045     // Scale represents reg2 * scale, thus account for 1
24046     // as soon as we use a second register.
24047     return AM.Scale != 0;
24048   return -1;
24049 }
24050
24051 bool X86TargetLowering::isTargetFTOL() const {
24052   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24053 }