[x86] Fix a really terrible bug in the repeated 128-bin-lane shuffle
[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/SmallBitVector.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/VariadicFunction.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/IR/CallSite.h"
36 #include "llvm/IR/CallingConv.h"
37 #include "llvm/IR/Constants.h"
38 #include "llvm/IR/DerivedTypes.h"
39 #include "llvm/IR/Function.h"
40 #include "llvm/IR/GlobalAlias.h"
41 #include "llvm/IR/GlobalVariable.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/Intrinsics.h"
44 #include "llvm/MC/MCAsmInfo.h"
45 #include "llvm/MC/MCContext.h"
46 #include "llvm/MC/MCExpr.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/Support/CommandLine.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Target/TargetOptions.h"
53 #include "X86IntrinsicsInfo.h"
54 #include <bitset>
55 #include <numeric>
56 #include <cctype>
57 using namespace llvm;
58
59 #define DEBUG_TYPE "x86-isel"
60
61 STATISTIC(NumTailCalls, "Number of tail calls");
62
63 static cl::opt<bool> ExperimentalVectorWideningLegalization(
64     "x86-experimental-vector-widening-legalization", cl::init(false),
65     cl::desc("Enable an experimental vector type legalization through widening "
66              "rather than promotion."),
67     cl::Hidden);
68
69 static cl::opt<bool> ExperimentalVectorShuffleLowering(
70     "x86-experimental-vector-shuffle-lowering", cl::init(false),
71     cl::desc("Enable an experimental vector shuffle lowering code path."),
72     cl::Hidden);
73
74 // Forward declarations.
75 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
76                        SDValue V2);
77
78 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
79                                 SelectionDAG &DAG, SDLoc dl,
80                                 unsigned vectorWidth) {
81   assert((vectorWidth == 128 || vectorWidth == 256) &&
82          "Unsupported vector width");
83   EVT VT = Vec.getValueType();
84   EVT ElVT = VT.getVectorElementType();
85   unsigned Factor = VT.getSizeInBits()/vectorWidth;
86   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
87                                   VT.getVectorNumElements()/Factor);
88
89   // Extract from UNDEF is UNDEF.
90   if (Vec.getOpcode() == ISD::UNDEF)
91     return DAG.getUNDEF(ResultVT);
92
93   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
94   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
95
96   // This is the index of the first element of the vectorWidth-bit chunk
97   // we want.
98   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
99                                * ElemsPerChunk);
100
101   // If the input is a buildvector just emit a smaller one.
102   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
103     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
104                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
105                                     ElemsPerChunk));
106
107   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
108   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
109                                VecIdx);
110
111   return Result;
112
113 }
114 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
115 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
116 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
117 /// instructions or a simple subregister reference. Idx is an index in the
118 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
119 /// lowering EXTRACT_VECTOR_ELT operations easier.
120 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
121                                    SelectionDAG &DAG, SDLoc dl) {
122   assert((Vec.getValueType().is256BitVector() ||
123           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
124   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
125 }
126
127 /// Generate a DAG to grab 256-bits from a 512-bit vector.
128 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
129                                    SelectionDAG &DAG, SDLoc dl) {
130   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
131   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
132 }
133
134 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
135                                unsigned IdxVal, SelectionDAG &DAG,
136                                SDLoc dl, unsigned vectorWidth) {
137   assert((vectorWidth == 128 || vectorWidth == 256) &&
138          "Unsupported vector width");
139   // Inserting UNDEF is Result
140   if (Vec.getOpcode() == ISD::UNDEF)
141     return Result;
142   EVT VT = Vec.getValueType();
143   EVT ElVT = VT.getVectorElementType();
144   EVT ResultVT = Result.getValueType();
145
146   // Insert the relevant vectorWidth bits.
147   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
148
149   // This is the index of the first element of the vectorWidth-bit chunk
150   // we want.
151   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
152                                * ElemsPerChunk);
153
154   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
155   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
156                      VecIdx);
157 }
158 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
159 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
160 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
161 /// simple superregister reference.  Idx is an index in the 128 bits
162 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
163 /// lowering INSERT_VECTOR_ELT operations easier.
164 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
165                                   unsigned IdxVal, SelectionDAG &DAG,
166                                   SDLoc dl) {
167   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
168   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
169 }
170
171 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
172                                   unsigned IdxVal, SelectionDAG &DAG,
173                                   SDLoc dl) {
174   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
175   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
176 }
177
178 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
179 /// instructions. This is used because creating CONCAT_VECTOR nodes of
180 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
181 /// large BUILD_VECTORS.
182 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
183                                    unsigned NumElems, SelectionDAG &DAG,
184                                    SDLoc dl) {
185   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
186   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
187 }
188
189 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
190                                    unsigned NumElems, SelectionDAG &DAG,
191                                    SDLoc dl) {
192   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
193   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
194 }
195
196 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
197   if (TT.isOSBinFormatMachO()) {
198     if (TT.getArch() == Triple::x86_64)
199       return new X86_64MachoTargetObjectFile();
200     return new TargetLoweringObjectFileMachO();
201   }
202
203   if (TT.isOSLinux())
204     return new X86LinuxTargetObjectFile();
205   if (TT.isOSBinFormatELF())
206     return new TargetLoweringObjectFileELF();
207   if (TT.isKnownWindowsMSVCEnvironment())
208     return new X86WindowsTargetObjectFile();
209   if (TT.isOSBinFormatCOFF())
210     return new TargetLoweringObjectFileCOFF();
211   llvm_unreachable("unknown subtarget type");
212 }
213
214 // FIXME: This should stop caching the target machine as soon as
215 // we can remove resetOperationActions et al.
216 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
217   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
218   Subtarget = &TM.getSubtarget<X86Subtarget>();
219   X86ScalarSSEf64 = Subtarget->hasSSE2();
220   X86ScalarSSEf32 = Subtarget->hasSSE1();
221   TD = getDataLayout();
222
223   resetOperationActions();
224 }
225
226 void X86TargetLowering::resetOperationActions() {
227   const TargetMachine &TM = getTargetMachine();
228   static bool FirstTimeThrough = true;
229
230   // If none of the target options have changed, then we don't need to reset the
231   // operation actions.
232   if (!FirstTimeThrough && TO == TM.Options) return;
233
234   if (!FirstTimeThrough) {
235     // Reinitialize the actions.
236     initActions();
237     FirstTimeThrough = false;
238   }
239
240   TO = TM.Options;
241
242   // Set up the TargetLowering object.
243   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
244
245   // X86 is weird, it always uses i8 for shift amounts and setcc results.
246   setBooleanContents(ZeroOrOneBooleanContent);
247   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
248   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
249
250   // For 64-bit since we have so many registers use the ILP scheduler, for
251   // 32-bit code use the register pressure specific scheduling.
252   // For Atom, always use ILP scheduling.
253   if (Subtarget->isAtom())
254     setSchedulingPreference(Sched::ILP);
255   else if (Subtarget->is64Bit())
256     setSchedulingPreference(Sched::ILP);
257   else
258     setSchedulingPreference(Sched::RegPressure);
259   const X86RegisterInfo *RegInfo =
260       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
261   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
262
263   // Bypass expensive divides on Atom when compiling with O2
264   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
265     addBypassSlowDiv(32, 8);
266     if (Subtarget->is64Bit())
267       addBypassSlowDiv(64, 16);
268   }
269
270   if (Subtarget->isTargetKnownWindowsMSVC()) {
271     // Setup Windows compiler runtime calls.
272     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
273     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
274     setLibcallName(RTLIB::SREM_I64, "_allrem");
275     setLibcallName(RTLIB::UREM_I64, "_aullrem");
276     setLibcallName(RTLIB::MUL_I64, "_allmul");
277     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
280     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
281     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
282
283     // The _ftol2 runtime function has an unusual calling conv, which
284     // is modeled by a special pseudo-instruction.
285     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
287     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
288     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
289   }
290
291   if (Subtarget->isTargetDarwin()) {
292     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
293     setUseUnderscoreSetJmp(false);
294     setUseUnderscoreLongJmp(false);
295   } else if (Subtarget->isTargetWindowsGNU()) {
296     // MS runtime is weird: it exports _setjmp, but longjmp!
297     setUseUnderscoreSetJmp(true);
298     setUseUnderscoreLongJmp(false);
299   } else {
300     setUseUnderscoreSetJmp(true);
301     setUseUnderscoreLongJmp(true);
302   }
303
304   // Set up the register classes.
305   addRegisterClass(MVT::i8, &X86::GR8RegClass);
306   addRegisterClass(MVT::i16, &X86::GR16RegClass);
307   addRegisterClass(MVT::i32, &X86::GR32RegClass);
308   if (Subtarget->is64Bit())
309     addRegisterClass(MVT::i64, &X86::GR64RegClass);
310
311   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
312
313   // We don't accept any truncstore of integer registers.
314   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
315   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
318   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
319   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
320
321   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
322
323   // SETOEQ and SETUNE require checking two conditions.
324   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
325   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
326   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
327   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
328   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
329   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
330
331   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
332   // operation.
333   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
334   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
335   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
336
337   if (Subtarget->is64Bit()) {
338     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340   } else if (!TM.Options.UseSoftFloat) {
341     // We have an algorithm for SSE2->double, and we turn this into a
342     // 64-bit FILD followed by conditional FADD for other targets.
343     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
344     // We have an algorithm for SSE2, and we turn this into a 64-bit
345     // FILD for other targets.
346     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
347   }
348
349   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
350   // this operation.
351   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
352   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
353
354   if (!TM.Options.UseSoftFloat) {
355     // SSE has no i16 to fp conversion, only i32
356     if (X86ScalarSSEf32) {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
358       // f32 and f64 cases are Legal, f80 case is not
359       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
360     } else {
361       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
362       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
363     }
364   } else {
365     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
366     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
367   }
368
369   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
370   // are Legal, f80 is custom lowered.
371   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
372   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
373
374   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
375   // this operation.
376   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
377   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
378
379   if (X86ScalarSSEf32) {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
381     // f32 and f64 cases are Legal, f80 case is not
382     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
383   } else {
384     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
385     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
386   }
387
388   // Handle FP_TO_UINT by promoting the destination to a larger signed
389   // conversion.
390   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
391   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
392   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
393
394   if (Subtarget->is64Bit()) {
395     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
396     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
397   } else if (!TM.Options.UseSoftFloat) {
398     // Since AVX is a superset of SSE3, only check for SSE here.
399     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
400       // Expand FP_TO_UINT into a select.
401       // FIXME: We would like to use a Custom expander here eventually to do
402       // the optimal thing for SSE vs. the default expansion in the legalizer.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
404     else
405       // With SSE3 we can use fisttpll to convert to a signed i64; without
406       // SSE, we're stuck with a fistpll.
407       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
408   }
409
410   if (isTargetFTOL()) {
411     // Use the _ftol2 runtime function, which has a pseudo-instruction
412     // to handle its weird calling convention.
413     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
414   }
415
416   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
417   if (!X86ScalarSSEf64) {
418     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
419     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
420     if (Subtarget->is64Bit()) {
421       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
422       // Without SSE, i64->f64 goes through memory.
423       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
424     }
425   }
426
427   // Scalar integer divide and remainder are lowered to use operations that
428   // produce two results, to match the available instructions. This exposes
429   // the two-result form to trivial CSE, which is able to combine x/y and x%y
430   // into a single instruction.
431   //
432   // Scalar integer multiply-high is also lowered to use two-result
433   // operations, to match the available instructions. However, plain multiply
434   // (low) operations are left as Legal, as there are single-result
435   // instructions for this in x86. Using the two-result multiply instructions
436   // when both high and low results are needed must be arranged by dagcombine.
437   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
438     MVT VT = IntVTs[i];
439     setOperationAction(ISD::MULHS, VT, Expand);
440     setOperationAction(ISD::MULHU, VT, Expand);
441     setOperationAction(ISD::SDIV, VT, Expand);
442     setOperationAction(ISD::UDIV, VT, Expand);
443     setOperationAction(ISD::SREM, VT, Expand);
444     setOperationAction(ISD::UREM, VT, Expand);
445
446     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
447     setOperationAction(ISD::ADDC, VT, Custom);
448     setOperationAction(ISD::ADDE, VT, Custom);
449     setOperationAction(ISD::SUBC, VT, Custom);
450     setOperationAction(ISD::SUBE, VT, Custom);
451   }
452
453   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
454   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
455   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
458   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
459   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
460   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
461   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
465   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
466   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
467   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
468   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
469   if (Subtarget->is64Bit())
470     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
471   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
472   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
473   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
474   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
475   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
476   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
477   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
478   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
479
480   // Promote the i8 variants and force them on up to i32 which has a shorter
481   // encoding.
482   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
483   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
484   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
485   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
486   if (Subtarget->hasBMI()) {
487     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
488     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
489     if (Subtarget->is64Bit())
490       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
491   } else {
492     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
493     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
494     if (Subtarget->is64Bit())
495       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
496   }
497
498   if (Subtarget->hasLZCNT()) {
499     // When promoting the i8 variants, force them to i32 for a shorter
500     // encoding.
501     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
502     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
503     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
504     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
505     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
506     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
507     if (Subtarget->is64Bit())
508       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
509   } else {
510     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
511     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
512     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
513     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
514     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
515     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
516     if (Subtarget->is64Bit()) {
517       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
518       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
519     }
520   }
521
522   // Special handling for half-precision floating point conversions.
523   // If we don't have F16C support, then lower half float conversions
524   // into library calls.
525   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
526     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
527     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
528   }
529
530   // There's never any support for operations beyond MVT::f32.
531   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
532   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
533   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
534   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
535
536   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
537   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
538   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
539   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
540
541   if (Subtarget->hasPOPCNT()) {
542     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
543   } else {
544     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
545     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
546     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
547     if (Subtarget->is64Bit())
548       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
549   }
550
551   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
552
553   if (!Subtarget->hasMOVBE())
554     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
555
556   // These should be promoted to a larger select which is supported.
557   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
558   // X86 wants to expand cmov itself.
559   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
560   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
561   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
562   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
563   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
564   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
566   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
567   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
568   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
569   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
570   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
571   if (Subtarget->is64Bit()) {
572     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
573     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
574   }
575   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
576   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
577   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
578   // support continuation, user-level threading, and etc.. As a result, no
579   // other SjLj exception interfaces are implemented and please don't build
580   // your own exception handling based on them.
581   // LLVM/Clang supports zero-cost DWARF exception handling.
582   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
583   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
584
585   // Darwin ABI issue.
586   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
587   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
588   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
589   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
590   if (Subtarget->is64Bit())
591     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
592   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
593   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
594   if (Subtarget->is64Bit()) {
595     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
596     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
597     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
598     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
599     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
600   }
601   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
602   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
603   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
604   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
605   if (Subtarget->is64Bit()) {
606     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
607     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
608     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
609   }
610
611   if (Subtarget->hasSSE1())
612     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
613
614   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
615
616   // Expand certain atomics
617   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
618     MVT VT = IntVTs[i];
619     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
620     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
621     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
622   }
623
624   if (Subtarget->hasCmpxchg16b()) {
625     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
626   }
627
628   // FIXME - use subtarget debug flags
629   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
630       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
631     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
632   }
633
634   if (Subtarget->is64Bit()) {
635     setExceptionPointerRegister(X86::RAX);
636     setExceptionSelectorRegister(X86::RDX);
637   } else {
638     setExceptionPointerRegister(X86::EAX);
639     setExceptionSelectorRegister(X86::EDX);
640   }
641   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
642   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
643
644   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
645   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
646
647   setOperationAction(ISD::TRAP, MVT::Other, Legal);
648   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
649
650   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
651   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
652   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
653   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
654     // TargetInfo::X86_64ABIBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
657   } else {
658     // TargetInfo::CharPtrBuiltinVaList
659     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
660     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
661   }
662
663   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
664   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
665
666   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
667
668   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
669     // f32 and f64 use SSE.
670     // Set up the FP register classes.
671     addRegisterClass(MVT::f32, &X86::FR32RegClass);
672     addRegisterClass(MVT::f64, &X86::FR64RegClass);
673
674     // Use ANDPD to simulate FABS.
675     setOperationAction(ISD::FABS , MVT::f64, Custom);
676     setOperationAction(ISD::FABS , MVT::f32, Custom);
677
678     // Use XORP to simulate FNEG.
679     setOperationAction(ISD::FNEG , MVT::f64, Custom);
680     setOperationAction(ISD::FNEG , MVT::f32, Custom);
681
682     // Use ANDPD and ORPD to simulate FCOPYSIGN.
683     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
684     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
685
686     // Lower this to FGETSIGNx86 plus an AND.
687     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
688     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
689
690     // We don't support sin/cos/fmod
691     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
694     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
695     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
696     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697
698     // Expand FP immediates into loads from the stack, except for the special
699     // cases we handle.
700     addLegalFPImmediate(APFloat(+0.0)); // xorpd
701     addLegalFPImmediate(APFloat(+0.0f)); // xorps
702   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
703     // Use SSE for f32, x87 for f64.
704     // Set up the FP register classes.
705     addRegisterClass(MVT::f32, &X86::FR32RegClass);
706     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
707
708     // Use ANDPS to simulate FABS.
709     setOperationAction(ISD::FABS , MVT::f32, Custom);
710
711     // Use XORP to simulate FNEG.
712     setOperationAction(ISD::FNEG , MVT::f32, Custom);
713
714     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
715
716     // Use ANDPS and ORPS to simulate FCOPYSIGN.
717     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
718     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
719
720     // We don't support sin/cos/fmod
721     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
722     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
723     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
724
725     // Special cases we handle for FP constants.
726     addLegalFPImmediate(APFloat(+0.0f)); // xorps
727     addLegalFPImmediate(APFloat(+0.0)); // FLD0
728     addLegalFPImmediate(APFloat(+1.0)); // FLD1
729     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
730     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
731
732     if (!TM.Options.UnsafeFPMath) {
733       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
734       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
735       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
736     }
737   } else if (!TM.Options.UseSoftFloat) {
738     // f32 and f64 in x87.
739     // Set up the FP register classes.
740     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
741     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
742
743     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
744     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
745     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
746     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
747
748     if (!TM.Options.UnsafeFPMath) {
749       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
750       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
751       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
752       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
753       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
754       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
755     }
756     addLegalFPImmediate(APFloat(+0.0)); // FLD0
757     addLegalFPImmediate(APFloat(+1.0)); // FLD1
758     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
759     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
760     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
761     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
762     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
763     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
764   }
765
766   // We don't support FMA.
767   setOperationAction(ISD::FMA, MVT::f64, Expand);
768   setOperationAction(ISD::FMA, MVT::f32, Expand);
769
770   // Long double always uses X87.
771   if (!TM.Options.UseSoftFloat) {
772     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
773     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
774     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
775     {
776       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
777       addLegalFPImmediate(TmpFlt);  // FLD0
778       TmpFlt.changeSign();
779       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
780
781       bool ignored;
782       APFloat TmpFlt2(+1.0);
783       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
784                       &ignored);
785       addLegalFPImmediate(TmpFlt2);  // FLD1
786       TmpFlt2.changeSign();
787       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
788     }
789
790     if (!TM.Options.UnsafeFPMath) {
791       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
792       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
793       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
794     }
795
796     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
797     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
798     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
799     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
800     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
801     setOperationAction(ISD::FMA, MVT::f80, Expand);
802   }
803
804   // Always use a library call for pow.
805   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
806   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
807   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
808
809   setOperationAction(ISD::FLOG, MVT::f80, Expand);
810   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
811   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
812   setOperationAction(ISD::FEXP, MVT::f80, Expand);
813   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
814
815   // First set operation action for all vector types to either promote
816   // (for widening) or expand (for scalarization). Then we will selectively
817   // turn on ones that can be effectively codegen'd.
818   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
819            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
820     MVT VT = (MVT::SimpleValueType)i;
821     setOperationAction(ISD::ADD , VT, Expand);
822     setOperationAction(ISD::SUB , VT, Expand);
823     setOperationAction(ISD::FADD, VT, Expand);
824     setOperationAction(ISD::FNEG, VT, Expand);
825     setOperationAction(ISD::FSUB, VT, Expand);
826     setOperationAction(ISD::MUL , VT, Expand);
827     setOperationAction(ISD::FMUL, VT, Expand);
828     setOperationAction(ISD::SDIV, VT, Expand);
829     setOperationAction(ISD::UDIV, VT, Expand);
830     setOperationAction(ISD::FDIV, VT, Expand);
831     setOperationAction(ISD::SREM, VT, Expand);
832     setOperationAction(ISD::UREM, VT, Expand);
833     setOperationAction(ISD::LOAD, VT, Expand);
834     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
835     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
836     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
837     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
838     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
839     setOperationAction(ISD::FABS, VT, Expand);
840     setOperationAction(ISD::FSIN, VT, Expand);
841     setOperationAction(ISD::FSINCOS, VT, Expand);
842     setOperationAction(ISD::FCOS, VT, Expand);
843     setOperationAction(ISD::FSINCOS, VT, Expand);
844     setOperationAction(ISD::FREM, VT, Expand);
845     setOperationAction(ISD::FMA,  VT, Expand);
846     setOperationAction(ISD::FPOWI, VT, Expand);
847     setOperationAction(ISD::FSQRT, VT, Expand);
848     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
849     setOperationAction(ISD::FFLOOR, VT, Expand);
850     setOperationAction(ISD::FCEIL, VT, Expand);
851     setOperationAction(ISD::FTRUNC, VT, Expand);
852     setOperationAction(ISD::FRINT, VT, Expand);
853     setOperationAction(ISD::FNEARBYINT, VT, Expand);
854     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
855     setOperationAction(ISD::MULHS, VT, Expand);
856     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
857     setOperationAction(ISD::MULHU, VT, Expand);
858     setOperationAction(ISD::SDIVREM, VT, Expand);
859     setOperationAction(ISD::UDIVREM, VT, Expand);
860     setOperationAction(ISD::FPOW, VT, Expand);
861     setOperationAction(ISD::CTPOP, VT, Expand);
862     setOperationAction(ISD::CTTZ, VT, Expand);
863     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
864     setOperationAction(ISD::CTLZ, VT, Expand);
865     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
866     setOperationAction(ISD::SHL, VT, Expand);
867     setOperationAction(ISD::SRA, VT, Expand);
868     setOperationAction(ISD::SRL, VT, Expand);
869     setOperationAction(ISD::ROTL, VT, Expand);
870     setOperationAction(ISD::ROTR, VT, Expand);
871     setOperationAction(ISD::BSWAP, VT, Expand);
872     setOperationAction(ISD::SETCC, VT, Expand);
873     setOperationAction(ISD::FLOG, VT, Expand);
874     setOperationAction(ISD::FLOG2, VT, Expand);
875     setOperationAction(ISD::FLOG10, VT, Expand);
876     setOperationAction(ISD::FEXP, VT, Expand);
877     setOperationAction(ISD::FEXP2, VT, Expand);
878     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
879     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
880     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
881     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
882     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
883     setOperationAction(ISD::TRUNCATE, VT, Expand);
884     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
885     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
886     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
887     setOperationAction(ISD::VSELECT, VT, Expand);
888     setOperationAction(ISD::SELECT_CC, VT, Expand);
889     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
890              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
891       setTruncStoreAction(VT,
892                           (MVT::SimpleValueType)InnerVT, Expand);
893     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
894     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
895
896     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
897     // we have to deal with them whether we ask for Expansion or not. Setting
898     // Expand causes its own optimisation problems though, so leave them legal.
899     if (VT.getVectorElementType() == MVT::i1)
900       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
901   }
902
903   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
904   // with -msoft-float, disable use of MMX as well.
905   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
906     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
907     // No operations on x86mmx supported, everything uses intrinsics.
908   }
909
910   // MMX-sized vectors (other than x86mmx) are expected to be expanded
911   // into smaller operations.
912   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
913   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
914   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
915   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
916   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
917   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
918   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
919   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
920   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
921   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
922   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
923   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
924   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
925   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
926   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
927   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
929   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
930   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
931   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
932   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
934   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
935   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
936   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
938   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
939   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
940   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
941
942   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
943     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
944
945     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
947     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
948     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
949     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
950     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
951     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
952     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
953     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
954     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
955     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
956     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
957   }
958
959   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
960     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
961
962     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
963     // registers cannot be used even for integer operations.
964     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
965     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
966     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
967     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
968
969     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
970     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
971     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
972     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
973     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
974     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
975     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
976     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
977     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
978     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
979     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
980     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
981     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
982     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
983     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
984     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
986     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
987     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
988     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
989     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
990     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
991
992     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
993     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
994     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
995     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
996
997     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
998     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
999     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1000     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1001     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1002
1003     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1004     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1005       MVT VT = (MVT::SimpleValueType)i;
1006       // Do not attempt to custom lower non-power-of-2 vectors
1007       if (!isPowerOf2_32(VT.getVectorNumElements()))
1008         continue;
1009       // Do not attempt to custom lower non-128-bit vectors
1010       if (!VT.is128BitVector())
1011         continue;
1012       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1013       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1014       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1015     }
1016
1017     // We support custom legalizing of sext and anyext loads for specific
1018     // memory vector types which we can load as a scalar (or sequence of
1019     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1020     // loads these must work with a single scalar load.
1021     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1022     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1023     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1029     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1030
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1032     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1034     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1035     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1036     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1037
1038     if (Subtarget->is64Bit()) {
1039       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1040       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1041     }
1042
1043     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1044     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1045       MVT VT = (MVT::SimpleValueType)i;
1046
1047       // Do not attempt to promote non-128-bit vectors
1048       if (!VT.is128BitVector())
1049         continue;
1050
1051       setOperationAction(ISD::AND,    VT, Promote);
1052       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1053       setOperationAction(ISD::OR,     VT, Promote);
1054       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1055       setOperationAction(ISD::XOR,    VT, Promote);
1056       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1057       setOperationAction(ISD::LOAD,   VT, Promote);
1058       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1059       setOperationAction(ISD::SELECT, VT, Promote);
1060       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1061     }
1062
1063     // Custom lower v2i64 and v2f64 selects.
1064     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1065     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1066     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1067     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1068
1069     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1070     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1071
1072     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1074     // As there is no 64-bit GPR available, we need build a special custom
1075     // sequence to convert from v2i32 to v2f32.
1076     if (!Subtarget->is64Bit())
1077       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1078
1079     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1080     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1081
1082     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1083
1084     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1085     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1087   }
1088
1089   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1090     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1091     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1092     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1093     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1094     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1095     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1096     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1097     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1098     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1099     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1100
1101     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1102     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1103     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1104     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1105     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1106     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1107     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1108     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1109     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1110     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1111
1112     // FIXME: Do we need to handle scalar-to-vector here?
1113     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1114
1115     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1116     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1120     // There is no BLENDI for byte vectors. We don't need to custom lower
1121     // some vselects for now.
1122     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1123
1124     // SSE41 brings specific instructions for doing vector sign extend even in
1125     // cases where we don't have SRA.
1126     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1129
1130     // i8 and i16 vectors are custom because the source register and source
1131     // source memory operand types are not the same width.  f32 vectors are
1132     // custom since the immediate controlling the insert encodes additional
1133     // information.
1134     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1138
1139     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1143
1144     // FIXME: these should be Legal, but that's only for the case where
1145     // the index is constant.  For now custom expand to deal with that.
1146     if (Subtarget->is64Bit()) {
1147       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1148       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1149     }
1150   }
1151
1152   if (Subtarget->hasSSE2()) {
1153     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1154     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1155
1156     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1157     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1158
1159     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1160     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1161
1162     // In the customized shift lowering, the legal cases in AVX2 will be
1163     // recognized.
1164     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1165     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1166
1167     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1168     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1169
1170     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1171   }
1172
1173   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1174     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1175     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1176     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1180
1181     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1182     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1184
1185     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1186     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1190     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1191     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1192     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1193     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1194     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1196     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1197
1198     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1199     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1203     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1204     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1205     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1206     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1207     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1209     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1210
1211     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1212     // even though v8i16 is a legal type.
1213     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1214     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1216
1217     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1219     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1220
1221     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1223
1224     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1225
1226     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1227     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1228
1229     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1230     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1231
1232     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1233     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1234
1235     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1236     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1239
1240     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1241     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1243
1244     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1245     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1248
1249     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1252     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1255     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1258     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1261
1262     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1263       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1264       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1267       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1269     }
1270
1271     if (Subtarget->hasInt256()) {
1272       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1273       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1276
1277       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1278       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1281
1282       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1283       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1284       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1285       // Don't lower v32i8 because there is no 128-bit byte mul
1286
1287       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1288       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1290       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1291
1292       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1293       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1294     } else {
1295       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1296       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1299
1300       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1301       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1304
1305       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1306       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1308       // Don't lower v32i8 because there is no 128-bit byte mul
1309     }
1310
1311     // In the customized shift lowering, the legal cases in AVX2 will be
1312     // recognized.
1313     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1314     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1315
1316     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1317     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1318
1319     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1320
1321     // Custom lower several nodes for 256-bit types.
1322     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1323              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1324       MVT VT = (MVT::SimpleValueType)i;
1325
1326       // Extract subvector is special because the value type
1327       // (result) is 128-bit but the source is 256-bit wide.
1328       if (VT.is128BitVector())
1329         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1330
1331       // Do not attempt to custom lower other non-256-bit vectors
1332       if (!VT.is256BitVector())
1333         continue;
1334
1335       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1336       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1337       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1338       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1339       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1340       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1341       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1342     }
1343
1344     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1345     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1346       MVT VT = (MVT::SimpleValueType)i;
1347
1348       // Do not attempt to promote non-256-bit vectors
1349       if (!VT.is256BitVector())
1350         continue;
1351
1352       setOperationAction(ISD::AND,    VT, Promote);
1353       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1354       setOperationAction(ISD::OR,     VT, Promote);
1355       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1356       setOperationAction(ISD::XOR,    VT, Promote);
1357       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1358       setOperationAction(ISD::LOAD,   VT, Promote);
1359       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1360       setOperationAction(ISD::SELECT, VT, Promote);
1361       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1362     }
1363   }
1364
1365   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1366     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1367     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1370
1371     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1372     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1373     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1374
1375     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1376     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1377     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1378     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1379     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1380     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1381     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1386
1387     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1388     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1392     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1393
1394     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1395     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1399     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1400     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1401     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1402
1403     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1404     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1406     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1407     if (Subtarget->is64Bit()) {
1408       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1409       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1411       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1412     }
1413     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1414     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1417     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1418     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1421     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1422     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1423
1424     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1425     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1430     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1432     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1437
1438     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1444
1445     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1446     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1447
1448     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1449
1450     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1452     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1454     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1456     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488
1489     // Custom lower several nodes.
1490     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1491              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1492       MVT VT = (MVT::SimpleValueType)i;
1493
1494       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1495       // Extract subvector is special because the value type
1496       // (result) is 256/128-bit but the source is 512-bit wide.
1497       if (VT.is128BitVector() || VT.is256BitVector())
1498         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1499
1500       if (VT.getVectorElementType() == MVT::i1)
1501         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1502
1503       // Do not attempt to custom lower other non-512-bit vectors
1504       if (!VT.is512BitVector())
1505         continue;
1506
1507       if ( EltSize >= 32) {
1508         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1509         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1510         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1511         setOperationAction(ISD::VSELECT,             VT, Legal);
1512         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1513         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1514         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1515       }
1516     }
1517     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1518       MVT VT = (MVT::SimpleValueType)i;
1519
1520       // Do not attempt to promote non-256-bit vectors
1521       if (!VT.is512BitVector())
1522         continue;
1523
1524       setOperationAction(ISD::SELECT, VT, Promote);
1525       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1526     }
1527   }// has  AVX-512
1528
1529   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1530     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1531     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1532
1533     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1534     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1535
1536     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1537     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1538     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1539     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1540
1541     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1542       const MVT VT = (MVT::SimpleValueType)i;
1543
1544       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1545
1546       // Do not attempt to promote non-256-bit vectors
1547       if (!VT.is512BitVector())
1548         continue;
1549
1550       if ( EltSize < 32) {
1551         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1552         setOperationAction(ISD::VSELECT,             VT, Legal);
1553       }
1554     }
1555   }
1556
1557   if (!TM.Options.UseSoftFloat && Subtarget->hasVLX()) {
1558     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1559     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1560
1561     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1562     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1563   }
1564
1565   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1566   // of this type with custom code.
1567   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1568            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1569     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1570                        Custom);
1571   }
1572
1573   // We want to custom lower some of our intrinsics.
1574   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1575   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1576   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1577   if (!Subtarget->is64Bit())
1578     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1579
1580   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1581   // handle type legalization for these operations here.
1582   //
1583   // FIXME: We really should do custom legalization for addition and
1584   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1585   // than generic legalization for 64-bit multiplication-with-overflow, though.
1586   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1587     // Add/Sub/Mul with overflow operations are custom lowered.
1588     MVT VT = IntVTs[i];
1589     setOperationAction(ISD::SADDO, VT, Custom);
1590     setOperationAction(ISD::UADDO, VT, Custom);
1591     setOperationAction(ISD::SSUBO, VT, Custom);
1592     setOperationAction(ISD::USUBO, VT, Custom);
1593     setOperationAction(ISD::SMULO, VT, Custom);
1594     setOperationAction(ISD::UMULO, VT, Custom);
1595   }
1596
1597   // There are no 8-bit 3-address imul/mul instructions
1598   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1599   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1600
1601   if (!Subtarget->is64Bit()) {
1602     // These libcalls are not available in 32-bit.
1603     setLibcallName(RTLIB::SHL_I128, nullptr);
1604     setLibcallName(RTLIB::SRL_I128, nullptr);
1605     setLibcallName(RTLIB::SRA_I128, nullptr);
1606   }
1607
1608   // Combine sin / cos into one node or libcall if possible.
1609   if (Subtarget->hasSinCos()) {
1610     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1611     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1612     if (Subtarget->isTargetDarwin()) {
1613       // For MacOSX, we don't want to the normal expansion of a libcall to
1614       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1615       // traffic.
1616       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1617       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1618     }
1619   }
1620
1621   if (Subtarget->isTargetWin64()) {
1622     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1623     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1624     setOperationAction(ISD::SREM, MVT::i128, Custom);
1625     setOperationAction(ISD::UREM, MVT::i128, Custom);
1626     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1627     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1628   }
1629
1630   // We have target-specific dag combine patterns for the following nodes:
1631   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1632   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1633   setTargetDAGCombine(ISD::VSELECT);
1634   setTargetDAGCombine(ISD::SELECT);
1635   setTargetDAGCombine(ISD::SHL);
1636   setTargetDAGCombine(ISD::SRA);
1637   setTargetDAGCombine(ISD::SRL);
1638   setTargetDAGCombine(ISD::OR);
1639   setTargetDAGCombine(ISD::AND);
1640   setTargetDAGCombine(ISD::ADD);
1641   setTargetDAGCombine(ISD::FADD);
1642   setTargetDAGCombine(ISD::FSUB);
1643   setTargetDAGCombine(ISD::FMA);
1644   setTargetDAGCombine(ISD::SUB);
1645   setTargetDAGCombine(ISD::LOAD);
1646   setTargetDAGCombine(ISD::STORE);
1647   setTargetDAGCombine(ISD::ZERO_EXTEND);
1648   setTargetDAGCombine(ISD::ANY_EXTEND);
1649   setTargetDAGCombine(ISD::SIGN_EXTEND);
1650   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1651   setTargetDAGCombine(ISD::TRUNCATE);
1652   setTargetDAGCombine(ISD::SINT_TO_FP);
1653   setTargetDAGCombine(ISD::SETCC);
1654   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1655   setTargetDAGCombine(ISD::BUILD_VECTOR);
1656   if (Subtarget->is64Bit())
1657     setTargetDAGCombine(ISD::MUL);
1658   setTargetDAGCombine(ISD::XOR);
1659
1660   computeRegisterProperties();
1661
1662   // On Darwin, -Os means optimize for size without hurting performance,
1663   // do not reduce the limit.
1664   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1665   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1666   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1667   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1668   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1669   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1670   setPrefLoopAlignment(4); // 2^4 bytes.
1671
1672   // Predictable cmov don't hurt on atom because it's in-order.
1673   PredictableSelectIsExpensive = !Subtarget->isAtom();
1674
1675   setPrefFunctionAlignment(4); // 2^4 bytes.
1676
1677   verifyIntrinsicTables();
1678 }
1679
1680 // This has so far only been implemented for 64-bit MachO.
1681 bool X86TargetLowering::useLoadStackGuardNode() const {
1682   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1683          Subtarget->is64Bit();
1684 }
1685
1686 TargetLoweringBase::LegalizeTypeAction
1687 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1688   if (ExperimentalVectorWideningLegalization &&
1689       VT.getVectorNumElements() != 1 &&
1690       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1691     return TypeWidenVector;
1692
1693   return TargetLoweringBase::getPreferredVectorAction(VT);
1694 }
1695
1696 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1697   if (!VT.isVector())
1698     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1699
1700   const unsigned NumElts = VT.getVectorNumElements();
1701   const EVT EltVT = VT.getVectorElementType();
1702   if (VT.is512BitVector()) {
1703     if (Subtarget->hasAVX512())
1704       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1705           EltVT == MVT::f32 || EltVT == MVT::f64)
1706         switch(NumElts) {
1707         case  8: return MVT::v8i1;
1708         case 16: return MVT::v16i1;
1709       }
1710     if (Subtarget->hasBWI())
1711       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1712         switch(NumElts) {
1713         case 32: return MVT::v32i1;
1714         case 64: return MVT::v64i1;
1715       }
1716   }
1717
1718   if (VT.is256BitVector() || VT.is128BitVector()) {
1719     if (Subtarget->hasVLX())
1720       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1721           EltVT == MVT::f32 || EltVT == MVT::f64)
1722         switch(NumElts) {
1723         case 2: return MVT::v2i1;
1724         case 4: return MVT::v4i1;
1725         case 8: return MVT::v8i1;
1726       }
1727     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1728       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1729         switch(NumElts) {
1730         case  8: return MVT::v8i1;
1731         case 16: return MVT::v16i1;
1732         case 32: return MVT::v32i1;
1733       }
1734   }
1735
1736   return VT.changeVectorElementTypeToInteger();
1737 }
1738
1739 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1740 /// the desired ByVal argument alignment.
1741 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1742   if (MaxAlign == 16)
1743     return;
1744   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1745     if (VTy->getBitWidth() == 128)
1746       MaxAlign = 16;
1747   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1748     unsigned EltAlign = 0;
1749     getMaxByValAlign(ATy->getElementType(), EltAlign);
1750     if (EltAlign > MaxAlign)
1751       MaxAlign = EltAlign;
1752   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1753     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1754       unsigned EltAlign = 0;
1755       getMaxByValAlign(STy->getElementType(i), EltAlign);
1756       if (EltAlign > MaxAlign)
1757         MaxAlign = EltAlign;
1758       if (MaxAlign == 16)
1759         break;
1760     }
1761   }
1762 }
1763
1764 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1765 /// function arguments in the caller parameter area. For X86, aggregates
1766 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1767 /// are at 4-byte boundaries.
1768 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1769   if (Subtarget->is64Bit()) {
1770     // Max of 8 and alignment of type.
1771     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1772     if (TyAlign > 8)
1773       return TyAlign;
1774     return 8;
1775   }
1776
1777   unsigned Align = 4;
1778   if (Subtarget->hasSSE1())
1779     getMaxByValAlign(Ty, Align);
1780   return Align;
1781 }
1782
1783 /// getOptimalMemOpType - Returns the target specific optimal type for load
1784 /// and store operations as a result of memset, memcpy, and memmove
1785 /// lowering. If DstAlign is zero that means it's safe to destination
1786 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1787 /// means there isn't a need to check it against alignment requirement,
1788 /// probably because the source does not need to be loaded. If 'IsMemset' is
1789 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1790 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1791 /// source is constant so it does not need to be loaded.
1792 /// It returns EVT::Other if the type should be determined using generic
1793 /// target-independent logic.
1794 EVT
1795 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1796                                        unsigned DstAlign, unsigned SrcAlign,
1797                                        bool IsMemset, bool ZeroMemset,
1798                                        bool MemcpyStrSrc,
1799                                        MachineFunction &MF) const {
1800   const Function *F = MF.getFunction();
1801   if ((!IsMemset || ZeroMemset) &&
1802       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1803                                        Attribute::NoImplicitFloat)) {
1804     if (Size >= 16 &&
1805         (Subtarget->isUnalignedMemAccessFast() ||
1806          ((DstAlign == 0 || DstAlign >= 16) &&
1807           (SrcAlign == 0 || SrcAlign >= 16)))) {
1808       if (Size >= 32) {
1809         if (Subtarget->hasInt256())
1810           return MVT::v8i32;
1811         if (Subtarget->hasFp256())
1812           return MVT::v8f32;
1813       }
1814       if (Subtarget->hasSSE2())
1815         return MVT::v4i32;
1816       if (Subtarget->hasSSE1())
1817         return MVT::v4f32;
1818     } else if (!MemcpyStrSrc && Size >= 8 &&
1819                !Subtarget->is64Bit() &&
1820                Subtarget->hasSSE2()) {
1821       // Do not use f64 to lower memcpy if source is string constant. It's
1822       // better to use i32 to avoid the loads.
1823       return MVT::f64;
1824     }
1825   }
1826   if (Subtarget->is64Bit() && Size >= 8)
1827     return MVT::i64;
1828   return MVT::i32;
1829 }
1830
1831 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1832   if (VT == MVT::f32)
1833     return X86ScalarSSEf32;
1834   else if (VT == MVT::f64)
1835     return X86ScalarSSEf64;
1836   return true;
1837 }
1838
1839 bool
1840 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1841                                                   unsigned,
1842                                                   unsigned,
1843                                                   bool *Fast) const {
1844   if (Fast)
1845     *Fast = Subtarget->isUnalignedMemAccessFast();
1846   return true;
1847 }
1848
1849 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1850 /// current function.  The returned value is a member of the
1851 /// MachineJumpTableInfo::JTEntryKind enum.
1852 unsigned X86TargetLowering::getJumpTableEncoding() const {
1853   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1854   // symbol.
1855   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1856       Subtarget->isPICStyleGOT())
1857     return MachineJumpTableInfo::EK_Custom32;
1858
1859   // Otherwise, use the normal jump table encoding heuristics.
1860   return TargetLowering::getJumpTableEncoding();
1861 }
1862
1863 const MCExpr *
1864 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1865                                              const MachineBasicBlock *MBB,
1866                                              unsigned uid,MCContext &Ctx) const{
1867   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1868          Subtarget->isPICStyleGOT());
1869   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1870   // entries.
1871   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1872                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1873 }
1874
1875 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1876 /// jumptable.
1877 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1878                                                     SelectionDAG &DAG) const {
1879   if (!Subtarget->is64Bit())
1880     // This doesn't have SDLoc associated with it, but is not really the
1881     // same as a Register.
1882     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1883   return Table;
1884 }
1885
1886 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1887 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1888 /// MCExpr.
1889 const MCExpr *X86TargetLowering::
1890 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1891                              MCContext &Ctx) const {
1892   // X86-64 uses RIP relative addressing based on the jump table label.
1893   if (Subtarget->isPICStyleRIPRel())
1894     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1895
1896   // Otherwise, the reference is relative to the PIC base.
1897   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1898 }
1899
1900 // FIXME: Why this routine is here? Move to RegInfo!
1901 std::pair<const TargetRegisterClass*, uint8_t>
1902 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1903   const TargetRegisterClass *RRC = nullptr;
1904   uint8_t Cost = 1;
1905   switch (VT.SimpleTy) {
1906   default:
1907     return TargetLowering::findRepresentativeClass(VT);
1908   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1909     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1910     break;
1911   case MVT::x86mmx:
1912     RRC = &X86::VR64RegClass;
1913     break;
1914   case MVT::f32: case MVT::f64:
1915   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1916   case MVT::v4f32: case MVT::v2f64:
1917   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1918   case MVT::v4f64:
1919     RRC = &X86::VR128RegClass;
1920     break;
1921   }
1922   return std::make_pair(RRC, Cost);
1923 }
1924
1925 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1926                                                unsigned &Offset) const {
1927   if (!Subtarget->isTargetLinux())
1928     return false;
1929
1930   if (Subtarget->is64Bit()) {
1931     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1932     Offset = 0x28;
1933     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1934       AddressSpace = 256;
1935     else
1936       AddressSpace = 257;
1937   } else {
1938     // %gs:0x14 on i386
1939     Offset = 0x14;
1940     AddressSpace = 256;
1941   }
1942   return true;
1943 }
1944
1945 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1946                                             unsigned DestAS) const {
1947   assert(SrcAS != DestAS && "Expected different address spaces!");
1948
1949   return SrcAS < 256 && DestAS < 256;
1950 }
1951
1952 //===----------------------------------------------------------------------===//
1953 //               Return Value Calling Convention Implementation
1954 //===----------------------------------------------------------------------===//
1955
1956 #include "X86GenCallingConv.inc"
1957
1958 bool
1959 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1960                                   MachineFunction &MF, bool isVarArg,
1961                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1962                         LLVMContext &Context) const {
1963   SmallVector<CCValAssign, 16> RVLocs;
1964   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1965   return CCInfo.CheckReturn(Outs, RetCC_X86);
1966 }
1967
1968 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1969   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1970   return ScratchRegs;
1971 }
1972
1973 SDValue
1974 X86TargetLowering::LowerReturn(SDValue Chain,
1975                                CallingConv::ID CallConv, bool isVarArg,
1976                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1977                                const SmallVectorImpl<SDValue> &OutVals,
1978                                SDLoc dl, SelectionDAG &DAG) const {
1979   MachineFunction &MF = DAG.getMachineFunction();
1980   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1981
1982   SmallVector<CCValAssign, 16> RVLocs;
1983   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
1984   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1985
1986   SDValue Flag;
1987   SmallVector<SDValue, 6> RetOps;
1988   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1989   // Operand #1 = Bytes To Pop
1990   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1991                    MVT::i16));
1992
1993   // Copy the result values into the output registers.
1994   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1995     CCValAssign &VA = RVLocs[i];
1996     assert(VA.isRegLoc() && "Can only return in registers!");
1997     SDValue ValToCopy = OutVals[i];
1998     EVT ValVT = ValToCopy.getValueType();
1999
2000     // Promote values to the appropriate types
2001     if (VA.getLocInfo() == CCValAssign::SExt)
2002       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2003     else if (VA.getLocInfo() == CCValAssign::ZExt)
2004       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2005     else if (VA.getLocInfo() == CCValAssign::AExt)
2006       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2007     else if (VA.getLocInfo() == CCValAssign::BCvt)
2008       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
2009
2010     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2011            "Unexpected FP-extend for return value.");  
2012
2013     // If this is x86-64, and we disabled SSE, we can't return FP values,
2014     // or SSE or MMX vectors.
2015     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2016          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2017           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2018       report_fatal_error("SSE register return with SSE disabled");
2019     }
2020     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2021     // llvm-gcc has never done it right and no one has noticed, so this
2022     // should be OK for now.
2023     if (ValVT == MVT::f64 &&
2024         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2025       report_fatal_error("SSE2 register return with SSE2 disabled");
2026
2027     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2028     // the RET instruction and handled by the FP Stackifier.
2029     if (VA.getLocReg() == X86::FP0 ||
2030         VA.getLocReg() == X86::FP1) {
2031       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2032       // change the value to the FP stack register class.
2033       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2034         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2035       RetOps.push_back(ValToCopy);
2036       // Don't emit a copytoreg.
2037       continue;
2038     }
2039
2040     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2041     // which is returned in RAX / RDX.
2042     if (Subtarget->is64Bit()) {
2043       if (ValVT == MVT::x86mmx) {
2044         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2045           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
2046           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2047                                   ValToCopy);
2048           // If we don't have SSE2 available, convert to v4f32 so the generated
2049           // register is legal.
2050           if (!Subtarget->hasSSE2())
2051             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
2052         }
2053       }
2054     }
2055
2056     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2057     Flag = Chain.getValue(1);
2058     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2059   }
2060
2061   // The x86-64 ABIs require that for returning structs by value we copy
2062   // the sret argument into %rax/%eax (depending on ABI) for the return.
2063   // Win32 requires us to put the sret argument to %eax as well.
2064   // We saved the argument into a virtual register in the entry block,
2065   // so now we copy the value out and into %rax/%eax.
2066   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2067       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2068     MachineFunction &MF = DAG.getMachineFunction();
2069     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2070     unsigned Reg = FuncInfo->getSRetReturnReg();
2071     assert(Reg &&
2072            "SRetReturnReg should have been set in LowerFormalArguments().");
2073     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2074
2075     unsigned RetValReg
2076         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2077           X86::RAX : X86::EAX;
2078     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2079     Flag = Chain.getValue(1);
2080
2081     // RAX/EAX now acts like a return value.
2082     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2083   }
2084
2085   RetOps[0] = Chain;  // Update chain.
2086
2087   // Add the flag if we have it.
2088   if (Flag.getNode())
2089     RetOps.push_back(Flag);
2090
2091   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2092 }
2093
2094 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2095   if (N->getNumValues() != 1)
2096     return false;
2097   if (!N->hasNUsesOfValue(1, 0))
2098     return false;
2099
2100   SDValue TCChain = Chain;
2101   SDNode *Copy = *N->use_begin();
2102   if (Copy->getOpcode() == ISD::CopyToReg) {
2103     // If the copy has a glue operand, we conservatively assume it isn't safe to
2104     // perform a tail call.
2105     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2106       return false;
2107     TCChain = Copy->getOperand(0);
2108   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2109     return false;
2110
2111   bool HasRet = false;
2112   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2113        UI != UE; ++UI) {
2114     if (UI->getOpcode() != X86ISD::RET_FLAG)
2115       return false;
2116     // If we are returning more than one value, we can definitely
2117     // not make a tail call see PR19530
2118     if (UI->getNumOperands() > 4)
2119       return false;
2120     if (UI->getNumOperands() == 4 &&
2121         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2122       return false;
2123     HasRet = true;
2124   }
2125
2126   if (!HasRet)
2127     return false;
2128
2129   Chain = TCChain;
2130   return true;
2131 }
2132
2133 EVT
2134 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2135                                             ISD::NodeType ExtendKind) const {
2136   MVT ReturnMVT;
2137   // TODO: Is this also valid on 32-bit?
2138   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2139     ReturnMVT = MVT::i8;
2140   else
2141     ReturnMVT = MVT::i32;
2142
2143   EVT MinVT = getRegisterType(Context, ReturnMVT);
2144   return VT.bitsLT(MinVT) ? MinVT : VT;
2145 }
2146
2147 /// LowerCallResult - Lower the result values of a call into the
2148 /// appropriate copies out of appropriate physical registers.
2149 ///
2150 SDValue
2151 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2152                                    CallingConv::ID CallConv, bool isVarArg,
2153                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2154                                    SDLoc dl, SelectionDAG &DAG,
2155                                    SmallVectorImpl<SDValue> &InVals) const {
2156
2157   // Assign locations to each value returned by this call.
2158   SmallVector<CCValAssign, 16> RVLocs;
2159   bool Is64Bit = Subtarget->is64Bit();
2160   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2161                  *DAG.getContext());
2162   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2163
2164   // Copy all of the result registers out of their specified physreg.
2165   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2166     CCValAssign &VA = RVLocs[i];
2167     EVT CopyVT = VA.getValVT();
2168
2169     // If this is x86-64, and we disabled SSE, we can't return FP values
2170     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2171         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2172       report_fatal_error("SSE register return with SSE disabled");
2173     }
2174
2175     // If we prefer to use the value in xmm registers, copy it out as f80 and
2176     // use a truncate to move it from fp stack reg to xmm reg.
2177     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2178         isScalarFPTypeInSSEReg(VA.getValVT()))
2179       CopyVT = MVT::f80;
2180
2181     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2182                                CopyVT, InFlag).getValue(1);
2183     SDValue Val = Chain.getValue(0);
2184
2185     if (CopyVT != VA.getValVT())
2186       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2187                         // This truncation won't change the value.
2188                         DAG.getIntPtrConstant(1));
2189
2190     InFlag = Chain.getValue(2);
2191     InVals.push_back(Val);
2192   }
2193
2194   return Chain;
2195 }
2196
2197 //===----------------------------------------------------------------------===//
2198 //                C & StdCall & Fast Calling Convention implementation
2199 //===----------------------------------------------------------------------===//
2200 //  StdCall calling convention seems to be standard for many Windows' API
2201 //  routines and around. It differs from C calling convention just a little:
2202 //  callee should clean up the stack, not caller. Symbols should be also
2203 //  decorated in some fancy way :) It doesn't support any vector arguments.
2204 //  For info on fast calling convention see Fast Calling Convention (tail call)
2205 //  implementation LowerX86_32FastCCCallTo.
2206
2207 /// CallIsStructReturn - Determines whether a call uses struct return
2208 /// semantics.
2209 enum StructReturnType {
2210   NotStructReturn,
2211   RegStructReturn,
2212   StackStructReturn
2213 };
2214 static StructReturnType
2215 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2216   if (Outs.empty())
2217     return NotStructReturn;
2218
2219   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2220   if (!Flags.isSRet())
2221     return NotStructReturn;
2222   if (Flags.isInReg())
2223     return RegStructReturn;
2224   return StackStructReturn;
2225 }
2226
2227 /// ArgsAreStructReturn - Determines whether a function uses struct
2228 /// return semantics.
2229 static StructReturnType
2230 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2231   if (Ins.empty())
2232     return NotStructReturn;
2233
2234   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2235   if (!Flags.isSRet())
2236     return NotStructReturn;
2237   if (Flags.isInReg())
2238     return RegStructReturn;
2239   return StackStructReturn;
2240 }
2241
2242 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2243 /// by "Src" to address "Dst" with size and alignment information specified by
2244 /// the specific parameter attribute. The copy will be passed as a byval
2245 /// function parameter.
2246 static SDValue
2247 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2248                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2249                           SDLoc dl) {
2250   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2251
2252   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2253                        /*isVolatile*/false, /*AlwaysInline=*/true,
2254                        MachinePointerInfo(), MachinePointerInfo());
2255 }
2256
2257 /// IsTailCallConvention - Return true if the calling convention is one that
2258 /// supports tail call optimization.
2259 static bool IsTailCallConvention(CallingConv::ID CC) {
2260   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2261           CC == CallingConv::HiPE);
2262 }
2263
2264 /// \brief Return true if the calling convention is a C calling convention.
2265 static bool IsCCallConvention(CallingConv::ID CC) {
2266   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2267           CC == CallingConv::X86_64_SysV);
2268 }
2269
2270 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2271   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2272     return false;
2273
2274   CallSite CS(CI);
2275   CallingConv::ID CalleeCC = CS.getCallingConv();
2276   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2277     return false;
2278
2279   return true;
2280 }
2281
2282 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2283 /// a tailcall target by changing its ABI.
2284 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2285                                    bool GuaranteedTailCallOpt) {
2286   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2287 }
2288
2289 SDValue
2290 X86TargetLowering::LowerMemArgument(SDValue Chain,
2291                                     CallingConv::ID CallConv,
2292                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2293                                     SDLoc dl, SelectionDAG &DAG,
2294                                     const CCValAssign &VA,
2295                                     MachineFrameInfo *MFI,
2296                                     unsigned i) const {
2297   // Create the nodes corresponding to a load from this parameter slot.
2298   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2299   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2300       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2301   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2302   EVT ValVT;
2303
2304   // If value is passed by pointer we have address passed instead of the value
2305   // itself.
2306   if (VA.getLocInfo() == CCValAssign::Indirect)
2307     ValVT = VA.getLocVT();
2308   else
2309     ValVT = VA.getValVT();
2310
2311   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2312   // changed with more analysis.
2313   // In case of tail call optimization mark all arguments mutable. Since they
2314   // could be overwritten by lowering of arguments in case of a tail call.
2315   if (Flags.isByVal()) {
2316     unsigned Bytes = Flags.getByValSize();
2317     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2318     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2319     return DAG.getFrameIndex(FI, getPointerTy());
2320   } else {
2321     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2322                                     VA.getLocMemOffset(), isImmutable);
2323     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2324     return DAG.getLoad(ValVT, dl, Chain, FIN,
2325                        MachinePointerInfo::getFixedStack(FI),
2326                        false, false, false, 0);
2327   }
2328 }
2329
2330 // FIXME: Get this from tablegen.
2331 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2332                                                 const X86Subtarget *Subtarget) {
2333   assert(Subtarget->is64Bit());
2334
2335   if (Subtarget->isCallingConvWin64(CallConv)) {
2336     static const MCPhysReg GPR64ArgRegsWin64[] = {
2337       X86::RCX, X86::RDX, X86::R8,  X86::R9
2338     };
2339     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2340   }
2341
2342   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2343     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2344   };
2345   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2346 }
2347
2348 // FIXME: Get this from tablegen.
2349 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2350                                                 CallingConv::ID CallConv,
2351                                                 const X86Subtarget *Subtarget) {
2352   assert(Subtarget->is64Bit());
2353   if (Subtarget->isCallingConvWin64(CallConv)) {
2354     // The XMM registers which might contain var arg parameters are shadowed
2355     // in their paired GPR.  So we only need to save the GPR to their home
2356     // slots.
2357     // TODO: __vectorcall will change this.
2358     return None;
2359   }
2360
2361   const Function *Fn = MF.getFunction();
2362   bool NoImplicitFloatOps = Fn->getAttributes().
2363       hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2364   assert(!(MF.getTarget().Options.UseSoftFloat && NoImplicitFloatOps) &&
2365          "SSE register cannot be used when SSE is disabled!");
2366   if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2367       !Subtarget->hasSSE1())
2368     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2369     // registers.
2370     return None;
2371
2372   static const MCPhysReg XMMArgRegs64Bit[] = {
2373     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2374     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2375   };
2376   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2377 }
2378
2379 SDValue
2380 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2381                                         CallingConv::ID CallConv,
2382                                         bool isVarArg,
2383                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2384                                         SDLoc dl,
2385                                         SelectionDAG &DAG,
2386                                         SmallVectorImpl<SDValue> &InVals)
2387                                           const {
2388   MachineFunction &MF = DAG.getMachineFunction();
2389   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2390
2391   const Function* Fn = MF.getFunction();
2392   if (Fn->hasExternalLinkage() &&
2393       Subtarget->isTargetCygMing() &&
2394       Fn->getName() == "main")
2395     FuncInfo->setForceFramePointer(true);
2396
2397   MachineFrameInfo *MFI = MF.getFrameInfo();
2398   bool Is64Bit = Subtarget->is64Bit();
2399   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2400
2401   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2402          "Var args not supported with calling convention fastcc, ghc or hipe");
2403
2404   // Assign locations to all of the incoming arguments.
2405   SmallVector<CCValAssign, 16> ArgLocs;
2406   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2407
2408   // Allocate shadow area for Win64
2409   if (IsWin64)
2410     CCInfo.AllocateStack(32, 8);
2411
2412   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2413
2414   unsigned LastVal = ~0U;
2415   SDValue ArgValue;
2416   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2417     CCValAssign &VA = ArgLocs[i];
2418     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2419     // places.
2420     assert(VA.getValNo() != LastVal &&
2421            "Don't support value assigned to multiple locs yet");
2422     (void)LastVal;
2423     LastVal = VA.getValNo();
2424
2425     if (VA.isRegLoc()) {
2426       EVT RegVT = VA.getLocVT();
2427       const TargetRegisterClass *RC;
2428       if (RegVT == MVT::i32)
2429         RC = &X86::GR32RegClass;
2430       else if (Is64Bit && RegVT == MVT::i64)
2431         RC = &X86::GR64RegClass;
2432       else if (RegVT == MVT::f32)
2433         RC = &X86::FR32RegClass;
2434       else if (RegVT == MVT::f64)
2435         RC = &X86::FR64RegClass;
2436       else if (RegVT.is512BitVector())
2437         RC = &X86::VR512RegClass;
2438       else if (RegVT.is256BitVector())
2439         RC = &X86::VR256RegClass;
2440       else if (RegVT.is128BitVector())
2441         RC = &X86::VR128RegClass;
2442       else if (RegVT == MVT::x86mmx)
2443         RC = &X86::VR64RegClass;
2444       else if (RegVT == MVT::i1)
2445         RC = &X86::VK1RegClass;
2446       else if (RegVT == MVT::v8i1)
2447         RC = &X86::VK8RegClass;
2448       else if (RegVT == MVT::v16i1)
2449         RC = &X86::VK16RegClass;
2450       else if (RegVT == MVT::v32i1)
2451         RC = &X86::VK32RegClass;
2452       else if (RegVT == MVT::v64i1)
2453         RC = &X86::VK64RegClass;
2454       else
2455         llvm_unreachable("Unknown argument type!");
2456
2457       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2458       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2459
2460       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2461       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2462       // right size.
2463       if (VA.getLocInfo() == CCValAssign::SExt)
2464         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2465                                DAG.getValueType(VA.getValVT()));
2466       else if (VA.getLocInfo() == CCValAssign::ZExt)
2467         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2468                                DAG.getValueType(VA.getValVT()));
2469       else if (VA.getLocInfo() == CCValAssign::BCvt)
2470         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2471
2472       if (VA.isExtInLoc()) {
2473         // Handle MMX values passed in XMM regs.
2474         if (RegVT.isVector())
2475           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2476         else
2477           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2478       }
2479     } else {
2480       assert(VA.isMemLoc());
2481       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2482     }
2483
2484     // If value is passed via pointer - do a load.
2485     if (VA.getLocInfo() == CCValAssign::Indirect)
2486       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2487                              MachinePointerInfo(), false, false, false, 0);
2488
2489     InVals.push_back(ArgValue);
2490   }
2491
2492   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2493     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2494       // The x86-64 ABIs require that for returning structs by value we copy
2495       // the sret argument into %rax/%eax (depending on ABI) for the return.
2496       // Win32 requires us to put the sret argument to %eax as well.
2497       // Save the argument into a virtual register so that we can access it
2498       // from the return points.
2499       if (Ins[i].Flags.isSRet()) {
2500         unsigned Reg = FuncInfo->getSRetReturnReg();
2501         if (!Reg) {
2502           MVT PtrTy = getPointerTy();
2503           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2504           FuncInfo->setSRetReturnReg(Reg);
2505         }
2506         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2507         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2508         break;
2509       }
2510     }
2511   }
2512
2513   unsigned StackSize = CCInfo.getNextStackOffset();
2514   // Align stack specially for tail calls.
2515   if (FuncIsMadeTailCallSafe(CallConv,
2516                              MF.getTarget().Options.GuaranteedTailCallOpt))
2517     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2518
2519   // If the function takes variable number of arguments, make a frame index for
2520   // the start of the first vararg value... for expansion of llvm.va_start. We
2521   // can skip this if there are no va_start calls.
2522   if (MFI->hasVAStart() &&
2523       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2524                    CallConv != CallingConv::X86_ThisCall))) {
2525     FuncInfo->setVarArgsFrameIndex(
2526         MFI->CreateFixedObject(1, StackSize, true));
2527   }
2528
2529   // 64-bit calling conventions support varargs and register parameters, so we
2530   // have to do extra work to spill them in the prologue or forward them to
2531   // musttail calls.
2532   if (Is64Bit && isVarArg &&
2533       (MFI->hasVAStart() || MFI->hasMustTailInVarArgFunc())) {
2534     // Find the first unallocated argument registers.
2535     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2536     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2537     unsigned NumIntRegs =
2538         CCInfo.getFirstUnallocated(ArgGPRs.data(), ArgGPRs.size());
2539     unsigned NumXMMRegs =
2540         CCInfo.getFirstUnallocated(ArgXMMs.data(), ArgXMMs.size());
2541     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2542            "SSE register cannot be used when SSE is disabled!");
2543
2544     // Gather all the live in physical registers.
2545     SmallVector<SDValue, 6> LiveGPRs;
2546     SmallVector<SDValue, 8> LiveXMMRegs;
2547     SDValue ALVal;
2548     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2549       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2550       LiveGPRs.push_back(
2551           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2552     }
2553     if (!ArgXMMs.empty()) {
2554       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2555       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2556       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2557         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2558         LiveXMMRegs.push_back(
2559             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2560       }
2561     }
2562
2563     // Store them to the va_list returned by va_start.
2564     if (MFI->hasVAStart()) {
2565       if (IsWin64) {
2566         const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering();
2567         // Get to the caller-allocated home save location.  Add 8 to account
2568         // for the return address.
2569         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2570         FuncInfo->setRegSaveFrameIndex(
2571           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2572         // Fixup to set vararg frame on shadow area (4 x i64).
2573         if (NumIntRegs < 4)
2574           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2575       } else {
2576         // For X86-64, if there are vararg parameters that are passed via
2577         // registers, then we must store them to their spots on the stack so
2578         // they may be loaded by deferencing the result of va_next.
2579         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2580         FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2581         FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2582             ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2583       }
2584
2585       // Store the integer parameter registers.
2586       SmallVector<SDValue, 8> MemOps;
2587       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2588                                         getPointerTy());
2589       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2590       for (SDValue Val : LiveGPRs) {
2591         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2592                                   DAG.getIntPtrConstant(Offset));
2593         SDValue Store =
2594           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2595                        MachinePointerInfo::getFixedStack(
2596                          FuncInfo->getRegSaveFrameIndex(), Offset),
2597                        false, false, 0);
2598         MemOps.push_back(Store);
2599         Offset += 8;
2600       }
2601
2602       if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2603         // Now store the XMM (fp + vector) parameter registers.
2604         SmallVector<SDValue, 12> SaveXMMOps;
2605         SaveXMMOps.push_back(Chain);
2606         SaveXMMOps.push_back(ALVal);
2607         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2608                                FuncInfo->getRegSaveFrameIndex()));
2609         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2610                                FuncInfo->getVarArgsFPOffset()));
2611         SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2612                           LiveXMMRegs.end());
2613         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2614                                      MVT::Other, SaveXMMOps));
2615       }
2616
2617       if (!MemOps.empty())
2618         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2619     } else {
2620       // Add all GPRs, al, and XMMs to the list of forwards.  We will add then
2621       // to the liveout set on a musttail call.
2622       assert(MFI->hasMustTailInVarArgFunc());
2623       auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
2624       typedef X86MachineFunctionInfo::Forward Forward;
2625
2626       for (unsigned I = 0, E = LiveGPRs.size(); I != E; ++I) {
2627         unsigned VReg =
2628             MF.getRegInfo().createVirtualRegister(&X86::GR64RegClass);
2629         Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveGPRs[I]);
2630         Forwards.push_back(Forward(VReg, ArgGPRs[NumIntRegs + I], MVT::i64));
2631       }
2632
2633       if (!ArgXMMs.empty()) {
2634         unsigned ALVReg =
2635             MF.getRegInfo().createVirtualRegister(&X86::GR8RegClass);
2636         Chain = DAG.getCopyToReg(Chain, dl, ALVReg, ALVal);
2637         Forwards.push_back(Forward(ALVReg, X86::AL, MVT::i8));
2638
2639         for (unsigned I = 0, E = LiveXMMRegs.size(); I != E; ++I) {
2640           unsigned VReg =
2641               MF.getRegInfo().createVirtualRegister(&X86::VR128RegClass);
2642           Chain = DAG.getCopyToReg(Chain, dl, VReg, LiveXMMRegs[I]);
2643           Forwards.push_back(
2644               Forward(VReg, ArgXMMs[NumXMMRegs + I], MVT::v4f32));
2645         }
2646       }
2647     }
2648   }
2649
2650   // Some CCs need callee pop.
2651   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2652                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2653     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2654   } else {
2655     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2656     // If this is an sret function, the return should pop the hidden pointer.
2657     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2658         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2659         argsAreStructReturn(Ins) == StackStructReturn)
2660       FuncInfo->setBytesToPopOnReturn(4);
2661   }
2662
2663   if (!Is64Bit) {
2664     // RegSaveFrameIndex is X86-64 only.
2665     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2666     if (CallConv == CallingConv::X86_FastCall ||
2667         CallConv == CallingConv::X86_ThisCall)
2668       // fastcc functions can't have varargs.
2669       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2670   }
2671
2672   FuncInfo->setArgumentStackSize(StackSize);
2673
2674   return Chain;
2675 }
2676
2677 SDValue
2678 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2679                                     SDValue StackPtr, SDValue Arg,
2680                                     SDLoc dl, SelectionDAG &DAG,
2681                                     const CCValAssign &VA,
2682                                     ISD::ArgFlagsTy Flags) const {
2683   unsigned LocMemOffset = VA.getLocMemOffset();
2684   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2685   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2686   if (Flags.isByVal())
2687     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2688
2689   return DAG.getStore(Chain, dl, Arg, PtrOff,
2690                       MachinePointerInfo::getStack(LocMemOffset),
2691                       false, false, 0);
2692 }
2693
2694 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2695 /// optimization is performed and it is required.
2696 SDValue
2697 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2698                                            SDValue &OutRetAddr, SDValue Chain,
2699                                            bool IsTailCall, bool Is64Bit,
2700                                            int FPDiff, SDLoc dl) const {
2701   // Adjust the Return address stack slot.
2702   EVT VT = getPointerTy();
2703   OutRetAddr = getReturnAddressFrameIndex(DAG);
2704
2705   // Load the "old" Return address.
2706   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2707                            false, false, false, 0);
2708   return SDValue(OutRetAddr.getNode(), 1);
2709 }
2710
2711 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2712 /// optimization is performed and it is required (FPDiff!=0).
2713 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2714                                         SDValue Chain, SDValue RetAddrFrIdx,
2715                                         EVT PtrVT, unsigned SlotSize,
2716                                         int FPDiff, SDLoc dl) {
2717   // Store the return address to the appropriate stack slot.
2718   if (!FPDiff) return Chain;
2719   // Calculate the new stack slot for the return address.
2720   int NewReturnAddrFI =
2721     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2722                                          false);
2723   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2724   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2725                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2726                        false, false, 0);
2727   return Chain;
2728 }
2729
2730 SDValue
2731 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2732                              SmallVectorImpl<SDValue> &InVals) const {
2733   SelectionDAG &DAG                     = CLI.DAG;
2734   SDLoc &dl                             = CLI.DL;
2735   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2736   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2737   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2738   SDValue Chain                         = CLI.Chain;
2739   SDValue Callee                        = CLI.Callee;
2740   CallingConv::ID CallConv              = CLI.CallConv;
2741   bool &isTailCall                      = CLI.IsTailCall;
2742   bool isVarArg                         = CLI.IsVarArg;
2743
2744   MachineFunction &MF = DAG.getMachineFunction();
2745   bool Is64Bit        = Subtarget->is64Bit();
2746   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2747   StructReturnType SR = callIsStructReturn(Outs);
2748   bool IsSibcall      = false;
2749   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2750
2751   if (MF.getTarget().Options.DisableTailCalls)
2752     isTailCall = false;
2753
2754   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2755   if (IsMustTail) {
2756     // Force this to be a tail call.  The verifier rules are enough to ensure
2757     // that we can lower this successfully without moving the return address
2758     // around.
2759     isTailCall = true;
2760   } else if (isTailCall) {
2761     // Check if it's really possible to do a tail call.
2762     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2763                     isVarArg, SR != NotStructReturn,
2764                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2765                     Outs, OutVals, Ins, DAG);
2766
2767     // Sibcalls are automatically detected tailcalls which do not require
2768     // ABI changes.
2769     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2770       IsSibcall = true;
2771
2772     if (isTailCall)
2773       ++NumTailCalls;
2774   }
2775
2776   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2777          "Var args not supported with calling convention fastcc, ghc or hipe");
2778
2779   // Analyze operands of the call, assigning locations to each operand.
2780   SmallVector<CCValAssign, 16> ArgLocs;
2781   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2782
2783   // Allocate shadow area for Win64
2784   if (IsWin64)
2785     CCInfo.AllocateStack(32, 8);
2786
2787   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2788
2789   // Get a count of how many bytes are to be pushed on the stack.
2790   unsigned NumBytes = CCInfo.getNextStackOffset();
2791   if (IsSibcall)
2792     // This is a sibcall. The memory operands are available in caller's
2793     // own caller's stack.
2794     NumBytes = 0;
2795   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2796            IsTailCallConvention(CallConv))
2797     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2798
2799   int FPDiff = 0;
2800   if (isTailCall && !IsSibcall && !IsMustTail) {
2801     // Lower arguments at fp - stackoffset + fpdiff.
2802     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2803
2804     FPDiff = NumBytesCallerPushed - NumBytes;
2805
2806     // Set the delta of movement of the returnaddr stackslot.
2807     // But only set if delta is greater than previous delta.
2808     if (FPDiff < X86Info->getTCReturnAddrDelta())
2809       X86Info->setTCReturnAddrDelta(FPDiff);
2810   }
2811
2812   unsigned NumBytesToPush = NumBytes;
2813   unsigned NumBytesToPop = NumBytes;
2814
2815   // If we have an inalloca argument, all stack space has already been allocated
2816   // for us and be right at the top of the stack.  We don't support multiple
2817   // arguments passed in memory when using inalloca.
2818   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2819     NumBytesToPush = 0;
2820     if (!ArgLocs.back().isMemLoc())
2821       report_fatal_error("cannot use inalloca attribute on a register "
2822                          "parameter");
2823     if (ArgLocs.back().getLocMemOffset() != 0)
2824       report_fatal_error("any parameter with the inalloca attribute must be "
2825                          "the only memory argument");
2826   }
2827
2828   if (!IsSibcall)
2829     Chain = DAG.getCALLSEQ_START(
2830         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2831
2832   SDValue RetAddrFrIdx;
2833   // Load return address for tail calls.
2834   if (isTailCall && FPDiff)
2835     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2836                                     Is64Bit, FPDiff, dl);
2837
2838   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2839   SmallVector<SDValue, 8> MemOpChains;
2840   SDValue StackPtr;
2841
2842   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2843   // of tail call optimization arguments are handle later.
2844   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2845       DAG.getSubtarget().getRegisterInfo());
2846   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2847     // Skip inalloca arguments, they have already been written.
2848     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2849     if (Flags.isInAlloca())
2850       continue;
2851
2852     CCValAssign &VA = ArgLocs[i];
2853     EVT RegVT = VA.getLocVT();
2854     SDValue Arg = OutVals[i];
2855     bool isByVal = Flags.isByVal();
2856
2857     // Promote the value if needed.
2858     switch (VA.getLocInfo()) {
2859     default: llvm_unreachable("Unknown loc info!");
2860     case CCValAssign::Full: break;
2861     case CCValAssign::SExt:
2862       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2863       break;
2864     case CCValAssign::ZExt:
2865       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2866       break;
2867     case CCValAssign::AExt:
2868       if (RegVT.is128BitVector()) {
2869         // Special case: passing MMX values in XMM registers.
2870         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2871         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2872         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2873       } else
2874         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2875       break;
2876     case CCValAssign::BCvt:
2877       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2878       break;
2879     case CCValAssign::Indirect: {
2880       // Store the argument.
2881       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2882       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2883       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2884                            MachinePointerInfo::getFixedStack(FI),
2885                            false, false, 0);
2886       Arg = SpillSlot;
2887       break;
2888     }
2889     }
2890
2891     if (VA.isRegLoc()) {
2892       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2893       if (isVarArg && IsWin64) {
2894         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2895         // shadow reg if callee is a varargs function.
2896         unsigned ShadowReg = 0;
2897         switch (VA.getLocReg()) {
2898         case X86::XMM0: ShadowReg = X86::RCX; break;
2899         case X86::XMM1: ShadowReg = X86::RDX; break;
2900         case X86::XMM2: ShadowReg = X86::R8; break;
2901         case X86::XMM3: ShadowReg = X86::R9; break;
2902         }
2903         if (ShadowReg)
2904           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2905       }
2906     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2907       assert(VA.isMemLoc());
2908       if (!StackPtr.getNode())
2909         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2910                                       getPointerTy());
2911       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2912                                              dl, DAG, VA, Flags));
2913     }
2914   }
2915
2916   if (!MemOpChains.empty())
2917     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2918
2919   if (Subtarget->isPICStyleGOT()) {
2920     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2921     // GOT pointer.
2922     if (!isTailCall) {
2923       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2924                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2925     } else {
2926       // If we are tail calling and generating PIC/GOT style code load the
2927       // address of the callee into ECX. The value in ecx is used as target of
2928       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2929       // for tail calls on PIC/GOT architectures. Normally we would just put the
2930       // address of GOT into ebx and then call target@PLT. But for tail calls
2931       // ebx would be restored (since ebx is callee saved) before jumping to the
2932       // target@PLT.
2933
2934       // Note: The actual moving to ECX is done further down.
2935       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2936       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2937           !G->getGlobal()->hasProtectedVisibility())
2938         Callee = LowerGlobalAddress(Callee, DAG);
2939       else if (isa<ExternalSymbolSDNode>(Callee))
2940         Callee = LowerExternalSymbol(Callee, DAG);
2941     }
2942   }
2943
2944   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
2945     // From AMD64 ABI document:
2946     // For calls that may call functions that use varargs or stdargs
2947     // (prototype-less calls or calls to functions containing ellipsis (...) in
2948     // the declaration) %al is used as hidden argument to specify the number
2949     // of SSE registers used. The contents of %al do not need to match exactly
2950     // the number of registers, but must be an ubound on the number of SSE
2951     // registers used and is in the range 0 - 8 inclusive.
2952
2953     // Count the number of XMM registers allocated.
2954     static const MCPhysReg XMMArgRegs[] = {
2955       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2956       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2957     };
2958     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2959     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2960            && "SSE registers cannot be used when SSE is disabled");
2961
2962     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2963                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2964   }
2965
2966   if (Is64Bit && isVarArg && IsMustTail) {
2967     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
2968     for (const auto &F : Forwards) {
2969       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2970       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
2971     }
2972   }
2973
2974   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2975   // don't need this because the eligibility check rejects calls that require
2976   // shuffling arguments passed in memory.
2977   if (!IsSibcall && isTailCall) {
2978     // Force all the incoming stack arguments to be loaded from the stack
2979     // before any new outgoing arguments are stored to the stack, because the
2980     // outgoing stack slots may alias the incoming argument stack slots, and
2981     // the alias isn't otherwise explicit. This is slightly more conservative
2982     // than necessary, because it means that each store effectively depends
2983     // on every argument instead of just those arguments it would clobber.
2984     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2985
2986     SmallVector<SDValue, 8> MemOpChains2;
2987     SDValue FIN;
2988     int FI = 0;
2989     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2990       CCValAssign &VA = ArgLocs[i];
2991       if (VA.isRegLoc())
2992         continue;
2993       assert(VA.isMemLoc());
2994       SDValue Arg = OutVals[i];
2995       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2996       // Skip inalloca arguments.  They don't require any work.
2997       if (Flags.isInAlloca())
2998         continue;
2999       // Create frame index.
3000       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3001       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3002       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3003       FIN = DAG.getFrameIndex(FI, getPointerTy());
3004
3005       if (Flags.isByVal()) {
3006         // Copy relative to framepointer.
3007         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
3008         if (!StackPtr.getNode())
3009           StackPtr = DAG.getCopyFromReg(Chain, dl,
3010                                         RegInfo->getStackRegister(),
3011                                         getPointerTy());
3012         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3013
3014         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3015                                                          ArgChain,
3016                                                          Flags, DAG, dl));
3017       } else {
3018         // Store relative to framepointer.
3019         MemOpChains2.push_back(
3020           DAG.getStore(ArgChain, dl, Arg, FIN,
3021                        MachinePointerInfo::getFixedStack(FI),
3022                        false, false, 0));
3023       }
3024     }
3025
3026     if (!MemOpChains2.empty())
3027       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3028
3029     // Store the return address to the appropriate stack slot.
3030     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3031                                      getPointerTy(), RegInfo->getSlotSize(),
3032                                      FPDiff, dl);
3033   }
3034
3035   // Build a sequence of copy-to-reg nodes chained together with token chain
3036   // and flag operands which copy the outgoing args into registers.
3037   SDValue InFlag;
3038   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3039     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3040                              RegsToPass[i].second, InFlag);
3041     InFlag = Chain.getValue(1);
3042   }
3043
3044   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3045     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3046     // In the 64-bit large code model, we have to make all calls
3047     // through a register, since the call instruction's 32-bit
3048     // pc-relative offset may not be large enough to hold the whole
3049     // address.
3050   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3051     // If the callee is a GlobalAddress node (quite common, every direct call
3052     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3053     // it.
3054
3055     // We should use extra load for direct calls to dllimported functions in
3056     // non-JIT mode.
3057     const GlobalValue *GV = G->getGlobal();
3058     if (!GV->hasDLLImportStorageClass()) {
3059       unsigned char OpFlags = 0;
3060       bool ExtraLoad = false;
3061       unsigned WrapperKind = ISD::DELETED_NODE;
3062
3063       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3064       // external symbols most go through the PLT in PIC mode.  If the symbol
3065       // has hidden or protected visibility, or if it is static or local, then
3066       // we don't need to use the PLT - we can directly call it.
3067       if (Subtarget->isTargetELF() &&
3068           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3069           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3070         OpFlags = X86II::MO_PLT;
3071       } else if (Subtarget->isPICStyleStubAny() &&
3072                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
3073                  (!Subtarget->getTargetTriple().isMacOSX() ||
3074                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3075         // PC-relative references to external symbols should go through $stub,
3076         // unless we're building with the leopard linker or later, which
3077         // automatically synthesizes these stubs.
3078         OpFlags = X86II::MO_DARWIN_STUB;
3079       } else if (Subtarget->isPICStyleRIPRel() &&
3080                  isa<Function>(GV) &&
3081                  cast<Function>(GV)->getAttributes().
3082                    hasAttribute(AttributeSet::FunctionIndex,
3083                                 Attribute::NonLazyBind)) {
3084         // If the function is marked as non-lazy, generate an indirect call
3085         // which loads from the GOT directly. This avoids runtime overhead
3086         // at the cost of eager binding (and one extra byte of encoding).
3087         OpFlags = X86II::MO_GOTPCREL;
3088         WrapperKind = X86ISD::WrapperRIP;
3089         ExtraLoad = true;
3090       }
3091
3092       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3093                                           G->getOffset(), OpFlags);
3094
3095       // Add a wrapper if needed.
3096       if (WrapperKind != ISD::DELETED_NODE)
3097         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3098       // Add extra indirection if needed.
3099       if (ExtraLoad)
3100         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3101                              MachinePointerInfo::getGOT(),
3102                              false, false, false, 0);
3103     }
3104   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3105     unsigned char OpFlags = 0;
3106
3107     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3108     // external symbols should go through the PLT.
3109     if (Subtarget->isTargetELF() &&
3110         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3111       OpFlags = X86II::MO_PLT;
3112     } else if (Subtarget->isPICStyleStubAny() &&
3113                (!Subtarget->getTargetTriple().isMacOSX() ||
3114                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3115       // PC-relative references to external symbols should go through $stub,
3116       // unless we're building with the leopard linker or later, which
3117       // automatically synthesizes these stubs.
3118       OpFlags = X86II::MO_DARWIN_STUB;
3119     }
3120
3121     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3122                                          OpFlags);
3123   } else if (Subtarget->isTarget64BitILP32() && Callee->getValueType(0) == MVT::i32) {
3124     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3125     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3126   }
3127
3128   // Returns a chain & a flag for retval copy to use.
3129   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3130   SmallVector<SDValue, 8> Ops;
3131
3132   if (!IsSibcall && isTailCall) {
3133     Chain = DAG.getCALLSEQ_END(Chain,
3134                                DAG.getIntPtrConstant(NumBytesToPop, true),
3135                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3136     InFlag = Chain.getValue(1);
3137   }
3138
3139   Ops.push_back(Chain);
3140   Ops.push_back(Callee);
3141
3142   if (isTailCall)
3143     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3144
3145   // Add argument registers to the end of the list so that they are known live
3146   // into the call.
3147   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3148     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3149                                   RegsToPass[i].second.getValueType()));
3150
3151   // Add a register mask operand representing the call-preserved registers.
3152   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
3153   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3154   assert(Mask && "Missing call preserved mask for calling convention");
3155   Ops.push_back(DAG.getRegisterMask(Mask));
3156
3157   if (InFlag.getNode())
3158     Ops.push_back(InFlag);
3159
3160   if (isTailCall) {
3161     // We used to do:
3162     //// If this is the first return lowered for this function, add the regs
3163     //// to the liveout set for the function.
3164     // This isn't right, although it's probably harmless on x86; liveouts
3165     // should be computed from returns not tail calls.  Consider a void
3166     // function making a tail call to a function returning int.
3167     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3168   }
3169
3170   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3171   InFlag = Chain.getValue(1);
3172
3173   // Create the CALLSEQ_END node.
3174   unsigned NumBytesForCalleeToPop;
3175   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3176                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3177     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3178   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3179            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3180            SR == StackStructReturn)
3181     // If this is a call to a struct-return function, the callee
3182     // pops the hidden struct pointer, so we have to push it back.
3183     // This is common for Darwin/X86, Linux & Mingw32 targets.
3184     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3185     NumBytesForCalleeToPop = 4;
3186   else
3187     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3188
3189   // Returns a flag for retval copy to use.
3190   if (!IsSibcall) {
3191     Chain = DAG.getCALLSEQ_END(Chain,
3192                                DAG.getIntPtrConstant(NumBytesToPop, true),
3193                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3194                                                      true),
3195                                InFlag, dl);
3196     InFlag = Chain.getValue(1);
3197   }
3198
3199   // Handle result values, copying them out of physregs into vregs that we
3200   // return.
3201   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3202                          Ins, dl, DAG, InVals);
3203 }
3204
3205 //===----------------------------------------------------------------------===//
3206 //                Fast Calling Convention (tail call) implementation
3207 //===----------------------------------------------------------------------===//
3208
3209 //  Like std call, callee cleans arguments, convention except that ECX is
3210 //  reserved for storing the tail called function address. Only 2 registers are
3211 //  free for argument passing (inreg). Tail call optimization is performed
3212 //  provided:
3213 //                * tailcallopt is enabled
3214 //                * caller/callee are fastcc
3215 //  On X86_64 architecture with GOT-style position independent code only local
3216 //  (within module) calls are supported at the moment.
3217 //  To keep the stack aligned according to platform abi the function
3218 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3219 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3220 //  If a tail called function callee has more arguments than the caller the
3221 //  caller needs to make sure that there is room to move the RETADDR to. This is
3222 //  achieved by reserving an area the size of the argument delta right after the
3223 //  original RETADDR, but before the saved framepointer or the spilled registers
3224 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3225 //  stack layout:
3226 //    arg1
3227 //    arg2
3228 //    RETADDR
3229 //    [ new RETADDR
3230 //      move area ]
3231 //    (possible EBP)
3232 //    ESI
3233 //    EDI
3234 //    local1 ..
3235
3236 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3237 /// for a 16 byte align requirement.
3238 unsigned
3239 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3240                                                SelectionDAG& DAG) const {
3241   MachineFunction &MF = DAG.getMachineFunction();
3242   const TargetMachine &TM = MF.getTarget();
3243   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3244       TM.getSubtargetImpl()->getRegisterInfo());
3245   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3246   unsigned StackAlignment = TFI.getStackAlignment();
3247   uint64_t AlignMask = StackAlignment - 1;
3248   int64_t Offset = StackSize;
3249   unsigned SlotSize = RegInfo->getSlotSize();
3250   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3251     // Number smaller than 12 so just add the difference.
3252     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3253   } else {
3254     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3255     Offset = ((~AlignMask) & Offset) + StackAlignment +
3256       (StackAlignment-SlotSize);
3257   }
3258   return Offset;
3259 }
3260
3261 /// MatchingStackOffset - Return true if the given stack call argument is
3262 /// already available in the same position (relatively) of the caller's
3263 /// incoming argument stack.
3264 static
3265 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3266                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3267                          const X86InstrInfo *TII) {
3268   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3269   int FI = INT_MAX;
3270   if (Arg.getOpcode() == ISD::CopyFromReg) {
3271     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3272     if (!TargetRegisterInfo::isVirtualRegister(VR))
3273       return false;
3274     MachineInstr *Def = MRI->getVRegDef(VR);
3275     if (!Def)
3276       return false;
3277     if (!Flags.isByVal()) {
3278       if (!TII->isLoadFromStackSlot(Def, FI))
3279         return false;
3280     } else {
3281       unsigned Opcode = Def->getOpcode();
3282       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3283           Def->getOperand(1).isFI()) {
3284         FI = Def->getOperand(1).getIndex();
3285         Bytes = Flags.getByValSize();
3286       } else
3287         return false;
3288     }
3289   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3290     if (Flags.isByVal())
3291       // ByVal argument is passed in as a pointer but it's now being
3292       // dereferenced. e.g.
3293       // define @foo(%struct.X* %A) {
3294       //   tail call @bar(%struct.X* byval %A)
3295       // }
3296       return false;
3297     SDValue Ptr = Ld->getBasePtr();
3298     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3299     if (!FINode)
3300       return false;
3301     FI = FINode->getIndex();
3302   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3303     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3304     FI = FINode->getIndex();
3305     Bytes = Flags.getByValSize();
3306   } else
3307     return false;
3308
3309   assert(FI != INT_MAX);
3310   if (!MFI->isFixedObjectIndex(FI))
3311     return false;
3312   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3313 }
3314
3315 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3316 /// for tail call optimization. Targets which want to do tail call
3317 /// optimization should implement this function.
3318 bool
3319 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3320                                                      CallingConv::ID CalleeCC,
3321                                                      bool isVarArg,
3322                                                      bool isCalleeStructRet,
3323                                                      bool isCallerStructRet,
3324                                                      Type *RetTy,
3325                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3326                                     const SmallVectorImpl<SDValue> &OutVals,
3327                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3328                                                      SelectionDAG &DAG) const {
3329   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3330     return false;
3331
3332   // If -tailcallopt is specified, make fastcc functions tail-callable.
3333   const MachineFunction &MF = DAG.getMachineFunction();
3334   const Function *CallerF = MF.getFunction();
3335
3336   // If the function return type is x86_fp80 and the callee return type is not,
3337   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3338   // perform a tailcall optimization here.
3339   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3340     return false;
3341
3342   CallingConv::ID CallerCC = CallerF->getCallingConv();
3343   bool CCMatch = CallerCC == CalleeCC;
3344   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3345   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3346
3347   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3348     if (IsTailCallConvention(CalleeCC) && CCMatch)
3349       return true;
3350     return false;
3351   }
3352
3353   // Look for obvious safe cases to perform tail call optimization that do not
3354   // require ABI changes. This is what gcc calls sibcall.
3355
3356   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3357   // emit a special epilogue.
3358   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3359       DAG.getSubtarget().getRegisterInfo());
3360   if (RegInfo->needsStackRealignment(MF))
3361     return false;
3362
3363   // Also avoid sibcall optimization if either caller or callee uses struct
3364   // return semantics.
3365   if (isCalleeStructRet || isCallerStructRet)
3366     return false;
3367
3368   // An stdcall/thiscall caller is expected to clean up its arguments; the
3369   // callee isn't going to do that.
3370   // FIXME: this is more restrictive than needed. We could produce a tailcall
3371   // when the stack adjustment matches. For example, with a thiscall that takes
3372   // only one argument.
3373   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3374                    CallerCC == CallingConv::X86_ThisCall))
3375     return false;
3376
3377   // Do not sibcall optimize vararg calls unless all arguments are passed via
3378   // registers.
3379   if (isVarArg && !Outs.empty()) {
3380
3381     // Optimizing for varargs on Win64 is unlikely to be safe without
3382     // additional testing.
3383     if (IsCalleeWin64 || IsCallerWin64)
3384       return false;
3385
3386     SmallVector<CCValAssign, 16> ArgLocs;
3387     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3388                    *DAG.getContext());
3389
3390     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3391     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3392       if (!ArgLocs[i].isRegLoc())
3393         return false;
3394   }
3395
3396   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3397   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3398   // this into a sibcall.
3399   bool Unused = false;
3400   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3401     if (!Ins[i].Used) {
3402       Unused = true;
3403       break;
3404     }
3405   }
3406   if (Unused) {
3407     SmallVector<CCValAssign, 16> RVLocs;
3408     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3409                    *DAG.getContext());
3410     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3411     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3412       CCValAssign &VA = RVLocs[i];
3413       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3414         return false;
3415     }
3416   }
3417
3418   // If the calling conventions do not match, then we'd better make sure the
3419   // results are returned in the same way as what the caller expects.
3420   if (!CCMatch) {
3421     SmallVector<CCValAssign, 16> RVLocs1;
3422     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3423                     *DAG.getContext());
3424     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3425
3426     SmallVector<CCValAssign, 16> RVLocs2;
3427     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3428                     *DAG.getContext());
3429     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3430
3431     if (RVLocs1.size() != RVLocs2.size())
3432       return false;
3433     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3434       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3435         return false;
3436       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3437         return false;
3438       if (RVLocs1[i].isRegLoc()) {
3439         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3440           return false;
3441       } else {
3442         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3443           return false;
3444       }
3445     }
3446   }
3447
3448   // If the callee takes no arguments then go on to check the results of the
3449   // call.
3450   if (!Outs.empty()) {
3451     // Check if stack adjustment is needed. For now, do not do this if any
3452     // argument is passed on the stack.
3453     SmallVector<CCValAssign, 16> ArgLocs;
3454     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3455                    *DAG.getContext());
3456
3457     // Allocate shadow area for Win64
3458     if (IsCalleeWin64)
3459       CCInfo.AllocateStack(32, 8);
3460
3461     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3462     if (CCInfo.getNextStackOffset()) {
3463       MachineFunction &MF = DAG.getMachineFunction();
3464       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3465         return false;
3466
3467       // Check if the arguments are already laid out in the right way as
3468       // the caller's fixed stack objects.
3469       MachineFrameInfo *MFI = MF.getFrameInfo();
3470       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3471       const X86InstrInfo *TII =
3472           static_cast<const X86InstrInfo *>(DAG.getSubtarget().getInstrInfo());
3473       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3474         CCValAssign &VA = ArgLocs[i];
3475         SDValue Arg = OutVals[i];
3476         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3477         if (VA.getLocInfo() == CCValAssign::Indirect)
3478           return false;
3479         if (!VA.isRegLoc()) {
3480           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3481                                    MFI, MRI, TII))
3482             return false;
3483         }
3484       }
3485     }
3486
3487     // If the tailcall address may be in a register, then make sure it's
3488     // possible to register allocate for it. In 32-bit, the call address can
3489     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3490     // callee-saved registers are restored. These happen to be the same
3491     // registers used to pass 'inreg' arguments so watch out for those.
3492     if (!Subtarget->is64Bit() &&
3493         ((!isa<GlobalAddressSDNode>(Callee) &&
3494           !isa<ExternalSymbolSDNode>(Callee)) ||
3495          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3496       unsigned NumInRegs = 0;
3497       // In PIC we need an extra register to formulate the address computation
3498       // for the callee.
3499       unsigned MaxInRegs =
3500         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3501
3502       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3503         CCValAssign &VA = ArgLocs[i];
3504         if (!VA.isRegLoc())
3505           continue;
3506         unsigned Reg = VA.getLocReg();
3507         switch (Reg) {
3508         default: break;
3509         case X86::EAX: case X86::EDX: case X86::ECX:
3510           if (++NumInRegs == MaxInRegs)
3511             return false;
3512           break;
3513         }
3514       }
3515     }
3516   }
3517
3518   return true;
3519 }
3520
3521 FastISel *
3522 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3523                                   const TargetLibraryInfo *libInfo) const {
3524   return X86::createFastISel(funcInfo, libInfo);
3525 }
3526
3527 //===----------------------------------------------------------------------===//
3528 //                           Other Lowering Hooks
3529 //===----------------------------------------------------------------------===//
3530
3531 static bool MayFoldLoad(SDValue Op) {
3532   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3533 }
3534
3535 static bool MayFoldIntoStore(SDValue Op) {
3536   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3537 }
3538
3539 static bool isTargetShuffle(unsigned Opcode) {
3540   switch(Opcode) {
3541   default: return false;
3542   case X86ISD::BLENDI:
3543   case X86ISD::PSHUFB:
3544   case X86ISD::PSHUFD:
3545   case X86ISD::PSHUFHW:
3546   case X86ISD::PSHUFLW:
3547   case X86ISD::SHUFP:
3548   case X86ISD::PALIGNR:
3549   case X86ISD::MOVLHPS:
3550   case X86ISD::MOVLHPD:
3551   case X86ISD::MOVHLPS:
3552   case X86ISD::MOVLPS:
3553   case X86ISD::MOVLPD:
3554   case X86ISD::MOVSHDUP:
3555   case X86ISD::MOVSLDUP:
3556   case X86ISD::MOVDDUP:
3557   case X86ISD::MOVSS:
3558   case X86ISD::MOVSD:
3559   case X86ISD::UNPCKL:
3560   case X86ISD::UNPCKH:
3561   case X86ISD::VPERMILPI:
3562   case X86ISD::VPERM2X128:
3563   case X86ISD::VPERMI:
3564     return true;
3565   }
3566 }
3567
3568 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3569                                     SDValue V1, SelectionDAG &DAG) {
3570   switch(Opc) {
3571   default: llvm_unreachable("Unknown x86 shuffle node");
3572   case X86ISD::MOVSHDUP:
3573   case X86ISD::MOVSLDUP:
3574   case X86ISD::MOVDDUP:
3575     return DAG.getNode(Opc, dl, VT, V1);
3576   }
3577 }
3578
3579 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3580                                     SDValue V1, unsigned TargetMask,
3581                                     SelectionDAG &DAG) {
3582   switch(Opc) {
3583   default: llvm_unreachable("Unknown x86 shuffle node");
3584   case X86ISD::PSHUFD:
3585   case X86ISD::PSHUFHW:
3586   case X86ISD::PSHUFLW:
3587   case X86ISD::VPERMILPI:
3588   case X86ISD::VPERMI:
3589     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3590   }
3591 }
3592
3593 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3594                                     SDValue V1, SDValue V2, unsigned TargetMask,
3595                                     SelectionDAG &DAG) {
3596   switch(Opc) {
3597   default: llvm_unreachable("Unknown x86 shuffle node");
3598   case X86ISD::PALIGNR:
3599   case X86ISD::VALIGN:
3600   case X86ISD::SHUFP:
3601   case X86ISD::VPERM2X128:
3602     return DAG.getNode(Opc, dl, VT, V1, V2,
3603                        DAG.getConstant(TargetMask, MVT::i8));
3604   }
3605 }
3606
3607 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3608                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3609   switch(Opc) {
3610   default: llvm_unreachable("Unknown x86 shuffle node");
3611   case X86ISD::MOVLHPS:
3612   case X86ISD::MOVLHPD:
3613   case X86ISD::MOVHLPS:
3614   case X86ISD::MOVLPS:
3615   case X86ISD::MOVLPD:
3616   case X86ISD::MOVSS:
3617   case X86ISD::MOVSD:
3618   case X86ISD::UNPCKL:
3619   case X86ISD::UNPCKH:
3620     return DAG.getNode(Opc, dl, VT, V1, V2);
3621   }
3622 }
3623
3624 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3625   MachineFunction &MF = DAG.getMachineFunction();
3626   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3627       DAG.getSubtarget().getRegisterInfo());
3628   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3629   int ReturnAddrIndex = FuncInfo->getRAIndex();
3630
3631   if (ReturnAddrIndex == 0) {
3632     // Set up a frame object for the return address.
3633     unsigned SlotSize = RegInfo->getSlotSize();
3634     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3635                                                            -(int64_t)SlotSize,
3636                                                            false);
3637     FuncInfo->setRAIndex(ReturnAddrIndex);
3638   }
3639
3640   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3641 }
3642
3643 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3644                                        bool hasSymbolicDisplacement) {
3645   // Offset should fit into 32 bit immediate field.
3646   if (!isInt<32>(Offset))
3647     return false;
3648
3649   // If we don't have a symbolic displacement - we don't have any extra
3650   // restrictions.
3651   if (!hasSymbolicDisplacement)
3652     return true;
3653
3654   // FIXME: Some tweaks might be needed for medium code model.
3655   if (M != CodeModel::Small && M != CodeModel::Kernel)
3656     return false;
3657
3658   // For small code model we assume that latest object is 16MB before end of 31
3659   // bits boundary. We may also accept pretty large negative constants knowing
3660   // that all objects are in the positive half of address space.
3661   if (M == CodeModel::Small && Offset < 16*1024*1024)
3662     return true;
3663
3664   // For kernel code model we know that all object resist in the negative half
3665   // of 32bits address space. We may not accept negative offsets, since they may
3666   // be just off and we may accept pretty large positive ones.
3667   if (M == CodeModel::Kernel && Offset > 0)
3668     return true;
3669
3670   return false;
3671 }
3672
3673 /// isCalleePop - Determines whether the callee is required to pop its
3674 /// own arguments. Callee pop is necessary to support tail calls.
3675 bool X86::isCalleePop(CallingConv::ID CallingConv,
3676                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3677   switch (CallingConv) {
3678   default:
3679     return false;
3680   case CallingConv::X86_StdCall:
3681   case CallingConv::X86_FastCall:
3682   case CallingConv::X86_ThisCall:
3683     return !is64Bit;
3684   case CallingConv::Fast:
3685   case CallingConv::GHC:
3686   case CallingConv::HiPE:
3687     if (IsVarArg)
3688       return false;
3689     return TailCallOpt;
3690   }
3691 }
3692
3693 /// \brief Return true if the condition is an unsigned comparison operation.
3694 static bool isX86CCUnsigned(unsigned X86CC) {
3695   switch (X86CC) {
3696   default: llvm_unreachable("Invalid integer condition!");
3697   case X86::COND_E:     return true;
3698   case X86::COND_G:     return false;
3699   case X86::COND_GE:    return false;
3700   case X86::COND_L:     return false;
3701   case X86::COND_LE:    return false;
3702   case X86::COND_NE:    return true;
3703   case X86::COND_B:     return true;
3704   case X86::COND_A:     return true;
3705   case X86::COND_BE:    return true;
3706   case X86::COND_AE:    return true;
3707   }
3708   llvm_unreachable("covered switch fell through?!");
3709 }
3710
3711 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3712 /// specific condition code, returning the condition code and the LHS/RHS of the
3713 /// comparison to make.
3714 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3715                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3716   if (!isFP) {
3717     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3718       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3719         // X > -1   -> X == 0, jump !sign.
3720         RHS = DAG.getConstant(0, RHS.getValueType());
3721         return X86::COND_NS;
3722       }
3723       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3724         // X < 0   -> X == 0, jump on sign.
3725         return X86::COND_S;
3726       }
3727       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3728         // X < 1   -> X <= 0
3729         RHS = DAG.getConstant(0, RHS.getValueType());
3730         return X86::COND_LE;
3731       }
3732     }
3733
3734     switch (SetCCOpcode) {
3735     default: llvm_unreachable("Invalid integer condition!");
3736     case ISD::SETEQ:  return X86::COND_E;
3737     case ISD::SETGT:  return X86::COND_G;
3738     case ISD::SETGE:  return X86::COND_GE;
3739     case ISD::SETLT:  return X86::COND_L;
3740     case ISD::SETLE:  return X86::COND_LE;
3741     case ISD::SETNE:  return X86::COND_NE;
3742     case ISD::SETULT: return X86::COND_B;
3743     case ISD::SETUGT: return X86::COND_A;
3744     case ISD::SETULE: return X86::COND_BE;
3745     case ISD::SETUGE: return X86::COND_AE;
3746     }
3747   }
3748
3749   // First determine if it is required or is profitable to flip the operands.
3750
3751   // If LHS is a foldable load, but RHS is not, flip the condition.
3752   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3753       !ISD::isNON_EXTLoad(RHS.getNode())) {
3754     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3755     std::swap(LHS, RHS);
3756   }
3757
3758   switch (SetCCOpcode) {
3759   default: break;
3760   case ISD::SETOLT:
3761   case ISD::SETOLE:
3762   case ISD::SETUGT:
3763   case ISD::SETUGE:
3764     std::swap(LHS, RHS);
3765     break;
3766   }
3767
3768   // On a floating point condition, the flags are set as follows:
3769   // ZF  PF  CF   op
3770   //  0 | 0 | 0 | X > Y
3771   //  0 | 0 | 1 | X < Y
3772   //  1 | 0 | 0 | X == Y
3773   //  1 | 1 | 1 | unordered
3774   switch (SetCCOpcode) {
3775   default: llvm_unreachable("Condcode should be pre-legalized away");
3776   case ISD::SETUEQ:
3777   case ISD::SETEQ:   return X86::COND_E;
3778   case ISD::SETOLT:              // flipped
3779   case ISD::SETOGT:
3780   case ISD::SETGT:   return X86::COND_A;
3781   case ISD::SETOLE:              // flipped
3782   case ISD::SETOGE:
3783   case ISD::SETGE:   return X86::COND_AE;
3784   case ISD::SETUGT:              // flipped
3785   case ISD::SETULT:
3786   case ISD::SETLT:   return X86::COND_B;
3787   case ISD::SETUGE:              // flipped
3788   case ISD::SETULE:
3789   case ISD::SETLE:   return X86::COND_BE;
3790   case ISD::SETONE:
3791   case ISD::SETNE:   return X86::COND_NE;
3792   case ISD::SETUO:   return X86::COND_P;
3793   case ISD::SETO:    return X86::COND_NP;
3794   case ISD::SETOEQ:
3795   case ISD::SETUNE:  return X86::COND_INVALID;
3796   }
3797 }
3798
3799 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3800 /// code. Current x86 isa includes the following FP cmov instructions:
3801 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3802 static bool hasFPCMov(unsigned X86CC) {
3803   switch (X86CC) {
3804   default:
3805     return false;
3806   case X86::COND_B:
3807   case X86::COND_BE:
3808   case X86::COND_E:
3809   case X86::COND_P:
3810   case X86::COND_A:
3811   case X86::COND_AE:
3812   case X86::COND_NE:
3813   case X86::COND_NP:
3814     return true;
3815   }
3816 }
3817
3818 /// isFPImmLegal - Returns true if the target can instruction select the
3819 /// specified FP immediate natively. If false, the legalizer will
3820 /// materialize the FP immediate as a load from a constant pool.
3821 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3822   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3823     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3824       return true;
3825   }
3826   return false;
3827 }
3828
3829 /// \brief Returns true if it is beneficial to convert a load of a constant
3830 /// to just the constant itself.
3831 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3832                                                           Type *Ty) const {
3833   assert(Ty->isIntegerTy());
3834
3835   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3836   if (BitSize == 0 || BitSize > 64)
3837     return false;
3838   return true;
3839 }
3840
3841 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3842 /// the specified range (L, H].
3843 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3844   return (Val < 0) || (Val >= Low && Val < Hi);
3845 }
3846
3847 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3848 /// specified value.
3849 static bool isUndefOrEqual(int Val, int CmpVal) {
3850   return (Val < 0 || Val == CmpVal);
3851 }
3852
3853 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3854 /// from position Pos and ending in Pos+Size, falls within the specified
3855 /// sequential range (L, L+Pos]. or is undef.
3856 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3857                                        unsigned Pos, unsigned Size, int Low) {
3858   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3859     if (!isUndefOrEqual(Mask[i], Low))
3860       return false;
3861   return true;
3862 }
3863
3864 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3865 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3866 /// the second operand.
3867 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3868   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3869     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3870   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3871     return (Mask[0] < 2 && Mask[1] < 2);
3872   return false;
3873 }
3874
3875 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3876 /// is suitable for input to PSHUFHW.
3877 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3878   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3879     return false;
3880
3881   // Lower quadword copied in order or undef.
3882   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3883     return false;
3884
3885   // Upper quadword shuffled.
3886   for (unsigned i = 4; i != 8; ++i)
3887     if (!isUndefOrInRange(Mask[i], 4, 8))
3888       return false;
3889
3890   if (VT == MVT::v16i16) {
3891     // Lower quadword copied in order or undef.
3892     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3893       return false;
3894
3895     // Upper quadword shuffled.
3896     for (unsigned i = 12; i != 16; ++i)
3897       if (!isUndefOrInRange(Mask[i], 12, 16))
3898         return false;
3899   }
3900
3901   return true;
3902 }
3903
3904 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3905 /// is suitable for input to PSHUFLW.
3906 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3907   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3908     return false;
3909
3910   // Upper quadword copied in order.
3911   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3912     return false;
3913
3914   // Lower quadword shuffled.
3915   for (unsigned i = 0; i != 4; ++i)
3916     if (!isUndefOrInRange(Mask[i], 0, 4))
3917       return false;
3918
3919   if (VT == MVT::v16i16) {
3920     // Upper quadword copied in order.
3921     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3922       return false;
3923
3924     // Lower quadword shuffled.
3925     for (unsigned i = 8; i != 12; ++i)
3926       if (!isUndefOrInRange(Mask[i], 8, 12))
3927         return false;
3928   }
3929
3930   return true;
3931 }
3932
3933 /// \brief Return true if the mask specifies a shuffle of elements that is
3934 /// suitable for input to intralane (palignr) or interlane (valign) vector
3935 /// right-shift.
3936 static bool isAlignrMask(ArrayRef<int> Mask, MVT VT, bool InterLane) {
3937   unsigned NumElts = VT.getVectorNumElements();
3938   unsigned NumLanes = InterLane ? 1: VT.getSizeInBits()/128;
3939   unsigned NumLaneElts = NumElts/NumLanes;
3940
3941   // Do not handle 64-bit element shuffles with palignr.
3942   if (NumLaneElts == 2)
3943     return false;
3944
3945   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3946     unsigned i;
3947     for (i = 0; i != NumLaneElts; ++i) {
3948       if (Mask[i+l] >= 0)
3949         break;
3950     }
3951
3952     // Lane is all undef, go to next lane
3953     if (i == NumLaneElts)
3954       continue;
3955
3956     int Start = Mask[i+l];
3957
3958     // Make sure its in this lane in one of the sources
3959     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3960         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3961       return false;
3962
3963     // If not lane 0, then we must match lane 0
3964     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3965       return false;
3966
3967     // Correct second source to be contiguous with first source
3968     if (Start >= (int)NumElts)
3969       Start -= NumElts - NumLaneElts;
3970
3971     // Make sure we're shifting in the right direction.
3972     if (Start <= (int)(i+l))
3973       return false;
3974
3975     Start -= i;
3976
3977     // Check the rest of the elements to see if they are consecutive.
3978     for (++i; i != NumLaneElts; ++i) {
3979       int Idx = Mask[i+l];
3980
3981       // Make sure its in this lane
3982       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3983           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3984         return false;
3985
3986       // If not lane 0, then we must match lane 0
3987       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3988         return false;
3989
3990       if (Idx >= (int)NumElts)
3991         Idx -= NumElts - NumLaneElts;
3992
3993       if (!isUndefOrEqual(Idx, Start+i))
3994         return false;
3995
3996     }
3997   }
3998
3999   return true;
4000 }
4001
4002 /// \brief Return true if the node specifies a shuffle of elements that is
4003 /// suitable for input to PALIGNR.
4004 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
4005                           const X86Subtarget *Subtarget) {
4006   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
4007       (VT.is256BitVector() && !Subtarget->hasInt256()) ||
4008       VT.is512BitVector())
4009     // FIXME: Add AVX512BW.
4010     return false;
4011
4012   return isAlignrMask(Mask, VT, false);
4013 }
4014
4015 /// \brief Return true if the node specifies a shuffle of elements that is
4016 /// suitable for input to VALIGN.
4017 static bool isVALIGNMask(ArrayRef<int> Mask, MVT VT,
4018                           const X86Subtarget *Subtarget) {
4019   // FIXME: Add AVX512VL.
4020   if (!VT.is512BitVector() || !Subtarget->hasAVX512())
4021     return false;
4022   return isAlignrMask(Mask, VT, true);
4023 }
4024
4025 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
4026 /// the two vector operands have swapped position.
4027 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
4028                                      unsigned NumElems) {
4029   for (unsigned i = 0; i != NumElems; ++i) {
4030     int idx = Mask[i];
4031     if (idx < 0)
4032       continue;
4033     else if (idx < (int)NumElems)
4034       Mask[i] = idx + NumElems;
4035     else
4036       Mask[i] = idx - NumElems;
4037   }
4038 }
4039
4040 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
4041 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
4042 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
4043 /// reverse of what x86 shuffles want.
4044 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
4045
4046   unsigned NumElems = VT.getVectorNumElements();
4047   unsigned NumLanes = VT.getSizeInBits()/128;
4048   unsigned NumLaneElems = NumElems/NumLanes;
4049
4050   if (NumLaneElems != 2 && NumLaneElems != 4)
4051     return false;
4052
4053   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4054   bool symetricMaskRequired =
4055     (VT.getSizeInBits() >= 256) && (EltSize == 32);
4056
4057   // VSHUFPSY divides the resulting vector into 4 chunks.
4058   // The sources are also splitted into 4 chunks, and each destination
4059   // chunk must come from a different source chunk.
4060   //
4061   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
4062   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
4063   //
4064   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
4065   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
4066   //
4067   // VSHUFPDY divides the resulting vector into 4 chunks.
4068   // The sources are also splitted into 4 chunks, and each destination
4069   // chunk must come from a different source chunk.
4070   //
4071   //  SRC1 =>      X3       X2       X1       X0
4072   //  SRC2 =>      Y3       Y2       Y1       Y0
4073   //
4074   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
4075   //
4076   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
4077   unsigned HalfLaneElems = NumLaneElems/2;
4078   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
4079     for (unsigned i = 0; i != NumLaneElems; ++i) {
4080       int Idx = Mask[i+l];
4081       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
4082       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
4083         return false;
4084       // For VSHUFPSY, the mask of the second half must be the same as the
4085       // first but with the appropriate offsets. This works in the same way as
4086       // VPERMILPS works with masks.
4087       if (!symetricMaskRequired || Idx < 0)
4088         continue;
4089       if (MaskVal[i] < 0) {
4090         MaskVal[i] = Idx - l;
4091         continue;
4092       }
4093       if ((signed)(Idx - l) != MaskVal[i])
4094         return false;
4095     }
4096   }
4097
4098   return true;
4099 }
4100
4101 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
4102 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
4103 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
4104   if (!VT.is128BitVector())
4105     return false;
4106
4107   unsigned NumElems = VT.getVectorNumElements();
4108
4109   if (NumElems != 4)
4110     return false;
4111
4112   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
4113   return isUndefOrEqual(Mask[0], 6) &&
4114          isUndefOrEqual(Mask[1], 7) &&
4115          isUndefOrEqual(Mask[2], 2) &&
4116          isUndefOrEqual(Mask[3], 3);
4117 }
4118
4119 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
4120 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
4121 /// <2, 3, 2, 3>
4122 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
4123   if (!VT.is128BitVector())
4124     return false;
4125
4126   unsigned NumElems = VT.getVectorNumElements();
4127
4128   if (NumElems != 4)
4129     return false;
4130
4131   return isUndefOrEqual(Mask[0], 2) &&
4132          isUndefOrEqual(Mask[1], 3) &&
4133          isUndefOrEqual(Mask[2], 2) &&
4134          isUndefOrEqual(Mask[3], 3);
4135 }
4136
4137 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
4138 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
4139 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
4140   if (!VT.is128BitVector())
4141     return false;
4142
4143   unsigned NumElems = VT.getVectorNumElements();
4144
4145   if (NumElems != 2 && NumElems != 4)
4146     return false;
4147
4148   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4149     if (!isUndefOrEqual(Mask[i], i + NumElems))
4150       return false;
4151
4152   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4153     if (!isUndefOrEqual(Mask[i], i))
4154       return false;
4155
4156   return true;
4157 }
4158
4159 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4160 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4161 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4162   if (!VT.is128BitVector())
4163     return false;
4164
4165   unsigned NumElems = VT.getVectorNumElements();
4166
4167   if (NumElems != 2 && NumElems != 4)
4168     return false;
4169
4170   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4171     if (!isUndefOrEqual(Mask[i], i))
4172       return false;
4173
4174   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4175     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4176       return false;
4177
4178   return true;
4179 }
4180
4181 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4182 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4183 /// i. e: If all but one element come from the same vector.
4184 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4185   // TODO: Deal with AVX's VINSERTPS
4186   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4187     return false;
4188
4189   unsigned CorrectPosV1 = 0;
4190   unsigned CorrectPosV2 = 0;
4191   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4192     if (Mask[i] == -1) {
4193       ++CorrectPosV1;
4194       ++CorrectPosV2;
4195       continue;
4196     }
4197
4198     if (Mask[i] == i)
4199       ++CorrectPosV1;
4200     else if (Mask[i] == i + 4)
4201       ++CorrectPosV2;
4202   }
4203
4204   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4205     // We have 3 elements (undefs count as elements from any vector) from one
4206     // vector, and one from another.
4207     return true;
4208
4209   return false;
4210 }
4211
4212 //
4213 // Some special combinations that can be optimized.
4214 //
4215 static
4216 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4217                                SelectionDAG &DAG) {
4218   MVT VT = SVOp->getSimpleValueType(0);
4219   SDLoc dl(SVOp);
4220
4221   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4222     return SDValue();
4223
4224   ArrayRef<int> Mask = SVOp->getMask();
4225
4226   // These are the special masks that may be optimized.
4227   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4228   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4229   bool MatchEvenMask = true;
4230   bool MatchOddMask  = true;
4231   for (int i=0; i<8; ++i) {
4232     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4233       MatchEvenMask = false;
4234     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4235       MatchOddMask = false;
4236   }
4237
4238   if (!MatchEvenMask && !MatchOddMask)
4239     return SDValue();
4240
4241   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4242
4243   SDValue Op0 = SVOp->getOperand(0);
4244   SDValue Op1 = SVOp->getOperand(1);
4245
4246   if (MatchEvenMask) {
4247     // Shift the second operand right to 32 bits.
4248     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4249     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4250   } else {
4251     // Shift the first operand left to 32 bits.
4252     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4253     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4254   }
4255   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4256   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4257 }
4258
4259 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4260 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4261 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4262                          bool HasInt256, bool V2IsSplat = false) {
4263
4264   assert(VT.getSizeInBits() >= 128 &&
4265          "Unsupported vector type for unpckl");
4266
4267   unsigned NumElts = VT.getVectorNumElements();
4268   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4269       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4270     return false;
4271
4272   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4273          "Unsupported vector type for unpckh");
4274
4275   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4276   unsigned NumLanes = VT.getSizeInBits()/128;
4277   unsigned NumLaneElts = NumElts/NumLanes;
4278
4279   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4280     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4281       int BitI  = Mask[l+i];
4282       int BitI1 = Mask[l+i+1];
4283       if (!isUndefOrEqual(BitI, j))
4284         return false;
4285       if (V2IsSplat) {
4286         if (!isUndefOrEqual(BitI1, NumElts))
4287           return false;
4288       } else {
4289         if (!isUndefOrEqual(BitI1, j + NumElts))
4290           return false;
4291       }
4292     }
4293   }
4294
4295   return true;
4296 }
4297
4298 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4299 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4300 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4301                          bool HasInt256, bool V2IsSplat = false) {
4302   assert(VT.getSizeInBits() >= 128 &&
4303          "Unsupported vector type for unpckh");
4304
4305   unsigned NumElts = VT.getVectorNumElements();
4306   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4307       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4308     return false;
4309
4310   assert((!VT.is512BitVector() || VT.getScalarType().getSizeInBits() >= 32) &&
4311          "Unsupported vector type for unpckh");
4312
4313   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4314   unsigned NumLanes = VT.getSizeInBits()/128;
4315   unsigned NumLaneElts = NumElts/NumLanes;
4316
4317   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4318     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4319       int BitI  = Mask[l+i];
4320       int BitI1 = Mask[l+i+1];
4321       if (!isUndefOrEqual(BitI, j))
4322         return false;
4323       if (V2IsSplat) {
4324         if (isUndefOrEqual(BitI1, NumElts))
4325           return false;
4326       } else {
4327         if (!isUndefOrEqual(BitI1, j+NumElts))
4328           return false;
4329       }
4330     }
4331   }
4332   return true;
4333 }
4334
4335 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4336 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4337 /// <0, 0, 1, 1>
4338 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4339   unsigned NumElts = VT.getVectorNumElements();
4340   bool Is256BitVec = VT.is256BitVector();
4341
4342   if (VT.is512BitVector())
4343     return false;
4344   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4345          "Unsupported vector type for unpckh");
4346
4347   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4348       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4349     return false;
4350
4351   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4352   // FIXME: Need a better way to get rid of this, there's no latency difference
4353   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4354   // the former later. We should also remove the "_undef" special mask.
4355   if (NumElts == 4 && Is256BitVec)
4356     return false;
4357
4358   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4359   // independently on 128-bit lanes.
4360   unsigned NumLanes = VT.getSizeInBits()/128;
4361   unsigned NumLaneElts = NumElts/NumLanes;
4362
4363   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4364     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4365       int BitI  = Mask[l+i];
4366       int BitI1 = Mask[l+i+1];
4367
4368       if (!isUndefOrEqual(BitI, j))
4369         return false;
4370       if (!isUndefOrEqual(BitI1, j))
4371         return false;
4372     }
4373   }
4374
4375   return true;
4376 }
4377
4378 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4379 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4380 /// <2, 2, 3, 3>
4381 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4382   unsigned NumElts = VT.getVectorNumElements();
4383
4384   if (VT.is512BitVector())
4385     return false;
4386
4387   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4388          "Unsupported vector type for unpckh");
4389
4390   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4391       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4392     return false;
4393
4394   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4395   // independently on 128-bit lanes.
4396   unsigned NumLanes = VT.getSizeInBits()/128;
4397   unsigned NumLaneElts = NumElts/NumLanes;
4398
4399   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4400     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4401       int BitI  = Mask[l+i];
4402       int BitI1 = Mask[l+i+1];
4403       if (!isUndefOrEqual(BitI, j))
4404         return false;
4405       if (!isUndefOrEqual(BitI1, j))
4406         return false;
4407     }
4408   }
4409   return true;
4410 }
4411
4412 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4413 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4414 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4415   if (!VT.is512BitVector())
4416     return false;
4417
4418   unsigned NumElts = VT.getVectorNumElements();
4419   unsigned HalfSize = NumElts/2;
4420   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4421     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4422       *Imm = 1;
4423       return true;
4424     }
4425   }
4426   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4427     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4428       *Imm = 0;
4429       return true;
4430     }
4431   }
4432   return false;
4433 }
4434
4435 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4436 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4437 /// MOVSD, and MOVD, i.e. setting the lowest element.
4438 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4439   if (VT.getVectorElementType().getSizeInBits() < 32)
4440     return false;
4441   if (!VT.is128BitVector())
4442     return false;
4443
4444   unsigned NumElts = VT.getVectorNumElements();
4445
4446   if (!isUndefOrEqual(Mask[0], NumElts))
4447     return false;
4448
4449   for (unsigned i = 1; i != NumElts; ++i)
4450     if (!isUndefOrEqual(Mask[i], i))
4451       return false;
4452
4453   return true;
4454 }
4455
4456 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4457 /// as permutations between 128-bit chunks or halves. As an example: this
4458 /// shuffle bellow:
4459 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4460 /// The first half comes from the second half of V1 and the second half from the
4461 /// the second half of V2.
4462 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4463   if (!HasFp256 || !VT.is256BitVector())
4464     return false;
4465
4466   // The shuffle result is divided into half A and half B. In total the two
4467   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4468   // B must come from C, D, E or F.
4469   unsigned HalfSize = VT.getVectorNumElements()/2;
4470   bool MatchA = false, MatchB = false;
4471
4472   // Check if A comes from one of C, D, E, F.
4473   for (unsigned Half = 0; Half != 4; ++Half) {
4474     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4475       MatchA = true;
4476       break;
4477     }
4478   }
4479
4480   // Check if B comes from one of C, D, E, F.
4481   for (unsigned Half = 0; Half != 4; ++Half) {
4482     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4483       MatchB = true;
4484       break;
4485     }
4486   }
4487
4488   return MatchA && MatchB;
4489 }
4490
4491 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4492 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4493 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4494   MVT VT = SVOp->getSimpleValueType(0);
4495
4496   unsigned HalfSize = VT.getVectorNumElements()/2;
4497
4498   unsigned FstHalf = 0, SndHalf = 0;
4499   for (unsigned i = 0; i < HalfSize; ++i) {
4500     if (SVOp->getMaskElt(i) > 0) {
4501       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4502       break;
4503     }
4504   }
4505   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4506     if (SVOp->getMaskElt(i) > 0) {
4507       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4508       break;
4509     }
4510   }
4511
4512   return (FstHalf | (SndHalf << 4));
4513 }
4514
4515 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4516 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4517   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4518   if (EltSize < 32)
4519     return false;
4520
4521   unsigned NumElts = VT.getVectorNumElements();
4522   Imm8 = 0;
4523   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4524     for (unsigned i = 0; i != NumElts; ++i) {
4525       if (Mask[i] < 0)
4526         continue;
4527       Imm8 |= Mask[i] << (i*2);
4528     }
4529     return true;
4530   }
4531
4532   unsigned LaneSize = 4;
4533   SmallVector<int, 4> MaskVal(LaneSize, -1);
4534
4535   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4536     for (unsigned i = 0; i != LaneSize; ++i) {
4537       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4538         return false;
4539       if (Mask[i+l] < 0)
4540         continue;
4541       if (MaskVal[i] < 0) {
4542         MaskVal[i] = Mask[i+l] - l;
4543         Imm8 |= MaskVal[i] << (i*2);
4544         continue;
4545       }
4546       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4547         return false;
4548     }
4549   }
4550   return true;
4551 }
4552
4553 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4554 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4555 /// Note that VPERMIL mask matching is different depending whether theunderlying
4556 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4557 /// to the same elements of the low, but to the higher half of the source.
4558 /// In VPERMILPD the two lanes could be shuffled independently of each other
4559 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4560 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4561   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4562   if (VT.getSizeInBits() < 256 || EltSize < 32)
4563     return false;
4564   bool symetricMaskRequired = (EltSize == 32);
4565   unsigned NumElts = VT.getVectorNumElements();
4566
4567   unsigned NumLanes = VT.getSizeInBits()/128;
4568   unsigned LaneSize = NumElts/NumLanes;
4569   // 2 or 4 elements in one lane
4570
4571   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4572   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4573     for (unsigned i = 0; i != LaneSize; ++i) {
4574       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4575         return false;
4576       if (symetricMaskRequired) {
4577         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4578           ExpectedMaskVal[i] = Mask[i+l] - l;
4579           continue;
4580         }
4581         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4582           return false;
4583       }
4584     }
4585   }
4586   return true;
4587 }
4588
4589 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4590 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4591 /// element of vector 2 and the other elements to come from vector 1 in order.
4592 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4593                                bool V2IsSplat = false, bool V2IsUndef = false) {
4594   if (!VT.is128BitVector())
4595     return false;
4596
4597   unsigned NumOps = VT.getVectorNumElements();
4598   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4599     return false;
4600
4601   if (!isUndefOrEqual(Mask[0], 0))
4602     return false;
4603
4604   for (unsigned i = 1; i != NumOps; ++i)
4605     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4606           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4607           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4608       return false;
4609
4610   return true;
4611 }
4612
4613 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4614 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4615 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4616 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4617                            const X86Subtarget *Subtarget) {
4618   if (!Subtarget->hasSSE3())
4619     return false;
4620
4621   unsigned NumElems = VT.getVectorNumElements();
4622
4623   if ((VT.is128BitVector() && NumElems != 4) ||
4624       (VT.is256BitVector() && NumElems != 8) ||
4625       (VT.is512BitVector() && NumElems != 16))
4626     return false;
4627
4628   // "i+1" is the value the indexed mask element must have
4629   for (unsigned i = 0; i != NumElems; i += 2)
4630     if (!isUndefOrEqual(Mask[i], i+1) ||
4631         !isUndefOrEqual(Mask[i+1], i+1))
4632       return false;
4633
4634   return true;
4635 }
4636
4637 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4638 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4639 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4640 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4641                            const X86Subtarget *Subtarget) {
4642   if (!Subtarget->hasSSE3())
4643     return false;
4644
4645   unsigned NumElems = VT.getVectorNumElements();
4646
4647   if ((VT.is128BitVector() && NumElems != 4) ||
4648       (VT.is256BitVector() && NumElems != 8) ||
4649       (VT.is512BitVector() && NumElems != 16))
4650     return false;
4651
4652   // "i" is the value the indexed mask element must have
4653   for (unsigned i = 0; i != NumElems; i += 2)
4654     if (!isUndefOrEqual(Mask[i], i) ||
4655         !isUndefOrEqual(Mask[i+1], i))
4656       return false;
4657
4658   return true;
4659 }
4660
4661 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4662 /// specifies a shuffle of elements that is suitable for input to 256-bit
4663 /// version of MOVDDUP.
4664 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4665   if (!HasFp256 || !VT.is256BitVector())
4666     return false;
4667
4668   unsigned NumElts = VT.getVectorNumElements();
4669   if (NumElts != 4)
4670     return false;
4671
4672   for (unsigned i = 0; i != NumElts/2; ++i)
4673     if (!isUndefOrEqual(Mask[i], 0))
4674       return false;
4675   for (unsigned i = NumElts/2; i != NumElts; ++i)
4676     if (!isUndefOrEqual(Mask[i], NumElts/2))
4677       return false;
4678   return true;
4679 }
4680
4681 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4682 /// specifies a shuffle of elements that is suitable for input to 128-bit
4683 /// version of MOVDDUP.
4684 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4685   if (!VT.is128BitVector())
4686     return false;
4687
4688   unsigned e = VT.getVectorNumElements() / 2;
4689   for (unsigned i = 0; i != e; ++i)
4690     if (!isUndefOrEqual(Mask[i], i))
4691       return false;
4692   for (unsigned i = 0; i != e; ++i)
4693     if (!isUndefOrEqual(Mask[e+i], i))
4694       return false;
4695   return true;
4696 }
4697
4698 /// isVEXTRACTIndex - Return true if the specified
4699 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4700 /// suitable for instruction that extract 128 or 256 bit vectors
4701 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4702   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4703   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4704     return false;
4705
4706   // The index should be aligned on a vecWidth-bit boundary.
4707   uint64_t Index =
4708     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4709
4710   MVT VT = N->getSimpleValueType(0);
4711   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4712   bool Result = (Index * ElSize) % vecWidth == 0;
4713
4714   return Result;
4715 }
4716
4717 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4718 /// operand specifies a subvector insert that is suitable for input to
4719 /// insertion of 128 or 256-bit subvectors
4720 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4721   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4722   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4723     return false;
4724   // The index should be aligned on a vecWidth-bit boundary.
4725   uint64_t Index =
4726     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4727
4728   MVT VT = N->getSimpleValueType(0);
4729   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4730   bool Result = (Index * ElSize) % vecWidth == 0;
4731
4732   return Result;
4733 }
4734
4735 bool X86::isVINSERT128Index(SDNode *N) {
4736   return isVINSERTIndex(N, 128);
4737 }
4738
4739 bool X86::isVINSERT256Index(SDNode *N) {
4740   return isVINSERTIndex(N, 256);
4741 }
4742
4743 bool X86::isVEXTRACT128Index(SDNode *N) {
4744   return isVEXTRACTIndex(N, 128);
4745 }
4746
4747 bool X86::isVEXTRACT256Index(SDNode *N) {
4748   return isVEXTRACTIndex(N, 256);
4749 }
4750
4751 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4752 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4753 /// Handles 128-bit and 256-bit.
4754 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4755   MVT VT = N->getSimpleValueType(0);
4756
4757   assert((VT.getSizeInBits() >= 128) &&
4758          "Unsupported vector type for PSHUF/SHUFP");
4759
4760   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4761   // independently on 128-bit lanes.
4762   unsigned NumElts = VT.getVectorNumElements();
4763   unsigned NumLanes = VT.getSizeInBits()/128;
4764   unsigned NumLaneElts = NumElts/NumLanes;
4765
4766   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4767          "Only supports 2, 4 or 8 elements per lane");
4768
4769   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4770   unsigned Mask = 0;
4771   for (unsigned i = 0; i != NumElts; ++i) {
4772     int Elt = N->getMaskElt(i);
4773     if (Elt < 0) continue;
4774     Elt &= NumLaneElts - 1;
4775     unsigned ShAmt = (i << Shift) % 8;
4776     Mask |= Elt << ShAmt;
4777   }
4778
4779   return Mask;
4780 }
4781
4782 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4783 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4784 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4785   MVT VT = N->getSimpleValueType(0);
4786
4787   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4788          "Unsupported vector type for PSHUFHW");
4789
4790   unsigned NumElts = VT.getVectorNumElements();
4791
4792   unsigned Mask = 0;
4793   for (unsigned l = 0; l != NumElts; l += 8) {
4794     // 8 nodes per lane, but we only care about the last 4.
4795     for (unsigned i = 0; i < 4; ++i) {
4796       int Elt = N->getMaskElt(l+i+4);
4797       if (Elt < 0) continue;
4798       Elt &= 0x3; // only 2-bits.
4799       Mask |= Elt << (i * 2);
4800     }
4801   }
4802
4803   return Mask;
4804 }
4805
4806 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4807 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4808 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4809   MVT VT = N->getSimpleValueType(0);
4810
4811   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4812          "Unsupported vector type for PSHUFHW");
4813
4814   unsigned NumElts = VT.getVectorNumElements();
4815
4816   unsigned Mask = 0;
4817   for (unsigned l = 0; l != NumElts; l += 8) {
4818     // 8 nodes per lane, but we only care about the first 4.
4819     for (unsigned i = 0; i < 4; ++i) {
4820       int Elt = N->getMaskElt(l+i);
4821       if (Elt < 0) continue;
4822       Elt &= 0x3; // only 2-bits
4823       Mask |= Elt << (i * 2);
4824     }
4825   }
4826
4827   return Mask;
4828 }
4829
4830 /// \brief Return the appropriate immediate to shuffle the specified
4831 /// VECTOR_SHUFFLE mask with the PALIGNR (if InterLane is false) or with
4832 /// VALIGN (if Interlane is true) instructions.
4833 static unsigned getShuffleAlignrImmediate(ShuffleVectorSDNode *SVOp,
4834                                            bool InterLane) {
4835   MVT VT = SVOp->getSimpleValueType(0);
4836   unsigned EltSize = InterLane ? 1 :
4837     VT.getVectorElementType().getSizeInBits() >> 3;
4838
4839   unsigned NumElts = VT.getVectorNumElements();
4840   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4841   unsigned NumLaneElts = NumElts/NumLanes;
4842
4843   int Val = 0;
4844   unsigned i;
4845   for (i = 0; i != NumElts; ++i) {
4846     Val = SVOp->getMaskElt(i);
4847     if (Val >= 0)
4848       break;
4849   }
4850   if (Val >= (int)NumElts)
4851     Val -= NumElts - NumLaneElts;
4852
4853   assert(Val - i > 0 && "PALIGNR imm should be positive");
4854   return (Val - i) * EltSize;
4855 }
4856
4857 /// \brief Return the appropriate immediate to shuffle the specified
4858 /// VECTOR_SHUFFLE mask with the PALIGNR instruction.
4859 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4860   return getShuffleAlignrImmediate(SVOp, false);
4861 }
4862
4863 /// \brief Return the appropriate immediate to shuffle the specified
4864 /// VECTOR_SHUFFLE mask with the VALIGN instruction.
4865 static unsigned getShuffleVALIGNImmediate(ShuffleVectorSDNode *SVOp) {
4866   return getShuffleAlignrImmediate(SVOp, true);
4867 }
4868
4869
4870 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4871   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4872   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4873     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4874
4875   uint64_t Index =
4876     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4877
4878   MVT VecVT = N->getOperand(0).getSimpleValueType();
4879   MVT ElVT = VecVT.getVectorElementType();
4880
4881   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4882   return Index / NumElemsPerChunk;
4883 }
4884
4885 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4886   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4887   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4888     llvm_unreachable("Illegal insert subvector for VINSERT");
4889
4890   uint64_t Index =
4891     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4892
4893   MVT VecVT = N->getSimpleValueType(0);
4894   MVT ElVT = VecVT.getVectorElementType();
4895
4896   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4897   return Index / NumElemsPerChunk;
4898 }
4899
4900 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4901 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4902 /// and VINSERTI128 instructions.
4903 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4904   return getExtractVEXTRACTImmediate(N, 128);
4905 }
4906
4907 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4908 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4909 /// and VINSERTI64x4 instructions.
4910 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4911   return getExtractVEXTRACTImmediate(N, 256);
4912 }
4913
4914 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4915 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4916 /// and VINSERTI128 instructions.
4917 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4918   return getInsertVINSERTImmediate(N, 128);
4919 }
4920
4921 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4922 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4923 /// and VINSERTI64x4 instructions.
4924 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4925   return getInsertVINSERTImmediate(N, 256);
4926 }
4927
4928 /// isZero - Returns true if Elt is a constant integer zero
4929 static bool isZero(SDValue V) {
4930   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4931   return C && C->isNullValue();
4932 }
4933
4934 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4935 /// constant +0.0.
4936 bool X86::isZeroNode(SDValue Elt) {
4937   if (isZero(Elt))
4938     return true;
4939   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4940     return CFP->getValueAPF().isPosZero();
4941   return false;
4942 }
4943
4944 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4945 /// match movhlps. The lower half elements should come from upper half of
4946 /// V1 (and in order), and the upper half elements should come from the upper
4947 /// half of V2 (and in order).
4948 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4949   if (!VT.is128BitVector())
4950     return false;
4951   if (VT.getVectorNumElements() != 4)
4952     return false;
4953   for (unsigned i = 0, e = 2; i != e; ++i)
4954     if (!isUndefOrEqual(Mask[i], i+2))
4955       return false;
4956   for (unsigned i = 2; i != 4; ++i)
4957     if (!isUndefOrEqual(Mask[i], i+4))
4958       return false;
4959   return true;
4960 }
4961
4962 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4963 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4964 /// required.
4965 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4966   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4967     return false;
4968   N = N->getOperand(0).getNode();
4969   if (!ISD::isNON_EXTLoad(N))
4970     return false;
4971   if (LD)
4972     *LD = cast<LoadSDNode>(N);
4973   return true;
4974 }
4975
4976 // Test whether the given value is a vector value which will be legalized
4977 // into a load.
4978 static bool WillBeConstantPoolLoad(SDNode *N) {
4979   if (N->getOpcode() != ISD::BUILD_VECTOR)
4980     return false;
4981
4982   // Check for any non-constant elements.
4983   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4984     switch (N->getOperand(i).getNode()->getOpcode()) {
4985     case ISD::UNDEF:
4986     case ISD::ConstantFP:
4987     case ISD::Constant:
4988       break;
4989     default:
4990       return false;
4991     }
4992
4993   // Vectors of all-zeros and all-ones are materialized with special
4994   // instructions rather than being loaded.
4995   return !ISD::isBuildVectorAllZeros(N) &&
4996          !ISD::isBuildVectorAllOnes(N);
4997 }
4998
4999 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
5000 /// match movlp{s|d}. The lower half elements should come from lower half of
5001 /// V1 (and in order), and the upper half elements should come from the upper
5002 /// half of V2 (and in order). And since V1 will become the source of the
5003 /// MOVLP, it must be either a vector load or a scalar load to vector.
5004 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
5005                                ArrayRef<int> Mask, MVT VT) {
5006   if (!VT.is128BitVector())
5007     return false;
5008
5009   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
5010     return false;
5011   // Is V2 is a vector load, don't do this transformation. We will try to use
5012   // load folding shufps op.
5013   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
5014     return false;
5015
5016   unsigned NumElems = VT.getVectorNumElements();
5017
5018   if (NumElems != 2 && NumElems != 4)
5019     return false;
5020   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
5021     if (!isUndefOrEqual(Mask[i], i))
5022       return false;
5023   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
5024     if (!isUndefOrEqual(Mask[i], i+NumElems))
5025       return false;
5026   return true;
5027 }
5028
5029 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
5030 /// to an zero vector.
5031 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
5032 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
5033   SDValue V1 = N->getOperand(0);
5034   SDValue V2 = N->getOperand(1);
5035   unsigned NumElems = N->getValueType(0).getVectorNumElements();
5036   for (unsigned i = 0; i != NumElems; ++i) {
5037     int Idx = N->getMaskElt(i);
5038     if (Idx >= (int)NumElems) {
5039       unsigned Opc = V2.getOpcode();
5040       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
5041         continue;
5042       if (Opc != ISD::BUILD_VECTOR ||
5043           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
5044         return false;
5045     } else if (Idx >= 0) {
5046       unsigned Opc = V1.getOpcode();
5047       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
5048         continue;
5049       if (Opc != ISD::BUILD_VECTOR ||
5050           !X86::isZeroNode(V1.getOperand(Idx)))
5051         return false;
5052     }
5053   }
5054   return true;
5055 }
5056
5057 /// getZeroVector - Returns a vector of specified type with all zero elements.
5058 ///
5059 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
5060                              SelectionDAG &DAG, SDLoc dl) {
5061   assert(VT.isVector() && "Expected a vector type");
5062
5063   // Always build SSE zero vectors as <4 x i32> bitcasted
5064   // to their dest type. This ensures they get CSE'd.
5065   SDValue Vec;
5066   if (VT.is128BitVector()) {  // SSE
5067     if (Subtarget->hasSSE2()) {  // SSE2
5068       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5069       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5070     } else { // SSE1
5071       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5072       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
5073     }
5074   } else if (VT.is256BitVector()) { // AVX
5075     if (Subtarget->hasInt256()) { // AVX2
5076       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5077       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5078       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5079     } else {
5080       // 256-bit logic and arithmetic instructions in AVX are all
5081       // floating-point, no support for integer ops. Emit fp zeroed vectors.
5082       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
5083       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5084       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
5085     }
5086   } else if (VT.is512BitVector()) { // AVX-512
5087       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
5088       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
5089                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5090       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
5091   } else if (VT.getScalarType() == MVT::i1) {
5092     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
5093     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5094     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5095     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5096   } else
5097     llvm_unreachable("Unexpected vector type");
5098
5099   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5100 }
5101
5102 /// getOnesVector - Returns a vector of specified type with all bits set.
5103 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
5104 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
5105 /// Then bitcast to their original type, ensuring they get CSE'd.
5106 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
5107                              SDLoc dl) {
5108   assert(VT.isVector() && "Expected a vector type");
5109
5110   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
5111   SDValue Vec;
5112   if (VT.is256BitVector()) {
5113     if (HasInt256) { // AVX2
5114       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
5115       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
5116     } else { // AVX
5117       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5118       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
5119     }
5120   } else if (VT.is128BitVector()) {
5121     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
5122   } else
5123     llvm_unreachable("Unexpected vector type");
5124
5125   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
5126 }
5127
5128 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
5129 /// that point to V2 points to its first element.
5130 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
5131   for (unsigned i = 0; i != NumElems; ++i) {
5132     if (Mask[i] > (int)NumElems) {
5133       Mask[i] = NumElems;
5134     }
5135   }
5136 }
5137
5138 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
5139 /// operation of specified width.
5140 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5141                        SDValue V2) {
5142   unsigned NumElems = VT.getVectorNumElements();
5143   SmallVector<int, 8> Mask;
5144   Mask.push_back(NumElems);
5145   for (unsigned i = 1; i != NumElems; ++i)
5146     Mask.push_back(i);
5147   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5148 }
5149
5150 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5151 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5152                           SDValue V2) {
5153   unsigned NumElems = VT.getVectorNumElements();
5154   SmallVector<int, 8> Mask;
5155   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5156     Mask.push_back(i);
5157     Mask.push_back(i + NumElems);
5158   }
5159   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5160 }
5161
5162 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5163 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5164                           SDValue V2) {
5165   unsigned NumElems = VT.getVectorNumElements();
5166   SmallVector<int, 8> Mask;
5167   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5168     Mask.push_back(i + Half);
5169     Mask.push_back(i + NumElems + Half);
5170   }
5171   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5172 }
5173
5174 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5175 // a generic shuffle instruction because the target has no such instructions.
5176 // Generate shuffles which repeat i16 and i8 several times until they can be
5177 // represented by v4f32 and then be manipulated by target suported shuffles.
5178 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5179   MVT VT = V.getSimpleValueType();
5180   int NumElems = VT.getVectorNumElements();
5181   SDLoc dl(V);
5182
5183   while (NumElems > 4) {
5184     if (EltNo < NumElems/2) {
5185       V = getUnpackl(DAG, dl, VT, V, V);
5186     } else {
5187       V = getUnpackh(DAG, dl, VT, V, V);
5188       EltNo -= NumElems/2;
5189     }
5190     NumElems >>= 1;
5191   }
5192   return V;
5193 }
5194
5195 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5196 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5197   MVT VT = V.getSimpleValueType();
5198   SDLoc dl(V);
5199
5200   if (VT.is128BitVector()) {
5201     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5202     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5203     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5204                              &SplatMask[0]);
5205   } else if (VT.is256BitVector()) {
5206     // To use VPERMILPS to splat scalars, the second half of indicies must
5207     // refer to the higher part, which is a duplication of the lower one,
5208     // because VPERMILPS can only handle in-lane permutations.
5209     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5210                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5211
5212     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5213     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5214                              &SplatMask[0]);
5215   } else
5216     llvm_unreachable("Vector size not supported");
5217
5218   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5219 }
5220
5221 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5222 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5223   MVT SrcVT = SV->getSimpleValueType(0);
5224   SDValue V1 = SV->getOperand(0);
5225   SDLoc dl(SV);
5226
5227   int EltNo = SV->getSplatIndex();
5228   int NumElems = SrcVT.getVectorNumElements();
5229   bool Is256BitVec = SrcVT.is256BitVector();
5230
5231   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5232          "Unknown how to promote splat for type");
5233
5234   // Extract the 128-bit part containing the splat element and update
5235   // the splat element index when it refers to the higher register.
5236   if (Is256BitVec) {
5237     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5238     if (EltNo >= NumElems/2)
5239       EltNo -= NumElems/2;
5240   }
5241
5242   // All i16 and i8 vector types can't be used directly by a generic shuffle
5243   // instruction because the target has no such instruction. Generate shuffles
5244   // which repeat i16 and i8 several times until they fit in i32, and then can
5245   // be manipulated by target suported shuffles.
5246   MVT EltVT = SrcVT.getVectorElementType();
5247   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5248     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5249
5250   // Recreate the 256-bit vector and place the same 128-bit vector
5251   // into the low and high part. This is necessary because we want
5252   // to use VPERM* to shuffle the vectors
5253   if (Is256BitVec) {
5254     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5255   }
5256
5257   return getLegalSplat(DAG, V1, EltNo);
5258 }
5259
5260 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5261 /// vector of zero or undef vector.  This produces a shuffle where the low
5262 /// element of V2 is swizzled into the zero/undef vector, landing at element
5263 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5264 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5265                                            bool IsZero,
5266                                            const X86Subtarget *Subtarget,
5267                                            SelectionDAG &DAG) {
5268   MVT VT = V2.getSimpleValueType();
5269   SDValue V1 = IsZero
5270     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5271   unsigned NumElems = VT.getVectorNumElements();
5272   SmallVector<int, 16> MaskVec;
5273   for (unsigned i = 0; i != NumElems; ++i)
5274     // If this is the insertion idx, put the low elt of V2 here.
5275     MaskVec.push_back(i == Idx ? NumElems : i);
5276   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5277 }
5278
5279 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5280 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5281 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5282 /// shuffles which use a single input multiple times, and in those cases it will
5283 /// adjust the mask to only have indices within that single input.
5284 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5285                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5286   unsigned NumElems = VT.getVectorNumElements();
5287   SDValue ImmN;
5288
5289   IsUnary = false;
5290   bool IsFakeUnary = false;
5291   switch(N->getOpcode()) {
5292   case X86ISD::BLENDI:
5293     ImmN = N->getOperand(N->getNumOperands()-1);
5294     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5295     break;
5296   case X86ISD::SHUFP:
5297     ImmN = N->getOperand(N->getNumOperands()-1);
5298     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5299     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5300     break;
5301   case X86ISD::UNPCKH:
5302     DecodeUNPCKHMask(VT, Mask);
5303     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5304     break;
5305   case X86ISD::UNPCKL:
5306     DecodeUNPCKLMask(VT, Mask);
5307     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5308     break;
5309   case X86ISD::MOVHLPS:
5310     DecodeMOVHLPSMask(NumElems, Mask);
5311     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5312     break;
5313   case X86ISD::MOVLHPS:
5314     DecodeMOVLHPSMask(NumElems, Mask);
5315     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5316     break;
5317   case X86ISD::PALIGNR:
5318     ImmN = N->getOperand(N->getNumOperands()-1);
5319     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5320     break;
5321   case X86ISD::PSHUFD:
5322   case X86ISD::VPERMILPI:
5323     ImmN = N->getOperand(N->getNumOperands()-1);
5324     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5325     IsUnary = true;
5326     break;
5327   case X86ISD::PSHUFHW:
5328     ImmN = N->getOperand(N->getNumOperands()-1);
5329     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5330     IsUnary = true;
5331     break;
5332   case X86ISD::PSHUFLW:
5333     ImmN = N->getOperand(N->getNumOperands()-1);
5334     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5335     IsUnary = true;
5336     break;
5337   case X86ISD::PSHUFB: {
5338     IsUnary = true;
5339     SDValue MaskNode = N->getOperand(1);
5340     while (MaskNode->getOpcode() == ISD::BITCAST)
5341       MaskNode = MaskNode->getOperand(0);
5342
5343     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5344       // If we have a build-vector, then things are easy.
5345       EVT VT = MaskNode.getValueType();
5346       assert(VT.isVector() &&
5347              "Can't produce a non-vector with a build_vector!");
5348       if (!VT.isInteger())
5349         return false;
5350
5351       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5352
5353       SmallVector<uint64_t, 32> RawMask;
5354       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5355         SDValue Op = MaskNode->getOperand(i);
5356         if (Op->getOpcode() == ISD::UNDEF) {
5357           RawMask.push_back((uint64_t)SM_SentinelUndef);
5358           continue;
5359         }
5360         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
5361         if (!CN)
5362           return false;
5363         APInt MaskElement = CN->getAPIntValue();
5364
5365         // We now have to decode the element which could be any integer size and
5366         // extract each byte of it.
5367         for (int j = 0; j < NumBytesPerElement; ++j) {
5368           // Note that this is x86 and so always little endian: the low byte is
5369           // the first byte of the mask.
5370           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5371           MaskElement = MaskElement.lshr(8);
5372         }
5373       }
5374       DecodePSHUFBMask(RawMask, Mask);
5375       break;
5376     }
5377
5378     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5379     if (!MaskLoad)
5380       return false;
5381
5382     SDValue Ptr = MaskLoad->getBasePtr();
5383     if (Ptr->getOpcode() == X86ISD::Wrapper)
5384       Ptr = Ptr->getOperand(0);
5385
5386     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5387     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5388       return false;
5389
5390     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
5391       // FIXME: Support AVX-512 here.
5392       Type *Ty = C->getType();
5393       if (!Ty->isVectorTy() || (Ty->getVectorNumElements() != 16 &&
5394                                 Ty->getVectorNumElements() != 32))
5395         return false;
5396
5397       DecodePSHUFBMask(C, Mask);
5398       break;
5399     }
5400
5401     return false;
5402   }
5403   case X86ISD::VPERMI:
5404     ImmN = N->getOperand(N->getNumOperands()-1);
5405     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5406     IsUnary = true;
5407     break;
5408   case X86ISD::MOVSS:
5409   case X86ISD::MOVSD: {
5410     // The index 0 always comes from the first element of the second source,
5411     // this is why MOVSS and MOVSD are used in the first place. The other
5412     // elements come from the other positions of the first source vector
5413     Mask.push_back(NumElems);
5414     for (unsigned i = 1; i != NumElems; ++i) {
5415       Mask.push_back(i);
5416     }
5417     break;
5418   }
5419   case X86ISD::VPERM2X128:
5420     ImmN = N->getOperand(N->getNumOperands()-1);
5421     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5422     if (Mask.empty()) return false;
5423     break;
5424   case X86ISD::MOVSLDUP:
5425     DecodeMOVSLDUPMask(VT, Mask);
5426     break;
5427   case X86ISD::MOVSHDUP:
5428     DecodeMOVSHDUPMask(VT, Mask);
5429     break;
5430   case X86ISD::MOVDDUP:
5431   case X86ISD::MOVLHPD:
5432   case X86ISD::MOVLPD:
5433   case X86ISD::MOVLPS:
5434     // Not yet implemented
5435     return false;
5436   default: llvm_unreachable("unknown target shuffle node");
5437   }
5438
5439   // If we have a fake unary shuffle, the shuffle mask is spread across two
5440   // inputs that are actually the same node. Re-map the mask to always point
5441   // into the first input.
5442   if (IsFakeUnary)
5443     for (int &M : Mask)
5444       if (M >= (int)Mask.size())
5445         M -= Mask.size();
5446
5447   return true;
5448 }
5449
5450 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5451 /// element of the result of the vector shuffle.
5452 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5453                                    unsigned Depth) {
5454   if (Depth == 6)
5455     return SDValue();  // Limit search depth.
5456
5457   SDValue V = SDValue(N, 0);
5458   EVT VT = V.getValueType();
5459   unsigned Opcode = V.getOpcode();
5460
5461   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5462   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5463     int Elt = SV->getMaskElt(Index);
5464
5465     if (Elt < 0)
5466       return DAG.getUNDEF(VT.getVectorElementType());
5467
5468     unsigned NumElems = VT.getVectorNumElements();
5469     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5470                                          : SV->getOperand(1);
5471     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5472   }
5473
5474   // Recurse into target specific vector shuffles to find scalars.
5475   if (isTargetShuffle(Opcode)) {
5476     MVT ShufVT = V.getSimpleValueType();
5477     unsigned NumElems = ShufVT.getVectorNumElements();
5478     SmallVector<int, 16> ShuffleMask;
5479     bool IsUnary;
5480
5481     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5482       return SDValue();
5483
5484     int Elt = ShuffleMask[Index];
5485     if (Elt < 0)
5486       return DAG.getUNDEF(ShufVT.getVectorElementType());
5487
5488     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5489                                          : N->getOperand(1);
5490     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5491                                Depth+1);
5492   }
5493
5494   // Actual nodes that may contain scalar elements
5495   if (Opcode == ISD::BITCAST) {
5496     V = V.getOperand(0);
5497     EVT SrcVT = V.getValueType();
5498     unsigned NumElems = VT.getVectorNumElements();
5499
5500     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5501       return SDValue();
5502   }
5503
5504   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5505     return (Index == 0) ? V.getOperand(0)
5506                         : DAG.getUNDEF(VT.getVectorElementType());
5507
5508   if (V.getOpcode() == ISD::BUILD_VECTOR)
5509     return V.getOperand(Index);
5510
5511   return SDValue();
5512 }
5513
5514 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5515 /// shuffle operation which come from a consecutively from a zero. The
5516 /// search can start in two different directions, from left or right.
5517 /// We count undefs as zeros until PreferredNum is reached.
5518 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5519                                          unsigned NumElems, bool ZerosFromLeft,
5520                                          SelectionDAG &DAG,
5521                                          unsigned PreferredNum = -1U) {
5522   unsigned NumZeros = 0;
5523   for (unsigned i = 0; i != NumElems; ++i) {
5524     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5525     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5526     if (!Elt.getNode())
5527       break;
5528
5529     if (X86::isZeroNode(Elt))
5530       ++NumZeros;
5531     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5532       NumZeros = std::min(NumZeros + 1, PreferredNum);
5533     else
5534       break;
5535   }
5536
5537   return NumZeros;
5538 }
5539
5540 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5541 /// correspond consecutively to elements from one of the vector operands,
5542 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5543 static
5544 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5545                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5546                               unsigned NumElems, unsigned &OpNum) {
5547   bool SeenV1 = false;
5548   bool SeenV2 = false;
5549
5550   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5551     int Idx = SVOp->getMaskElt(i);
5552     // Ignore undef indicies
5553     if (Idx < 0)
5554       continue;
5555
5556     if (Idx < (int)NumElems)
5557       SeenV1 = true;
5558     else
5559       SeenV2 = true;
5560
5561     // Only accept consecutive elements from the same vector
5562     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5563       return false;
5564   }
5565
5566   OpNum = SeenV1 ? 0 : 1;
5567   return true;
5568 }
5569
5570 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5571 /// logical left shift of a vector.
5572 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5573                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5574   unsigned NumElems =
5575     SVOp->getSimpleValueType(0).getVectorNumElements();
5576   unsigned NumZeros = getNumOfConsecutiveZeros(
5577       SVOp, NumElems, false /* check zeros from right */, DAG,
5578       SVOp->getMaskElt(0));
5579   unsigned OpSrc;
5580
5581   if (!NumZeros)
5582     return false;
5583
5584   // Considering the elements in the mask that are not consecutive zeros,
5585   // check if they consecutively come from only one of the source vectors.
5586   //
5587   //               V1 = {X, A, B, C}     0
5588   //                         \  \  \    /
5589   //   vector_shuffle V1, V2 <1, 2, 3, X>
5590   //
5591   if (!isShuffleMaskConsecutive(SVOp,
5592             0,                   // Mask Start Index
5593             NumElems-NumZeros,   // Mask End Index(exclusive)
5594             NumZeros,            // Where to start looking in the src vector
5595             NumElems,            // Number of elements in vector
5596             OpSrc))              // Which source operand ?
5597     return false;
5598
5599   isLeft = false;
5600   ShAmt = NumZeros;
5601   ShVal = SVOp->getOperand(OpSrc);
5602   return true;
5603 }
5604
5605 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5606 /// logical left shift of a vector.
5607 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5608                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5609   unsigned NumElems =
5610     SVOp->getSimpleValueType(0).getVectorNumElements();
5611   unsigned NumZeros = getNumOfConsecutiveZeros(
5612       SVOp, NumElems, true /* check zeros from left */, DAG,
5613       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5614   unsigned OpSrc;
5615
5616   if (!NumZeros)
5617     return false;
5618
5619   // Considering the elements in the mask that are not consecutive zeros,
5620   // check if they consecutively come from only one of the source vectors.
5621   //
5622   //                           0    { A, B, X, X } = V2
5623   //                          / \    /  /
5624   //   vector_shuffle V1, V2 <X, X, 4, 5>
5625   //
5626   if (!isShuffleMaskConsecutive(SVOp,
5627             NumZeros,     // Mask Start Index
5628             NumElems,     // Mask End Index(exclusive)
5629             0,            // Where to start looking in the src vector
5630             NumElems,     // Number of elements in vector
5631             OpSrc))       // Which source operand ?
5632     return false;
5633
5634   isLeft = true;
5635   ShAmt = NumZeros;
5636   ShVal = SVOp->getOperand(OpSrc);
5637   return true;
5638 }
5639
5640 /// isVectorShift - Returns true if the shuffle can be implemented as a
5641 /// logical left or right shift of a vector.
5642 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5643                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5644   // Although the logic below support any bitwidth size, there are no
5645   // shift instructions which handle more than 128-bit vectors.
5646   if (!SVOp->getSimpleValueType(0).is128BitVector())
5647     return false;
5648
5649   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5650       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5651     return true;
5652
5653   return false;
5654 }
5655
5656 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5657 ///
5658 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5659                                        unsigned NumNonZero, unsigned NumZero,
5660                                        SelectionDAG &DAG,
5661                                        const X86Subtarget* Subtarget,
5662                                        const TargetLowering &TLI) {
5663   if (NumNonZero > 8)
5664     return SDValue();
5665
5666   SDLoc dl(Op);
5667   SDValue V;
5668   bool First = true;
5669   for (unsigned i = 0; i < 16; ++i) {
5670     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5671     if (ThisIsNonZero && First) {
5672       if (NumZero)
5673         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5674       else
5675         V = DAG.getUNDEF(MVT::v8i16);
5676       First = false;
5677     }
5678
5679     if ((i & 1) != 0) {
5680       SDValue ThisElt, LastElt;
5681       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5682       if (LastIsNonZero) {
5683         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5684                               MVT::i16, Op.getOperand(i-1));
5685       }
5686       if (ThisIsNonZero) {
5687         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5688         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5689                               ThisElt, DAG.getConstant(8, MVT::i8));
5690         if (LastIsNonZero)
5691           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5692       } else
5693         ThisElt = LastElt;
5694
5695       if (ThisElt.getNode())
5696         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5697                         DAG.getIntPtrConstant(i/2));
5698     }
5699   }
5700
5701   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5702 }
5703
5704 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5705 ///
5706 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5707                                      unsigned NumNonZero, unsigned NumZero,
5708                                      SelectionDAG &DAG,
5709                                      const X86Subtarget* Subtarget,
5710                                      const TargetLowering &TLI) {
5711   if (NumNonZero > 4)
5712     return SDValue();
5713
5714   SDLoc dl(Op);
5715   SDValue V;
5716   bool First = true;
5717   for (unsigned i = 0; i < 8; ++i) {
5718     bool isNonZero = (NonZeros & (1 << i)) != 0;
5719     if (isNonZero) {
5720       if (First) {
5721         if (NumZero)
5722           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5723         else
5724           V = DAG.getUNDEF(MVT::v8i16);
5725         First = false;
5726       }
5727       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5728                       MVT::v8i16, V, Op.getOperand(i),
5729                       DAG.getIntPtrConstant(i));
5730     }
5731   }
5732
5733   return V;
5734 }
5735
5736 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5737 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5738                                      unsigned NonZeros, unsigned NumNonZero,
5739                                      unsigned NumZero, SelectionDAG &DAG,
5740                                      const X86Subtarget *Subtarget,
5741                                      const TargetLowering &TLI) {
5742   // We know there's at least one non-zero element
5743   unsigned FirstNonZeroIdx = 0;
5744   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5745   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5746          X86::isZeroNode(FirstNonZero)) {
5747     ++FirstNonZeroIdx;
5748     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5749   }
5750
5751   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5752       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5753     return SDValue();
5754
5755   SDValue V = FirstNonZero.getOperand(0);
5756   MVT VVT = V.getSimpleValueType();
5757   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5758     return SDValue();
5759
5760   unsigned FirstNonZeroDst =
5761       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5762   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5763   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5764   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5765
5766   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5767     SDValue Elem = Op.getOperand(Idx);
5768     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5769       continue;
5770
5771     // TODO: What else can be here? Deal with it.
5772     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5773       return SDValue();
5774
5775     // TODO: Some optimizations are still possible here
5776     // ex: Getting one element from a vector, and the rest from another.
5777     if (Elem.getOperand(0) != V)
5778       return SDValue();
5779
5780     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5781     if (Dst == Idx)
5782       ++CorrectIdx;
5783     else if (IncorrectIdx == -1U) {
5784       IncorrectIdx = Idx;
5785       IncorrectDst = Dst;
5786     } else
5787       // There was already one element with an incorrect index.
5788       // We can't optimize this case to an insertps.
5789       return SDValue();
5790   }
5791
5792   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5793     SDLoc dl(Op);
5794     EVT VT = Op.getSimpleValueType();
5795     unsigned ElementMoveMask = 0;
5796     if (IncorrectIdx == -1U)
5797       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5798     else
5799       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5800
5801     SDValue InsertpsMask =
5802         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5803     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5804   }
5805
5806   return SDValue();
5807 }
5808
5809 /// getVShift - Return a vector logical shift node.
5810 ///
5811 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5812                          unsigned NumBits, SelectionDAG &DAG,
5813                          const TargetLowering &TLI, SDLoc dl) {
5814   assert(VT.is128BitVector() && "Unknown type for VShift");
5815   EVT ShVT = MVT::v2i64;
5816   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5817   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5818   return DAG.getNode(ISD::BITCAST, dl, VT,
5819                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5820                              DAG.getConstant(NumBits,
5821                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5822 }
5823
5824 static SDValue
5825 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5826
5827   // Check if the scalar load can be widened into a vector load. And if
5828   // the address is "base + cst" see if the cst can be "absorbed" into
5829   // the shuffle mask.
5830   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5831     SDValue Ptr = LD->getBasePtr();
5832     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5833       return SDValue();
5834     EVT PVT = LD->getValueType(0);
5835     if (PVT != MVT::i32 && PVT != MVT::f32)
5836       return SDValue();
5837
5838     int FI = -1;
5839     int64_t Offset = 0;
5840     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5841       FI = FINode->getIndex();
5842       Offset = 0;
5843     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5844                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5845       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5846       Offset = Ptr.getConstantOperandVal(1);
5847       Ptr = Ptr.getOperand(0);
5848     } else {
5849       return SDValue();
5850     }
5851
5852     // FIXME: 256-bit vector instructions don't require a strict alignment,
5853     // improve this code to support it better.
5854     unsigned RequiredAlign = VT.getSizeInBits()/8;
5855     SDValue Chain = LD->getChain();
5856     // Make sure the stack object alignment is at least 16 or 32.
5857     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5858     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5859       if (MFI->isFixedObjectIndex(FI)) {
5860         // Can't change the alignment. FIXME: It's possible to compute
5861         // the exact stack offset and reference FI + adjust offset instead.
5862         // If someone *really* cares about this. That's the way to implement it.
5863         return SDValue();
5864       } else {
5865         MFI->setObjectAlignment(FI, RequiredAlign);
5866       }
5867     }
5868
5869     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5870     // Ptr + (Offset & ~15).
5871     if (Offset < 0)
5872       return SDValue();
5873     if ((Offset % RequiredAlign) & 3)
5874       return SDValue();
5875     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5876     if (StartOffset)
5877       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5878                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5879
5880     int EltNo = (Offset - StartOffset) >> 2;
5881     unsigned NumElems = VT.getVectorNumElements();
5882
5883     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5884     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5885                              LD->getPointerInfo().getWithOffset(StartOffset),
5886                              false, false, false, 0);
5887
5888     SmallVector<int, 8> Mask;
5889     for (unsigned i = 0; i != NumElems; ++i)
5890       Mask.push_back(EltNo);
5891
5892     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5893   }
5894
5895   return SDValue();
5896 }
5897
5898 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5899 /// vector of type 'VT', see if the elements can be replaced by a single large
5900 /// load which has the same value as a build_vector whose operands are 'elts'.
5901 ///
5902 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5903 ///
5904 /// FIXME: we'd also like to handle the case where the last elements are zero
5905 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5906 /// There's even a handy isZeroNode for that purpose.
5907 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5908                                         SDLoc &DL, SelectionDAG &DAG,
5909                                         bool isAfterLegalize) {
5910   EVT EltVT = VT.getVectorElementType();
5911   unsigned NumElems = Elts.size();
5912
5913   LoadSDNode *LDBase = nullptr;
5914   unsigned LastLoadedElt = -1U;
5915
5916   // For each element in the initializer, see if we've found a load or an undef.
5917   // If we don't find an initial load element, or later load elements are
5918   // non-consecutive, bail out.
5919   for (unsigned i = 0; i < NumElems; ++i) {
5920     SDValue Elt = Elts[i];
5921
5922     if (!Elt.getNode() ||
5923         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5924       return SDValue();
5925     if (!LDBase) {
5926       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5927         return SDValue();
5928       LDBase = cast<LoadSDNode>(Elt.getNode());
5929       LastLoadedElt = i;
5930       continue;
5931     }
5932     if (Elt.getOpcode() == ISD::UNDEF)
5933       continue;
5934
5935     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5936     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5937       return SDValue();
5938     LastLoadedElt = i;
5939   }
5940
5941   // If we have found an entire vector of loads and undefs, then return a large
5942   // load of the entire vector width starting at the base pointer.  If we found
5943   // consecutive loads for the low half, generate a vzext_load node.
5944   if (LastLoadedElt == NumElems - 1) {
5945
5946     if (isAfterLegalize &&
5947         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5948       return SDValue();
5949
5950     SDValue NewLd = SDValue();
5951
5952     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5953       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5954                           LDBase->getPointerInfo(),
5955                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5956                           LDBase->isInvariant(), 0);
5957     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5958                         LDBase->getPointerInfo(),
5959                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5960                         LDBase->isInvariant(), LDBase->getAlignment());
5961
5962     if (LDBase->hasAnyUseOfValue(1)) {
5963       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5964                                      SDValue(LDBase, 1),
5965                                      SDValue(NewLd.getNode(), 1));
5966       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5967       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5968                              SDValue(NewLd.getNode(), 1));
5969     }
5970
5971     return NewLd;
5972   }
5973   if (NumElems == 4 && LastLoadedElt == 1 &&
5974       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5975     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5976     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5977     SDValue ResNode =
5978         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5979                                 LDBase->getPointerInfo(),
5980                                 LDBase->getAlignment(),
5981                                 false/*isVolatile*/, true/*ReadMem*/,
5982                                 false/*WriteMem*/);
5983
5984     // Make sure the newly-created LOAD is in the same position as LDBase in
5985     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5986     // update uses of LDBase's output chain to use the TokenFactor.
5987     if (LDBase->hasAnyUseOfValue(1)) {
5988       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5989                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5990       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5991       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5992                              SDValue(ResNode.getNode(), 1));
5993     }
5994
5995     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5996   }
5997   return SDValue();
5998 }
5999
6000 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
6001 /// to generate a splat value for the following cases:
6002 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
6003 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
6004 /// a scalar load, or a constant.
6005 /// The VBROADCAST node is returned when a pattern is found,
6006 /// or SDValue() otherwise.
6007 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
6008                                     SelectionDAG &DAG) {
6009   // VBROADCAST requires AVX.
6010   // TODO: Splats could be generated for non-AVX CPUs using SSE
6011   // instructions, but there's less potential gain for only 128-bit vectors.
6012   if (!Subtarget->hasAVX())
6013     return SDValue();
6014
6015   MVT VT = Op.getSimpleValueType();
6016   SDLoc dl(Op);
6017
6018   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
6019          "Unsupported vector type for broadcast.");
6020
6021   SDValue Ld;
6022   bool ConstSplatVal;
6023
6024   switch (Op.getOpcode()) {
6025     default:
6026       // Unknown pattern found.
6027       return SDValue();
6028
6029     case ISD::BUILD_VECTOR: {
6030       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
6031       BitVector UndefElements;
6032       SDValue Splat = BVOp->getSplatValue(&UndefElements);
6033
6034       // We need a splat of a single value to use broadcast, and it doesn't
6035       // make any sense if the value is only in one element of the vector.
6036       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
6037         return SDValue();
6038
6039       Ld = Splat;
6040       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6041                        Ld.getOpcode() == ISD::ConstantFP);
6042
6043       // Make sure that all of the users of a non-constant load are from the
6044       // BUILD_VECTOR node.
6045       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
6046         return SDValue();
6047       break;
6048     }
6049
6050     case ISD::VECTOR_SHUFFLE: {
6051       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6052
6053       // Shuffles must have a splat mask where the first element is
6054       // broadcasted.
6055       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
6056         return SDValue();
6057
6058       SDValue Sc = Op.getOperand(0);
6059       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
6060           Sc.getOpcode() != ISD::BUILD_VECTOR) {
6061
6062         if (!Subtarget->hasInt256())
6063           return SDValue();
6064
6065         // Use the register form of the broadcast instruction available on AVX2.
6066         if (VT.getSizeInBits() >= 256)
6067           Sc = Extract128BitVector(Sc, 0, DAG, dl);
6068         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
6069       }
6070
6071       Ld = Sc.getOperand(0);
6072       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
6073                        Ld.getOpcode() == ISD::ConstantFP);
6074
6075       // The scalar_to_vector node and the suspected
6076       // load node must have exactly one user.
6077       // Constants may have multiple users.
6078
6079       // AVX-512 has register version of the broadcast
6080       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
6081         Ld.getValueType().getSizeInBits() >= 32;
6082       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
6083           !hasRegVer))
6084         return SDValue();
6085       break;
6086     }
6087   }
6088
6089   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
6090   bool IsGE256 = (VT.getSizeInBits() >= 256);
6091
6092   // When optimizing for size, generate up to 5 extra bytes for a broadcast
6093   // instruction to save 8 or more bytes of constant pool data.
6094   // TODO: If multiple splats are generated to load the same constant,
6095   // it may be detrimental to overall size. There needs to be a way to detect
6096   // that condition to know if this is truly a size win.
6097   const Function *F = DAG.getMachineFunction().getFunction();
6098   bool OptForSize = F->getAttributes().
6099     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
6100
6101   // Handle broadcasting a single constant scalar from the constant pool
6102   // into a vector.
6103   // On Sandybridge (no AVX2), it is still better to load a constant vector
6104   // from the constant pool and not to broadcast it from a scalar.
6105   // But override that restriction when optimizing for size.
6106   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
6107   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
6108     EVT CVT = Ld.getValueType();
6109     assert(!CVT.isVector() && "Must not broadcast a vector type");
6110
6111     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
6112     // For size optimization, also splat v2f64 and v2i64, and for size opt
6113     // with AVX2, also splat i8 and i16.
6114     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
6115     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
6116         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
6117       const Constant *C = nullptr;
6118       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
6119         C = CI->getConstantIntValue();
6120       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
6121         C = CF->getConstantFPValue();
6122
6123       assert(C && "Invalid constant type");
6124
6125       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6126       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
6127       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
6128       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
6129                        MachinePointerInfo::getConstantPool(),
6130                        false, false, false, Alignment);
6131
6132       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6133     }
6134   }
6135
6136   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
6137
6138   // Handle AVX2 in-register broadcasts.
6139   if (!IsLoad && Subtarget->hasInt256() &&
6140       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
6141     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6142
6143   // The scalar source must be a normal load.
6144   if (!IsLoad)
6145     return SDValue();
6146
6147   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
6148     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6149
6150   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
6151   // double since there is no vbroadcastsd xmm
6152   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
6153     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
6154       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
6155   }
6156
6157   // Unsupported broadcast.
6158   return SDValue();
6159 }
6160
6161 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
6162 /// underlying vector and index.
6163 ///
6164 /// Modifies \p ExtractedFromVec to the real vector and returns the real
6165 /// index.
6166 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
6167                                          SDValue ExtIdx) {
6168   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
6169   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
6170     return Idx;
6171
6172   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6173   // lowered this:
6174   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6175   // to:
6176   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6177   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6178   //                           undef)
6179   //                       Constant<0>)
6180   // In this case the vector is the extract_subvector expression and the index
6181   // is 2, as specified by the shuffle.
6182   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6183   SDValue ShuffleVec = SVOp->getOperand(0);
6184   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6185   assert(ShuffleVecVT.getVectorElementType() ==
6186          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6187
6188   int ShuffleIdx = SVOp->getMaskElt(Idx);
6189   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6190     ExtractedFromVec = ShuffleVec;
6191     return ShuffleIdx;
6192   }
6193   return Idx;
6194 }
6195
6196 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6197   MVT VT = Op.getSimpleValueType();
6198
6199   // Skip if insert_vec_elt is not supported.
6200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6201   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6202     return SDValue();
6203
6204   SDLoc DL(Op);
6205   unsigned NumElems = Op.getNumOperands();
6206
6207   SDValue VecIn1;
6208   SDValue VecIn2;
6209   SmallVector<unsigned, 4> InsertIndices;
6210   SmallVector<int, 8> Mask(NumElems, -1);
6211
6212   for (unsigned i = 0; i != NumElems; ++i) {
6213     unsigned Opc = Op.getOperand(i).getOpcode();
6214
6215     if (Opc == ISD::UNDEF)
6216       continue;
6217
6218     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6219       // Quit if more than 1 elements need inserting.
6220       if (InsertIndices.size() > 1)
6221         return SDValue();
6222
6223       InsertIndices.push_back(i);
6224       continue;
6225     }
6226
6227     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6228     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6229     // Quit if non-constant index.
6230     if (!isa<ConstantSDNode>(ExtIdx))
6231       return SDValue();
6232     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6233
6234     // Quit if extracted from vector of different type.
6235     if (ExtractedFromVec.getValueType() != VT)
6236       return SDValue();
6237
6238     if (!VecIn1.getNode())
6239       VecIn1 = ExtractedFromVec;
6240     else if (VecIn1 != ExtractedFromVec) {
6241       if (!VecIn2.getNode())
6242         VecIn2 = ExtractedFromVec;
6243       else if (VecIn2 != ExtractedFromVec)
6244         // Quit if more than 2 vectors to shuffle
6245         return SDValue();
6246     }
6247
6248     if (ExtractedFromVec == VecIn1)
6249       Mask[i] = Idx;
6250     else if (ExtractedFromVec == VecIn2)
6251       Mask[i] = Idx + NumElems;
6252   }
6253
6254   if (!VecIn1.getNode())
6255     return SDValue();
6256
6257   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6258   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6259   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6260     unsigned Idx = InsertIndices[i];
6261     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6262                      DAG.getIntPtrConstant(Idx));
6263   }
6264
6265   return NV;
6266 }
6267
6268 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6269 SDValue
6270 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6271
6272   MVT VT = Op.getSimpleValueType();
6273   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6274          "Unexpected type in LowerBUILD_VECTORvXi1!");
6275
6276   SDLoc dl(Op);
6277   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6278     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6279     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6280     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6281   }
6282
6283   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6284     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6285     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6286     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6287   }
6288
6289   bool AllContants = true;
6290   uint64_t Immediate = 0;
6291   int NonConstIdx = -1;
6292   bool IsSplat = true;
6293   unsigned NumNonConsts = 0;
6294   unsigned NumConsts = 0;
6295   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6296     SDValue In = Op.getOperand(idx);
6297     if (In.getOpcode() == ISD::UNDEF)
6298       continue;
6299     if (!isa<ConstantSDNode>(In)) {
6300       AllContants = false;
6301       NonConstIdx = idx;
6302       NumNonConsts++;
6303     }
6304     else {
6305       NumConsts++;
6306       if (cast<ConstantSDNode>(In)->getZExtValue())
6307       Immediate |= (1ULL << idx);
6308     }
6309     if (In != Op.getOperand(0))
6310       IsSplat = false;
6311   }
6312
6313   if (AllContants) {
6314     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6315       DAG.getConstant(Immediate, MVT::i16));
6316     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6317                        DAG.getIntPtrConstant(0));
6318   }
6319
6320   if (NumNonConsts == 1 && NonConstIdx != 0) {
6321     SDValue DstVec;
6322     if (NumConsts) {
6323       SDValue VecAsImm = DAG.getConstant(Immediate,
6324                                          MVT::getIntegerVT(VT.getSizeInBits()));
6325       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6326     }
6327     else 
6328       DstVec = DAG.getUNDEF(VT);
6329     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6330                        Op.getOperand(NonConstIdx),
6331                        DAG.getIntPtrConstant(NonConstIdx));
6332   }
6333   if (!IsSplat && (NonConstIdx != 0))
6334     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6335   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6336   SDValue Select;
6337   if (IsSplat)
6338     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6339                           DAG.getConstant(-1, SelectVT),
6340                           DAG.getConstant(0, SelectVT));
6341   else
6342     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6343                          DAG.getConstant((Immediate | 1), SelectVT),
6344                          DAG.getConstant(Immediate, SelectVT));
6345   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6346 }
6347
6348 /// \brief Return true if \p N implements a horizontal binop and return the
6349 /// operands for the horizontal binop into V0 and V1.
6350 /// 
6351 /// This is a helper function of PerformBUILD_VECTORCombine.
6352 /// This function checks that the build_vector \p N in input implements a
6353 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6354 /// operation to match.
6355 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6356 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6357 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6358 /// arithmetic sub.
6359 ///
6360 /// This function only analyzes elements of \p N whose indices are
6361 /// in range [BaseIdx, LastIdx).
6362 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6363                               SelectionDAG &DAG,
6364                               unsigned BaseIdx, unsigned LastIdx,
6365                               SDValue &V0, SDValue &V1) {
6366   EVT VT = N->getValueType(0);
6367
6368   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6369   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6370          "Invalid Vector in input!");
6371   
6372   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6373   bool CanFold = true;
6374   unsigned ExpectedVExtractIdx = BaseIdx;
6375   unsigned NumElts = LastIdx - BaseIdx;
6376   V0 = DAG.getUNDEF(VT);
6377   V1 = DAG.getUNDEF(VT);
6378
6379   // Check if N implements a horizontal binop.
6380   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6381     SDValue Op = N->getOperand(i + BaseIdx);
6382
6383     // Skip UNDEFs.
6384     if (Op->getOpcode() == ISD::UNDEF) {
6385       // Update the expected vector extract index.
6386       if (i * 2 == NumElts)
6387         ExpectedVExtractIdx = BaseIdx;
6388       ExpectedVExtractIdx += 2;
6389       continue;
6390     }
6391
6392     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6393
6394     if (!CanFold)
6395       break;
6396
6397     SDValue Op0 = Op.getOperand(0);
6398     SDValue Op1 = Op.getOperand(1);
6399
6400     // Try to match the following pattern:
6401     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6402     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6403         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6404         Op0.getOperand(0) == Op1.getOperand(0) &&
6405         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6406         isa<ConstantSDNode>(Op1.getOperand(1)));
6407     if (!CanFold)
6408       break;
6409
6410     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6411     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6412
6413     if (i * 2 < NumElts) {
6414       if (V0.getOpcode() == ISD::UNDEF)
6415         V0 = Op0.getOperand(0);
6416     } else {
6417       if (V1.getOpcode() == ISD::UNDEF)
6418         V1 = Op0.getOperand(0);
6419       if (i * 2 == NumElts)
6420         ExpectedVExtractIdx = BaseIdx;
6421     }
6422
6423     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6424     if (I0 == ExpectedVExtractIdx)
6425       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6426     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6427       // Try to match the following dag sequence:
6428       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6429       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6430     } else
6431       CanFold = false;
6432
6433     ExpectedVExtractIdx += 2;
6434   }
6435
6436   return CanFold;
6437 }
6438
6439 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6440 /// a concat_vector. 
6441 ///
6442 /// This is a helper function of PerformBUILD_VECTORCombine.
6443 /// This function expects two 256-bit vectors called V0 and V1.
6444 /// At first, each vector is split into two separate 128-bit vectors.
6445 /// Then, the resulting 128-bit vectors are used to implement two
6446 /// horizontal binary operations. 
6447 ///
6448 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6449 ///
6450 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6451 /// the two new horizontal binop.
6452 /// When Mode is set, the first horizontal binop dag node would take as input
6453 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6454 /// horizontal binop dag node would take as input the lower 128-bit of V1
6455 /// and the upper 128-bit of V1.
6456 ///   Example:
6457 ///     HADD V0_LO, V0_HI
6458 ///     HADD V1_LO, V1_HI
6459 ///
6460 /// Otherwise, the first horizontal binop dag node takes as input the lower
6461 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6462 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6463 ///   Example:
6464 ///     HADD V0_LO, V1_LO
6465 ///     HADD V0_HI, V1_HI
6466 ///
6467 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6468 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6469 /// the upper 128-bits of the result.
6470 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6471                                      SDLoc DL, SelectionDAG &DAG,
6472                                      unsigned X86Opcode, bool Mode,
6473                                      bool isUndefLO, bool isUndefHI) {
6474   EVT VT = V0.getValueType();
6475   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6476          "Invalid nodes in input!");
6477
6478   unsigned NumElts = VT.getVectorNumElements();
6479   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6480   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6481   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6482   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6483   EVT NewVT = V0_LO.getValueType();
6484
6485   SDValue LO = DAG.getUNDEF(NewVT);
6486   SDValue HI = DAG.getUNDEF(NewVT);
6487
6488   if (Mode) {
6489     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6490     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6491       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6492     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6493       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6494   } else {
6495     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6496     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6497                        V1_LO->getOpcode() != ISD::UNDEF))
6498       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6499
6500     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6501                        V1_HI->getOpcode() != ISD::UNDEF))
6502       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6503   }
6504
6505   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6506 }
6507
6508 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6509 /// sequence of 'vadd + vsub + blendi'.
6510 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6511                            const X86Subtarget *Subtarget) {
6512   SDLoc DL(BV);
6513   EVT VT = BV->getValueType(0);
6514   unsigned NumElts = VT.getVectorNumElements();
6515   SDValue InVec0 = DAG.getUNDEF(VT);
6516   SDValue InVec1 = DAG.getUNDEF(VT);
6517
6518   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6519           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6520
6521   // Odd-numbered elements in the input build vector are obtained from
6522   // adding two integer/float elements.
6523   // Even-numbered elements in the input build vector are obtained from
6524   // subtracting two integer/float elements.
6525   unsigned ExpectedOpcode = ISD::FSUB;
6526   unsigned NextExpectedOpcode = ISD::FADD;
6527   bool AddFound = false;
6528   bool SubFound = false;
6529
6530   for (unsigned i = 0, e = NumElts; i != e; i++) {
6531     SDValue Op = BV->getOperand(i);
6532
6533     // Skip 'undef' values.
6534     unsigned Opcode = Op.getOpcode();
6535     if (Opcode == ISD::UNDEF) {
6536       std::swap(ExpectedOpcode, NextExpectedOpcode);
6537       continue;
6538     }
6539
6540     // Early exit if we found an unexpected opcode.
6541     if (Opcode != ExpectedOpcode)
6542       return SDValue();
6543
6544     SDValue Op0 = Op.getOperand(0);
6545     SDValue Op1 = Op.getOperand(1);
6546
6547     // Try to match the following pattern:
6548     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6549     // Early exit if we cannot match that sequence.
6550     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6551         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6552         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6553         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6554         Op0.getOperand(1) != Op1.getOperand(1))
6555       return SDValue();
6556
6557     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6558     if (I0 != i)
6559       return SDValue();
6560
6561     // We found a valid add/sub node. Update the information accordingly.
6562     if (i & 1)
6563       AddFound = true;
6564     else
6565       SubFound = true;
6566
6567     // Update InVec0 and InVec1.
6568     if (InVec0.getOpcode() == ISD::UNDEF)
6569       InVec0 = Op0.getOperand(0);
6570     if (InVec1.getOpcode() == ISD::UNDEF)
6571       InVec1 = Op1.getOperand(0);
6572
6573     // Make sure that operands in input to each add/sub node always
6574     // come from a same pair of vectors.
6575     if (InVec0 != Op0.getOperand(0)) {
6576       if (ExpectedOpcode == ISD::FSUB)
6577         return SDValue();
6578
6579       // FADD is commutable. Try to commute the operands
6580       // and then test again.
6581       std::swap(Op0, Op1);
6582       if (InVec0 != Op0.getOperand(0))
6583         return SDValue();
6584     }
6585
6586     if (InVec1 != Op1.getOperand(0))
6587       return SDValue();
6588
6589     // Update the pair of expected opcodes.
6590     std::swap(ExpectedOpcode, NextExpectedOpcode);
6591   }
6592
6593   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
6594   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6595       InVec1.getOpcode() != ISD::UNDEF)
6596     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
6597
6598   return SDValue();
6599 }
6600
6601 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6602                                           const X86Subtarget *Subtarget) {
6603   SDLoc DL(N);
6604   EVT VT = N->getValueType(0);
6605   unsigned NumElts = VT.getVectorNumElements();
6606   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6607   SDValue InVec0, InVec1;
6608
6609   // Try to match an ADDSUB.
6610   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6611       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6612     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6613     if (Value.getNode())
6614       return Value;
6615   }
6616
6617   // Try to match horizontal ADD/SUB.
6618   unsigned NumUndefsLO = 0;
6619   unsigned NumUndefsHI = 0;
6620   unsigned Half = NumElts/2;
6621
6622   // Count the number of UNDEF operands in the build_vector in input.
6623   for (unsigned i = 0, e = Half; i != e; ++i)
6624     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6625       NumUndefsLO++;
6626
6627   for (unsigned i = Half, e = NumElts; i != e; ++i)
6628     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6629       NumUndefsHI++;
6630
6631   // Early exit if this is either a build_vector of all UNDEFs or all the
6632   // operands but one are UNDEF.
6633   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6634     return SDValue();
6635
6636   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6637     // Try to match an SSE3 float HADD/HSUB.
6638     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6639       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6640     
6641     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6642       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6643   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6644     // Try to match an SSSE3 integer HADD/HSUB.
6645     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6646       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6647     
6648     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6649       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6650   }
6651   
6652   if (!Subtarget->hasAVX())
6653     return SDValue();
6654
6655   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6656     // Try to match an AVX horizontal add/sub of packed single/double
6657     // precision floating point values from 256-bit vectors.
6658     SDValue InVec2, InVec3;
6659     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6660         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6661         ((InVec0.getOpcode() == ISD::UNDEF ||
6662           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6663         ((InVec1.getOpcode() == ISD::UNDEF ||
6664           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6665       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6666
6667     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6668         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6669         ((InVec0.getOpcode() == ISD::UNDEF ||
6670           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6671         ((InVec1.getOpcode() == ISD::UNDEF ||
6672           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6673       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6674   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6675     // Try to match an AVX2 horizontal add/sub of signed integers.
6676     SDValue InVec2, InVec3;
6677     unsigned X86Opcode;
6678     bool CanFold = true;
6679
6680     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6681         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6682         ((InVec0.getOpcode() == ISD::UNDEF ||
6683           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6684         ((InVec1.getOpcode() == ISD::UNDEF ||
6685           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6686       X86Opcode = X86ISD::HADD;
6687     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6688         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6689         ((InVec0.getOpcode() == ISD::UNDEF ||
6690           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6691         ((InVec1.getOpcode() == ISD::UNDEF ||
6692           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6693       X86Opcode = X86ISD::HSUB;
6694     else
6695       CanFold = false;
6696
6697     if (CanFold) {
6698       // Fold this build_vector into a single horizontal add/sub.
6699       // Do this only if the target has AVX2.
6700       if (Subtarget->hasAVX2())
6701         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6702  
6703       // Do not try to expand this build_vector into a pair of horizontal
6704       // add/sub if we can emit a pair of scalar add/sub.
6705       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6706         return SDValue();
6707
6708       // Convert this build_vector into a pair of horizontal binop followed by
6709       // a concat vector.
6710       bool isUndefLO = NumUndefsLO == Half;
6711       bool isUndefHI = NumUndefsHI == Half;
6712       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6713                                    isUndefLO, isUndefHI);
6714     }
6715   }
6716
6717   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6718        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6719     unsigned X86Opcode;
6720     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6721       X86Opcode = X86ISD::HADD;
6722     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6723       X86Opcode = X86ISD::HSUB;
6724     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6725       X86Opcode = X86ISD::FHADD;
6726     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6727       X86Opcode = X86ISD::FHSUB;
6728     else
6729       return SDValue();
6730
6731     // Don't try to expand this build_vector into a pair of horizontal add/sub
6732     // if we can simply emit a pair of scalar add/sub.
6733     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6734       return SDValue();
6735
6736     // Convert this build_vector into two horizontal add/sub followed by
6737     // a concat vector.
6738     bool isUndefLO = NumUndefsLO == Half;
6739     bool isUndefHI = NumUndefsHI == Half;
6740     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6741                                  isUndefLO, isUndefHI);
6742   }
6743
6744   return SDValue();
6745 }
6746
6747 SDValue
6748 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6749   SDLoc dl(Op);
6750
6751   MVT VT = Op.getSimpleValueType();
6752   MVT ExtVT = VT.getVectorElementType();
6753   unsigned NumElems = Op.getNumOperands();
6754
6755   // Generate vectors for predicate vectors.
6756   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6757     return LowerBUILD_VECTORvXi1(Op, DAG);
6758
6759   // Vectors containing all zeros can be matched by pxor and xorps later
6760   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6761     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6762     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6763     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6764       return Op;
6765
6766     return getZeroVector(VT, Subtarget, DAG, dl);
6767   }
6768
6769   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6770   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6771   // vpcmpeqd on 256-bit vectors.
6772   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6773     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6774       return Op;
6775
6776     if (!VT.is512BitVector())
6777       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6778   }
6779
6780   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6781   if (Broadcast.getNode())
6782     return Broadcast;
6783
6784   unsigned EVTBits = ExtVT.getSizeInBits();
6785
6786   unsigned NumZero  = 0;
6787   unsigned NumNonZero = 0;
6788   unsigned NonZeros = 0;
6789   bool IsAllConstants = true;
6790   SmallSet<SDValue, 8> Values;
6791   for (unsigned i = 0; i < NumElems; ++i) {
6792     SDValue Elt = Op.getOperand(i);
6793     if (Elt.getOpcode() == ISD::UNDEF)
6794       continue;
6795     Values.insert(Elt);
6796     if (Elt.getOpcode() != ISD::Constant &&
6797         Elt.getOpcode() != ISD::ConstantFP)
6798       IsAllConstants = false;
6799     if (X86::isZeroNode(Elt))
6800       NumZero++;
6801     else {
6802       NonZeros |= (1 << i);
6803       NumNonZero++;
6804     }
6805   }
6806
6807   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6808   if (NumNonZero == 0)
6809     return DAG.getUNDEF(VT);
6810
6811   // Special case for single non-zero, non-undef, element.
6812   if (NumNonZero == 1) {
6813     unsigned Idx = countTrailingZeros(NonZeros);
6814     SDValue Item = Op.getOperand(Idx);
6815
6816     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6817     // the value are obviously zero, truncate the value to i32 and do the
6818     // insertion that way.  Only do this if the value is non-constant or if the
6819     // value is a constant being inserted into element 0.  It is cheaper to do
6820     // a constant pool load than it is to do a movd + shuffle.
6821     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6822         (!IsAllConstants || Idx == 0)) {
6823       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6824         // Handle SSE only.
6825         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6826         EVT VecVT = MVT::v4i32;
6827         unsigned VecElts = 4;
6828
6829         // Truncate the value (which may itself be a constant) to i32, and
6830         // convert it to a vector with movd (S2V+shuffle to zero extend).
6831         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6832         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6833
6834         // If using the new shuffle lowering, just directly insert this.
6835         if (ExperimentalVectorShuffleLowering)
6836           return DAG.getNode(
6837               ISD::BITCAST, dl, VT,
6838               getShuffleVectorZeroOrUndef(Item, Idx * 2, true, Subtarget, DAG));
6839
6840         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6841
6842         // Now we have our 32-bit value zero extended in the low element of
6843         // a vector.  If Idx != 0, swizzle it into place.
6844         if (Idx != 0) {
6845           SmallVector<int, 4> Mask;
6846           Mask.push_back(Idx);
6847           for (unsigned i = 1; i != VecElts; ++i)
6848             Mask.push_back(i);
6849           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6850                                       &Mask[0]);
6851         }
6852         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6853       }
6854     }
6855
6856     // If we have a constant or non-constant insertion into the low element of
6857     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6858     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6859     // depending on what the source datatype is.
6860     if (Idx == 0) {
6861       if (NumZero == 0)
6862         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6863
6864       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6865           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6866         if (VT.is256BitVector() || VT.is512BitVector()) {
6867           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6868           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6869                              Item, DAG.getIntPtrConstant(0));
6870         }
6871         assert(VT.is128BitVector() && "Expected an SSE value type!");
6872         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6873         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6874         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6875       }
6876
6877       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6878         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6879         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6880         if (VT.is256BitVector()) {
6881           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6882           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6883         } else {
6884           assert(VT.is128BitVector() && "Expected an SSE value type!");
6885           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6886         }
6887         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6888       }
6889     }
6890
6891     // Is it a vector logical left shift?
6892     if (NumElems == 2 && Idx == 1 &&
6893         X86::isZeroNode(Op.getOperand(0)) &&
6894         !X86::isZeroNode(Op.getOperand(1))) {
6895       unsigned NumBits = VT.getSizeInBits();
6896       return getVShift(true, VT,
6897                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6898                                    VT, Op.getOperand(1)),
6899                        NumBits/2, DAG, *this, dl);
6900     }
6901
6902     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6903       return SDValue();
6904
6905     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6906     // is a non-constant being inserted into an element other than the low one,
6907     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6908     // movd/movss) to move this into the low element, then shuffle it into
6909     // place.
6910     if (EVTBits == 32) {
6911       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6912
6913       // If using the new shuffle lowering, just directly insert this.
6914       if (ExperimentalVectorShuffleLowering)
6915         return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6916
6917       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6918       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6919       SmallVector<int, 8> MaskVec;
6920       for (unsigned i = 0; i != NumElems; ++i)
6921         MaskVec.push_back(i == Idx ? 0 : 1);
6922       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6923     }
6924   }
6925
6926   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6927   if (Values.size() == 1) {
6928     if (EVTBits == 32) {
6929       // Instead of a shuffle like this:
6930       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6931       // Check if it's possible to issue this instead.
6932       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6933       unsigned Idx = countTrailingZeros(NonZeros);
6934       SDValue Item = Op.getOperand(Idx);
6935       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6936         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6937     }
6938     return SDValue();
6939   }
6940
6941   // A vector full of immediates; various special cases are already
6942   // handled, so this is best done with a single constant-pool load.
6943   if (IsAllConstants)
6944     return SDValue();
6945
6946   // For AVX-length vectors, build the individual 128-bit pieces and use
6947   // shuffles to put them in place.
6948   if (VT.is256BitVector() || VT.is512BitVector()) {
6949     SmallVector<SDValue, 64> V;
6950     for (unsigned i = 0; i != NumElems; ++i)
6951       V.push_back(Op.getOperand(i));
6952
6953     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6954
6955     // Build both the lower and upper subvector.
6956     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6957                                 makeArrayRef(&V[0], NumElems/2));
6958     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6959                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6960
6961     // Recreate the wider vector with the lower and upper part.
6962     if (VT.is256BitVector())
6963       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6964     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6965   }
6966
6967   // Let legalizer expand 2-wide build_vectors.
6968   if (EVTBits == 64) {
6969     if (NumNonZero == 1) {
6970       // One half is zero or undef.
6971       unsigned Idx = countTrailingZeros(NonZeros);
6972       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6973                                  Op.getOperand(Idx));
6974       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6975     }
6976     return SDValue();
6977   }
6978
6979   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6980   if (EVTBits == 8 && NumElems == 16) {
6981     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6982                                         Subtarget, *this);
6983     if (V.getNode()) return V;
6984   }
6985
6986   if (EVTBits == 16 && NumElems == 8) {
6987     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6988                                       Subtarget, *this);
6989     if (V.getNode()) return V;
6990   }
6991
6992   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6993   if (EVTBits == 32 && NumElems == 4) {
6994     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6995                                       NumZero, DAG, Subtarget, *this);
6996     if (V.getNode())
6997       return V;
6998   }
6999
7000   // If element VT is == 32 bits, turn it into a number of shuffles.
7001   SmallVector<SDValue, 8> V(NumElems);
7002   if (NumElems == 4 && NumZero > 0) {
7003     for (unsigned i = 0; i < 4; ++i) {
7004       bool isZero = !(NonZeros & (1 << i));
7005       if (isZero)
7006         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
7007       else
7008         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7009     }
7010
7011     for (unsigned i = 0; i < 2; ++i) {
7012       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
7013         default: break;
7014         case 0:
7015           V[i] = V[i*2];  // Must be a zero vector.
7016           break;
7017         case 1:
7018           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
7019           break;
7020         case 2:
7021           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
7022           break;
7023         case 3:
7024           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
7025           break;
7026       }
7027     }
7028
7029     bool Reverse1 = (NonZeros & 0x3) == 2;
7030     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
7031     int MaskVec[] = {
7032       Reverse1 ? 1 : 0,
7033       Reverse1 ? 0 : 1,
7034       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
7035       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
7036     };
7037     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
7038   }
7039
7040   if (Values.size() > 1 && VT.is128BitVector()) {
7041     // Check for a build vector of consecutive loads.
7042     for (unsigned i = 0; i < NumElems; ++i)
7043       V[i] = Op.getOperand(i);
7044
7045     // Check for elements which are consecutive loads.
7046     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
7047     if (LD.getNode())
7048       return LD;
7049
7050     // Check for a build vector from mostly shuffle plus few inserting.
7051     SDValue Sh = buildFromShuffleMostly(Op, DAG);
7052     if (Sh.getNode())
7053       return Sh;
7054
7055     // For SSE 4.1, use insertps to put the high elements into the low element.
7056     if (getSubtarget()->hasSSE41()) {
7057       SDValue Result;
7058       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
7059         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
7060       else
7061         Result = DAG.getUNDEF(VT);
7062
7063       for (unsigned i = 1; i < NumElems; ++i) {
7064         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
7065         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
7066                              Op.getOperand(i), DAG.getIntPtrConstant(i));
7067       }
7068       return Result;
7069     }
7070
7071     // Otherwise, expand into a number of unpckl*, start by extending each of
7072     // our (non-undef) elements to the full vector width with the element in the
7073     // bottom slot of the vector (which generates no code for SSE).
7074     for (unsigned i = 0; i < NumElems; ++i) {
7075       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
7076         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
7077       else
7078         V[i] = DAG.getUNDEF(VT);
7079     }
7080
7081     // Next, we iteratively mix elements, e.g. for v4f32:
7082     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
7083     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
7084     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
7085     unsigned EltStride = NumElems >> 1;
7086     while (EltStride != 0) {
7087       for (unsigned i = 0; i < EltStride; ++i) {
7088         // If V[i+EltStride] is undef and this is the first round of mixing,
7089         // then it is safe to just drop this shuffle: V[i] is already in the
7090         // right place, the one element (since it's the first round) being
7091         // inserted as undef can be dropped.  This isn't safe for successive
7092         // rounds because they will permute elements within both vectors.
7093         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
7094             EltStride == NumElems/2)
7095           continue;
7096
7097         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
7098       }
7099       EltStride >>= 1;
7100     }
7101     return V[0];
7102   }
7103   return SDValue();
7104 }
7105
7106 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
7107 // to create 256-bit vectors from two other 128-bit ones.
7108 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7109   SDLoc dl(Op);
7110   MVT ResVT = Op.getSimpleValueType();
7111
7112   assert((ResVT.is256BitVector() ||
7113           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
7114
7115   SDValue V1 = Op.getOperand(0);
7116   SDValue V2 = Op.getOperand(1);
7117   unsigned NumElems = ResVT.getVectorNumElements();
7118   if(ResVT.is256BitVector())
7119     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7120
7121   if (Op.getNumOperands() == 4) {
7122     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
7123                                 ResVT.getVectorNumElements()/2);
7124     SDValue V3 = Op.getOperand(2);
7125     SDValue V4 = Op.getOperand(3);
7126     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
7127       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
7128   }
7129   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
7130 }
7131
7132 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
7133   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
7134   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
7135          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
7136           Op.getNumOperands() == 4)));
7137
7138   // AVX can use the vinsertf128 instruction to create 256-bit vectors
7139   // from two other 128-bit ones.
7140
7141   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
7142   return LowerAVXCONCAT_VECTORS(Op, DAG);
7143 }
7144
7145
7146 //===----------------------------------------------------------------------===//
7147 // Vector shuffle lowering
7148 //
7149 // This is an experimental code path for lowering vector shuffles on x86. It is
7150 // designed to handle arbitrary vector shuffles and blends, gracefully
7151 // degrading performance as necessary. It works hard to recognize idiomatic
7152 // shuffles and lower them to optimal instruction patterns without leaving
7153 // a framework that allows reasonably efficient handling of all vector shuffle
7154 // patterns.
7155 //===----------------------------------------------------------------------===//
7156
7157 /// \brief Tiny helper function to identify a no-op mask.
7158 ///
7159 /// This is a somewhat boring predicate function. It checks whether the mask
7160 /// array input, which is assumed to be a single-input shuffle mask of the kind
7161 /// used by the X86 shuffle instructions (not a fully general
7162 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7163 /// in-place shuffle are 'no-op's.
7164 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7165   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7166     if (Mask[i] != -1 && Mask[i] != i)
7167       return false;
7168   return true;
7169 }
7170
7171 /// \brief Helper function to classify a mask as a single-input mask.
7172 ///
7173 /// This isn't a generic single-input test because in the vector shuffle
7174 /// lowering we canonicalize single inputs to be the first input operand. This
7175 /// means we can more quickly test for a single input by only checking whether
7176 /// an input from the second operand exists. We also assume that the size of
7177 /// mask corresponds to the size of the input vectors which isn't true in the
7178 /// fully general case.
7179 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7180   for (int M : Mask)
7181     if (M >= (int)Mask.size())
7182       return false;
7183   return true;
7184 }
7185
7186 // Hide this symbol with an anonymous namespace instead of 'static' so that MSVC
7187 // 2013 will allow us to use it as a non-type template parameter.
7188 namespace {
7189
7190 /// \brief Implementation of the \c isShuffleEquivalent variadic functor.
7191 ///
7192 /// See its documentation for details.
7193 bool isShuffleEquivalentImpl(ArrayRef<int> Mask, ArrayRef<const int *> Args) {
7194   if (Mask.size() != Args.size())
7195     return false;
7196   for (int i = 0, e = Mask.size(); i < e; ++i) {
7197     assert(*Args[i] >= 0 && "Arguments must be positive integers!");
7198     if (Mask[i] != -1 && Mask[i] != *Args[i])
7199       return false;
7200   }
7201   return true;
7202 }
7203
7204 } // namespace
7205
7206 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
7207 /// arguments.
7208 ///
7209 /// This is a fast way to test a shuffle mask against a fixed pattern:
7210 ///
7211 ///   if (isShuffleEquivalent(Mask, 3, 2, 1, 0)) { ... }
7212 ///
7213 /// It returns true if the mask is exactly as wide as the argument list, and
7214 /// each element of the mask is either -1 (signifying undef) or the value given
7215 /// in the argument.
7216 static const VariadicFunction1<
7217     bool, ArrayRef<int>, int, isShuffleEquivalentImpl> isShuffleEquivalent = {};
7218
7219 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7220 ///
7221 /// This helper function produces an 8-bit shuffle immediate corresponding to
7222 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7223 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7224 /// example.
7225 ///
7226 /// NB: We rely heavily on "undef" masks preserving the input lane.
7227 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7228                                           SelectionDAG &DAG) {
7229   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7230   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7231   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7232   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7233   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7234
7235   unsigned Imm = 0;
7236   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7237   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7238   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7239   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7240   return DAG.getConstant(Imm, MVT::i8);
7241 }
7242
7243 /// \brief Try to emit a blend instruction for a shuffle.
7244 ///
7245 /// This doesn't do any checks for the availability of instructions for blending
7246 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
7247 /// be matched in the backend with the type given. What it does check for is
7248 /// that the shuffle mask is in fact a blend.
7249 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
7250                                          SDValue V2, ArrayRef<int> Mask,
7251                                          const X86Subtarget *Subtarget,
7252                                          SelectionDAG &DAG) {
7253
7254   unsigned BlendMask = 0;
7255   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7256     if (Mask[i] >= Size) {
7257       if (Mask[i] != i + Size)
7258         return SDValue(); // Shuffled V2 input!
7259       BlendMask |= 1u << i;
7260       continue;
7261     }
7262     if (Mask[i] >= 0 && Mask[i] != i)
7263       return SDValue(); // Shuffled V1 input!
7264   }
7265   switch (VT.SimpleTy) {
7266   case MVT::v2f64:
7267   case MVT::v4f32:
7268   case MVT::v4f64:
7269   case MVT::v8f32:
7270     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
7271                        DAG.getConstant(BlendMask, MVT::i8));
7272
7273   case MVT::v4i64:
7274   case MVT::v8i32:
7275     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
7276     // FALLTHROUGH
7277   case MVT::v2i64:
7278   case MVT::v4i32:
7279     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
7280     // that instruction.
7281     if (Subtarget->hasAVX2()) {
7282       // Scale the blend by the number of 32-bit dwords per element.
7283       int Scale =  VT.getScalarSizeInBits() / 32;
7284       BlendMask = 0;
7285       for (int i = 0, Size = Mask.size(); i < Size; ++i)
7286         if (Mask[i] >= Size)
7287           for (int j = 0; j < Scale; ++j)
7288             BlendMask |= 1u << (i * Scale + j);
7289
7290       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
7291       V1 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V1);
7292       V2 = DAG.getNode(ISD::BITCAST, DL, BlendVT, V2);
7293       return DAG.getNode(ISD::BITCAST, DL, VT,
7294                          DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
7295                                      DAG.getConstant(BlendMask, MVT::i8)));
7296     }
7297     // FALLTHROUGH
7298   case MVT::v8i16: {
7299     // For integer shuffles we need to expand the mask and cast the inputs to
7300     // v8i16s prior to blending.
7301     int Scale = 8 / VT.getVectorNumElements();
7302     BlendMask = 0;
7303     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7304       if (Mask[i] >= Size)
7305         for (int j = 0; j < Scale; ++j)
7306           BlendMask |= 1u << (i * Scale + j);
7307
7308     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
7309     V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
7310     return DAG.getNode(ISD::BITCAST, DL, VT,
7311                        DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
7312                                    DAG.getConstant(BlendMask, MVT::i8)));
7313   }
7314
7315   default:
7316     llvm_unreachable("Not a supported integer vector type!");
7317   }
7318 }
7319
7320 /// \brief Try to lower a vector shuffle as a byte rotation.
7321 ///
7322 /// We have a generic PALIGNR instruction in x86 that will do an arbitrary
7323 /// byte-rotation of a the concatentation of two vectors. This routine will
7324 /// try to generically lower a vector shuffle through such an instruction. It
7325 /// does not check for the availability of PALIGNR-based lowerings, only the
7326 /// applicability of this strategy to the given mask. This matches shuffle
7327 /// vectors that look like:
7328 /// 
7329 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
7330 /// 
7331 /// Essentially it concatenates V1 and V2, shifts right by some number of
7332 /// elements, and takes the low elements as the result. Note that while this is
7333 /// specified as a *right shift* because x86 is little-endian, it is a *left
7334 /// rotate* of the vector lanes.
7335 ///
7336 /// Note that this only handles 128-bit vector widths currently.
7337 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
7338                                               SDValue V2,
7339                                               ArrayRef<int> Mask,
7340                                               SelectionDAG &DAG) {
7341   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
7342
7343   // We need to detect various ways of spelling a rotation:
7344   //   [11, 12, 13, 14, 15,  0,  1,  2]
7345   //   [-1, 12, 13, 14, -1, -1,  1, -1]
7346   //   [-1, -1, -1, -1, -1, -1,  1,  2]
7347   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
7348   //   [-1,  4,  5,  6, -1, -1,  9, -1]
7349   //   [-1,  4,  5,  6, -1, -1, -1, -1]
7350   int Rotation = 0;
7351   SDValue Lo, Hi;
7352   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7353     if (Mask[i] == -1)
7354       continue;
7355     assert(Mask[i] >= 0 && "Only -1 is a valid negative mask element!");
7356
7357     // Based on the mod-Size value of this mask element determine where
7358     // a rotated vector would have started.
7359     int StartIdx = i - (Mask[i] % Size);
7360     if (StartIdx == 0)
7361       // The identity rotation isn't interesting, stop.
7362       return SDValue();
7363
7364     // If we found the tail of a vector the rotation must be the missing
7365     // front. If we found the head of a vector, it must be how much of the head.
7366     int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
7367
7368     if (Rotation == 0)
7369       Rotation = CandidateRotation;
7370     else if (Rotation != CandidateRotation)
7371       // The rotations don't match, so we can't match this mask.
7372       return SDValue();
7373
7374     // Compute which value this mask is pointing at.
7375     SDValue MaskV = Mask[i] < Size ? V1 : V2;
7376
7377     // Compute which of the two target values this index should be assigned to.
7378     // This reflects whether the high elements are remaining or the low elements
7379     // are remaining.
7380     SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
7381
7382     // Either set up this value if we've not encountered it before, or check
7383     // that it remains consistent.
7384     if (!TargetV)
7385       TargetV = MaskV;
7386     else if (TargetV != MaskV)
7387       // This may be a rotation, but it pulls from the inputs in some
7388       // unsupported interleaving.
7389       return SDValue();
7390   }
7391
7392   // Check that we successfully analyzed the mask, and normalize the results.
7393   assert(Rotation != 0 && "Failed to locate a viable rotation!");
7394   assert((Lo || Hi) && "Failed to find a rotated input vector!");
7395   if (!Lo)
7396     Lo = Hi;
7397   else if (!Hi)
7398     Hi = Lo;
7399
7400   // Cast the inputs to v16i8 to match PALIGNR.
7401   Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Lo);
7402   Hi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Hi);
7403
7404   assert(VT.getSizeInBits() == 128 &&
7405          "Rotate-based lowering only supports 128-bit lowering!");
7406   assert(Mask.size() <= 16 &&
7407          "Can shuffle at most 16 bytes in a 128-bit vector!");
7408   // The actual rotate instruction rotates bytes, so we need to scale the
7409   // rotation based on how many bytes are in the vector.
7410   int Scale = 16 / Mask.size();
7411
7412   return DAG.getNode(ISD::BITCAST, DL, VT,
7413                      DAG.getNode(X86ISD::PALIGNR, DL, MVT::v16i8, Hi, Lo,
7414                                  DAG.getConstant(Rotation * Scale, MVT::i8)));
7415 }
7416
7417 /// \brief Compute whether each element of a shuffle is zeroable.
7418 ///
7419 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
7420 /// Either it is an undef element in the shuffle mask, the element of the input
7421 /// referenced is undef, or the element of the input referenced is known to be
7422 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
7423 /// as many lanes with this technique as possible to simplify the remaining
7424 /// shuffle.
7425 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
7426                                                      SDValue V1, SDValue V2) {
7427   SmallBitVector Zeroable(Mask.size(), false);
7428
7429   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
7430   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
7431
7432   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7433     int M = Mask[i];
7434     // Handle the easy cases.
7435     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
7436       Zeroable[i] = true;
7437       continue;
7438     }
7439
7440     // If this is an index into a build_vector node, dig out the input value and
7441     // use it.
7442     SDValue V = M < Size ? V1 : V2;
7443     if (V.getOpcode() != ISD::BUILD_VECTOR)
7444       continue;
7445
7446     SDValue Input = V.getOperand(M % Size);
7447     // The UNDEF opcode check really should be dead code here, but not quite
7448     // worth asserting on (it isn't invalid, just unexpected).
7449     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
7450       Zeroable[i] = true;
7451   }
7452
7453   return Zeroable;
7454 }
7455
7456 /// \brief Lower a vector shuffle as a zero or any extension.
7457 ///
7458 /// Given a specific number of elements, element bit width, and extension
7459 /// stride, produce either a zero or any extension based on the available
7460 /// features of the subtarget.
7461 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7462     SDLoc DL, MVT VT, int NumElements, int Scale, bool AnyExt, SDValue InputV,
7463     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7464   assert(Scale > 1 && "Need a scale to extend.");
7465   int EltBits = VT.getSizeInBits() / NumElements;
7466   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7467          "Only 8, 16, and 32 bit elements can be extended.");
7468   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7469
7470   // Found a valid zext mask! Try various lowering strategies based on the
7471   // input type and available ISA extensions.
7472   if (Subtarget->hasSSE41()) {
7473     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7474     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7475                                  NumElements / Scale);
7476     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7477     return DAG.getNode(ISD::BITCAST, DL, VT,
7478                        DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7479   }
7480
7481   // For any extends we can cheat for larger element sizes and use shuffle
7482   // instructions that can fold with a load and/or copy.
7483   if (AnyExt && EltBits == 32) {
7484     int PSHUFDMask[4] = {0, -1, 1, -1};
7485     return DAG.getNode(
7486         ISD::BITCAST, DL, VT,
7487         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7488                     DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7489                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7490   }
7491   if (AnyExt && EltBits == 16 && Scale > 2) {
7492     int PSHUFDMask[4] = {0, -1, 0, -1};
7493     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7494                          DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, InputV),
7495                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG));
7496     int PSHUFHWMask[4] = {1, -1, -1, -1};
7497     return DAG.getNode(
7498         ISD::BITCAST, DL, VT,
7499         DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7500                     DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, InputV),
7501                     getV4X86ShuffleImm8ForMask(PSHUFHWMask, DAG)));
7502   }
7503
7504   // If this would require more than 2 unpack instructions to expand, use
7505   // pshufb when available. We can only use more than 2 unpack instructions
7506   // when zero extending i8 elements which also makes it easier to use pshufb.
7507   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7508     assert(NumElements == 16 && "Unexpected byte vector width!");
7509     SDValue PSHUFBMask[16];
7510     for (int i = 0; i < 16; ++i)
7511       PSHUFBMask[i] =
7512           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, MVT::i8);
7513     InputV = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, InputV);
7514     return DAG.getNode(ISD::BITCAST, DL, VT,
7515                        DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7516                                    DAG.getNode(ISD::BUILD_VECTOR, DL,
7517                                                MVT::v16i8, PSHUFBMask)));
7518   }
7519
7520   // Otherwise emit a sequence of unpacks.
7521   do {
7522     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7523     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7524                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7525     InputV = DAG.getNode(ISD::BITCAST, DL, InputVT, InputV);
7526     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7527     Scale /= 2;
7528     EltBits *= 2;
7529     NumElements /= 2;
7530   } while (Scale > 1);
7531   return DAG.getNode(ISD::BITCAST, DL, VT, InputV);
7532 }
7533
7534 /// \brief Try to lower a vector shuffle as a zero extension on any micrarch.
7535 ///
7536 /// This routine will try to do everything in its power to cleverly lower
7537 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7538 /// check for the profitability of this lowering,  it tries to aggressively
7539 /// match this pattern. It will use all of the micro-architectural details it
7540 /// can to emit an efficient lowering. It handles both blends with all-zero
7541 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7542 /// masking out later).
7543 ///
7544 /// The reason we have dedicated lowering for zext-style shuffles is that they
7545 /// are both incredibly common and often quite performance sensitive.
7546 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7547     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7548     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7549   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7550
7551   int Bits = VT.getSizeInBits();
7552   int NumElements = Mask.size();
7553
7554   // Define a helper function to check a particular ext-scale and lower to it if
7555   // valid.
7556   auto Lower = [&](int Scale) -> SDValue {
7557     SDValue InputV;
7558     bool AnyExt = true;
7559     for (int i = 0; i < NumElements; ++i) {
7560       if (Mask[i] == -1)
7561         continue; // Valid anywhere but doesn't tell us anything.
7562       if (i % Scale != 0) {
7563         // Each of the extend elements needs to be zeroable.
7564         if (!Zeroable[i])
7565           return SDValue();
7566
7567         // We no lorger are in the anyext case.
7568         AnyExt = false;
7569         continue;
7570       }
7571
7572       // Each of the base elements needs to be consecutive indices into the
7573       // same input vector.
7574       SDValue V = Mask[i] < NumElements ? V1 : V2;
7575       if (!InputV)
7576         InputV = V;
7577       else if (InputV != V)
7578         return SDValue(); // Flip-flopping inputs.
7579
7580       if (Mask[i] % NumElements != i / Scale)
7581         return SDValue(); // Non-consecutive strided elemenst.
7582     }
7583
7584     // If we fail to find an input, we have a zero-shuffle which should always
7585     // have already been handled.
7586     // FIXME: Maybe handle this here in case during blending we end up with one?
7587     if (!InputV)
7588       return SDValue();
7589
7590     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7591         DL, VT, NumElements, Scale, AnyExt, InputV, Subtarget, DAG);
7592   };
7593
7594   // The widest scale possible for extending is to a 64-bit integer.
7595   assert(Bits % 64 == 0 &&
7596          "The number of bits in a vector must be divisible by 64 on x86!");
7597   int NumExtElements = Bits / 64;
7598
7599   // Each iteration, try extending the elements half as much, but into twice as
7600   // many elements.
7601   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7602     assert(NumElements % NumExtElements == 0 &&
7603            "The input vector size must be divisble by the extended size.");
7604     if (SDValue V = Lower(NumElements / NumExtElements))
7605       return V;
7606   }
7607
7608   // No viable ext lowering found.
7609   return SDValue();
7610 }
7611
7612 /// \brief Try to lower insertion of a single element into a zero vector.
7613 ///
7614 /// This is a common pattern that we have especially efficient patterns to lower
7615 /// across all subtarget feature sets.
7616 static SDValue lowerVectorShuffleAsElementInsertion(
7617     MVT VT, SDLoc DL, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7618     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7619   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7620
7621   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7622                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7623                 Mask.begin();
7624   if (Mask.size() == 2) {
7625     if (!Zeroable[V2Index ^ 1]) {
7626       // For 2-wide masks we may be able to just invert the inputs. We use an xor
7627       // with 2 to flip from {2,3} to {0,1} and vice versa.
7628       int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7629                             Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7630       if (Zeroable[V2Index])
7631         return lowerVectorShuffleAsElementInsertion(VT, DL, V2, V1, InverseMask,
7632                                                     Subtarget, DAG);
7633       else
7634         return SDValue();
7635     }
7636   } else {
7637     for (int i = 0, Size = Mask.size(); i < Size; ++i)
7638       if (i != V2Index && !Zeroable[i])
7639         return SDValue(); // Not inserting into a zero vector.
7640   }
7641
7642   // Step over any bitcasts on either input so we can scan the actual
7643   // BUILD_VECTOR nodes.
7644   while (V1.getOpcode() == ISD::BITCAST)
7645     V1 = V1.getOperand(0);
7646   while (V2.getOpcode() == ISD::BITCAST)
7647     V2 = V2.getOperand(0);
7648
7649   // Check for a single input from a SCALAR_TO_VECTOR node.
7650   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7651   // all the smarts here sunk into that routine. However, the current
7652   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7653   // vector shuffle lowering is dead.
7654   if (!((V2.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7655          Mask[V2Index] == (int)Mask.size()) ||
7656         V2.getOpcode() == ISD::BUILD_VECTOR))
7657     return SDValue();
7658
7659   SDValue V2S = V2.getOperand(Mask[V2Index] - Mask.size());
7660
7661   // First, we need to zext the scalar if it is smaller than an i32.
7662   MVT ExtVT = VT;
7663   MVT EltVT = VT.getVectorElementType();
7664   V2S = DAG.getNode(ISD::BITCAST, DL, EltVT, V2S);
7665   if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7666     // Zero-extend directly to i32.
7667     ExtVT = MVT::v4i32;
7668     V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7669   }
7670
7671   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT,
7672                    DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S));
7673   if (ExtVT != VT)
7674     V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7675
7676   if (V2Index != 0) {
7677     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7678     // the desired position. Otherwise it is more efficient to do a vector
7679     // shift left. We know that we can do a vector shift left because all
7680     // the inputs are zero.
7681     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7682       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7683       V2Shuffle[V2Index] = 0;
7684       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7685     } else {
7686       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, V2);
7687       V2 = DAG.getNode(
7688           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7689           DAG.getConstant(
7690               V2Index * EltVT.getSizeInBits(),
7691               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7692       V2 = DAG.getNode(ISD::BITCAST, DL, VT, V2);
7693     }
7694   }
7695   return V2;
7696 }
7697
7698 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7699 ///
7700 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7701 /// support for floating point shuffles but not integer shuffles. These
7702 /// instructions will incur a domain crossing penalty on some chips though so
7703 /// it is better to avoid lowering through this for integer vectors where
7704 /// possible.
7705 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7706                                        const X86Subtarget *Subtarget,
7707                                        SelectionDAG &DAG) {
7708   SDLoc DL(Op);
7709   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7710   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7711   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7712   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7713   ArrayRef<int> Mask = SVOp->getMask();
7714   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7715
7716   if (isSingleInputShuffleMask(Mask)) {
7717     // Straight shuffle of a single input vector. Simulate this by using the
7718     // single input as both of the "inputs" to this instruction..
7719     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7720
7721     if (Subtarget->hasAVX()) {
7722       // If we have AVX, we can use VPERMILPS which will allow folding a load
7723       // into the shuffle.
7724       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7725                          DAG.getConstant(SHUFPDMask, MVT::i8));
7726     }
7727
7728     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7729                        DAG.getConstant(SHUFPDMask, MVT::i8));
7730   }
7731   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7732   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7733
7734   // Use dedicated unpack instructions for masks that match their pattern.
7735   if (isShuffleEquivalent(Mask, 0, 2))
7736     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7737   if (isShuffleEquivalent(Mask, 1, 3))
7738     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7739
7740   // If we have a single input, insert that into V1 if we can do so cheaply.
7741   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1)
7742     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7743             MVT::v2f64, DL, V1, V2, Mask, Subtarget, DAG))
7744       return Insertion;
7745
7746   if (Subtarget->hasSSE41())
7747     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7748                                                   Subtarget, DAG))
7749       return Blend;
7750
7751   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7752   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7753                      DAG.getConstant(SHUFPDMask, MVT::i8));
7754 }
7755
7756 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7757 ///
7758 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7759 /// the integer unit to minimize domain crossing penalties. However, for blends
7760 /// it falls back to the floating point shuffle operation with appropriate bit
7761 /// casting.
7762 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7763                                        const X86Subtarget *Subtarget,
7764                                        SelectionDAG &DAG) {
7765   SDLoc DL(Op);
7766   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7767   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7768   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7769   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7770   ArrayRef<int> Mask = SVOp->getMask();
7771   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7772
7773   if (isSingleInputShuffleMask(Mask)) {
7774     // Straight shuffle of a single input vector. For everything from SSE2
7775     // onward this has a single fast instruction with no scary immediates.
7776     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7777     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7778     int WidenedMask[4] = {
7779         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7780         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7781     return DAG.getNode(
7782         ISD::BITCAST, DL, MVT::v2i64,
7783         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7784                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7785   }
7786
7787   // Use dedicated unpack instructions for masks that match their pattern.
7788   if (isShuffleEquivalent(Mask, 0, 2))
7789     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7790   if (isShuffleEquivalent(Mask, 1, 3))
7791     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7792
7793   // If we have a single input from V2 insert that into V1 if we can do so
7794   // cheaply.
7795   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1)
7796     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7797             MVT::v2i64, DL, V1, V2, Mask, Subtarget, DAG))
7798       return Insertion;
7799
7800   if (Subtarget->hasSSE41())
7801     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7802                                                   Subtarget, DAG))
7803       return Blend;
7804
7805   // Try to use rotation instructions if available.
7806   if (Subtarget->hasSSSE3())
7807     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7808             DL, MVT::v2i64, V1, V2, Mask, DAG))
7809       return Rotate;
7810
7811   // We implement this with SHUFPD which is pretty lame because it will likely
7812   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7813   // However, all the alternatives are still more cycles and newer chips don't
7814   // have this problem. It would be really nice if x86 had better shuffles here.
7815   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7816   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7817   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7818                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7819 }
7820
7821 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7822 ///
7823 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7824 /// It makes no assumptions about whether this is the *best* lowering, it simply
7825 /// uses it.
7826 static SDValue lowerVectorShuffleWithSHUPFS(SDLoc DL, MVT VT,
7827                                             ArrayRef<int> Mask, SDValue V1,
7828                                             SDValue V2, SelectionDAG &DAG) {
7829   SDValue LowV = V1, HighV = V2;
7830   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7831
7832   int NumV2Elements =
7833       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7834
7835   if (NumV2Elements == 1) {
7836     int V2Index =
7837         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7838         Mask.begin();
7839
7840     // Compute the index adjacent to V2Index and in the same half by toggling
7841     // the low bit.
7842     int V2AdjIndex = V2Index ^ 1;
7843
7844     if (Mask[V2AdjIndex] == -1) {
7845       // Handles all the cases where we have a single V2 element and an undef.
7846       // This will only ever happen in the high lanes because we commute the
7847       // vector otherwise.
7848       if (V2Index < 2)
7849         std::swap(LowV, HighV);
7850       NewMask[V2Index] -= 4;
7851     } else {
7852       // Handle the case where the V2 element ends up adjacent to a V1 element.
7853       // To make this work, blend them together as the first step.
7854       int V1Index = V2AdjIndex;
7855       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7856       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7857                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7858
7859       // Now proceed to reconstruct the final blend as we have the necessary
7860       // high or low half formed.
7861       if (V2Index < 2) {
7862         LowV = V2;
7863         HighV = V1;
7864       } else {
7865         HighV = V2;
7866       }
7867       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7868       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7869     }
7870   } else if (NumV2Elements == 2) {
7871     if (Mask[0] < 4 && Mask[1] < 4) {
7872       // Handle the easy case where we have V1 in the low lanes and V2 in the
7873       // high lanes. We never see this reversed because we sort the shuffle.
7874       NewMask[2] -= 4;
7875       NewMask[3] -= 4;
7876     } else {
7877       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7878       // trying to place elements directly, just blend them and set up the final
7879       // shuffle to place them.
7880
7881       // The first two blend mask elements are for V1, the second two are for
7882       // V2.
7883       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7884                           Mask[2] < 4 ? Mask[2] : Mask[3],
7885                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7886                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7887       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7888                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7889
7890       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7891       // a blend.
7892       LowV = HighV = V1;
7893       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7894       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7895       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7896       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7897     }
7898   }
7899   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7900                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7901 }
7902
7903 /// \brief Lower 4-lane 32-bit floating point shuffles.
7904 ///
7905 /// Uses instructions exclusively from the floating point unit to minimize
7906 /// domain crossing penalties, as these are sufficient to implement all v4f32
7907 /// shuffles.
7908 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7909                                        const X86Subtarget *Subtarget,
7910                                        SelectionDAG &DAG) {
7911   SDLoc DL(Op);
7912   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7913   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7914   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7915   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7916   ArrayRef<int> Mask = SVOp->getMask();
7917   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7918
7919   int NumV2Elements =
7920       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7921
7922   if (NumV2Elements == 0) {
7923     if (Subtarget->hasAVX()) {
7924       // If we have AVX, we can use VPERMILPS which will allow folding a load
7925       // into the shuffle.
7926       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7927                          getV4X86ShuffleImm8ForMask(Mask, DAG));
7928     }
7929
7930     // Otherwise, use a straight shuffle of a single input vector. We pass the
7931     // input vector to both operands to simulate this with a SHUFPS.
7932     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7933                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7934   }
7935
7936   // Use dedicated unpack instructions for masks that match their pattern.
7937   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
7938     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7939   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
7940     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7941
7942   // There are special ways we can lower some single-element blends. However, we
7943   // have custom ways we can lower more complex single-element blends below that
7944   // we defer to if both this and BLENDPS fail to match, so restrict this to
7945   // when the V2 input is targeting element 0 of the mask -- that is the fast
7946   // case here.
7947   if (NumV2Elements == 1 && Mask[0] >= 4)
7948     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4f32, DL, V1, V2,
7949                                                          Mask, Subtarget, DAG))
7950       return V;
7951
7952   if (Subtarget->hasSSE41())
7953     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7954                                                   Subtarget, DAG))
7955       return Blend;
7956
7957   // Check for whether we can use INSERTPS to perform the blend. We only use
7958   // INSERTPS when the V1 elements are already in the correct locations
7959   // because otherwise we can just always use two SHUFPS instructions which
7960   // are much smaller to encode than a SHUFPS and an INSERTPS.
7961   if (NumV2Elements == 1 && Subtarget->hasSSE41()) {
7962     int V2Index =
7963         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7964         Mask.begin();
7965
7966     // When using INSERTPS we can zero any lane of the destination. Collect
7967     // the zero inputs into a mask and drop them from the lanes of V1 which
7968     // actually need to be present as inputs to the INSERTPS.
7969     SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7970
7971     // Synthesize a shuffle mask for the non-zero and non-v2 inputs.
7972     bool InsertNeedsShuffle = false;
7973     unsigned ZMask = 0;
7974     for (int i = 0; i < 4; ++i)
7975       if (i != V2Index) {
7976         if (Zeroable[i]) {
7977           ZMask |= 1 << i;
7978         } else if (Mask[i] != i) {
7979           InsertNeedsShuffle = true;
7980           break;
7981         }
7982       }
7983
7984     // We don't want to use INSERTPS or other insertion techniques if it will
7985     // require shuffling anyways.
7986     if (!InsertNeedsShuffle) {
7987       // If all of V1 is zeroable, replace it with undef.
7988       if ((ZMask | 1 << V2Index) == 0xF)
7989         V1 = DAG.getUNDEF(MVT::v4f32);
7990
7991       unsigned InsertPSMask = (Mask[V2Index] - 4) << 6 | V2Index << 4 | ZMask;
7992       assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7993
7994       // Insert the V2 element into the desired position.
7995       return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7996                          DAG.getConstant(InsertPSMask, MVT::i8));
7997     }
7998   }
7999
8000   // Otherwise fall back to a SHUFPS lowering strategy.
8001   return lowerVectorShuffleWithSHUPFS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8002 }
8003
8004 /// \brief Lower 4-lane i32 vector shuffles.
8005 ///
8006 /// We try to handle these with integer-domain shuffles where we can, but for
8007 /// blends we use the floating point domain blend instructions.
8008 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8009                                        const X86Subtarget *Subtarget,
8010                                        SelectionDAG &DAG) {
8011   SDLoc DL(Op);
8012   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8013   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8014   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8015   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8016   ArrayRef<int> Mask = SVOp->getMask();
8017   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8018
8019   int NumV2Elements =
8020       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8021
8022   if (NumV2Elements == 0) {
8023     // Straight shuffle of a single input vector. For everything from SSE2
8024     // onward this has a single fast instruction with no scary immediates.
8025     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8026     // but we aren't actually going to use the UNPCK instruction because doing
8027     // so prevents folding a load into this instruction or making a copy.
8028     const int UnpackLoMask[] = {0, 0, 1, 1};
8029     const int UnpackHiMask[] = {2, 2, 3, 3};
8030     if (isShuffleEquivalent(Mask, 0, 0, 1, 1))
8031       Mask = UnpackLoMask;
8032     else if (isShuffleEquivalent(Mask, 2, 2, 3, 3))
8033       Mask = UnpackHiMask;
8034
8035     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8036                        getV4X86ShuffleImm8ForMask(Mask, DAG));
8037   }
8038
8039   // Whenever we can lower this as a zext, that instruction is strictly faster
8040   // than any alternative.
8041   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8042                                                          Mask, Subtarget, DAG))
8043     return ZExt;
8044
8045   // Use dedicated unpack instructions for masks that match their pattern.
8046   if (isShuffleEquivalent(Mask, 0, 4, 1, 5))
8047     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8048   if (isShuffleEquivalent(Mask, 2, 6, 3, 7))
8049     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8050
8051   // There are special ways we can lower some single-element blends.
8052   if (NumV2Elements == 1)
8053     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v4i32, DL, V1, V2,
8054                                                          Mask, Subtarget, DAG))
8055       return V;
8056
8057   if (Subtarget->hasSSE41())
8058     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8059                                                   Subtarget, DAG))
8060       return Blend;
8061
8062   // Try to use rotation instructions if available.
8063   if (Subtarget->hasSSSE3())
8064     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8065             DL, MVT::v4i32, V1, V2, Mask, DAG))
8066       return Rotate;
8067
8068   // We implement this with SHUFPS because it can blend from two vectors.
8069   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8070   // up the inputs, bypassing domain shift penalties that we would encur if we
8071   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8072   // relevant.
8073   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
8074                      DAG.getVectorShuffle(
8075                          MVT::v4f32, DL,
8076                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
8077                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
8078 }
8079
8080 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8081 /// shuffle lowering, and the most complex part.
8082 ///
8083 /// The lowering strategy is to try to form pairs of input lanes which are
8084 /// targeted at the same half of the final vector, and then use a dword shuffle
8085 /// to place them onto the right half, and finally unpack the paired lanes into
8086 /// their final position.
8087 ///
8088 /// The exact breakdown of how to form these dword pairs and align them on the
8089 /// correct sides is really tricky. See the comments within the function for
8090 /// more of the details.
8091 static SDValue lowerV8I16SingleInputVectorShuffle(
8092     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
8093     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8094   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8095   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8096   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8097
8098   SmallVector<int, 4> LoInputs;
8099   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8100                [](int M) { return M >= 0; });
8101   std::sort(LoInputs.begin(), LoInputs.end());
8102   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8103   SmallVector<int, 4> HiInputs;
8104   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8105                [](int M) { return M >= 0; });
8106   std::sort(HiInputs.begin(), HiInputs.end());
8107   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8108   int NumLToL =
8109       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8110   int NumHToL = LoInputs.size() - NumLToL;
8111   int NumLToH =
8112       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8113   int NumHToH = HiInputs.size() - NumLToH;
8114   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8115   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8116   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8117   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8118
8119   // Use dedicated unpack instructions for masks that match their pattern.
8120   if (isShuffleEquivalent(Mask, 0, 0, 1, 1, 2, 2, 3, 3))
8121     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V, V);
8122   if (isShuffleEquivalent(Mask, 4, 4, 5, 5, 6, 6, 7, 7))
8123     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V, V);
8124
8125   // Try to use rotation instructions if available.
8126   if (Subtarget->hasSSSE3())
8127     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8128             DL, MVT::v8i16, V, V, Mask, DAG))
8129       return Rotate;
8130
8131   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8132   // such inputs we can swap two of the dwords across the half mark and end up
8133   // with <=2 inputs to each half in each half. Once there, we can fall through
8134   // to the generic code below. For example:
8135   //
8136   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8137   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8138   //
8139   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8140   // and an existing 2-into-2 on the other half. In this case we may have to
8141   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8142   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8143   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8144   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8145   // half than the one we target for fixing) will be fixed when we re-enter this
8146   // path. We will also combine away any sequence of PSHUFD instructions that
8147   // result into a single instruction. Here is an example of the tricky case:
8148   //
8149   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8150   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8151   //
8152   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8153   //
8154   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8155   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8156   //
8157   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8158   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8159   //
8160   // The result is fine to be handled by the generic logic.
8161   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8162                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8163                           int AOffset, int BOffset) {
8164     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8165            "Must call this with A having 3 or 1 inputs from the A half.");
8166     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8167            "Must call this with B having 1 or 3 inputs from the B half.");
8168     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8169            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8170
8171     // Compute the index of dword with only one word among the three inputs in
8172     // a half by taking the sum of the half with three inputs and subtracting
8173     // the sum of the actual three inputs. The difference is the remaining
8174     // slot.
8175     int ADWord, BDWord;
8176     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8177     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8178     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8179     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8180     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8181     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8182     int TripleNonInputIdx =
8183         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8184     TripleDWord = TripleNonInputIdx / 2;
8185
8186     // We use xor with one to compute the adjacent DWord to whichever one the
8187     // OneInput is in.
8188     OneInputDWord = (OneInput / 2) ^ 1;
8189
8190     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8191     // and BToA inputs. If there is also such a problem with the BToB and AToB
8192     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8193     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8194     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8195     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8196       // Compute how many inputs will be flipped by swapping these DWords. We
8197       // need
8198       // to balance this to ensure we don't form a 3-1 shuffle in the other
8199       // half.
8200       int NumFlippedAToBInputs =
8201           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8202           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8203       int NumFlippedBToBInputs =
8204           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8205           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8206       if ((NumFlippedAToBInputs == 1 &&
8207            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8208           (NumFlippedBToBInputs == 1 &&
8209            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8210         // We choose whether to fix the A half or B half based on whether that
8211         // half has zero flipped inputs. At zero, we may not be able to fix it
8212         // with that half. We also bias towards fixing the B half because that
8213         // will more commonly be the high half, and we have to bias one way.
8214         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8215                                                        ArrayRef<int> Inputs) {
8216           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8217           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8218                                          PinnedIdx ^ 1) != Inputs.end();
8219           // Determine whether the free index is in the flipped dword or the
8220           // unflipped dword based on where the pinned index is. We use this bit
8221           // in an xor to conditionally select the adjacent dword.
8222           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8223           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8224                                              FixFreeIdx) != Inputs.end();
8225           if (IsFixIdxInput == IsFixFreeIdxInput)
8226             FixFreeIdx += 1;
8227           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8228                                         FixFreeIdx) != Inputs.end();
8229           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8230                  "We need to be changing the number of flipped inputs!");
8231           int PSHUFHalfMask[] = {0, 1, 2, 3};
8232           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8233           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8234                           MVT::v8i16, V,
8235                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DAG));
8236
8237           for (int &M : Mask)
8238             if (M != -1 && M == FixIdx)
8239               M = FixFreeIdx;
8240             else if (M != -1 && M == FixFreeIdx)
8241               M = FixIdx;
8242         };
8243         if (NumFlippedBToBInputs != 0) {
8244           int BPinnedIdx =
8245               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8246           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8247         } else {
8248           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8249           int APinnedIdx =
8250               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8251           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8252         }
8253       }
8254     }
8255
8256     int PSHUFDMask[] = {0, 1, 2, 3};
8257     PSHUFDMask[ADWord] = BDWord;
8258     PSHUFDMask[BDWord] = ADWord;
8259     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8260                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8261                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8262                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8263
8264     // Adjust the mask to match the new locations of A and B.
8265     for (int &M : Mask)
8266       if (M != -1 && M/2 == ADWord)
8267         M = 2 * BDWord + M % 2;
8268       else if (M != -1 && M/2 == BDWord)
8269         M = 2 * ADWord + M % 2;
8270
8271     // Recurse back into this routine to re-compute state now that this isn't
8272     // a 3 and 1 problem.
8273     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8274                                 Mask);
8275   };
8276   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8277     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8278   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8279     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8280
8281   // At this point there are at most two inputs to the low and high halves from
8282   // each half. That means the inputs can always be grouped into dwords and
8283   // those dwords can then be moved to the correct half with a dword shuffle.
8284   // We use at most one low and one high word shuffle to collect these paired
8285   // inputs into dwords, and finally a dword shuffle to place them.
8286   int PSHUFLMask[4] = {-1, -1, -1, -1};
8287   int PSHUFHMask[4] = {-1, -1, -1, -1};
8288   int PSHUFDMask[4] = {-1, -1, -1, -1};
8289
8290   // First fix the masks for all the inputs that are staying in their
8291   // original halves. This will then dictate the targets of the cross-half
8292   // shuffles.
8293   auto fixInPlaceInputs =
8294       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8295                     MutableArrayRef<int> SourceHalfMask,
8296                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8297     if (InPlaceInputs.empty())
8298       return;
8299     if (InPlaceInputs.size() == 1) {
8300       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8301           InPlaceInputs[0] - HalfOffset;
8302       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8303       return;
8304     }
8305     if (IncomingInputs.empty()) {
8306       // Just fix all of the in place inputs.
8307       for (int Input : InPlaceInputs) {
8308         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8309         PSHUFDMask[Input / 2] = Input / 2;
8310       }
8311       return;
8312     }
8313
8314     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8315     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8316         InPlaceInputs[0] - HalfOffset;
8317     // Put the second input next to the first so that they are packed into
8318     // a dword. We find the adjacent index by toggling the low bit.
8319     int AdjIndex = InPlaceInputs[0] ^ 1;
8320     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8321     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8322     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8323   };
8324   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8325   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8326
8327   // Now gather the cross-half inputs and place them into a free dword of
8328   // their target half.
8329   // FIXME: This operation could almost certainly be simplified dramatically to
8330   // look more like the 3-1 fixing operation.
8331   auto moveInputsToRightHalf = [&PSHUFDMask](
8332       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8333       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8334       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8335       int DestOffset) {
8336     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8337       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8338     };
8339     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8340                                                int Word) {
8341       int LowWord = Word & ~1;
8342       int HighWord = Word | 1;
8343       return isWordClobbered(SourceHalfMask, LowWord) ||
8344              isWordClobbered(SourceHalfMask, HighWord);
8345     };
8346
8347     if (IncomingInputs.empty())
8348       return;
8349
8350     if (ExistingInputs.empty()) {
8351       // Map any dwords with inputs from them into the right half.
8352       for (int Input : IncomingInputs) {
8353         // If the source half mask maps over the inputs, turn those into
8354         // swaps and use the swapped lane.
8355         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8356           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8357             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8358                 Input - SourceOffset;
8359             // We have to swap the uses in our half mask in one sweep.
8360             for (int &M : HalfMask)
8361               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8362                 M = Input;
8363               else if (M == Input)
8364                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8365           } else {
8366             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8367                        Input - SourceOffset &&
8368                    "Previous placement doesn't match!");
8369           }
8370           // Note that this correctly re-maps both when we do a swap and when
8371           // we observe the other side of the swap above. We rely on that to
8372           // avoid swapping the members of the input list directly.
8373           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8374         }
8375
8376         // Map the input's dword into the correct half.
8377         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8378           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8379         else
8380           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8381                      Input / 2 &&
8382                  "Previous placement doesn't match!");
8383       }
8384
8385       // And just directly shift any other-half mask elements to be same-half
8386       // as we will have mirrored the dword containing the element into the
8387       // same position within that half.
8388       for (int &M : HalfMask)
8389         if (M >= SourceOffset && M < SourceOffset + 4) {
8390           M = M - SourceOffset + DestOffset;
8391           assert(M >= 0 && "This should never wrap below zero!");
8392         }
8393       return;
8394     }
8395
8396     // Ensure we have the input in a viable dword of its current half. This
8397     // is particularly tricky because the original position may be clobbered
8398     // by inputs being moved and *staying* in that half.
8399     if (IncomingInputs.size() == 1) {
8400       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8401         int InputFixed = std::find(std::begin(SourceHalfMask),
8402                                    std::end(SourceHalfMask), -1) -
8403                          std::begin(SourceHalfMask) + SourceOffset;
8404         SourceHalfMask[InputFixed - SourceOffset] =
8405             IncomingInputs[0] - SourceOffset;
8406         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8407                      InputFixed);
8408         IncomingInputs[0] = InputFixed;
8409       }
8410     } else if (IncomingInputs.size() == 2) {
8411       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8412           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8413         // We have two non-adjacent or clobbered inputs we need to extract from
8414         // the source half. To do this, we need to map them into some adjacent
8415         // dword slot in the source mask.
8416         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8417                               IncomingInputs[1] - SourceOffset};
8418
8419         // If there is a free slot in the source half mask adjacent to one of
8420         // the inputs, place the other input in it. We use (Index XOR 1) to
8421         // compute an adjacent index.
8422         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8423             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8424           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8425           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8426           InputsFixed[1] = InputsFixed[0] ^ 1;
8427         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8428                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8429           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8430           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8431           InputsFixed[0] = InputsFixed[1] ^ 1;
8432         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8433                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8434           // The two inputs are in the same DWord but it is clobbered and the
8435           // adjacent DWord isn't used at all. Move both inputs to the free
8436           // slot.
8437           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8438           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8439           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8440           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8441         } else {
8442           // The only way we hit this point is if there is no clobbering
8443           // (because there are no off-half inputs to this half) and there is no
8444           // free slot adjacent to one of the inputs. In this case, we have to
8445           // swap an input with a non-input.
8446           for (int i = 0; i < 4; ++i)
8447             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8448                    "We can't handle any clobbers here!");
8449           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8450                  "Cannot have adjacent inputs here!");
8451
8452           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8453           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8454
8455           // We also have to update the final source mask in this case because
8456           // it may need to undo the above swap.
8457           for (int &M : FinalSourceHalfMask)
8458             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8459               M = InputsFixed[1] + SourceOffset;
8460             else if (M == InputsFixed[1] + SourceOffset)
8461               M = (InputsFixed[0] ^ 1) + SourceOffset;
8462
8463           InputsFixed[1] = InputsFixed[0] ^ 1;
8464         }
8465
8466         // Point everything at the fixed inputs.
8467         for (int &M : HalfMask)
8468           if (M == IncomingInputs[0])
8469             M = InputsFixed[0] + SourceOffset;
8470           else if (M == IncomingInputs[1])
8471             M = InputsFixed[1] + SourceOffset;
8472
8473         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8474         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8475       }
8476     } else {
8477       llvm_unreachable("Unhandled input size!");
8478     }
8479
8480     // Now hoist the DWord down to the right half.
8481     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8482     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8483     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8484     for (int &M : HalfMask)
8485       for (int Input : IncomingInputs)
8486         if (M == Input)
8487           M = FreeDWord * 2 + Input % 2;
8488   };
8489   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8490                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8491   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8492                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8493
8494   // Now enact all the shuffles we've computed to move the inputs into their
8495   // target half.
8496   if (!isNoopShuffleMask(PSHUFLMask))
8497     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8498                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
8499   if (!isNoopShuffleMask(PSHUFHMask))
8500     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8501                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
8502   if (!isNoopShuffleMask(PSHUFDMask))
8503     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8504                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
8505                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
8506                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
8507
8508   // At this point, each half should contain all its inputs, and we can then
8509   // just shuffle them into their final position.
8510   assert(std::count_if(LoMask.begin(), LoMask.end(),
8511                        [](int M) { return M >= 4; }) == 0 &&
8512          "Failed to lift all the high half inputs to the low mask!");
8513   assert(std::count_if(HiMask.begin(), HiMask.end(),
8514                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8515          "Failed to lift all the low half inputs to the high mask!");
8516
8517   // Do a half shuffle for the low mask.
8518   if (!isNoopShuffleMask(LoMask))
8519     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
8520                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
8521
8522   // Do a half shuffle with the high mask after shifting its values down.
8523   for (int &M : HiMask)
8524     if (M >= 0)
8525       M -= 4;
8526   if (!isNoopShuffleMask(HiMask))
8527     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
8528                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
8529
8530   return V;
8531 }
8532
8533 /// \brief Detect whether the mask pattern should be lowered through
8534 /// interleaving.
8535 ///
8536 /// This essentially tests whether viewing the mask as an interleaving of two
8537 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
8538 /// lowering it through interleaving is a significantly better strategy.
8539 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
8540   int NumEvenInputs[2] = {0, 0};
8541   int NumOddInputs[2] = {0, 0};
8542   int NumLoInputs[2] = {0, 0};
8543   int NumHiInputs[2] = {0, 0};
8544   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
8545     if (Mask[i] < 0)
8546       continue;
8547
8548     int InputIdx = Mask[i] >= Size;
8549
8550     if (i < Size / 2)
8551       ++NumLoInputs[InputIdx];
8552     else
8553       ++NumHiInputs[InputIdx];
8554
8555     if ((i % 2) == 0)
8556       ++NumEvenInputs[InputIdx];
8557     else
8558       ++NumOddInputs[InputIdx];
8559   }
8560
8561   // The minimum number of cross-input results for both the interleaved and
8562   // split cases. If interleaving results in fewer cross-input results, return
8563   // true.
8564   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
8565                                     NumEvenInputs[0] + NumOddInputs[1]);
8566   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
8567                               NumLoInputs[0] + NumHiInputs[1]);
8568   return InterleavedCrosses < SplitCrosses;
8569 }
8570
8571 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
8572 ///
8573 /// This strategy only works when the inputs from each vector fit into a single
8574 /// half of that vector, and generally there are not so many inputs as to leave
8575 /// the in-place shuffles required highly constrained (and thus expensive). It
8576 /// shifts all the inputs into a single side of both input vectors and then
8577 /// uses an unpack to interleave these inputs in a single vector. At that
8578 /// point, we will fall back on the generic single input shuffle lowering.
8579 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
8580                                                  SDValue V2,
8581                                                  MutableArrayRef<int> Mask,
8582                                                  const X86Subtarget *Subtarget,
8583                                                  SelectionDAG &DAG) {
8584   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8585   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
8586   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
8587   for (int i = 0; i < 8; ++i)
8588     if (Mask[i] >= 0 && Mask[i] < 4)
8589       LoV1Inputs.push_back(i);
8590     else if (Mask[i] >= 4 && Mask[i] < 8)
8591       HiV1Inputs.push_back(i);
8592     else if (Mask[i] >= 8 && Mask[i] < 12)
8593       LoV2Inputs.push_back(i);
8594     else if (Mask[i] >= 12)
8595       HiV2Inputs.push_back(i);
8596
8597   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
8598   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
8599   (void)NumV1Inputs;
8600   (void)NumV2Inputs;
8601   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
8602   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
8603   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
8604
8605   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
8606                      HiV1Inputs.size() + HiV2Inputs.size();
8607
8608   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
8609                               ArrayRef<int> HiInputs, bool MoveToLo,
8610                               int MaskOffset) {
8611     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
8612     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
8613     if (BadInputs.empty())
8614       return V;
8615
8616     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8617     int MoveOffset = MoveToLo ? 0 : 4;
8618
8619     if (GoodInputs.empty()) {
8620       for (int BadInput : BadInputs) {
8621         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
8622         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
8623       }
8624     } else {
8625       if (GoodInputs.size() == 2) {
8626         // If the low inputs are spread across two dwords, pack them into
8627         // a single dword.
8628         MoveMask[MoveOffset] = Mask[GoodInputs[0]] - MaskOffset;
8629         MoveMask[MoveOffset + 1] = Mask[GoodInputs[1]] - MaskOffset;
8630         Mask[GoodInputs[0]] = MoveOffset + MaskOffset;
8631         Mask[GoodInputs[1]] = MoveOffset + 1 + MaskOffset;
8632       } else {
8633         // Otherwise pin the good inputs.
8634         for (int GoodInput : GoodInputs)
8635           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
8636       }
8637
8638       if (BadInputs.size() == 2) {
8639         // If we have two bad inputs then there may be either one or two good
8640         // inputs fixed in place. Find a fixed input, and then find the *other*
8641         // two adjacent indices by using modular arithmetic.
8642         int GoodMaskIdx =
8643             std::find_if(std::begin(MoveMask) + MoveOffset, std::end(MoveMask),
8644                          [](int M) { return M >= 0; }) -
8645             std::begin(MoveMask);
8646         int MoveMaskIdx =
8647             ((((GoodMaskIdx - MoveOffset) & ~1) + 2) % 4) + MoveOffset;
8648         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
8649         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
8650         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8651         MoveMask[MoveMaskIdx + 1] = Mask[BadInputs[1]] - MaskOffset;
8652         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8653         Mask[BadInputs[1]] = MoveMaskIdx + 1 + MaskOffset;
8654       } else {
8655         assert(BadInputs.size() == 1 && "All sizes handled");
8656         int MoveMaskIdx = std::find(std::begin(MoveMask) + MoveOffset,
8657                                     std::end(MoveMask), -1) -
8658                           std::begin(MoveMask);
8659         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
8660         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
8661       }
8662     }
8663
8664     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
8665                                 MoveMask);
8666   };
8667   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
8668                         /*MaskOffset*/ 0);
8669   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
8670                         /*MaskOffset*/ 8);
8671
8672   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
8673   // cross-half traffic in the final shuffle.
8674
8675   // Munge the mask to be a single-input mask after the unpack merges the
8676   // results.
8677   for (int &M : Mask)
8678     if (M != -1)
8679       M = 2 * (M % 4) + (M / 8);
8680
8681   return DAG.getVectorShuffle(
8682       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
8683                                   DL, MVT::v8i16, V1, V2),
8684       DAG.getUNDEF(MVT::v8i16), Mask);
8685 }
8686
8687 /// \brief Generic lowering of 8-lane i16 shuffles.
8688 ///
8689 /// This handles both single-input shuffles and combined shuffle/blends with
8690 /// two inputs. The single input shuffles are immediately delegated to
8691 /// a dedicated lowering routine.
8692 ///
8693 /// The blends are lowered in one of three fundamental ways. If there are few
8694 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8695 /// of the input is significantly cheaper when lowered as an interleaving of
8696 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8697 /// halves of the inputs separately (making them have relatively few inputs)
8698 /// and then concatenate them.
8699 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8700                                        const X86Subtarget *Subtarget,
8701                                        SelectionDAG &DAG) {
8702   SDLoc DL(Op);
8703   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8704   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8705   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8706   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8707   ArrayRef<int> OrigMask = SVOp->getMask();
8708   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8709                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8710   MutableArrayRef<int> Mask(MaskStorage);
8711
8712   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8713
8714   // Whenever we can lower this as a zext, that instruction is strictly faster
8715   // than any alternative.
8716   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8717           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8718     return ZExt;
8719
8720   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8721   auto isV2 = [](int M) { return M >= 8; };
8722
8723   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
8724   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8725
8726   if (NumV2Inputs == 0)
8727     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
8728
8729   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
8730                             "to be V1-input shuffles.");
8731
8732   // There are special ways we can lower some single-element blends.
8733   if (NumV2Inputs == 1)
8734     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v8i16, DL, V1, V2,
8735                                                          Mask, Subtarget, DAG))
8736       return V;
8737
8738   if (Subtarget->hasSSE41())
8739     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8740                                                   Subtarget, DAG))
8741       return Blend;
8742
8743   // Try to use rotation instructions if available.
8744   if (Subtarget->hasSSSE3())
8745     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V2, Mask, DAG))
8746       return Rotate;
8747
8748   if (NumV1Inputs + NumV2Inputs <= 4)
8749     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
8750
8751   // Check whether an interleaving lowering is likely to be more efficient.
8752   // This isn't perfect but it is a strong heuristic that tends to work well on
8753   // the kinds of shuffles that show up in practice.
8754   //
8755   // FIXME: Handle 1x, 2x, and 4x interleaving.
8756   if (shouldLowerAsInterleaving(Mask)) {
8757     // FIXME: Figure out whether we should pack these into the low or high
8758     // halves.
8759
8760     int EMask[8], OMask[8];
8761     for (int i = 0; i < 4; ++i) {
8762       EMask[i] = Mask[2*i];
8763       OMask[i] = Mask[2*i + 1];
8764       EMask[i + 4] = -1;
8765       OMask[i + 4] = -1;
8766     }
8767
8768     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
8769     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
8770
8771     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
8772   }
8773
8774   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8775   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8776
8777   for (int i = 0; i < 4; ++i) {
8778     LoBlendMask[i] = Mask[i];
8779     HiBlendMask[i] = Mask[i + 4];
8780   }
8781
8782   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8783   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8784   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
8785   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
8786
8787   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8788                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
8789 }
8790
8791 /// \brief Check whether a compaction lowering can be done by dropping even
8792 /// elements and compute how many times even elements must be dropped.
8793 ///
8794 /// This handles shuffles which take every Nth element where N is a power of
8795 /// two. Example shuffle masks:
8796 ///
8797 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8798 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8799 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8800 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8801 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8802 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8803 ///
8804 /// Any of these lanes can of course be undef.
8805 ///
8806 /// This routine only supports N <= 3.
8807 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8808 /// for larger N.
8809 ///
8810 /// \returns N above, or the number of times even elements must be dropped if
8811 /// there is such a number. Otherwise returns zero.
8812 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8813   // Figure out whether we're looping over two inputs or just one.
8814   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8815
8816   // The modulus for the shuffle vector entries is based on whether this is
8817   // a single input or not.
8818   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8819   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8820          "We should only be called with masks with a power-of-2 size!");
8821
8822   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8823
8824   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8825   // and 2^3 simultaneously. This is because we may have ambiguity with
8826   // partially undef inputs.
8827   bool ViableForN[3] = {true, true, true};
8828
8829   for (int i = 0, e = Mask.size(); i < e; ++i) {
8830     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8831     // want.
8832     if (Mask[i] == -1)
8833       continue;
8834
8835     bool IsAnyViable = false;
8836     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8837       if (ViableForN[j]) {
8838         uint64_t N = j + 1;
8839
8840         // The shuffle mask must be equal to (i * 2^N) % M.
8841         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8842           IsAnyViable = true;
8843         else
8844           ViableForN[j] = false;
8845       }
8846     // Early exit if we exhaust the possible powers of two.
8847     if (!IsAnyViable)
8848       break;
8849   }
8850
8851   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8852     if (ViableForN[j])
8853       return j + 1;
8854
8855   // Return 0 as there is no viable power of two.
8856   return 0;
8857 }
8858
8859 /// \brief Generic lowering of v16i8 shuffles.
8860 ///
8861 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8862 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8863 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8864 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8865 /// back together.
8866 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8867                                        const X86Subtarget *Subtarget,
8868                                        SelectionDAG &DAG) {
8869   SDLoc DL(Op);
8870   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8871   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8872   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8873   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8874   ArrayRef<int> OrigMask = SVOp->getMask();
8875   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8876
8877   // Try to use rotation instructions if available.
8878   if (Subtarget->hasSSSE3())
8879     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v16i8, V1, V2,
8880                                                         OrigMask, DAG))
8881       return Rotate;
8882
8883   // Try to use a zext lowering.
8884   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8885           DL, MVT::v16i8, V1, V2, OrigMask, Subtarget, DAG))
8886     return ZExt;
8887
8888   int MaskStorage[16] = {
8889       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
8890       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
8891       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
8892       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
8893   MutableArrayRef<int> Mask(MaskStorage);
8894   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
8895   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
8896
8897   int NumV2Elements =
8898       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8899
8900   // For single-input shuffles, there are some nicer lowering tricks we can use.
8901   if (NumV2Elements == 0) {
8902     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8903     // Notably, this handles splat and partial-splat shuffles more efficiently.
8904     // However, it only makes sense if the pre-duplication shuffle simplifies
8905     // things significantly. Currently, this means we need to be able to
8906     // express the pre-duplication shuffle as an i16 shuffle.
8907     //
8908     // FIXME: We should check for other patterns which can be widened into an
8909     // i16 shuffle as well.
8910     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8911       for (int i = 0; i < 16; i += 2)
8912         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8913           return false;
8914
8915       return true;
8916     };
8917     auto tryToWidenViaDuplication = [&]() -> SDValue {
8918       if (!canWidenViaDuplication(Mask))
8919         return SDValue();
8920       SmallVector<int, 4> LoInputs;
8921       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8922                    [](int M) { return M >= 0 && M < 8; });
8923       std::sort(LoInputs.begin(), LoInputs.end());
8924       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8925                      LoInputs.end());
8926       SmallVector<int, 4> HiInputs;
8927       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8928                    [](int M) { return M >= 8; });
8929       std::sort(HiInputs.begin(), HiInputs.end());
8930       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8931                      HiInputs.end());
8932
8933       bool TargetLo = LoInputs.size() >= HiInputs.size();
8934       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8935       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8936
8937       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8938       SmallDenseMap<int, int, 8> LaneMap;
8939       for (int I : InPlaceInputs) {
8940         PreDupI16Shuffle[I/2] = I/2;
8941         LaneMap[I] = I;
8942       }
8943       int j = TargetLo ? 0 : 4, je = j + 4;
8944       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8945         // Check if j is already a shuffle of this input. This happens when
8946         // there are two adjacent bytes after we move the low one.
8947         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8948           // If we haven't yet mapped the input, search for a slot into which
8949           // we can map it.
8950           while (j < je && PreDupI16Shuffle[j] != -1)
8951             ++j;
8952
8953           if (j == je)
8954             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8955             return SDValue();
8956
8957           // Map this input with the i16 shuffle.
8958           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8959         }
8960
8961         // Update the lane map based on the mapping we ended up with.
8962         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8963       }
8964       V1 = DAG.getNode(
8965           ISD::BITCAST, DL, MVT::v16i8,
8966           DAG.getVectorShuffle(MVT::v8i16, DL,
8967                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8968                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8969
8970       // Unpack the bytes to form the i16s that will be shuffled into place.
8971       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8972                        MVT::v16i8, V1, V1);
8973
8974       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8975       for (int i = 0; i < 16; i += 2) {
8976         if (Mask[i] != -1)
8977           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8978         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
8979       }
8980       return DAG.getNode(
8981           ISD::BITCAST, DL, MVT::v16i8,
8982           DAG.getVectorShuffle(MVT::v8i16, DL,
8983                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
8984                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8985     };
8986     if (SDValue V = tryToWidenViaDuplication())
8987       return V;
8988   }
8989
8990   // Check whether an interleaving lowering is likely to be more efficient.
8991   // This isn't perfect but it is a strong heuristic that tends to work well on
8992   // the kinds of shuffles that show up in practice.
8993   //
8994   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
8995   if (shouldLowerAsInterleaving(Mask)) {
8996     // FIXME: Figure out whether we should pack these into the low or high
8997     // halves.
8998
8999     int EMask[16], OMask[16];
9000     for (int i = 0; i < 8; ++i) {
9001       EMask[i] = Mask[2*i];
9002       OMask[i] = Mask[2*i + 1];
9003       EMask[i + 8] = -1;
9004       OMask[i + 8] = -1;
9005     }
9006
9007     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
9008     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
9009
9010     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
9011   }
9012
9013   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9014   // with PSHUFB. It is important to do this before we attempt to generate any
9015   // blends but after all of the single-input lowerings. If the single input
9016   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9017   // want to preserve that and we can DAG combine any longer sequences into
9018   // a PSHUFB in the end. But once we start blending from multiple inputs,
9019   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9020   // and there are *very* few patterns that would actually be faster than the
9021   // PSHUFB approach because of its ability to zero lanes.
9022   //
9023   // FIXME: The only exceptions to the above are blends which are exact
9024   // interleavings with direct instructions supporting them. We currently don't
9025   // handle those well here.
9026   if (Subtarget->hasSSSE3()) {
9027     SDValue V1Mask[16];
9028     SDValue V2Mask[16];
9029     for (int i = 0; i < 16; ++i)
9030       if (Mask[i] == -1) {
9031         V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
9032       } else {
9033         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
9034         V2Mask[i] =
9035             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
9036       }
9037     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
9038                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
9039     if (isSingleInputShuffleMask(Mask))
9040       return V1; // Single inputs are easy.
9041
9042     // Otherwise, blend the two.
9043     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
9044                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
9045     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
9046   }
9047
9048   // There are special ways we can lower some single-element blends.
9049   if (NumV2Elements == 1)
9050     if (SDValue V = lowerVectorShuffleAsElementInsertion(MVT::v16i8, DL, V1, V2,
9051                                                          Mask, Subtarget, DAG))
9052       return V;
9053
9054   // Check whether a compaction lowering can be done. This handles shuffles
9055   // which take every Nth element for some even N. See the helper function for
9056   // details.
9057   //
9058   // We special case these as they can be particularly efficiently handled with
9059   // the PACKUSB instruction on x86 and they show up in common patterns of
9060   // rearranging bytes to truncate wide elements.
9061   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9062     // NumEvenDrops is the power of two stride of the elements. Another way of
9063     // thinking about it is that we need to drop the even elements this many
9064     // times to get the original input.
9065     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9066
9067     // First we need to zero all the dropped bytes.
9068     assert(NumEvenDrops <= 3 &&
9069            "No support for dropping even elements more than 3 times.");
9070     // We use the mask type to pick which bytes are preserved based on how many
9071     // elements are dropped.
9072     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9073     SDValue ByteClearMask =
9074         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
9075                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
9076     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9077     if (!IsSingleInput)
9078       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9079
9080     // Now pack things back together.
9081     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
9082     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
9083     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9084     for (int i = 1; i < NumEvenDrops; ++i) {
9085       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
9086       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9087     }
9088
9089     return Result;
9090   }
9091
9092   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9093   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9094   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9095   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9096
9097   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
9098                             MutableArrayRef<int> V1HalfBlendMask,
9099                             MutableArrayRef<int> V2HalfBlendMask) {
9100     for (int i = 0; i < 8; ++i)
9101       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
9102         V1HalfBlendMask[i] = HalfMask[i];
9103         HalfMask[i] = i;
9104       } else if (HalfMask[i] >= 16) {
9105         V2HalfBlendMask[i] = HalfMask[i] - 16;
9106         HalfMask[i] = i + 8;
9107       }
9108   };
9109   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
9110   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
9111
9112   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9113
9114   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
9115                              MutableArrayRef<int> HiBlendMask) {
9116     SDValue V1, V2;
9117     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9118     // them out and avoid using UNPCK{L,H} to extract the elements of V as
9119     // i16s.
9120     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
9121                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
9122         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
9123                      [](int M) { return M >= 0 && M % 2 == 1; })) {
9124       // Use a mask to drop the high bytes.
9125       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
9126       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
9127                        DAG.getConstant(0x00FF, MVT::v8i16));
9128
9129       // This will be a single vector shuffle instead of a blend so nuke V2.
9130       V2 = DAG.getUNDEF(MVT::v8i16);
9131
9132       // Squash the masks to point directly into V1.
9133       for (int &M : LoBlendMask)
9134         if (M >= 0)
9135           M /= 2;
9136       for (int &M : HiBlendMask)
9137         if (M >= 0)
9138           M /= 2;
9139     } else {
9140       // Otherwise just unpack the low half of V into V1 and the high half into
9141       // V2 so that we can blend them as i16s.
9142       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9143                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9144       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
9145                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9146     }
9147
9148     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
9149     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
9150     return std::make_pair(BlendedLo, BlendedHi);
9151   };
9152   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
9153   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
9154   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
9155
9156   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
9157   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
9158
9159   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9160 }
9161
9162 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9163 ///
9164 /// This routine breaks down the specific type of 128-bit shuffle and
9165 /// dispatches to the lowering routines accordingly.
9166 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9167                                         MVT VT, const X86Subtarget *Subtarget,
9168                                         SelectionDAG &DAG) {
9169   switch (VT.SimpleTy) {
9170   case MVT::v2i64:
9171     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9172   case MVT::v2f64:
9173     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9174   case MVT::v4i32:
9175     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9176   case MVT::v4f32:
9177     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9178   case MVT::v8i16:
9179     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9180   case MVT::v16i8:
9181     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9182
9183   default:
9184     llvm_unreachable("Unimplemented!");
9185   }
9186 }
9187
9188 /// \brief Test whether there are elements crossing 128-bit lanes in this
9189 /// shuffle mask.
9190 ///
9191 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
9192 /// and we routinely test for these.
9193 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
9194   int LaneSize = 128 / VT.getScalarSizeInBits();
9195   int Size = Mask.size();
9196   for (int i = 0; i < Size; ++i)
9197     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9198       return true;
9199   return false;
9200 }
9201
9202 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
9203 ///
9204 /// This checks a shuffle mask to see if it is performing the same
9205 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
9206 /// that it is also not lane-crossing. It may however involve a blend from the
9207 /// same lane of a second vector.
9208 ///
9209 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
9210 /// non-trivial to compute in the face of undef lanes. The representation is
9211 /// *not* suitable for use with existing 128-bit shuffles as it will contain
9212 /// entries from both V1 and V2 inputs to the wider mask.
9213 static bool
9214 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
9215                                 SmallVectorImpl<int> &RepeatedMask) {
9216   int LaneSize = 128 / VT.getScalarSizeInBits();
9217   RepeatedMask.resize(LaneSize, -1);
9218   int Size = Mask.size();
9219   for (int i = 0; i < Size; ++i) {
9220     if (Mask[i] < 0)
9221       continue;
9222     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
9223       // This entry crosses lanes, so there is no way to model this shuffle.
9224       return false;
9225
9226     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
9227     if (RepeatedMask[i % LaneSize] == -1)
9228       // This is the first non-undef entry in this slot of a 128-bit lane.
9229       RepeatedMask[i % LaneSize] =
9230           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
9231     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
9232       // Found a mismatch with the repeated mask.
9233       return false;
9234   }
9235   return true;
9236 }
9237
9238 /// \brief Generic routine to split a 256-bit vector shuffle into 128-bit
9239 /// shuffles.
9240 ///
9241 /// There is a severely limited set of shuffles available in AVX1 for 256-bit
9242 /// vectors resulting in routinely needing to split the shuffle into two 128-bit
9243 /// shuffles. This can be done generically for any 256-bit vector shuffle and so
9244 /// we encode the logic here for specific shuffle lowering routines to bail to
9245 /// when they exhaust the features avaible to more directly handle the shuffle.
9246 static SDValue splitAndLower256BitVectorShuffle(SDValue Op, SDValue V1,
9247                                                 SDValue V2,
9248                                                 const X86Subtarget *Subtarget,
9249                                                 SelectionDAG &DAG) {
9250   SDLoc DL(Op);
9251   MVT VT = Op.getSimpleValueType();
9252   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9253   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9254   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9255   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9256   ArrayRef<int> Mask = SVOp->getMask();
9257
9258   ArrayRef<int> LoMask = Mask.slice(0, Mask.size()/2);
9259   ArrayRef<int> HiMask = Mask.slice(Mask.size()/2);
9260
9261   int NumElements = VT.getVectorNumElements();
9262   int SplitNumElements = NumElements / 2;
9263   MVT ScalarVT = VT.getScalarType();
9264   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9265
9266   SDValue LoV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9267                              DAG.getIntPtrConstant(0));
9268   SDValue HiV1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V1,
9269                              DAG.getIntPtrConstant(SplitNumElements));
9270   SDValue LoV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9271                              DAG.getIntPtrConstant(0));
9272   SDValue HiV2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, V2,
9273                              DAG.getIntPtrConstant(SplitNumElements));
9274
9275   // Now create two 4-way blends of these half-width vectors.
9276   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9277     SmallVector<int, 16> V1BlendMask, V2BlendMask, BlendMask;
9278     for (int i = 0; i < SplitNumElements; ++i) {
9279       int M = HalfMask[i];
9280       if (M >= NumElements) {
9281         V2BlendMask.push_back(M - NumElements);
9282         V1BlendMask.push_back(-1);
9283         BlendMask.push_back(SplitNumElements + i);
9284       } else if (M >= 0) {
9285         V2BlendMask.push_back(-1);
9286         V1BlendMask.push_back(M);
9287         BlendMask.push_back(i);
9288       } else {
9289         V2BlendMask.push_back(-1);
9290         V1BlendMask.push_back(-1);
9291         BlendMask.push_back(-1);
9292       }
9293     }
9294     SDValue V1Blend = DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9295     SDValue V2Blend = DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9296     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9297   };
9298   SDValue Lo = HalfBlend(LoMask);
9299   SDValue Hi = HalfBlend(HiMask);
9300   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9301 }
9302
9303 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9304 ///
9305 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9306 /// isn't available.
9307 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9308                                        const X86Subtarget *Subtarget,
9309                                        SelectionDAG &DAG) {
9310   SDLoc DL(Op);
9311   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9312   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9313   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9314   ArrayRef<int> Mask = SVOp->getMask();
9315   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9316
9317   if (is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask))
9318     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
9319
9320   if (isSingleInputShuffleMask(Mask)) {
9321     // Non-half-crossing single input shuffles can be lowerid with an
9322     // interleaved permutation.
9323     unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9324                             ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9325     return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9326                        DAG.getConstant(VPERMILPMask, MVT::i8));
9327   }
9328
9329   // X86 has dedicated unpack instructions that can handle specific blend
9330   // operations: UNPCKH and UNPCKL.
9331   if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
9332     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9333   if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
9334     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9335
9336   // If we have a single input to the zero element, insert that into V1 if we
9337   // can do so cheaply.
9338   int NumV2Elements =
9339       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
9340   if (NumV2Elements == 1 && Mask[0] >= 4)
9341     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
9342             MVT::v4f64, DL, V1, V2, Mask, Subtarget, DAG))
9343       return Insertion;
9344
9345   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9346                                                 Subtarget, DAG))
9347     return Blend;
9348
9349   // Check if the blend happens to exactly fit that of SHUFPD.
9350   if (Mask[0] < 4 && (Mask[1] == -1 || Mask[1] >= 4) &&
9351       Mask[2] < 4 && (Mask[3] == -1 || Mask[3] >= 4)) {
9352     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 5) << 1) |
9353                           ((Mask[2] == 3) << 2) | ((Mask[3] == 7) << 3);
9354     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V1, V2,
9355                        DAG.getConstant(SHUFPDMask, MVT::i8));
9356   }
9357   if ((Mask[0] == -1 || Mask[0] >= 4) && Mask[1] < 4 &&
9358       (Mask[2] == -1 || Mask[2] >= 4) && Mask[3] < 4) {
9359     unsigned SHUFPDMask = (Mask[0] == 5) | ((Mask[1] == 1) << 1) |
9360                           ((Mask[2] == 7) << 2) | ((Mask[3] == 3) << 3);
9361     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f64, V2, V1,
9362                        DAG.getConstant(SHUFPDMask, MVT::i8));
9363   }
9364
9365   // Shuffle the input elements into the desired positions in V1 and V2 and
9366   // blend them together.
9367   int V1Mask[] = {-1, -1, -1, -1};
9368   int V2Mask[] = {-1, -1, -1, -1};
9369   for (int i = 0; i < 4; ++i)
9370     if (Mask[i] >= 0 && Mask[i] < 4)
9371       V1Mask[i] = Mask[i];
9372     else if (Mask[i] >= 4)
9373       V2Mask[i] = Mask[i] - 4;
9374
9375   V1 = DAG.getVectorShuffle(MVT::v4f64, DL, V1, DAG.getUNDEF(MVT::v4f64), V1Mask);
9376   V2 = DAG.getVectorShuffle(MVT::v4f64, DL, V2, DAG.getUNDEF(MVT::v4f64), V2Mask);
9377
9378   unsigned BlendMask = 0;
9379   for (int i = 0; i < 4; ++i)
9380     if (Mask[i] >= 4)
9381       BlendMask |= 1 << i;
9382
9383   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v4f64, V1, V2,
9384                      DAG.getConstant(BlendMask, MVT::i8));
9385 }
9386
9387 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9388 ///
9389 /// This routine is only called when we have AVX2 and thus a reasonable
9390 /// instruction set for v4i64 shuffling..
9391 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9392                                        const X86Subtarget *Subtarget,
9393                                        SelectionDAG &DAG) {
9394   SDLoc DL(Op);
9395   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9396   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9397   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9398   ArrayRef<int> Mask = SVOp->getMask();
9399   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9400   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9401
9402   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9403                                                 Subtarget, DAG))
9404     return Blend;
9405
9406   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9407   // use lower latency instructions that will operate on both 128-bit lanes.
9408   SmallVector<int, 2> RepeatedMask;
9409   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9410     if (isSingleInputShuffleMask(Mask)) {
9411       int PSHUFDMask[] = {-1, -1, -1, -1};
9412       for (int i = 0; i < 2; ++i)
9413         if (RepeatedMask[i] >= 0) {
9414           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9415           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9416         }
9417       return DAG.getNode(
9418           ISD::BITCAST, DL, MVT::v4i64,
9419           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9420                       DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, V1),
9421                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
9422     }
9423
9424     // Use dedicated unpack instructions for masks that match their pattern.
9425     if (isShuffleEquivalent(Mask, 0, 4, 2, 6))
9426       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9427     if (isShuffleEquivalent(Mask, 1, 5, 3, 7))
9428       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9429   }
9430
9431   // AVX2 provides a direct instruction for permuting a single input across
9432   // lanes.
9433   if (isSingleInputShuffleMask(Mask))
9434     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9435                        getV4X86ShuffleImm8ForMask(Mask, DAG));
9436
9437   // Shuffle the input elements into the desired positions in V1 and V2 and
9438   // blend them together.
9439   int V1Mask[] = {-1, -1, -1, -1};
9440   int V2Mask[] = {-1, -1, -1, -1};
9441   int BlendMask[] = {-1, -1, -1, -1};
9442   for (int i = 0; i < 4; ++i)
9443     if (Mask[i] >= 0 && Mask[i] < 4) {
9444       V1Mask[i] = Mask[i];
9445       BlendMask[i] = i;
9446     } else if (Mask[i] >= 4) {
9447       V2Mask[i] = Mask[i] - 4;
9448       BlendMask[i] = i + 4;
9449     }
9450
9451   V1 = DAG.getVectorShuffle(MVT::v4i64, DL, V1, DAG.getUNDEF(MVT::v4i64), V1Mask);
9452   V2 = DAG.getVectorShuffle(MVT::v4i64, DL, V2, DAG.getUNDEF(MVT::v4i64), V2Mask);
9453   return DAG.getVectorShuffle(MVT::v4i64, DL, V1, V2, BlendMask);
9454 }
9455
9456 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9457 ///
9458 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9459 /// isn't available.
9460 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9461                                        const X86Subtarget *Subtarget,
9462                                        SelectionDAG &DAG) {
9463   SDLoc DL(Op);
9464   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9465   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9466   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9467   ArrayRef<int> Mask = SVOp->getMask();
9468   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9469
9470   if (is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9471     return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
9472
9473   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9474                                                 Subtarget, DAG))
9475     return Blend;
9476
9477   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9478   // options to efficiently lower the shuffle.
9479   SmallVector<int, 2> RepeatedMask;
9480   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9481     if (isSingleInputShuffleMask(Mask))
9482       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9483                          getV4X86ShuffleImm8ForMask(RepeatedMask, DAG));
9484
9485     // Use dedicated unpack instructions for masks that match their pattern.
9486     if (isShuffleEquivalent(Mask, 0, 8, 1, 9, 4, 12, 5, 13))
9487       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9488     if (isShuffleEquivalent(Mask, 2, 10, 3, 11, 6, 14, 7, 15))
9489       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9490
9491     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9492     // have already handled any direct blends.
9493     int SHUFPSMask[] = {Mask[0], Mask[1], Mask[2], Mask[3]};
9494     for (int &M : SHUFPSMask)
9495       if (M >= 8)
9496         M -= 4;
9497     return lowerVectorShuffleWithSHUPFS(DL, MVT::v8f32, SHUFPSMask, V1, V2, DAG);
9498   }
9499
9500   // If we have a single input shuffle with different shuffle patterns in the
9501   // two 128-bit lanes use the variable mask to VPERMILPS.
9502   if (isSingleInputShuffleMask(Mask)) {
9503     SDValue VPermMask[8];
9504     for (int i = 0; i < 8; ++i)
9505       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9506                                  : DAG.getConstant(Mask[i], MVT::i32);
9507     return DAG.getNode(
9508         X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9509         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9510   }
9511
9512   // Shuffle the input elements into the desired positions in V1 and V2 and
9513   // blend them together.
9514   int V1Mask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9515   int V2Mask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9516   unsigned BlendMask = 0;
9517   for (int i = 0; i < 8; ++i)
9518     if (Mask[i] >= 0 && Mask[i] < 8) {
9519       V1Mask[i] = Mask[i];
9520     } else if (Mask[i] >= 8) {
9521       V2Mask[i] = Mask[i] - 8;
9522       BlendMask |= 1 << i;
9523     }
9524
9525   V1 = DAG.getVectorShuffle(MVT::v8f32, DL, V1, DAG.getUNDEF(MVT::v8f32), V1Mask);
9526   V2 = DAG.getVectorShuffle(MVT::v8f32, DL, V2, DAG.getUNDEF(MVT::v8f32), V2Mask);
9527
9528   return DAG.getNode(X86ISD::BLENDI, DL, MVT::v8f32, V1, V2,
9529                      DAG.getConstant(BlendMask, MVT::i8));
9530 }
9531
9532 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9533 ///
9534 /// This routine is only called when we have AVX2 and thus a reasonable
9535 /// instruction set for v8i32 shuffling..
9536 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9537                                        const X86Subtarget *Subtarget,
9538                                        SelectionDAG &DAG) {
9539   SDLoc DL(Op);
9540   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9541   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9542   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9543   ArrayRef<int> Mask = SVOp->getMask();
9544   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9545   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9546
9547   // FIXME: Actually implement this using AVX2!!!
9548   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8f32, V1);
9549   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8f32, V2);
9550   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i32,
9551                      DAG.getVectorShuffle(MVT::v8f32, DL, V1, V2, Mask));
9552 }
9553
9554 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9555 ///
9556 /// This routine is only called when we have AVX2 and thus a reasonable
9557 /// instruction set for v16i16 shuffling..
9558 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9559                                         const X86Subtarget *Subtarget,
9560                                         SelectionDAG &DAG) {
9561   SDLoc DL(Op);
9562   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9563   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9564   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9565   ArrayRef<int> Mask = SVOp->getMask();
9566   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9567   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9568
9569   // FIXME: Actually implement this using AVX2!!!
9570   (void)Mask;
9571   return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
9572 }
9573
9574 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9575 ///
9576 /// This routine is only called when we have AVX2 and thus a reasonable
9577 /// instruction set for v32i8 shuffling..
9578 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9579                                        const X86Subtarget *Subtarget,
9580                                        SelectionDAG &DAG) {
9581   SDLoc DL(Op);
9582   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9583   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9584   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9585   ArrayRef<int> Mask = SVOp->getMask();
9586   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9587   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9588
9589   // FIXME: Actually implement this using AVX2!!!
9590   (void)Mask;
9591   return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
9592 }
9593
9594 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
9595 ///
9596 /// This routine either breaks down the specific type of a 256-bit x86 vector
9597 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
9598 /// together based on the available instructions.
9599 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9600                                         MVT VT, const X86Subtarget *Subtarget,
9601                                         SelectionDAG &DAG) {
9602   SDLoc DL(Op);
9603   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9604   ArrayRef<int> Mask = SVOp->getMask();
9605
9606   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
9607   // check for those subtargets here and avoid much of the subtarget querying in
9608   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
9609   // ability to manipulate a 256-bit vector with integer types. Since we'll use
9610   // floating point types there eventually, just immediately cast everything to
9611   // a float and operate entirely in that domain.
9612   if (VT.isInteger() && !Subtarget->hasAVX2()) {
9613     int ElementBits = VT.getScalarSizeInBits();
9614     if (ElementBits < 32)
9615       // No floating point type available, decompose into 128-bit vectors.
9616       return splitAndLower256BitVectorShuffle(Op, V1, V2, Subtarget, DAG);
9617
9618     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
9619                                 VT.getVectorNumElements());
9620     V1 = DAG.getNode(ISD::BITCAST, DL, FpVT, V1);
9621     V2 = DAG.getNode(ISD::BITCAST, DL, FpVT, V2);
9622     return DAG.getNode(ISD::BITCAST, DL, VT,
9623                        DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
9624   }
9625
9626   switch (VT.SimpleTy) {
9627   case MVT::v4f64:
9628     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9629   case MVT::v4i64:
9630     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9631   case MVT::v8f32:
9632     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9633   case MVT::v8i32:
9634     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9635   case MVT::v16i16:
9636     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9637   case MVT::v32i8:
9638     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9639
9640   default:
9641     llvm_unreachable("Not a valid 256-bit x86 vector type!");
9642   }
9643 }
9644
9645 /// \brief Tiny helper function to test whether a shuffle mask could be
9646 /// simplified by widening the elements being shuffled.
9647 static bool canWidenShuffleElements(ArrayRef<int> Mask) {
9648   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
9649     if ((Mask[i] != -1 && Mask[i] % 2 != 0) ||
9650         (Mask[i + 1] != -1 && (Mask[i + 1] % 2 != 1 ||
9651                                (Mask[i] != -1 && Mask[i] + 1 != Mask[i + 1]))))
9652       return false;
9653
9654   return true;
9655 }
9656
9657 /// \brief Top-level lowering for x86 vector shuffles.
9658 ///
9659 /// This handles decomposition, canonicalization, and lowering of all x86
9660 /// vector shuffles. Most of the specific lowering strategies are encapsulated
9661 /// above in helper routines. The canonicalization attempts to widen shuffles
9662 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
9663 /// s.t. only one of the two inputs needs to be tested, etc.
9664 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9665                                   SelectionDAG &DAG) {
9666   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9667   ArrayRef<int> Mask = SVOp->getMask();
9668   SDValue V1 = Op.getOperand(0);
9669   SDValue V2 = Op.getOperand(1);
9670   MVT VT = Op.getSimpleValueType();
9671   int NumElements = VT.getVectorNumElements();
9672   SDLoc dl(Op);
9673
9674   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9675
9676   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9677   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9678   if (V1IsUndef && V2IsUndef)
9679     return DAG.getUNDEF(VT);
9680
9681   // When we create a shuffle node we put the UNDEF node to second operand,
9682   // but in some cases the first operand may be transformed to UNDEF.
9683   // In this case we should just commute the node.
9684   if (V1IsUndef)
9685     return DAG.getCommutedVectorShuffle(*SVOp);
9686
9687   // Check for non-undef masks pointing at an undef vector and make the masks
9688   // undef as well. This makes it easier to match the shuffle based solely on
9689   // the mask.
9690   if (V2IsUndef)
9691     for (int M : Mask)
9692       if (M >= NumElements) {
9693         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
9694         for (int &M : NewMask)
9695           if (M >= NumElements)
9696             M = -1;
9697         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
9698       }
9699
9700   // For integer vector shuffles, try to collapse them into a shuffle of fewer
9701   // lanes but wider integers. We cap this to not form integers larger than i64
9702   // but it might be interesting to form i128 integers to handle flipping the
9703   // low and high halves of AVX 256-bit vectors.
9704   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
9705       canWidenShuffleElements(Mask)) {
9706     SmallVector<int, 8> NewMask;
9707     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
9708       NewMask.push_back(Mask[i] != -1
9709                             ? Mask[i] / 2
9710                             : (Mask[i + 1] != -1 ? Mask[i + 1] / 2 : -1));
9711     MVT NewVT =
9712         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
9713                          VT.getVectorNumElements() / 2);
9714     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
9715     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
9716     return DAG.getNode(ISD::BITCAST, dl, VT,
9717                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
9718   }
9719
9720   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
9721   for (int M : SVOp->getMask())
9722     if (M < 0)
9723       ++NumUndefElements;
9724     else if (M < NumElements)
9725       ++NumV1Elements;
9726     else
9727       ++NumV2Elements;
9728
9729   // Commute the shuffle as needed such that more elements come from V1 than
9730   // V2. This allows us to match the shuffle pattern strictly on how many
9731   // elements come from V1 without handling the symmetric cases.
9732   if (NumV2Elements > NumV1Elements)
9733     return DAG.getCommutedVectorShuffle(*SVOp);
9734
9735   // When the number of V1 and V2 elements are the same, try to minimize the
9736   // number of uses of V2 in the low half of the vector. When that is tied,
9737   // ensure that the sum of indices for V1 is equal to or lower than the sum
9738   // indices for V2.
9739   if (NumV1Elements == NumV2Elements) {
9740     int LowV1Elements = 0, LowV2Elements = 0;
9741     for (int M : SVOp->getMask().slice(0, NumElements / 2))
9742       if (M >= NumElements)
9743         ++LowV2Elements;
9744       else if (M >= 0)
9745         ++LowV1Elements;
9746     if (LowV2Elements > LowV1Elements)
9747       return DAG.getCommutedVectorShuffle(*SVOp);
9748
9749     int SumV1Indices = 0, SumV2Indices = 0;
9750     for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
9751       if (SVOp->getMask()[i] >= NumElements)
9752         SumV2Indices += i;
9753       else if (SVOp->getMask()[i] >= 0)
9754         SumV1Indices += i;
9755     if (SumV2Indices < SumV1Indices)
9756       return DAG.getCommutedVectorShuffle(*SVOp);
9757   }
9758
9759   // For each vector width, delegate to a specialized lowering routine.
9760   if (VT.getSizeInBits() == 128)
9761     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
9762
9763   if (VT.getSizeInBits() == 256)
9764     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
9765
9766   llvm_unreachable("Unimplemented!");
9767 }
9768
9769
9770 //===----------------------------------------------------------------------===//
9771 // Legacy vector shuffle lowering
9772 //
9773 // This code is the legacy code handling vector shuffles until the above
9774 // replaces its functionality and performance.
9775 //===----------------------------------------------------------------------===//
9776
9777 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
9778                         bool hasInt256, unsigned *MaskOut = nullptr) {
9779   MVT EltVT = VT.getVectorElementType();
9780
9781   // There is no blend with immediate in AVX-512.
9782   if (VT.is512BitVector())
9783     return false;
9784
9785   if (!hasSSE41 || EltVT == MVT::i8)
9786     return false;
9787   if (!hasInt256 && VT == MVT::v16i16)
9788     return false;
9789
9790   unsigned MaskValue = 0;
9791   unsigned NumElems = VT.getVectorNumElements();
9792   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9793   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9794   unsigned NumElemsInLane = NumElems / NumLanes;
9795
9796   // Blend for v16i16 should be symetric for the both lanes.
9797   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9798
9799     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
9800     int EltIdx = MaskVals[i];
9801
9802     if ((EltIdx < 0 || EltIdx == (int)i) &&
9803         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
9804       continue;
9805
9806     if (((unsigned)EltIdx == (i + NumElems)) &&
9807         (SndLaneEltIdx < 0 ||
9808          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
9809       MaskValue |= (1 << i);
9810     else
9811       return false;
9812   }
9813
9814   if (MaskOut)
9815     *MaskOut = MaskValue;
9816   return true;
9817 }
9818
9819 // Try to lower a shuffle node into a simple blend instruction.
9820 // This function assumes isBlendMask returns true for this
9821 // SuffleVectorSDNode
9822 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
9823                                           unsigned MaskValue,
9824                                           const X86Subtarget *Subtarget,
9825                                           SelectionDAG &DAG) {
9826   MVT VT = SVOp->getSimpleValueType(0);
9827   MVT EltVT = VT.getVectorElementType();
9828   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
9829                      Subtarget->hasInt256() && "Trying to lower a "
9830                                                "VECTOR_SHUFFLE to a Blend but "
9831                                                "with the wrong mask"));
9832   SDValue V1 = SVOp->getOperand(0);
9833   SDValue V2 = SVOp->getOperand(1);
9834   SDLoc dl(SVOp);
9835   unsigned NumElems = VT.getVectorNumElements();
9836
9837   // Convert i32 vectors to floating point if it is not AVX2.
9838   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9839   MVT BlendVT = VT;
9840   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9841     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9842                                NumElems);
9843     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
9844     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
9845   }
9846
9847   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
9848                             DAG.getConstant(MaskValue, MVT::i32));
9849   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9850 }
9851
9852 /// In vector type \p VT, return true if the element at index \p InputIdx
9853 /// falls on a different 128-bit lane than \p OutputIdx.
9854 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
9855                                      unsigned OutputIdx) {
9856   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
9857   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
9858 }
9859
9860 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
9861 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
9862 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
9863 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
9864 /// zero.
9865 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
9866                          SelectionDAG &DAG) {
9867   MVT VT = V1.getSimpleValueType();
9868   assert(VT.is128BitVector() || VT.is256BitVector());
9869
9870   MVT EltVT = VT.getVectorElementType();
9871   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
9872   unsigned NumElts = VT.getVectorNumElements();
9873
9874   SmallVector<SDValue, 32> PshufbMask;
9875   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
9876     int InputIdx = MaskVals[OutputIdx];
9877     unsigned InputByteIdx;
9878
9879     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
9880       InputByteIdx = 0x80;
9881     else {
9882       // Cross lane is not allowed.
9883       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
9884         return SDValue();
9885       InputByteIdx = InputIdx * EltSizeInBytes;
9886       // Index is an byte offset within the 128-bit lane.
9887       InputByteIdx &= 0xf;
9888     }
9889
9890     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
9891       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
9892       if (InputByteIdx != 0x80)
9893         ++InputByteIdx;
9894     }
9895   }
9896
9897   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
9898   if (ShufVT != VT)
9899     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
9900   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
9901                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
9902 }
9903
9904 // v8i16 shuffles - Prefer shuffles in the following order:
9905 // 1. [all]   pshuflw, pshufhw, optional move
9906 // 2. [ssse3] 1 x pshufb
9907 // 3. [ssse3] 2 x pshufb + 1 x por
9908 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
9909 static SDValue
9910 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
9911                          SelectionDAG &DAG) {
9912   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9913   SDValue V1 = SVOp->getOperand(0);
9914   SDValue V2 = SVOp->getOperand(1);
9915   SDLoc dl(SVOp);
9916   SmallVector<int, 8> MaskVals;
9917
9918   // Determine if more than 1 of the words in each of the low and high quadwords
9919   // of the result come from the same quadword of one of the two inputs.  Undef
9920   // mask values count as coming from any quadword, for better codegen.
9921   //
9922   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
9923   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
9924   unsigned LoQuad[] = { 0, 0, 0, 0 };
9925   unsigned HiQuad[] = { 0, 0, 0, 0 };
9926   // Indices of quads used.
9927   std::bitset<4> InputQuads;
9928   for (unsigned i = 0; i < 8; ++i) {
9929     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
9930     int EltIdx = SVOp->getMaskElt(i);
9931     MaskVals.push_back(EltIdx);
9932     if (EltIdx < 0) {
9933       ++Quad[0];
9934       ++Quad[1];
9935       ++Quad[2];
9936       ++Quad[3];
9937       continue;
9938     }
9939     ++Quad[EltIdx / 4];
9940     InputQuads.set(EltIdx / 4);
9941   }
9942
9943   int BestLoQuad = -1;
9944   unsigned MaxQuad = 1;
9945   for (unsigned i = 0; i < 4; ++i) {
9946     if (LoQuad[i] > MaxQuad) {
9947       BestLoQuad = i;
9948       MaxQuad = LoQuad[i];
9949     }
9950   }
9951
9952   int BestHiQuad = -1;
9953   MaxQuad = 1;
9954   for (unsigned i = 0; i < 4; ++i) {
9955     if (HiQuad[i] > MaxQuad) {
9956       BestHiQuad = i;
9957       MaxQuad = HiQuad[i];
9958     }
9959   }
9960
9961   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
9962   // of the two input vectors, shuffle them into one input vector so only a
9963   // single pshufb instruction is necessary. If there are more than 2 input
9964   // quads, disable the next transformation since it does not help SSSE3.
9965   bool V1Used = InputQuads[0] || InputQuads[1];
9966   bool V2Used = InputQuads[2] || InputQuads[3];
9967   if (Subtarget->hasSSSE3()) {
9968     if (InputQuads.count() == 2 && V1Used && V2Used) {
9969       BestLoQuad = InputQuads[0] ? 0 : 1;
9970       BestHiQuad = InputQuads[2] ? 2 : 3;
9971     }
9972     if (InputQuads.count() > 2) {
9973       BestLoQuad = -1;
9974       BestHiQuad = -1;
9975     }
9976   }
9977
9978   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
9979   // the shuffle mask.  If a quad is scored as -1, that means that it contains
9980   // words from all 4 input quadwords.
9981   SDValue NewV;
9982   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
9983     int MaskV[] = {
9984       BestLoQuad < 0 ? 0 : BestLoQuad,
9985       BestHiQuad < 0 ? 1 : BestHiQuad
9986     };
9987     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
9988                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
9989                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
9990     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
9991
9992     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
9993     // source words for the shuffle, to aid later transformations.
9994     bool AllWordsInNewV = true;
9995     bool InOrder[2] = { true, true };
9996     for (unsigned i = 0; i != 8; ++i) {
9997       int idx = MaskVals[i];
9998       if (idx != (int)i)
9999         InOrder[i/4] = false;
10000       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
10001         continue;
10002       AllWordsInNewV = false;
10003       break;
10004     }
10005
10006     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
10007     if (AllWordsInNewV) {
10008       for (int i = 0; i != 8; ++i) {
10009         int idx = MaskVals[i];
10010         if (idx < 0)
10011           continue;
10012         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
10013         if ((idx != i) && idx < 4)
10014           pshufhw = false;
10015         if ((idx != i) && idx > 3)
10016           pshuflw = false;
10017       }
10018       V1 = NewV;
10019       V2Used = false;
10020       BestLoQuad = 0;
10021       BestHiQuad = 1;
10022     }
10023
10024     // If we've eliminated the use of V2, and the new mask is a pshuflw or
10025     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
10026     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
10027       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
10028       unsigned TargetMask = 0;
10029       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
10030                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
10031       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10032       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
10033                              getShufflePSHUFLWImmediate(SVOp);
10034       V1 = NewV.getOperand(0);
10035       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
10036     }
10037   }
10038
10039   // Promote splats to a larger type which usually leads to more efficient code.
10040   // FIXME: Is this true if pshufb is available?
10041   if (SVOp->isSplat())
10042     return PromoteSplat(SVOp, DAG);
10043
10044   // If we have SSSE3, and all words of the result are from 1 input vector,
10045   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
10046   // is present, fall back to case 4.
10047   if (Subtarget->hasSSSE3()) {
10048     SmallVector<SDValue,16> pshufbMask;
10049
10050     // If we have elements from both input vectors, set the high bit of the
10051     // shuffle mask element to zero out elements that come from V2 in the V1
10052     // mask, and elements that come from V1 in the V2 mask, so that the two
10053     // results can be OR'd together.
10054     bool TwoInputs = V1Used && V2Used;
10055     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
10056     if (!TwoInputs)
10057       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10058
10059     // Calculate the shuffle mask for the second input, shuffle it, and
10060     // OR it with the first shuffled input.
10061     CommuteVectorShuffleMask(MaskVals, 8);
10062     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
10063     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
10064     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10065   }
10066
10067   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
10068   // and update MaskVals with new element order.
10069   std::bitset<8> InOrder;
10070   if (BestLoQuad >= 0) {
10071     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
10072     for (int i = 0; i != 4; ++i) {
10073       int idx = MaskVals[i];
10074       if (idx < 0) {
10075         InOrder.set(i);
10076       } else if ((idx / 4) == BestLoQuad) {
10077         MaskV[i] = idx & 3;
10078         InOrder.set(i);
10079       }
10080     }
10081     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
10082                                 &MaskV[0]);
10083
10084     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
10085       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10086       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
10087                                   NewV.getOperand(0),
10088                                   getShufflePSHUFLWImmediate(SVOp), DAG);
10089     }
10090   }
10091
10092   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
10093   // and update MaskVals with the new element order.
10094   if (BestHiQuad >= 0) {
10095     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
10096     for (unsigned i = 4; i != 8; ++i) {
10097       int idx = MaskVals[i];
10098       if (idx < 0) {
10099         InOrder.set(i);
10100       } else if ((idx / 4) == BestHiQuad) {
10101         MaskV[i] = (idx & 3) + 4;
10102         InOrder.set(i);
10103       }
10104     }
10105     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
10106                                 &MaskV[0]);
10107
10108     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
10109       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
10110       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
10111                                   NewV.getOperand(0),
10112                                   getShufflePSHUFHWImmediate(SVOp), DAG);
10113     }
10114   }
10115
10116   // In case BestHi & BestLo were both -1, which means each quadword has a word
10117   // from each of the four input quadwords, calculate the InOrder bitvector now
10118   // before falling through to the insert/extract cleanup.
10119   if (BestLoQuad == -1 && BestHiQuad == -1) {
10120     NewV = V1;
10121     for (int i = 0; i != 8; ++i)
10122       if (MaskVals[i] < 0 || MaskVals[i] == i)
10123         InOrder.set(i);
10124   }
10125
10126   // The other elements are put in the right place using pextrw and pinsrw.
10127   for (unsigned i = 0; i != 8; ++i) {
10128     if (InOrder[i])
10129       continue;
10130     int EltIdx = MaskVals[i];
10131     if (EltIdx < 0)
10132       continue;
10133     SDValue ExtOp = (EltIdx < 8) ?
10134       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
10135                   DAG.getIntPtrConstant(EltIdx)) :
10136       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
10137                   DAG.getIntPtrConstant(EltIdx - 8));
10138     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
10139                        DAG.getIntPtrConstant(i));
10140   }
10141   return NewV;
10142 }
10143
10144 /// \brief v16i16 shuffles
10145 ///
10146 /// FIXME: We only support generation of a single pshufb currently.  We can
10147 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
10148 /// well (e.g 2 x pshufb + 1 x por).
10149 static SDValue
10150 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
10151   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10152   SDValue V1 = SVOp->getOperand(0);
10153   SDValue V2 = SVOp->getOperand(1);
10154   SDLoc dl(SVOp);
10155
10156   if (V2.getOpcode() != ISD::UNDEF)
10157     return SDValue();
10158
10159   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
10160   return getPSHUFB(MaskVals, V1, dl, DAG);
10161 }
10162
10163 // v16i8 shuffles - Prefer shuffles in the following order:
10164 // 1. [ssse3] 1 x pshufb
10165 // 2. [ssse3] 2 x pshufb + 1 x por
10166 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
10167 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
10168                                         const X86Subtarget* Subtarget,
10169                                         SelectionDAG &DAG) {
10170   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10171   SDValue V1 = SVOp->getOperand(0);
10172   SDValue V2 = SVOp->getOperand(1);
10173   SDLoc dl(SVOp);
10174   ArrayRef<int> MaskVals = SVOp->getMask();
10175
10176   // Promote splats to a larger type which usually leads to more efficient code.
10177   // FIXME: Is this true if pshufb is available?
10178   if (SVOp->isSplat())
10179     return PromoteSplat(SVOp, DAG);
10180
10181   // If we have SSSE3, case 1 is generated when all result bytes come from
10182   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
10183   // present, fall back to case 3.
10184
10185   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
10186   if (Subtarget->hasSSSE3()) {
10187     SmallVector<SDValue,16> pshufbMask;
10188
10189     // If all result elements are from one input vector, then only translate
10190     // undef mask values to 0x80 (zero out result) in the pshufb mask.
10191     //
10192     // Otherwise, we have elements from both input vectors, and must zero out
10193     // elements that come from V2 in the first mask, and V1 in the second mask
10194     // so that we can OR them together.
10195     for (unsigned i = 0; i != 16; ++i) {
10196       int EltIdx = MaskVals[i];
10197       if (EltIdx < 0 || EltIdx >= 16)
10198         EltIdx = 0x80;
10199       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
10200     }
10201     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
10202                      DAG.getNode(ISD::BUILD_VECTOR, dl,
10203                                  MVT::v16i8, pshufbMask));
10204
10205     // As PSHUFB will zero elements with negative indices, it's safe to ignore
10206     // the 2nd operand if it's undefined or zero.
10207     if (V2.getOpcode() == ISD::UNDEF ||
10208         ISD::isBuildVectorAllZeros(V2.getNode()))
10209       return V1;
10210
10211     // Calculate the shuffle mask for the second input, shuffle it, and
10212     // OR it with the first shuffled input.
10213     pshufbMask.clear();
10214     for (unsigned i = 0; i != 16; ++i) {
10215       int EltIdx = MaskVals[i];
10216       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
10217       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
10218     }
10219     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
10220                      DAG.getNode(ISD::BUILD_VECTOR, dl,
10221                                  MVT::v16i8, pshufbMask));
10222     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
10223   }
10224
10225   // No SSSE3 - Calculate in place words and then fix all out of place words
10226   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
10227   // the 16 different words that comprise the two doublequadword input vectors.
10228   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
10229   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
10230   SDValue NewV = V1;
10231   for (int i = 0; i != 8; ++i) {
10232     int Elt0 = MaskVals[i*2];
10233     int Elt1 = MaskVals[i*2+1];
10234
10235     // This word of the result is all undef, skip it.
10236     if (Elt0 < 0 && Elt1 < 0)
10237       continue;
10238
10239     // This word of the result is already in the correct place, skip it.
10240     if ((Elt0 == i*2) && (Elt1 == i*2+1))
10241       continue;
10242
10243     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
10244     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
10245     SDValue InsElt;
10246
10247     // If Elt0 and Elt1 are defined, are consecutive, and can be load
10248     // using a single extract together, load it and store it.
10249     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
10250       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
10251                            DAG.getIntPtrConstant(Elt1 / 2));
10252       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
10253                         DAG.getIntPtrConstant(i));
10254       continue;
10255     }
10256
10257     // If Elt1 is defined, extract it from the appropriate source.  If the
10258     // source byte is not also odd, shift the extracted word left 8 bits
10259     // otherwise clear the bottom 8 bits if we need to do an or.
10260     if (Elt1 >= 0) {
10261       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
10262                            DAG.getIntPtrConstant(Elt1 / 2));
10263       if ((Elt1 & 1) == 0)
10264         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
10265                              DAG.getConstant(8,
10266                                   TLI.getShiftAmountTy(InsElt.getValueType())));
10267       else if (Elt0 >= 0)
10268         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
10269                              DAG.getConstant(0xFF00, MVT::i16));
10270     }
10271     // If Elt0 is defined, extract it from the appropriate source.  If the
10272     // source byte is not also even, shift the extracted word right 8 bits. If
10273     // Elt1 was also defined, OR the extracted values together before
10274     // inserting them in the result.
10275     if (Elt0 >= 0) {
10276       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
10277                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
10278       if ((Elt0 & 1) != 0)
10279         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
10280                               DAG.getConstant(8,
10281                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
10282       else if (Elt1 >= 0)
10283         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
10284                              DAG.getConstant(0x00FF, MVT::i16));
10285       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
10286                          : InsElt0;
10287     }
10288     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
10289                        DAG.getIntPtrConstant(i));
10290   }
10291   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
10292 }
10293
10294 // v32i8 shuffles - Translate to VPSHUFB if possible.
10295 static
10296 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
10297                                  const X86Subtarget *Subtarget,
10298                                  SelectionDAG &DAG) {
10299   MVT VT = SVOp->getSimpleValueType(0);
10300   SDValue V1 = SVOp->getOperand(0);
10301   SDValue V2 = SVOp->getOperand(1);
10302   SDLoc dl(SVOp);
10303   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
10304
10305   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10306   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
10307   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
10308
10309   // VPSHUFB may be generated if
10310   // (1) one of input vector is undefined or zeroinitializer.
10311   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
10312   // And (2) the mask indexes don't cross the 128-bit lane.
10313   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
10314       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
10315     return SDValue();
10316
10317   if (V1IsAllZero && !V2IsAllZero) {
10318     CommuteVectorShuffleMask(MaskVals, 32);
10319     V1 = V2;
10320   }
10321   return getPSHUFB(MaskVals, V1, dl, DAG);
10322 }
10323
10324 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
10325 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
10326 /// done when every pair / quad of shuffle mask elements point to elements in
10327 /// the right sequence. e.g.
10328 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
10329 static
10330 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
10331                                  SelectionDAG &DAG) {
10332   MVT VT = SVOp->getSimpleValueType(0);
10333   SDLoc dl(SVOp);
10334   unsigned NumElems = VT.getVectorNumElements();
10335   MVT NewVT;
10336   unsigned Scale;
10337   switch (VT.SimpleTy) {
10338   default: llvm_unreachable("Unexpected!");
10339   case MVT::v2i64:
10340   case MVT::v2f64:
10341            return SDValue(SVOp, 0);
10342   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
10343   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
10344   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
10345   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
10346   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
10347   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
10348   }
10349
10350   SmallVector<int, 8> MaskVec;
10351   for (unsigned i = 0; i != NumElems; i += Scale) {
10352     int StartIdx = -1;
10353     for (unsigned j = 0; j != Scale; ++j) {
10354       int EltIdx = SVOp->getMaskElt(i+j);
10355       if (EltIdx < 0)
10356         continue;
10357       if (StartIdx < 0)
10358         StartIdx = (EltIdx / Scale);
10359       if (EltIdx != (int)(StartIdx*Scale + j))
10360         return SDValue();
10361     }
10362     MaskVec.push_back(StartIdx);
10363   }
10364
10365   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
10366   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
10367   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
10368 }
10369
10370 /// getVZextMovL - Return a zero-extending vector move low node.
10371 ///
10372 static SDValue getVZextMovL(MVT VT, MVT OpVT,
10373                             SDValue SrcOp, SelectionDAG &DAG,
10374                             const X86Subtarget *Subtarget, SDLoc dl) {
10375   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
10376     LoadSDNode *LD = nullptr;
10377     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
10378       LD = dyn_cast<LoadSDNode>(SrcOp);
10379     if (!LD) {
10380       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
10381       // instead.
10382       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
10383       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
10384           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10385           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
10386           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
10387         // PR2108
10388         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
10389         return DAG.getNode(ISD::BITCAST, dl, VT,
10390                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
10391                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10392                                                    OpVT,
10393                                                    SrcOp.getOperand(0)
10394                                                           .getOperand(0))));
10395       }
10396     }
10397   }
10398
10399   return DAG.getNode(ISD::BITCAST, dl, VT,
10400                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
10401                                  DAG.getNode(ISD::BITCAST, dl,
10402                                              OpVT, SrcOp)));
10403 }
10404
10405 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
10406 /// which could not be matched by any known target speficic shuffle
10407 static SDValue
10408 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
10409
10410   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
10411   if (NewOp.getNode())
10412     return NewOp;
10413
10414   MVT VT = SVOp->getSimpleValueType(0);
10415
10416   unsigned NumElems = VT.getVectorNumElements();
10417   unsigned NumLaneElems = NumElems / 2;
10418
10419   SDLoc dl(SVOp);
10420   MVT EltVT = VT.getVectorElementType();
10421   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
10422   SDValue Output[2];
10423
10424   SmallVector<int, 16> Mask;
10425   for (unsigned l = 0; l < 2; ++l) {
10426     // Build a shuffle mask for the output, discovering on the fly which
10427     // input vectors to use as shuffle operands (recorded in InputUsed).
10428     // If building a suitable shuffle vector proves too hard, then bail
10429     // out with UseBuildVector set.
10430     bool UseBuildVector = false;
10431     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
10432     unsigned LaneStart = l * NumLaneElems;
10433     for (unsigned i = 0; i != NumLaneElems; ++i) {
10434       // The mask element.  This indexes into the input.
10435       int Idx = SVOp->getMaskElt(i+LaneStart);
10436       if (Idx < 0) {
10437         // the mask element does not index into any input vector.
10438         Mask.push_back(-1);
10439         continue;
10440       }
10441
10442       // The input vector this mask element indexes into.
10443       int Input = Idx / NumLaneElems;
10444
10445       // Turn the index into an offset from the start of the input vector.
10446       Idx -= Input * NumLaneElems;
10447
10448       // Find or create a shuffle vector operand to hold this input.
10449       unsigned OpNo;
10450       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
10451         if (InputUsed[OpNo] == Input)
10452           // This input vector is already an operand.
10453           break;
10454         if (InputUsed[OpNo] < 0) {
10455           // Create a new operand for this input vector.
10456           InputUsed[OpNo] = Input;
10457           break;
10458         }
10459       }
10460
10461       if (OpNo >= array_lengthof(InputUsed)) {
10462         // More than two input vectors used!  Give up on trying to create a
10463         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
10464         UseBuildVector = true;
10465         break;
10466       }
10467
10468       // Add the mask index for the new shuffle vector.
10469       Mask.push_back(Idx + OpNo * NumLaneElems);
10470     }
10471
10472     if (UseBuildVector) {
10473       SmallVector<SDValue, 16> SVOps;
10474       for (unsigned i = 0; i != NumLaneElems; ++i) {
10475         // The mask element.  This indexes into the input.
10476         int Idx = SVOp->getMaskElt(i+LaneStart);
10477         if (Idx < 0) {
10478           SVOps.push_back(DAG.getUNDEF(EltVT));
10479           continue;
10480         }
10481
10482         // The input vector this mask element indexes into.
10483         int Input = Idx / NumElems;
10484
10485         // Turn the index into an offset from the start of the input vector.
10486         Idx -= Input * NumElems;
10487
10488         // Extract the vector element by hand.
10489         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
10490                                     SVOp->getOperand(Input),
10491                                     DAG.getIntPtrConstant(Idx)));
10492       }
10493
10494       // Construct the output using a BUILD_VECTOR.
10495       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
10496     } else if (InputUsed[0] < 0) {
10497       // No input vectors were used! The result is undefined.
10498       Output[l] = DAG.getUNDEF(NVT);
10499     } else {
10500       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
10501                                         (InputUsed[0] % 2) * NumLaneElems,
10502                                         DAG, dl);
10503       // If only one input was used, use an undefined vector for the other.
10504       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
10505         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
10506                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
10507       // At least one input vector was used. Create a new shuffle vector.
10508       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
10509     }
10510
10511     Mask.clear();
10512   }
10513
10514   // Concatenate the result back
10515   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
10516 }
10517
10518 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
10519 /// 4 elements, and match them with several different shuffle types.
10520 static SDValue
10521 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
10522   SDValue V1 = SVOp->getOperand(0);
10523   SDValue V2 = SVOp->getOperand(1);
10524   SDLoc dl(SVOp);
10525   MVT VT = SVOp->getSimpleValueType(0);
10526
10527   assert(VT.is128BitVector() && "Unsupported vector size");
10528
10529   std::pair<int, int> Locs[4];
10530   int Mask1[] = { -1, -1, -1, -1 };
10531   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
10532
10533   unsigned NumHi = 0;
10534   unsigned NumLo = 0;
10535   for (unsigned i = 0; i != 4; ++i) {
10536     int Idx = PermMask[i];
10537     if (Idx < 0) {
10538       Locs[i] = std::make_pair(-1, -1);
10539     } else {
10540       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
10541       if (Idx < 4) {
10542         Locs[i] = std::make_pair(0, NumLo);
10543         Mask1[NumLo] = Idx;
10544         NumLo++;
10545       } else {
10546         Locs[i] = std::make_pair(1, NumHi);
10547         if (2+NumHi < 4)
10548           Mask1[2+NumHi] = Idx;
10549         NumHi++;
10550       }
10551     }
10552   }
10553
10554   if (NumLo <= 2 && NumHi <= 2) {
10555     // If no more than two elements come from either vector. This can be
10556     // implemented with two shuffles. First shuffle gather the elements.
10557     // The second shuffle, which takes the first shuffle as both of its
10558     // vector operands, put the elements into the right order.
10559     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
10560
10561     int Mask2[] = { -1, -1, -1, -1 };
10562
10563     for (unsigned i = 0; i != 4; ++i)
10564       if (Locs[i].first != -1) {
10565         unsigned Idx = (i < 2) ? 0 : 4;
10566         Idx += Locs[i].first * 2 + Locs[i].second;
10567         Mask2[i] = Idx;
10568       }
10569
10570     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
10571   }
10572
10573   if (NumLo == 3 || NumHi == 3) {
10574     // Otherwise, we must have three elements from one vector, call it X, and
10575     // one element from the other, call it Y.  First, use a shufps to build an
10576     // intermediate vector with the one element from Y and the element from X
10577     // that will be in the same half in the final destination (the indexes don't
10578     // matter). Then, use a shufps to build the final vector, taking the half
10579     // containing the element from Y from the intermediate, and the other half
10580     // from X.
10581     if (NumHi == 3) {
10582       // Normalize it so the 3 elements come from V1.
10583       CommuteVectorShuffleMask(PermMask, 4);
10584       std::swap(V1, V2);
10585     }
10586
10587     // Find the element from V2.
10588     unsigned HiIndex;
10589     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
10590       int Val = PermMask[HiIndex];
10591       if (Val < 0)
10592         continue;
10593       if (Val >= 4)
10594         break;
10595     }
10596
10597     Mask1[0] = PermMask[HiIndex];
10598     Mask1[1] = -1;
10599     Mask1[2] = PermMask[HiIndex^1];
10600     Mask1[3] = -1;
10601     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
10602
10603     if (HiIndex >= 2) {
10604       Mask1[0] = PermMask[0];
10605       Mask1[1] = PermMask[1];
10606       Mask1[2] = HiIndex & 1 ? 6 : 4;
10607       Mask1[3] = HiIndex & 1 ? 4 : 6;
10608       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
10609     }
10610
10611     Mask1[0] = HiIndex & 1 ? 2 : 0;
10612     Mask1[1] = HiIndex & 1 ? 0 : 2;
10613     Mask1[2] = PermMask[2];
10614     Mask1[3] = PermMask[3];
10615     if (Mask1[2] >= 0)
10616       Mask1[2] += 4;
10617     if (Mask1[3] >= 0)
10618       Mask1[3] += 4;
10619     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
10620   }
10621
10622   // Break it into (shuffle shuffle_hi, shuffle_lo).
10623   int LoMask[] = { -1, -1, -1, -1 };
10624   int HiMask[] = { -1, -1, -1, -1 };
10625
10626   int *MaskPtr = LoMask;
10627   unsigned MaskIdx = 0;
10628   unsigned LoIdx = 0;
10629   unsigned HiIdx = 2;
10630   for (unsigned i = 0; i != 4; ++i) {
10631     if (i == 2) {
10632       MaskPtr = HiMask;
10633       MaskIdx = 1;
10634       LoIdx = 0;
10635       HiIdx = 2;
10636     }
10637     int Idx = PermMask[i];
10638     if (Idx < 0) {
10639       Locs[i] = std::make_pair(-1, -1);
10640     } else if (Idx < 4) {
10641       Locs[i] = std::make_pair(MaskIdx, LoIdx);
10642       MaskPtr[LoIdx] = Idx;
10643       LoIdx++;
10644     } else {
10645       Locs[i] = std::make_pair(MaskIdx, HiIdx);
10646       MaskPtr[HiIdx] = Idx;
10647       HiIdx++;
10648     }
10649   }
10650
10651   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
10652   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
10653   int MaskOps[] = { -1, -1, -1, -1 };
10654   for (unsigned i = 0; i != 4; ++i)
10655     if (Locs[i].first != -1)
10656       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
10657   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
10658 }
10659
10660 static bool MayFoldVectorLoad(SDValue V) {
10661   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
10662     V = V.getOperand(0);
10663
10664   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
10665     V = V.getOperand(0);
10666   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
10667       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
10668     // BUILD_VECTOR (load), undef
10669     V = V.getOperand(0);
10670
10671   return MayFoldLoad(V);
10672 }
10673
10674 static
10675 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
10676   MVT VT = Op.getSimpleValueType();
10677
10678   // Canonizalize to v2f64.
10679   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
10680   return DAG.getNode(ISD::BITCAST, dl, VT,
10681                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
10682                                           V1, DAG));
10683 }
10684
10685 static
10686 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
10687                         bool HasSSE2) {
10688   SDValue V1 = Op.getOperand(0);
10689   SDValue V2 = Op.getOperand(1);
10690   MVT VT = Op.getSimpleValueType();
10691
10692   assert(VT != MVT::v2i64 && "unsupported shuffle type");
10693
10694   if (HasSSE2 && VT == MVT::v2f64)
10695     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
10696
10697   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
10698   return DAG.getNode(ISD::BITCAST, dl, VT,
10699                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
10700                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
10701                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
10702 }
10703
10704 static
10705 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
10706   SDValue V1 = Op.getOperand(0);
10707   SDValue V2 = Op.getOperand(1);
10708   MVT VT = Op.getSimpleValueType();
10709
10710   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
10711          "unsupported shuffle type");
10712
10713   if (V2.getOpcode() == ISD::UNDEF)
10714     V2 = V1;
10715
10716   // v4i32 or v4f32
10717   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
10718 }
10719
10720 static
10721 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
10722   SDValue V1 = Op.getOperand(0);
10723   SDValue V2 = Op.getOperand(1);
10724   MVT VT = Op.getSimpleValueType();
10725   unsigned NumElems = VT.getVectorNumElements();
10726
10727   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
10728   // operand of these instructions is only memory, so check if there's a
10729   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
10730   // same masks.
10731   bool CanFoldLoad = false;
10732
10733   // Trivial case, when V2 comes from a load.
10734   if (MayFoldVectorLoad(V2))
10735     CanFoldLoad = true;
10736
10737   // When V1 is a load, it can be folded later into a store in isel, example:
10738   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
10739   //    turns into:
10740   //  (MOVLPSmr addr:$src1, VR128:$src2)
10741   // So, recognize this potential and also use MOVLPS or MOVLPD
10742   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
10743     CanFoldLoad = true;
10744
10745   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10746   if (CanFoldLoad) {
10747     if (HasSSE2 && NumElems == 2)
10748       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
10749
10750     if (NumElems == 4)
10751       // If we don't care about the second element, proceed to use movss.
10752       if (SVOp->getMaskElt(1) != -1)
10753         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
10754   }
10755
10756   // movl and movlp will both match v2i64, but v2i64 is never matched by
10757   // movl earlier because we make it strict to avoid messing with the movlp load
10758   // folding logic (see the code above getMOVLP call). Match it here then,
10759   // this is horrible, but will stay like this until we move all shuffle
10760   // matching to x86 specific nodes. Note that for the 1st condition all
10761   // types are matched with movsd.
10762   if (HasSSE2) {
10763     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
10764     // as to remove this logic from here, as much as possible
10765     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
10766       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
10767     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
10768   }
10769
10770   assert(VT != MVT::v4i32 && "unsupported shuffle type");
10771
10772   // Invert the operand order and use SHUFPS to match it.
10773   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
10774                               getShuffleSHUFImmediate(SVOp), DAG);
10775 }
10776
10777 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
10778                                          SelectionDAG &DAG) {
10779   SDLoc dl(Load);
10780   MVT VT = Load->getSimpleValueType(0);
10781   MVT EVT = VT.getVectorElementType();
10782   SDValue Addr = Load->getOperand(1);
10783   SDValue NewAddr = DAG.getNode(
10784       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
10785       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
10786
10787   SDValue NewLoad =
10788       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
10789                   DAG.getMachineFunction().getMachineMemOperand(
10790                       Load->getMemOperand(), 0, EVT.getStoreSize()));
10791   return NewLoad;
10792 }
10793
10794 // It is only safe to call this function if isINSERTPSMask is true for
10795 // this shufflevector mask.
10796 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
10797                            SelectionDAG &DAG) {
10798   // Generate an insertps instruction when inserting an f32 from memory onto a
10799   // v4f32 or when copying a member from one v4f32 to another.
10800   // We also use it for transferring i32 from one register to another,
10801   // since it simply copies the same bits.
10802   // If we're transferring an i32 from memory to a specific element in a
10803   // register, we output a generic DAG that will match the PINSRD
10804   // instruction.
10805   MVT VT = SVOp->getSimpleValueType(0);
10806   MVT EVT = VT.getVectorElementType();
10807   SDValue V1 = SVOp->getOperand(0);
10808   SDValue V2 = SVOp->getOperand(1);
10809   auto Mask = SVOp->getMask();
10810   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
10811          "unsupported vector type for insertps/pinsrd");
10812
10813   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
10814   auto FromV2Predicate = [](const int &i) { return i >= 4; };
10815   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
10816
10817   SDValue From;
10818   SDValue To;
10819   unsigned DestIndex;
10820   if (FromV1 == 1) {
10821     From = V1;
10822     To = V2;
10823     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
10824                 Mask.begin();
10825
10826     // If we have 1 element from each vector, we have to check if we're
10827     // changing V1's element's place. If so, we're done. Otherwise, we
10828     // should assume we're changing V2's element's place and behave
10829     // accordingly.
10830     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
10831     assert(DestIndex <= INT32_MAX && "truncated destination index");
10832     if (FromV1 == FromV2 &&
10833         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
10834       From = V2;
10835       To = V1;
10836       DestIndex =
10837           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
10838     }
10839   } else {
10840     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
10841            "More than one element from V1 and from V2, or no elements from one "
10842            "of the vectors. This case should not have returned true from "
10843            "isINSERTPSMask");
10844     From = V2;
10845     To = V1;
10846     DestIndex =
10847         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
10848   }
10849
10850   // Get an index into the source vector in the range [0,4) (the mask is
10851   // in the range [0,8) because it can address V1 and V2)
10852   unsigned SrcIndex = Mask[DestIndex] % 4;
10853   if (MayFoldLoad(From)) {
10854     // Trivial case, when From comes from a load and is only used by the
10855     // shuffle. Make it use insertps from the vector that we need from that
10856     // load.
10857     SDValue NewLoad =
10858         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
10859     if (!NewLoad.getNode())
10860       return SDValue();
10861
10862     if (EVT == MVT::f32) {
10863       // Create this as a scalar to vector to match the instruction pattern.
10864       SDValue LoadScalarToVector =
10865           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
10866       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
10867       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
10868                          InsertpsMask);
10869     } else { // EVT == MVT::i32
10870       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
10871       // instruction, to match the PINSRD instruction, which loads an i32 to a
10872       // certain vector element.
10873       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
10874                          DAG.getConstant(DestIndex, MVT::i32));
10875     }
10876   }
10877
10878   // Vector-element-to-vector
10879   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
10880   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
10881 }
10882
10883 // Reduce a vector shuffle to zext.
10884 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
10885                                     SelectionDAG &DAG) {
10886   // PMOVZX is only available from SSE41.
10887   if (!Subtarget->hasSSE41())
10888     return SDValue();
10889
10890   MVT VT = Op.getSimpleValueType();
10891
10892   // Only AVX2 support 256-bit vector integer extending.
10893   if (!Subtarget->hasInt256() && VT.is256BitVector())
10894     return SDValue();
10895
10896   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10897   SDLoc DL(Op);
10898   SDValue V1 = Op.getOperand(0);
10899   SDValue V2 = Op.getOperand(1);
10900   unsigned NumElems = VT.getVectorNumElements();
10901
10902   // Extending is an unary operation and the element type of the source vector
10903   // won't be equal to or larger than i64.
10904   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
10905       VT.getVectorElementType() == MVT::i64)
10906     return SDValue();
10907
10908   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
10909   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
10910   while ((1U << Shift) < NumElems) {
10911     if (SVOp->getMaskElt(1U << Shift) == 1)
10912       break;
10913     Shift += 1;
10914     // The maximal ratio is 8, i.e. from i8 to i64.
10915     if (Shift > 3)
10916       return SDValue();
10917   }
10918
10919   // Check the shuffle mask.
10920   unsigned Mask = (1U << Shift) - 1;
10921   for (unsigned i = 0; i != NumElems; ++i) {
10922     int EltIdx = SVOp->getMaskElt(i);
10923     if ((i & Mask) != 0 && EltIdx != -1)
10924       return SDValue();
10925     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
10926       return SDValue();
10927   }
10928
10929   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
10930   MVT NeVT = MVT::getIntegerVT(NBits);
10931   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
10932
10933   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
10934     return SDValue();
10935
10936   // Simplify the operand as it's prepared to be fed into shuffle.
10937   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
10938   if (V1.getOpcode() == ISD::BITCAST &&
10939       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
10940       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
10941       V1.getOperand(0).getOperand(0)
10942         .getSimpleValueType().getSizeInBits() == SignificantBits) {
10943     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
10944     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
10945     ConstantSDNode *CIdx =
10946       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
10947     // If it's foldable, i.e. normal load with single use, we will let code
10948     // selection to fold it. Otherwise, we will short the conversion sequence.
10949     if (CIdx && CIdx->getZExtValue() == 0 &&
10950         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
10951       MVT FullVT = V.getSimpleValueType();
10952       MVT V1VT = V1.getSimpleValueType();
10953       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
10954         // The "ext_vec_elt" node is wider than the result node.
10955         // In this case we should extract subvector from V.
10956         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
10957         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
10958         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
10959                                         FullVT.getVectorNumElements()/Ratio);
10960         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
10961                         DAG.getIntPtrConstant(0));
10962       }
10963       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
10964     }
10965   }
10966
10967   return DAG.getNode(ISD::BITCAST, DL, VT,
10968                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
10969 }
10970
10971 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10972                                       SelectionDAG &DAG) {
10973   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10974   MVT VT = Op.getSimpleValueType();
10975   SDLoc dl(Op);
10976   SDValue V1 = Op.getOperand(0);
10977   SDValue V2 = Op.getOperand(1);
10978
10979   if (isZeroShuffle(SVOp))
10980     return getZeroVector(VT, Subtarget, DAG, dl);
10981
10982   // Handle splat operations
10983   if (SVOp->isSplat()) {
10984     // Use vbroadcast whenever the splat comes from a foldable load
10985     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
10986     if (Broadcast.getNode())
10987       return Broadcast;
10988   }
10989
10990   // Check integer expanding shuffles.
10991   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
10992   if (NewOp.getNode())
10993     return NewOp;
10994
10995   // If the shuffle can be profitably rewritten as a narrower shuffle, then
10996   // do it!
10997   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
10998       VT == MVT::v32i8) {
10999     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11000     if (NewOp.getNode())
11001       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
11002   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
11003     // FIXME: Figure out a cleaner way to do this.
11004     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
11005       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11006       if (NewOp.getNode()) {
11007         MVT NewVT = NewOp.getSimpleValueType();
11008         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
11009                                NewVT, true, false))
11010           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
11011                               dl);
11012       }
11013     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
11014       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
11015       if (NewOp.getNode()) {
11016         MVT NewVT = NewOp.getSimpleValueType();
11017         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
11018           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
11019                               dl);
11020       }
11021     }
11022   }
11023   return SDValue();
11024 }
11025
11026 SDValue
11027 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
11028   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
11029   SDValue V1 = Op.getOperand(0);
11030   SDValue V2 = Op.getOperand(1);
11031   MVT VT = Op.getSimpleValueType();
11032   SDLoc dl(Op);
11033   unsigned NumElems = VT.getVectorNumElements();
11034   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
11035   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
11036   bool V1IsSplat = false;
11037   bool V2IsSplat = false;
11038   bool HasSSE2 = Subtarget->hasSSE2();
11039   bool HasFp256    = Subtarget->hasFp256();
11040   bool HasInt256   = Subtarget->hasInt256();
11041   MachineFunction &MF = DAG.getMachineFunction();
11042   bool OptForSize = MF.getFunction()->getAttributes().
11043     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
11044
11045   // Check if we should use the experimental vector shuffle lowering. If so,
11046   // delegate completely to that code path.
11047   if (ExperimentalVectorShuffleLowering)
11048     return lowerVectorShuffle(Op, Subtarget, DAG);
11049
11050   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
11051
11052   if (V1IsUndef && V2IsUndef)
11053     return DAG.getUNDEF(VT);
11054
11055   // When we create a shuffle node we put the UNDEF node to second operand,
11056   // but in some cases the first operand may be transformed to UNDEF.
11057   // In this case we should just commute the node.
11058   if (V1IsUndef)
11059     return DAG.getCommutedVectorShuffle(*SVOp);
11060
11061   // Vector shuffle lowering takes 3 steps:
11062   //
11063   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
11064   //    narrowing and commutation of operands should be handled.
11065   // 2) Matching of shuffles with known shuffle masks to x86 target specific
11066   //    shuffle nodes.
11067   // 3) Rewriting of unmatched masks into new generic shuffle operations,
11068   //    so the shuffle can be broken into other shuffles and the legalizer can
11069   //    try the lowering again.
11070   //
11071   // The general idea is that no vector_shuffle operation should be left to
11072   // be matched during isel, all of them must be converted to a target specific
11073   // node here.
11074
11075   // Normalize the input vectors. Here splats, zeroed vectors, profitable
11076   // narrowing and commutation of operands should be handled. The actual code
11077   // doesn't include all of those, work in progress...
11078   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
11079   if (NewOp.getNode())
11080     return NewOp;
11081
11082   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
11083
11084   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
11085   // unpckh_undef). Only use pshufd if speed is more important than size.
11086   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
11087     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
11088   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
11089     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
11090
11091   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
11092       V2IsUndef && MayFoldVectorLoad(V1))
11093     return getMOVDDup(Op, dl, V1, DAG);
11094
11095   if (isMOVHLPS_v_undef_Mask(M, VT))
11096     return getMOVHighToLow(Op, dl, DAG);
11097
11098   // Use to match splats
11099   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
11100       (VT == MVT::v2f64 || VT == MVT::v2i64))
11101     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
11102
11103   if (isPSHUFDMask(M, VT)) {
11104     // The actual implementation will match the mask in the if above and then
11105     // during isel it can match several different instructions, not only pshufd
11106     // as its name says, sad but true, emulate the behavior for now...
11107     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
11108       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
11109
11110     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
11111
11112     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
11113       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
11114
11115     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
11116       return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1, TargetMask,
11117                                   DAG);
11118
11119     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
11120                                 TargetMask, DAG);
11121   }
11122
11123   if (isPALIGNRMask(M, VT, Subtarget))
11124     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
11125                                 getShufflePALIGNRImmediate(SVOp),
11126                                 DAG);
11127
11128   if (isVALIGNMask(M, VT, Subtarget))
11129     return getTargetShuffleNode(X86ISD::VALIGN, dl, VT, V1, V2,
11130                                 getShuffleVALIGNImmediate(SVOp),
11131                                 DAG);
11132
11133   // Check if this can be converted into a logical shift.
11134   bool isLeft = false;
11135   unsigned ShAmt = 0;
11136   SDValue ShVal;
11137   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
11138   if (isShift && ShVal.hasOneUse()) {
11139     // If the shifted value has multiple uses, it may be cheaper to use
11140     // v_set0 + movlhps or movhlps, etc.
11141     MVT EltVT = VT.getVectorElementType();
11142     ShAmt *= EltVT.getSizeInBits();
11143     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
11144   }
11145
11146   if (isMOVLMask(M, VT)) {
11147     if (ISD::isBuildVectorAllZeros(V1.getNode()))
11148       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
11149     if (!isMOVLPMask(M, VT)) {
11150       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
11151         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
11152
11153       if (VT == MVT::v4i32 || VT == MVT::v4f32)
11154         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
11155     }
11156   }
11157
11158   // FIXME: fold these into legal mask.
11159   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
11160     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
11161
11162   if (isMOVHLPSMask(M, VT))
11163     return getMOVHighToLow(Op, dl, DAG);
11164
11165   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
11166     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
11167
11168   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
11169     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
11170
11171   if (isMOVLPMask(M, VT))
11172     return getMOVLP(Op, dl, DAG, HasSSE2);
11173
11174   if (ShouldXformToMOVHLPS(M, VT) ||
11175       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
11176     return DAG.getCommutedVectorShuffle(*SVOp);
11177
11178   if (isShift) {
11179     // No better options. Use a vshldq / vsrldq.
11180     MVT EltVT = VT.getVectorElementType();
11181     ShAmt *= EltVT.getSizeInBits();
11182     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
11183   }
11184
11185   bool Commuted = false;
11186   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
11187   // 1,1,1,1 -> v8i16 though.
11188   BitVector UndefElements;
11189   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
11190     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
11191       V1IsSplat = true;
11192   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
11193     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
11194       V2IsSplat = true;
11195
11196   // Canonicalize the splat or undef, if present, to be on the RHS.
11197   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
11198     CommuteVectorShuffleMask(M, NumElems);
11199     std::swap(V1, V2);
11200     std::swap(V1IsSplat, V2IsSplat);
11201     Commuted = true;
11202   }
11203
11204   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
11205     // Shuffling low element of v1 into undef, just return v1.
11206     if (V2IsUndef)
11207       return V1;
11208     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
11209     // the instruction selector will not match, so get a canonical MOVL with
11210     // swapped operands to undo the commute.
11211     return getMOVL(DAG, dl, VT, V2, V1);
11212   }
11213
11214   if (isUNPCKLMask(M, VT, HasInt256))
11215     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11216
11217   if (isUNPCKHMask(M, VT, HasInt256))
11218     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
11219
11220   if (V2IsSplat) {
11221     // Normalize mask so all entries that point to V2 points to its first
11222     // element then try to match unpck{h|l} again. If match, return a
11223     // new vector_shuffle with the corrected mask.p
11224     SmallVector<int, 8> NewMask(M.begin(), M.end());
11225     NormalizeMask(NewMask, NumElems);
11226     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
11227       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11228     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
11229       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
11230   }
11231
11232   if (Commuted) {
11233     // Commute is back and try unpck* again.
11234     // FIXME: this seems wrong.
11235     CommuteVectorShuffleMask(M, NumElems);
11236     std::swap(V1, V2);
11237     std::swap(V1IsSplat, V2IsSplat);
11238
11239     if (isUNPCKLMask(M, VT, HasInt256))
11240       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
11241
11242     if (isUNPCKHMask(M, VT, HasInt256))
11243       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
11244   }
11245
11246   // Normalize the node to match x86 shuffle ops if needed
11247   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
11248     return DAG.getCommutedVectorShuffle(*SVOp);
11249
11250   // The checks below are all present in isShuffleMaskLegal, but they are
11251   // inlined here right now to enable us to directly emit target specific
11252   // nodes, and remove one by one until they don't return Op anymore.
11253
11254   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
11255       SVOp->getSplatIndex() == 0 && V2IsUndef) {
11256     if (VT == MVT::v2f64 || VT == MVT::v2i64)
11257       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
11258   }
11259
11260   if (isPSHUFHWMask(M, VT, HasInt256))
11261     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
11262                                 getShufflePSHUFHWImmediate(SVOp),
11263                                 DAG);
11264
11265   if (isPSHUFLWMask(M, VT, HasInt256))
11266     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
11267                                 getShufflePSHUFLWImmediate(SVOp),
11268                                 DAG);
11269
11270   unsigned MaskValue;
11271   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
11272                   &MaskValue))
11273     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
11274
11275   if (isSHUFPMask(M, VT))
11276     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
11277                                 getShuffleSHUFImmediate(SVOp), DAG);
11278
11279   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
11280     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
11281   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
11282     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
11283
11284   //===--------------------------------------------------------------------===//
11285   // Generate target specific nodes for 128 or 256-bit shuffles only
11286   // supported in the AVX instruction set.
11287   //
11288
11289   // Handle VMOVDDUPY permutations
11290   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
11291     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
11292
11293   // Handle VPERMILPS/D* permutations
11294   if (isVPERMILPMask(M, VT)) {
11295     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
11296       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
11297                                   getShuffleSHUFImmediate(SVOp), DAG);
11298     return getTargetShuffleNode(X86ISD::VPERMILPI, dl, VT, V1,
11299                                 getShuffleSHUFImmediate(SVOp), DAG);
11300   }
11301
11302   unsigned Idx;
11303   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
11304     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
11305                               Idx*(NumElems/2), DAG, dl);
11306
11307   // Handle VPERM2F128/VPERM2I128 permutations
11308   if (isVPERM2X128Mask(M, VT, HasFp256))
11309     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
11310                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
11311
11312   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
11313     return getINSERTPS(SVOp, dl, DAG);
11314
11315   unsigned Imm8;
11316   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
11317     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
11318
11319   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
11320       VT.is512BitVector()) {
11321     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
11322     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
11323     SmallVector<SDValue, 16> permclMask;
11324     for (unsigned i = 0; i != NumElems; ++i) {
11325       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
11326     }
11327
11328     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
11329     if (V2IsUndef)
11330       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
11331       return DAG.getNode(X86ISD::VPERMV, dl, VT,
11332                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
11333     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
11334                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
11335   }
11336
11337   //===--------------------------------------------------------------------===//
11338   // Since no target specific shuffle was selected for this generic one,
11339   // lower it into other known shuffles. FIXME: this isn't true yet, but
11340   // this is the plan.
11341   //
11342
11343   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
11344   if (VT == MVT::v8i16) {
11345     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
11346     if (NewOp.getNode())
11347       return NewOp;
11348   }
11349
11350   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
11351     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
11352     if (NewOp.getNode())
11353       return NewOp;
11354   }
11355
11356   if (VT == MVT::v16i8) {
11357     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
11358     if (NewOp.getNode())
11359       return NewOp;
11360   }
11361
11362   if (VT == MVT::v32i8) {
11363     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
11364     if (NewOp.getNode())
11365       return NewOp;
11366   }
11367
11368   // Handle all 128-bit wide vectors with 4 elements, and match them with
11369   // several different shuffle types.
11370   if (NumElems == 4 && VT.is128BitVector())
11371     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
11372
11373   // Handle general 256-bit shuffles
11374   if (VT.is256BitVector())
11375     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
11376
11377   return SDValue();
11378 }
11379
11380 // This function assumes its argument is a BUILD_VECTOR of constants or
11381 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
11382 // true.
11383 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
11384                                     unsigned &MaskValue) {
11385   MaskValue = 0;
11386   unsigned NumElems = BuildVector->getNumOperands();
11387   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
11388   unsigned NumLanes = (NumElems - 1) / 8 + 1;
11389   unsigned NumElemsInLane = NumElems / NumLanes;
11390
11391   // Blend for v16i16 should be symetric for the both lanes.
11392   for (unsigned i = 0; i < NumElemsInLane; ++i) {
11393     SDValue EltCond = BuildVector->getOperand(i);
11394     SDValue SndLaneEltCond =
11395         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
11396
11397     int Lane1Cond = -1, Lane2Cond = -1;
11398     if (isa<ConstantSDNode>(EltCond))
11399       Lane1Cond = !isZero(EltCond);
11400     if (isa<ConstantSDNode>(SndLaneEltCond))
11401       Lane2Cond = !isZero(SndLaneEltCond);
11402
11403     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
11404       // Lane1Cond != 0, means we want the first argument.
11405       // Lane1Cond == 0, means we want the second argument.
11406       // The encoding of this argument is 0 for the first argument, 1
11407       // for the second. Therefore, invert the condition.
11408       MaskValue |= !Lane1Cond << i;
11409     else if (Lane1Cond < 0)
11410       MaskValue |= !Lane2Cond << i;
11411     else
11412       return false;
11413   }
11414   return true;
11415 }
11416
11417 // Try to lower a vselect node into a simple blend instruction.
11418 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
11419                                    SelectionDAG &DAG) {
11420   SDValue Cond = Op.getOperand(0);
11421   SDValue LHS = Op.getOperand(1);
11422   SDValue RHS = Op.getOperand(2);
11423   SDLoc dl(Op);
11424   MVT VT = Op.getSimpleValueType();
11425   MVT EltVT = VT.getVectorElementType();
11426   unsigned NumElems = VT.getVectorNumElements();
11427
11428   // There is no blend with immediate in AVX-512.
11429   if (VT.is512BitVector())
11430     return SDValue();
11431
11432   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
11433     return SDValue();
11434   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
11435     return SDValue();
11436
11437   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
11438     return SDValue();
11439
11440   // Check the mask for BLEND and build the value.
11441   unsigned MaskValue = 0;
11442   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
11443     return SDValue();
11444
11445   // Convert i32 vectors to floating point if it is not AVX2.
11446   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
11447   MVT BlendVT = VT;
11448   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
11449     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
11450                                NumElems);
11451     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
11452     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
11453   }
11454
11455   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
11456                             DAG.getConstant(MaskValue, MVT::i32));
11457   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
11458 }
11459
11460 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
11461   // A vselect where all conditions and data are constants can be optimized into
11462   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
11463   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
11464       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
11465       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
11466     return SDValue();
11467   
11468   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
11469   if (BlendOp.getNode())
11470     return BlendOp;
11471
11472   // Some types for vselect were previously set to Expand, not Legal or
11473   // Custom. Return an empty SDValue so we fall-through to Expand, after
11474   // the Custom lowering phase.
11475   MVT VT = Op.getSimpleValueType();
11476   switch (VT.SimpleTy) {
11477   default:
11478     break;
11479   case MVT::v8i16:
11480   case MVT::v16i16:
11481     if (Subtarget->hasBWI() && Subtarget->hasVLX())
11482       break;
11483     return SDValue();
11484   }
11485
11486   // We couldn't create a "Blend with immediate" node.
11487   // This node should still be legal, but we'll have to emit a blendv*
11488   // instruction.
11489   return Op;
11490 }
11491
11492 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
11493   MVT VT = Op.getSimpleValueType();
11494   SDLoc dl(Op);
11495
11496   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
11497     return SDValue();
11498
11499   if (VT.getSizeInBits() == 8) {
11500     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
11501                                   Op.getOperand(0), Op.getOperand(1));
11502     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11503                                   DAG.getValueType(VT));
11504     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11505   }
11506
11507   if (VT.getSizeInBits() == 16) {
11508     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11509     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
11510     if (Idx == 0)
11511       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11512                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11513                                      DAG.getNode(ISD::BITCAST, dl,
11514                                                  MVT::v4i32,
11515                                                  Op.getOperand(0)),
11516                                      Op.getOperand(1)));
11517     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
11518                                   Op.getOperand(0), Op.getOperand(1));
11519     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
11520                                   DAG.getValueType(VT));
11521     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11522   }
11523
11524   if (VT == MVT::f32) {
11525     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
11526     // the result back to FR32 register. It's only worth matching if the
11527     // result has a single use which is a store or a bitcast to i32.  And in
11528     // the case of a store, it's not worth it if the index is a constant 0,
11529     // because a MOVSSmr can be used instead, which is smaller and faster.
11530     if (!Op.hasOneUse())
11531       return SDValue();
11532     SDNode *User = *Op.getNode()->use_begin();
11533     if ((User->getOpcode() != ISD::STORE ||
11534          (isa<ConstantSDNode>(Op.getOperand(1)) &&
11535           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
11536         (User->getOpcode() != ISD::BITCAST ||
11537          User->getValueType(0) != MVT::i32))
11538       return SDValue();
11539     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11540                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
11541                                               Op.getOperand(0)),
11542                                               Op.getOperand(1));
11543     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
11544   }
11545
11546   if (VT == MVT::i32 || VT == MVT::i64) {
11547     // ExtractPS/pextrq works with constant index.
11548     if (isa<ConstantSDNode>(Op.getOperand(1)))
11549       return Op;
11550   }
11551   return SDValue();
11552 }
11553
11554 /// Extract one bit from mask vector, like v16i1 or v8i1.
11555 /// AVX-512 feature.
11556 SDValue
11557 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
11558   SDValue Vec = Op.getOperand(0);
11559   SDLoc dl(Vec);
11560   MVT VecVT = Vec.getSimpleValueType();
11561   SDValue Idx = Op.getOperand(1);
11562   MVT EltVT = Op.getSimpleValueType();
11563
11564   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
11565
11566   // variable index can't be handled in mask registers,
11567   // extend vector to VR512
11568   if (!isa<ConstantSDNode>(Idx)) {
11569     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11570     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
11571     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
11572                               ExtVT.getVectorElementType(), Ext, Idx);
11573     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
11574   }
11575
11576   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11577   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11578   unsigned MaxSift = rc->getSize()*8 - 1;
11579   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
11580                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
11581   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
11582                     DAG.getConstant(MaxSift, MVT::i8));
11583   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
11584                        DAG.getIntPtrConstant(0));
11585 }
11586
11587 SDValue
11588 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
11589                                            SelectionDAG &DAG) const {
11590   SDLoc dl(Op);
11591   SDValue Vec = Op.getOperand(0);
11592   MVT VecVT = Vec.getSimpleValueType();
11593   SDValue Idx = Op.getOperand(1);
11594
11595   if (Op.getSimpleValueType() == MVT::i1)
11596     return ExtractBitFromMaskVector(Op, DAG);
11597
11598   if (!isa<ConstantSDNode>(Idx)) {
11599     if (VecVT.is512BitVector() ||
11600         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
11601          VecVT.getVectorElementType().getSizeInBits() == 32)) {
11602
11603       MVT MaskEltVT =
11604         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
11605       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
11606                                     MaskEltVT.getSizeInBits());
11607
11608       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
11609       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
11610                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
11611                                 Idx, DAG.getConstant(0, getPointerTy()));
11612       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
11613       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
11614                         Perm, DAG.getConstant(0, getPointerTy()));
11615     }
11616     return SDValue();
11617   }
11618
11619   // If this is a 256-bit vector result, first extract the 128-bit vector and
11620   // then extract the element from the 128-bit vector.
11621   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
11622
11623     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11624     // Get the 128-bit vector.
11625     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
11626     MVT EltVT = VecVT.getVectorElementType();
11627
11628     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
11629
11630     //if (IdxVal >= NumElems/2)
11631     //  IdxVal -= NumElems/2;
11632     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
11633     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
11634                        DAG.getConstant(IdxVal, MVT::i32));
11635   }
11636
11637   assert(VecVT.is128BitVector() && "Unexpected vector length");
11638
11639   if (Subtarget->hasSSE41()) {
11640     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
11641     if (Res.getNode())
11642       return Res;
11643   }
11644
11645   MVT VT = Op.getSimpleValueType();
11646   // TODO: handle v16i8.
11647   if (VT.getSizeInBits() == 16) {
11648     SDValue Vec = Op.getOperand(0);
11649     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11650     if (Idx == 0)
11651       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
11652                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
11653                                      DAG.getNode(ISD::BITCAST, dl,
11654                                                  MVT::v4i32, Vec),
11655                                      Op.getOperand(1)));
11656     // Transform it so it match pextrw which produces a 32-bit result.
11657     MVT EltVT = MVT::i32;
11658     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
11659                                   Op.getOperand(0), Op.getOperand(1));
11660     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
11661                                   DAG.getValueType(VT));
11662     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
11663   }
11664
11665   if (VT.getSizeInBits() == 32) {
11666     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11667     if (Idx == 0)
11668       return Op;
11669
11670     // SHUFPS the element to the lowest double word, then movss.
11671     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
11672     MVT VVT = Op.getOperand(0).getSimpleValueType();
11673     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11674                                        DAG.getUNDEF(VVT), Mask);
11675     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11676                        DAG.getIntPtrConstant(0));
11677   }
11678
11679   if (VT.getSizeInBits() == 64) {
11680     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11681     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11682     //        to match extract_elt for f64.
11683     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11684     if (Idx == 0)
11685       return Op;
11686
11687     // UNPCKHPD the element to the lowest double word, then movsd.
11688     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11689     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11690     int Mask[2] = { 1, -1 };
11691     MVT VVT = Op.getOperand(0).getSimpleValueType();
11692     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11693                                        DAG.getUNDEF(VVT), Mask);
11694     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11695                        DAG.getIntPtrConstant(0));
11696   }
11697
11698   return SDValue();
11699 }
11700
11701 /// Insert one bit to mask vector, like v16i1 or v8i1.
11702 /// AVX-512 feature.
11703 SDValue 
11704 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11705   SDLoc dl(Op);
11706   SDValue Vec = Op.getOperand(0);
11707   SDValue Elt = Op.getOperand(1);
11708   SDValue Idx = Op.getOperand(2);
11709   MVT VecVT = Vec.getSimpleValueType();
11710
11711   if (!isa<ConstantSDNode>(Idx)) {
11712     // Non constant index. Extend source and destination,
11713     // insert element and then truncate the result.
11714     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11715     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11716     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
11717       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11718       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11719     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11720   }
11721
11722   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11723   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11724   if (Vec.getOpcode() == ISD::UNDEF)
11725     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11726                        DAG.getConstant(IdxVal, MVT::i8));
11727   const TargetRegisterClass* rc = getRegClassFor(VecVT);
11728   unsigned MaxSift = rc->getSize()*8 - 1;
11729   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11730                     DAG.getConstant(MaxSift, MVT::i8));
11731   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
11732                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
11733   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11734 }
11735
11736 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11737                                                   SelectionDAG &DAG) const {
11738   MVT VT = Op.getSimpleValueType();
11739   MVT EltVT = VT.getVectorElementType();
11740
11741   if (EltVT == MVT::i1)
11742     return InsertBitToMaskVector(Op, DAG);
11743
11744   SDLoc dl(Op);
11745   SDValue N0 = Op.getOperand(0);
11746   SDValue N1 = Op.getOperand(1);
11747   SDValue N2 = Op.getOperand(2);
11748   if (!isa<ConstantSDNode>(N2))
11749     return SDValue();
11750   auto *N2C = cast<ConstantSDNode>(N2);
11751   unsigned IdxVal = N2C->getZExtValue();
11752
11753   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11754   // into that, and then insert the subvector back into the result.
11755   if (VT.is256BitVector() || VT.is512BitVector()) {
11756     // Get the desired 128-bit vector half.
11757     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11758
11759     // Insert the element into the desired half.
11760     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11761     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11762
11763     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11764                     DAG.getConstant(IdxIn128, MVT::i32));
11765
11766     // Insert the changed part back to the 256-bit vector
11767     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11768   }
11769   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11770
11771   if (Subtarget->hasSSE41()) {
11772     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11773       unsigned Opc;
11774       if (VT == MVT::v8i16) {
11775         Opc = X86ISD::PINSRW;
11776       } else {
11777         assert(VT == MVT::v16i8);
11778         Opc = X86ISD::PINSRB;
11779       }
11780
11781       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11782       // argument.
11783       if (N1.getValueType() != MVT::i32)
11784         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11785       if (N2.getValueType() != MVT::i32)
11786         N2 = DAG.getIntPtrConstant(IdxVal);
11787       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11788     }
11789
11790     if (EltVT == MVT::f32) {
11791       // Bits [7:6] of the constant are the source select.  This will always be
11792       //  zero here.  The DAG Combiner may combine an extract_elt index into
11793       //  these
11794       //  bits.  For example (insert (extract, 3), 2) could be matched by
11795       //  putting
11796       //  the '3' into bits [7:6] of X86ISD::INSERTPS.
11797       // Bits [5:4] of the constant are the destination select.  This is the
11798       //  value of the incoming immediate.
11799       // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
11800       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11801       N2 = DAG.getIntPtrConstant(IdxVal << 4);
11802       // Create this as a scalar to vector..
11803       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11804       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11805     }
11806
11807     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11808       // PINSR* works with constant index.
11809       return Op;
11810     }
11811   }
11812
11813   if (EltVT == MVT::i8)
11814     return SDValue();
11815
11816   if (EltVT.getSizeInBits() == 16) {
11817     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11818     // as its second argument.
11819     if (N1.getValueType() != MVT::i32)
11820       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11821     if (N2.getValueType() != MVT::i32)
11822       N2 = DAG.getIntPtrConstant(IdxVal);
11823     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11824   }
11825   return SDValue();
11826 }
11827
11828 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11829   SDLoc dl(Op);
11830   MVT OpVT = Op.getSimpleValueType();
11831
11832   // If this is a 256-bit vector result, first insert into a 128-bit
11833   // vector and then insert into the 256-bit vector.
11834   if (!OpVT.is128BitVector()) {
11835     // Insert into a 128-bit vector.
11836     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11837     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11838                                  OpVT.getVectorNumElements() / SizeFactor);
11839
11840     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11841
11842     // Insert the 128-bit vector.
11843     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11844   }
11845
11846   if (OpVT == MVT::v1i64 &&
11847       Op.getOperand(0).getValueType() == MVT::i64)
11848     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11849
11850   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11851   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11852   return DAG.getNode(ISD::BITCAST, dl, OpVT,
11853                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
11854 }
11855
11856 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11857 // a simple subregister reference or explicit instructions to grab
11858 // upper bits of a vector.
11859 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11860                                       SelectionDAG &DAG) {
11861   SDLoc dl(Op);
11862   SDValue In =  Op.getOperand(0);
11863   SDValue Idx = Op.getOperand(1);
11864   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11865   MVT ResVT   = Op.getSimpleValueType();
11866   MVT InVT    = In.getSimpleValueType();
11867
11868   if (Subtarget->hasFp256()) {
11869     if (ResVT.is128BitVector() &&
11870         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11871         isa<ConstantSDNode>(Idx)) {
11872       return Extract128BitVector(In, IdxVal, DAG, dl);
11873     }
11874     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11875         isa<ConstantSDNode>(Idx)) {
11876       return Extract256BitVector(In, IdxVal, DAG, dl);
11877     }
11878   }
11879   return SDValue();
11880 }
11881
11882 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11883 // simple superregister reference or explicit instructions to insert
11884 // the upper bits of a vector.
11885 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11886                                      SelectionDAG &DAG) {
11887   if (Subtarget->hasFp256()) {
11888     SDLoc dl(Op.getNode());
11889     SDValue Vec = Op.getNode()->getOperand(0);
11890     SDValue SubVec = Op.getNode()->getOperand(1);
11891     SDValue Idx = Op.getNode()->getOperand(2);
11892
11893     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
11894          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
11895         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
11896         isa<ConstantSDNode>(Idx)) {
11897       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11898       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11899     }
11900
11901     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
11902         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
11903         isa<ConstantSDNode>(Idx)) {
11904       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11905       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11906     }
11907   }
11908   return SDValue();
11909 }
11910
11911 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11912 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11913 // one of the above mentioned nodes. It has to be wrapped because otherwise
11914 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11915 // be used to form addressing mode. These wrapped nodes will be selected
11916 // into MOV32ri.
11917 SDValue
11918 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11919   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11920
11921   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11922   // global base reg.
11923   unsigned char OpFlag = 0;
11924   unsigned WrapperKind = X86ISD::Wrapper;
11925   CodeModel::Model M = DAG.getTarget().getCodeModel();
11926
11927   if (Subtarget->isPICStyleRIPRel() &&
11928       (M == CodeModel::Small || M == CodeModel::Kernel))
11929     WrapperKind = X86ISD::WrapperRIP;
11930   else if (Subtarget->isPICStyleGOT())
11931     OpFlag = X86II::MO_GOTOFF;
11932   else if (Subtarget->isPICStyleStubPIC())
11933     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11934
11935   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11936                                              CP->getAlignment(),
11937                                              CP->getOffset(), OpFlag);
11938   SDLoc DL(CP);
11939   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11940   // With PIC, the address is actually $g + Offset.
11941   if (OpFlag) {
11942     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11943                          DAG.getNode(X86ISD::GlobalBaseReg,
11944                                      SDLoc(), getPointerTy()),
11945                          Result);
11946   }
11947
11948   return Result;
11949 }
11950
11951 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11952   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11953
11954   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11955   // global base reg.
11956   unsigned char OpFlag = 0;
11957   unsigned WrapperKind = X86ISD::Wrapper;
11958   CodeModel::Model M = DAG.getTarget().getCodeModel();
11959
11960   if (Subtarget->isPICStyleRIPRel() &&
11961       (M == CodeModel::Small || M == CodeModel::Kernel))
11962     WrapperKind = X86ISD::WrapperRIP;
11963   else if (Subtarget->isPICStyleGOT())
11964     OpFlag = X86II::MO_GOTOFF;
11965   else if (Subtarget->isPICStyleStubPIC())
11966     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11967
11968   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11969                                           OpFlag);
11970   SDLoc DL(JT);
11971   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11972
11973   // With PIC, the address is actually $g + Offset.
11974   if (OpFlag)
11975     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11976                          DAG.getNode(X86ISD::GlobalBaseReg,
11977                                      SDLoc(), getPointerTy()),
11978                          Result);
11979
11980   return Result;
11981 }
11982
11983 SDValue
11984 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11985   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11986
11987   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11988   // global base reg.
11989   unsigned char OpFlag = 0;
11990   unsigned WrapperKind = X86ISD::Wrapper;
11991   CodeModel::Model M = DAG.getTarget().getCodeModel();
11992
11993   if (Subtarget->isPICStyleRIPRel() &&
11994       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11995     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11996       OpFlag = X86II::MO_GOTPCREL;
11997     WrapperKind = X86ISD::WrapperRIP;
11998   } else if (Subtarget->isPICStyleGOT()) {
11999     OpFlag = X86II::MO_GOT;
12000   } else if (Subtarget->isPICStyleStubPIC()) {
12001     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
12002   } else if (Subtarget->isPICStyleStubNoDynamic()) {
12003     OpFlag = X86II::MO_DARWIN_NONLAZY;
12004   }
12005
12006   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
12007
12008   SDLoc DL(Op);
12009   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
12010
12011   // With PIC, the address is actually $g + Offset.
12012   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
12013       !Subtarget->is64Bit()) {
12014     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12015                          DAG.getNode(X86ISD::GlobalBaseReg,
12016                                      SDLoc(), getPointerTy()),
12017                          Result);
12018   }
12019
12020   // For symbols that require a load from a stub to get the address, emit the
12021   // load.
12022   if (isGlobalStubReference(OpFlag))
12023     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
12024                          MachinePointerInfo::getGOT(), false, false, false, 0);
12025
12026   return Result;
12027 }
12028
12029 SDValue
12030 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
12031   // Create the TargetBlockAddressAddress node.
12032   unsigned char OpFlags =
12033     Subtarget->ClassifyBlockAddressReference();
12034   CodeModel::Model M = DAG.getTarget().getCodeModel();
12035   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
12036   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
12037   SDLoc dl(Op);
12038   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
12039                                              OpFlags);
12040
12041   if (Subtarget->isPICStyleRIPRel() &&
12042       (M == CodeModel::Small || M == CodeModel::Kernel))
12043     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
12044   else
12045     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
12046
12047   // With PIC, the address is actually $g + Offset.
12048   if (isGlobalRelativeToPICBase(OpFlags)) {
12049     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
12050                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
12051                          Result);
12052   }
12053
12054   return Result;
12055 }
12056
12057 SDValue
12058 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
12059                                       int64_t Offset, SelectionDAG &DAG) const {
12060   // Create the TargetGlobalAddress node, folding in the constant
12061   // offset if it is legal.
12062   unsigned char OpFlags =
12063       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
12064   CodeModel::Model M = DAG.getTarget().getCodeModel();
12065   SDValue Result;
12066   if (OpFlags == X86II::MO_NO_FLAG &&
12067       X86::isOffsetSuitableForCodeModel(Offset, M)) {
12068     // A direct static reference to a global.
12069     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
12070     Offset = 0;
12071   } else {
12072     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
12073   }
12074
12075   if (Subtarget->isPICStyleRIPRel() &&
12076       (M == CodeModel::Small || M == CodeModel::Kernel))
12077     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
12078   else
12079     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
12080
12081   // With PIC, the address is actually $g + Offset.
12082   if (isGlobalRelativeToPICBase(OpFlags)) {
12083     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
12084                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
12085                          Result);
12086   }
12087
12088   // For globals that require a load from a stub to get the address, emit the
12089   // load.
12090   if (isGlobalStubReference(OpFlags))
12091     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
12092                          MachinePointerInfo::getGOT(), false, false, false, 0);
12093
12094   // If there was a non-zero offset that we didn't fold, create an explicit
12095   // addition for it.
12096   if (Offset != 0)
12097     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
12098                          DAG.getConstant(Offset, getPointerTy()));
12099
12100   return Result;
12101 }
12102
12103 SDValue
12104 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
12105   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
12106   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
12107   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
12108 }
12109
12110 static SDValue
12111 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
12112            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
12113            unsigned char OperandFlags, bool LocalDynamic = false) {
12114   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12115   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12116   SDLoc dl(GA);
12117   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12118                                            GA->getValueType(0),
12119                                            GA->getOffset(),
12120                                            OperandFlags);
12121
12122   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
12123                                            : X86ISD::TLSADDR;
12124
12125   if (InFlag) {
12126     SDValue Ops[] = { Chain,  TGA, *InFlag };
12127     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12128   } else {
12129     SDValue Ops[]  = { Chain, TGA };
12130     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
12131   }
12132
12133   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
12134   MFI->setAdjustsStack(true);
12135
12136   SDValue Flag = Chain.getValue(1);
12137   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
12138 }
12139
12140 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
12141 static SDValue
12142 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12143                                 const EVT PtrVT) {
12144   SDValue InFlag;
12145   SDLoc dl(GA);  // ? function entry point might be better
12146   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12147                                    DAG.getNode(X86ISD::GlobalBaseReg,
12148                                                SDLoc(), PtrVT), InFlag);
12149   InFlag = Chain.getValue(1);
12150
12151   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
12152 }
12153
12154 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
12155 static SDValue
12156 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12157                                 const EVT PtrVT) {
12158   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
12159                     X86::RAX, X86II::MO_TLSGD);
12160 }
12161
12162 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
12163                                            SelectionDAG &DAG,
12164                                            const EVT PtrVT,
12165                                            bool is64Bit) {
12166   SDLoc dl(GA);
12167
12168   // Get the start address of the TLS block for this module.
12169   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
12170       .getInfo<X86MachineFunctionInfo>();
12171   MFI->incNumLocalDynamicTLSAccesses();
12172
12173   SDValue Base;
12174   if (is64Bit) {
12175     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
12176                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
12177   } else {
12178     SDValue InFlag;
12179     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
12180         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
12181     InFlag = Chain.getValue(1);
12182     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
12183                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
12184   }
12185
12186   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
12187   // of Base.
12188
12189   // Build x@dtpoff.
12190   unsigned char OperandFlags = X86II::MO_DTPOFF;
12191   unsigned WrapperKind = X86ISD::Wrapper;
12192   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12193                                            GA->getValueType(0),
12194                                            GA->getOffset(), OperandFlags);
12195   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12196
12197   // Add x@dtpoff with the base.
12198   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
12199 }
12200
12201 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
12202 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
12203                                    const EVT PtrVT, TLSModel::Model model,
12204                                    bool is64Bit, bool isPIC) {
12205   SDLoc dl(GA);
12206
12207   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
12208   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
12209                                                          is64Bit ? 257 : 256));
12210
12211   SDValue ThreadPointer =
12212       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
12213                   MachinePointerInfo(Ptr), false, false, false, 0);
12214
12215   unsigned char OperandFlags = 0;
12216   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
12217   // initialexec.
12218   unsigned WrapperKind = X86ISD::Wrapper;
12219   if (model == TLSModel::LocalExec) {
12220     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
12221   } else if (model == TLSModel::InitialExec) {
12222     if (is64Bit) {
12223       OperandFlags = X86II::MO_GOTTPOFF;
12224       WrapperKind = X86ISD::WrapperRIP;
12225     } else {
12226       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
12227     }
12228   } else {
12229     llvm_unreachable("Unexpected model");
12230   }
12231
12232   // emit "addl x@ntpoff,%eax" (local exec)
12233   // or "addl x@indntpoff,%eax" (initial exec)
12234   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
12235   SDValue TGA =
12236       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
12237                                  GA->getOffset(), OperandFlags);
12238   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
12239
12240   if (model == TLSModel::InitialExec) {
12241     if (isPIC && !is64Bit) {
12242       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
12243                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
12244                            Offset);
12245     }
12246
12247     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
12248                          MachinePointerInfo::getGOT(), false, false, false, 0);
12249   }
12250
12251   // The address of the thread local variable is the add of the thread
12252   // pointer with the offset of the variable.
12253   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
12254 }
12255
12256 SDValue
12257 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
12258
12259   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
12260   const GlobalValue *GV = GA->getGlobal();
12261
12262   if (Subtarget->isTargetELF()) {
12263     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
12264
12265     switch (model) {
12266       case TLSModel::GeneralDynamic:
12267         if (Subtarget->is64Bit())
12268           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
12269         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
12270       case TLSModel::LocalDynamic:
12271         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
12272                                            Subtarget->is64Bit());
12273       case TLSModel::InitialExec:
12274       case TLSModel::LocalExec:
12275         return LowerToTLSExecModel(
12276             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
12277             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
12278     }
12279     llvm_unreachable("Unknown TLS model.");
12280   }
12281
12282   if (Subtarget->isTargetDarwin()) {
12283     // Darwin only has one model of TLS.  Lower to that.
12284     unsigned char OpFlag = 0;
12285     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
12286                            X86ISD::WrapperRIP : X86ISD::Wrapper;
12287
12288     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
12289     // global base reg.
12290     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
12291                  !Subtarget->is64Bit();
12292     if (PIC32)
12293       OpFlag = X86II::MO_TLVP_PIC_BASE;
12294     else
12295       OpFlag = X86II::MO_TLVP;
12296     SDLoc DL(Op);
12297     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
12298                                                 GA->getValueType(0),
12299                                                 GA->getOffset(), OpFlag);
12300     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
12301
12302     // With PIC32, the address is actually $g + Offset.
12303     if (PIC32)
12304       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12305                            DAG.getNode(X86ISD::GlobalBaseReg,
12306                                        SDLoc(), getPointerTy()),
12307                            Offset);
12308
12309     // Lowering the machine isd will make sure everything is in the right
12310     // location.
12311     SDValue Chain = DAG.getEntryNode();
12312     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12313     SDValue Args[] = { Chain, Offset };
12314     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
12315
12316     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
12317     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12318     MFI->setAdjustsStack(true);
12319
12320     // And our return value (tls address) is in the standard call return value
12321     // location.
12322     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
12323     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
12324                               Chain.getValue(1));
12325   }
12326
12327   if (Subtarget->isTargetKnownWindowsMSVC() ||
12328       Subtarget->isTargetWindowsGNU()) {
12329     // Just use the implicit TLS architecture
12330     // Need to generate someting similar to:
12331     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
12332     //                                  ; from TEB
12333     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
12334     //   mov     rcx, qword [rdx+rcx*8]
12335     //   mov     eax, .tls$:tlsvar
12336     //   [rax+rcx] contains the address
12337     // Windows 64bit: gs:0x58
12338     // Windows 32bit: fs:__tls_array
12339
12340     SDLoc dl(GA);
12341     SDValue Chain = DAG.getEntryNode();
12342
12343     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
12344     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
12345     // use its literal value of 0x2C.
12346     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
12347                                         ? Type::getInt8PtrTy(*DAG.getContext(),
12348                                                              256)
12349                                         : Type::getInt32PtrTy(*DAG.getContext(),
12350                                                               257));
12351
12352     SDValue TlsArray =
12353         Subtarget->is64Bit()
12354             ? DAG.getIntPtrConstant(0x58)
12355             : (Subtarget->isTargetWindowsGNU()
12356                    ? DAG.getIntPtrConstant(0x2C)
12357                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
12358
12359     SDValue ThreadPointer =
12360         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
12361                     MachinePointerInfo(Ptr), false, false, false, 0);
12362
12363     // Load the _tls_index variable
12364     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
12365     if (Subtarget->is64Bit())
12366       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
12367                            IDX, MachinePointerInfo(), MVT::i32,
12368                            false, false, false, 0);
12369     else
12370       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
12371                         false, false, false, 0);
12372
12373     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
12374                                     getPointerTy());
12375     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
12376
12377     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
12378     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
12379                       false, false, false, 0);
12380
12381     // Get the offset of start of .tls section
12382     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
12383                                              GA->getValueType(0),
12384                                              GA->getOffset(), X86II::MO_SECREL);
12385     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
12386
12387     // The address of the thread local variable is the add of the thread
12388     // pointer with the offset of the variable.
12389     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
12390   }
12391
12392   llvm_unreachable("TLS not implemented for this target.");
12393 }
12394
12395 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
12396 /// and take a 2 x i32 value to shift plus a shift amount.
12397 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
12398   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
12399   MVT VT = Op.getSimpleValueType();
12400   unsigned VTBits = VT.getSizeInBits();
12401   SDLoc dl(Op);
12402   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
12403   SDValue ShOpLo = Op.getOperand(0);
12404   SDValue ShOpHi = Op.getOperand(1);
12405   SDValue ShAmt  = Op.getOperand(2);
12406   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
12407   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
12408   // during isel.
12409   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12410                                   DAG.getConstant(VTBits - 1, MVT::i8));
12411   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
12412                                      DAG.getConstant(VTBits - 1, MVT::i8))
12413                        : DAG.getConstant(0, VT);
12414
12415   SDValue Tmp2, Tmp3;
12416   if (Op.getOpcode() == ISD::SHL_PARTS) {
12417     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
12418     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
12419   } else {
12420     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
12421     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
12422   }
12423
12424   // If the shift amount is larger or equal than the width of a part we can't
12425   // rely on the results of shld/shrd. Insert a test and select the appropriate
12426   // values for large shift amounts.
12427   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
12428                                 DAG.getConstant(VTBits, MVT::i8));
12429   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
12430                              AndNode, DAG.getConstant(0, MVT::i8));
12431
12432   SDValue Hi, Lo;
12433   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12434   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
12435   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
12436
12437   if (Op.getOpcode() == ISD::SHL_PARTS) {
12438     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12439     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12440   } else {
12441     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
12442     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
12443   }
12444
12445   SDValue Ops[2] = { Lo, Hi };
12446   return DAG.getMergeValues(Ops, dl);
12447 }
12448
12449 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
12450                                            SelectionDAG &DAG) const {
12451   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
12452
12453   if (SrcVT.isVector())
12454     return SDValue();
12455
12456   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
12457          "Unknown SINT_TO_FP to lower!");
12458
12459   // These are really Legal; return the operand so the caller accepts it as
12460   // Legal.
12461   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
12462     return Op;
12463   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
12464       Subtarget->is64Bit()) {
12465     return Op;
12466   }
12467
12468   SDLoc dl(Op);
12469   unsigned Size = SrcVT.getSizeInBits()/8;
12470   MachineFunction &MF = DAG.getMachineFunction();
12471   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
12472   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12473   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12474                                StackSlot,
12475                                MachinePointerInfo::getFixedStack(SSFI),
12476                                false, false, 0);
12477   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
12478 }
12479
12480 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
12481                                      SDValue StackSlot,
12482                                      SelectionDAG &DAG) const {
12483   // Build the FILD
12484   SDLoc DL(Op);
12485   SDVTList Tys;
12486   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
12487   if (useSSE)
12488     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
12489   else
12490     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
12491
12492   unsigned ByteSize = SrcVT.getSizeInBits()/8;
12493
12494   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
12495   MachineMemOperand *MMO;
12496   if (FI) {
12497     int SSFI = FI->getIndex();
12498     MMO =
12499       DAG.getMachineFunction()
12500       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12501                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
12502   } else {
12503     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
12504     StackSlot = StackSlot.getOperand(1);
12505   }
12506   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
12507   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
12508                                            X86ISD::FILD, DL,
12509                                            Tys, Ops, SrcVT, MMO);
12510
12511   if (useSSE) {
12512     Chain = Result.getValue(1);
12513     SDValue InFlag = Result.getValue(2);
12514
12515     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
12516     // shouldn't be necessary except that RFP cannot be live across
12517     // multiple blocks. When stackifier is fixed, they can be uncoupled.
12518     MachineFunction &MF = DAG.getMachineFunction();
12519     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
12520     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
12521     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12522     Tys = DAG.getVTList(MVT::Other);
12523     SDValue Ops[] = {
12524       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
12525     };
12526     MachineMemOperand *MMO =
12527       DAG.getMachineFunction()
12528       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12529                             MachineMemOperand::MOStore, SSFISize, SSFISize);
12530
12531     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
12532                                     Ops, Op.getValueType(), MMO);
12533     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
12534                          MachinePointerInfo::getFixedStack(SSFI),
12535                          false, false, false, 0);
12536   }
12537
12538   return Result;
12539 }
12540
12541 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
12542 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
12543                                                SelectionDAG &DAG) const {
12544   // This algorithm is not obvious. Here it is what we're trying to output:
12545   /*
12546      movq       %rax,  %xmm0
12547      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
12548      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
12549      #ifdef __SSE3__
12550        haddpd   %xmm0, %xmm0
12551      #else
12552        pshufd   $0x4e, %xmm0, %xmm1
12553        addpd    %xmm1, %xmm0
12554      #endif
12555   */
12556
12557   SDLoc dl(Op);
12558   LLVMContext *Context = DAG.getContext();
12559
12560   // Build some magic constants.
12561   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
12562   Constant *C0 = ConstantDataVector::get(*Context, CV0);
12563   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
12564
12565   SmallVector<Constant*,2> CV1;
12566   CV1.push_back(
12567     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12568                                       APInt(64, 0x4330000000000000ULL))));
12569   CV1.push_back(
12570     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
12571                                       APInt(64, 0x4530000000000000ULL))));
12572   Constant *C1 = ConstantVector::get(CV1);
12573   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
12574
12575   // Load the 64-bit value into an XMM register.
12576   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
12577                             Op.getOperand(0));
12578   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
12579                               MachinePointerInfo::getConstantPool(),
12580                               false, false, false, 16);
12581   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
12582                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
12583                               CLod0);
12584
12585   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
12586                               MachinePointerInfo::getConstantPool(),
12587                               false, false, false, 16);
12588   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
12589   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12590   SDValue Result;
12591
12592   if (Subtarget->hasSSE3()) {
12593     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12594     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12595   } else {
12596     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
12597     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12598                                            S2F, 0x4E, DAG);
12599     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12600                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
12601                          Sub);
12602   }
12603
12604   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12605                      DAG.getIntPtrConstant(0));
12606 }
12607
12608 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12609 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12610                                                SelectionDAG &DAG) const {
12611   SDLoc dl(Op);
12612   // FP constant to bias correct the final result.
12613   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
12614                                    MVT::f64);
12615
12616   // Load the 32-bit value into an XMM register.
12617   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12618                              Op.getOperand(0));
12619
12620   // Zero out the upper parts of the register.
12621   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12622
12623   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12624                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
12625                      DAG.getIntPtrConstant(0));
12626
12627   // Or the load with the bias.
12628   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
12629                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
12630                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
12631                                                    MVT::v2f64, Load)),
12632                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
12633                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
12634                                                    MVT::v2f64, Bias)));
12635   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12636                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
12637                    DAG.getIntPtrConstant(0));
12638
12639   // Subtract the bias.
12640   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12641
12642   // Handle final rounding.
12643   EVT DestVT = Op.getValueType();
12644
12645   if (DestVT.bitsLT(MVT::f64))
12646     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12647                        DAG.getIntPtrConstant(0));
12648   if (DestVT.bitsGT(MVT::f64))
12649     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12650
12651   // Handle final rounding.
12652   return Sub;
12653 }
12654
12655 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12656                                                SelectionDAG &DAG) const {
12657   SDValue N0 = Op.getOperand(0);
12658   MVT SVT = N0.getSimpleValueType();
12659   SDLoc dl(Op);
12660
12661   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
12662           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
12663          "Custom UINT_TO_FP is not supported!");
12664
12665   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12666   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12667                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12668 }
12669
12670 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12671                                            SelectionDAG &DAG) const {
12672   SDValue N0 = Op.getOperand(0);
12673   SDLoc dl(Op);
12674
12675   if (Op.getValueType().isVector())
12676     return lowerUINT_TO_FP_vec(Op, DAG);
12677
12678   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12679   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12680   // the optimization here.
12681   if (DAG.SignBitIsZero(N0))
12682     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12683
12684   MVT SrcVT = N0.getSimpleValueType();
12685   MVT DstVT = Op.getSimpleValueType();
12686   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12687     return LowerUINT_TO_FP_i64(Op, DAG);
12688   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12689     return LowerUINT_TO_FP_i32(Op, DAG);
12690   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12691     return SDValue();
12692
12693   // Make a 64-bit buffer, and use it to build an FILD.
12694   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12695   if (SrcVT == MVT::i32) {
12696     SDValue WordOff = DAG.getConstant(4, getPointerTy());
12697     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
12698                                      getPointerTy(), StackSlot, WordOff);
12699     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12700                                   StackSlot, MachinePointerInfo(),
12701                                   false, false, 0);
12702     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
12703                                   OffsetSlot, MachinePointerInfo(),
12704                                   false, false, 0);
12705     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12706     return Fild;
12707   }
12708
12709   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12710   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12711                                StackSlot, MachinePointerInfo(),
12712                                false, false, 0);
12713   // For i64 source, we need to add the appropriate power of 2 if the input
12714   // was negative.  This is the same as the optimization in
12715   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12716   // we must be careful to do the computation in x87 extended precision, not
12717   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12718   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12719   MachineMemOperand *MMO =
12720     DAG.getMachineFunction()
12721     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12722                           MachineMemOperand::MOLoad, 8, 8);
12723
12724   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12725   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12726   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12727                                          MVT::i64, MMO);
12728
12729   APInt FF(32, 0x5F800000ULL);
12730
12731   // Check whether the sign bit is set.
12732   SDValue SignSet = DAG.getSetCC(dl,
12733                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
12734                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
12735                                  ISD::SETLT);
12736
12737   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12738   SDValue FudgePtr = DAG.getConstantPool(
12739                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
12740                                          getPointerTy());
12741
12742   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12743   SDValue Zero = DAG.getIntPtrConstant(0);
12744   SDValue Four = DAG.getIntPtrConstant(4);
12745   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12746                                Zero, Four);
12747   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
12748
12749   // Load the value out, extending it from f32 to f80.
12750   // FIXME: Avoid the extend by constructing the right constant pool?
12751   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12752                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12753                                  MVT::f32, false, false, false, 4);
12754   // Extend everything to 80 bits to force it to be done on x87.
12755   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12756   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
12757 }
12758
12759 std::pair<SDValue,SDValue>
12760 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12761                                     bool IsSigned, bool IsReplace) const {
12762   SDLoc DL(Op);
12763
12764   EVT DstTy = Op.getValueType();
12765
12766   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12767     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12768     DstTy = MVT::i64;
12769   }
12770
12771   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12772          DstTy.getSimpleVT() >= MVT::i16 &&
12773          "Unknown FP_TO_INT to lower!");
12774
12775   // These are really Legal.
12776   if (DstTy == MVT::i32 &&
12777       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12778     return std::make_pair(SDValue(), SDValue());
12779   if (Subtarget->is64Bit() &&
12780       DstTy == MVT::i64 &&
12781       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12782     return std::make_pair(SDValue(), SDValue());
12783
12784   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12785   // stack slot, or into the FTOL runtime function.
12786   MachineFunction &MF = DAG.getMachineFunction();
12787   unsigned MemSize = DstTy.getSizeInBits()/8;
12788   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12789   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12790
12791   unsigned Opc;
12792   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12793     Opc = X86ISD::WIN_FTOL;
12794   else
12795     switch (DstTy.getSimpleVT().SimpleTy) {
12796     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12797     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12798     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12799     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12800     }
12801
12802   SDValue Chain = DAG.getEntryNode();
12803   SDValue Value = Op.getOperand(0);
12804   EVT TheVT = Op.getOperand(0).getValueType();
12805   // FIXME This causes a redundant load/store if the SSE-class value is already
12806   // in memory, such as if it is on the callstack.
12807   if (isScalarFPTypeInSSEReg(TheVT)) {
12808     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12809     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12810                          MachinePointerInfo::getFixedStack(SSFI),
12811                          false, false, 0);
12812     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12813     SDValue Ops[] = {
12814       Chain, StackSlot, DAG.getValueType(TheVT)
12815     };
12816
12817     MachineMemOperand *MMO =
12818       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12819                               MachineMemOperand::MOLoad, MemSize, MemSize);
12820     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12821     Chain = Value.getValue(1);
12822     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12823     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12824   }
12825
12826   MachineMemOperand *MMO =
12827     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12828                             MachineMemOperand::MOStore, MemSize, MemSize);
12829
12830   if (Opc != X86ISD::WIN_FTOL) {
12831     // Build the FP_TO_INT*_IN_MEM
12832     SDValue Ops[] = { Chain, Value, StackSlot };
12833     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12834                                            Ops, DstTy, MMO);
12835     return std::make_pair(FIST, StackSlot);
12836   } else {
12837     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12838       DAG.getVTList(MVT::Other, MVT::Glue),
12839       Chain, Value);
12840     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12841       MVT::i32, ftol.getValue(1));
12842     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12843       MVT::i32, eax.getValue(2));
12844     SDValue Ops[] = { eax, edx };
12845     SDValue pair = IsReplace
12846       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12847       : DAG.getMergeValues(Ops, DL);
12848     return std::make_pair(pair, SDValue());
12849   }
12850 }
12851
12852 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12853                               const X86Subtarget *Subtarget) {
12854   MVT VT = Op->getSimpleValueType(0);
12855   SDValue In = Op->getOperand(0);
12856   MVT InVT = In.getSimpleValueType();
12857   SDLoc dl(Op);
12858
12859   // Optimize vectors in AVX mode:
12860   //
12861   //   v8i16 -> v8i32
12862   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12863   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12864   //   Concat upper and lower parts.
12865   //
12866   //   v4i32 -> v4i64
12867   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12868   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12869   //   Concat upper and lower parts.
12870   //
12871
12872   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12873       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12874       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12875     return SDValue();
12876
12877   if (Subtarget->hasInt256())
12878     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12879
12880   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12881   SDValue Undef = DAG.getUNDEF(InVT);
12882   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12883   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12884   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12885
12886   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12887                              VT.getVectorNumElements()/2);
12888
12889   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
12890   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
12891
12892   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12893 }
12894
12895 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12896                                         SelectionDAG &DAG) {
12897   MVT VT = Op->getSimpleValueType(0);
12898   SDValue In = Op->getOperand(0);
12899   MVT InVT = In.getSimpleValueType();
12900   SDLoc DL(Op);
12901   unsigned int NumElts = VT.getVectorNumElements();
12902   if (NumElts != 8 && NumElts != 16)
12903     return SDValue();
12904
12905   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12906     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12907
12908   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
12909   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12910   // Now we have only mask extension
12911   assert(InVT.getVectorElementType() == MVT::i1);
12912   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
12913   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12914   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12915   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12916   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12917                            MachinePointerInfo::getConstantPool(),
12918                            false, false, false, Alignment);
12919
12920   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
12921   if (VT.is512BitVector())
12922     return Brcst;
12923   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
12924 }
12925
12926 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12927                                SelectionDAG &DAG) {
12928   if (Subtarget->hasFp256()) {
12929     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12930     if (Res.getNode())
12931       return Res;
12932   }
12933
12934   return SDValue();
12935 }
12936
12937 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12938                                 SelectionDAG &DAG) {
12939   SDLoc DL(Op);
12940   MVT VT = Op.getSimpleValueType();
12941   SDValue In = Op.getOperand(0);
12942   MVT SVT = In.getSimpleValueType();
12943
12944   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12945     return LowerZERO_EXTEND_AVX512(Op, DAG);
12946
12947   if (Subtarget->hasFp256()) {
12948     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
12949     if (Res.getNode())
12950       return Res;
12951   }
12952
12953   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12954          VT.getVectorNumElements() != SVT.getVectorNumElements());
12955   return SDValue();
12956 }
12957
12958 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12959   SDLoc DL(Op);
12960   MVT VT = Op.getSimpleValueType();
12961   SDValue In = Op.getOperand(0);
12962   MVT InVT = In.getSimpleValueType();
12963
12964   if (VT == MVT::i1) {
12965     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12966            "Invalid scalar TRUNCATE operation");
12967     if (InVT.getSizeInBits() >= 32)
12968       return SDValue();
12969     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12970     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12971   }
12972   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12973          "Invalid TRUNCATE operation");
12974
12975   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12976     if (VT.getVectorElementType().getSizeInBits() >=8)
12977       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12978
12979     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12980     unsigned NumElts = InVT.getVectorNumElements();
12981     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12982     if (InVT.getSizeInBits() < 512) {
12983       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12984       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12985       InVT = ExtVT;
12986     }
12987     
12988     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
12989     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
12990     SDValue CP = DAG.getConstantPool(C, getPointerTy());
12991     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12992     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
12993                            MachinePointerInfo::getConstantPool(),
12994                            false, false, false, Alignment);
12995     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
12996     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12997     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12998   }
12999
13000   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
13001     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
13002     if (Subtarget->hasInt256()) {
13003       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
13004       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
13005       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
13006                                 ShufMask);
13007       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
13008                          DAG.getIntPtrConstant(0));
13009     }
13010
13011     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13012                                DAG.getIntPtrConstant(0));
13013     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13014                                DAG.getIntPtrConstant(2));
13015     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
13016     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
13017     static const int ShufMask[] = {0, 2, 4, 6};
13018     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
13019   }
13020
13021   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
13022     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
13023     if (Subtarget->hasInt256()) {
13024       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
13025
13026       SmallVector<SDValue,32> pshufbMask;
13027       for (unsigned i = 0; i < 2; ++i) {
13028         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
13029         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
13030         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
13031         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
13032         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
13033         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
13034         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
13035         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
13036         for (unsigned j = 0; j < 8; ++j)
13037           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
13038       }
13039       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
13040       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
13041       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
13042
13043       static const int ShufMask[] = {0,  2,  -1,  -1};
13044       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
13045                                 &ShufMask[0]);
13046       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
13047                        DAG.getIntPtrConstant(0));
13048       return DAG.getNode(ISD::BITCAST, DL, VT, In);
13049     }
13050
13051     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13052                                DAG.getIntPtrConstant(0));
13053
13054     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
13055                                DAG.getIntPtrConstant(4));
13056
13057     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
13058     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
13059
13060     // The PSHUFB mask:
13061     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
13062                                    -1, -1, -1, -1, -1, -1, -1, -1};
13063
13064     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
13065     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
13066     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
13067
13068     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
13069     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
13070
13071     // The MOVLHPS Mask:
13072     static const int ShufMask2[] = {0, 1, 4, 5};
13073     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
13074     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
13075   }
13076
13077   // Handle truncation of V256 to V128 using shuffles.
13078   if (!VT.is128BitVector() || !InVT.is256BitVector())
13079     return SDValue();
13080
13081   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
13082
13083   unsigned NumElems = VT.getVectorNumElements();
13084   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
13085
13086   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
13087   // Prepare truncation shuffle mask
13088   for (unsigned i = 0; i != NumElems; ++i)
13089     MaskVec[i] = i * 2;
13090   SDValue V = DAG.getVectorShuffle(NVT, DL,
13091                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
13092                                    DAG.getUNDEF(NVT), &MaskVec[0]);
13093   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
13094                      DAG.getIntPtrConstant(0));
13095 }
13096
13097 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
13098                                            SelectionDAG &DAG) const {
13099   assert(!Op.getSimpleValueType().isVector());
13100
13101   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13102     /*IsSigned=*/ true, /*IsReplace=*/ false);
13103   SDValue FIST = Vals.first, StackSlot = Vals.second;
13104   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
13105   if (!FIST.getNode()) return Op;
13106
13107   if (StackSlot.getNode())
13108     // Load the result.
13109     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13110                        FIST, StackSlot, MachinePointerInfo(),
13111                        false, false, false, 0);
13112
13113   // The node is the result.
13114   return FIST;
13115 }
13116
13117 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
13118                                            SelectionDAG &DAG) const {
13119   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
13120     /*IsSigned=*/ false, /*IsReplace=*/ false);
13121   SDValue FIST = Vals.first, StackSlot = Vals.second;
13122   assert(FIST.getNode() && "Unexpected failure");
13123
13124   if (StackSlot.getNode())
13125     // Load the result.
13126     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
13127                        FIST, StackSlot, MachinePointerInfo(),
13128                        false, false, false, 0);
13129
13130   // The node is the result.
13131   return FIST;
13132 }
13133
13134 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
13135   SDLoc DL(Op);
13136   MVT VT = Op.getSimpleValueType();
13137   SDValue In = Op.getOperand(0);
13138   MVT SVT = In.getSimpleValueType();
13139
13140   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
13141
13142   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
13143                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
13144                                  In, DAG.getUNDEF(SVT)));
13145 }
13146
13147 // The only differences between FABS and FNEG are the mask and the logic op.
13148 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
13149   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
13150          "Wrong opcode for lowering FABS or FNEG.");
13151
13152   bool IsFABS = (Op.getOpcode() == ISD::FABS);
13153   SDLoc dl(Op);
13154   MVT VT = Op.getSimpleValueType();
13155   // Assume scalar op for initialization; update for vector if needed.
13156   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
13157   // generate a 16-byte vector constant and logic op even for the scalar case.
13158   // Using a 16-byte mask allows folding the load of the mask with
13159   // the logic op, so it can save (~4 bytes) on code size.
13160   MVT EltVT = VT;
13161   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
13162   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
13163   // decide if we should generate a 16-byte constant mask when we only need 4 or
13164   // 8 bytes for the scalar case.
13165   if (VT.isVector()) {
13166     EltVT = VT.getVectorElementType();
13167     NumElts = VT.getVectorNumElements();
13168   }
13169   
13170   unsigned EltBits = EltVT.getSizeInBits();
13171   LLVMContext *Context = DAG.getContext();
13172   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
13173   APInt MaskElt =
13174     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
13175   Constant *C = ConstantInt::get(*Context, MaskElt);
13176   C = ConstantVector::getSplat(NumElts, C);
13177   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13178   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
13179   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13180   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
13181                              MachinePointerInfo::getConstantPool(),
13182                              false, false, false, Alignment);
13183
13184   if (VT.isVector()) {
13185     // For a vector, cast operands to a vector type, perform the logic op,
13186     // and cast the result back to the original value type.
13187     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
13188     SDValue Op0Casted = DAG.getNode(ISD::BITCAST, dl, VecVT, Op.getOperand(0));
13189     SDValue MaskCasted = DAG.getNode(ISD::BITCAST, dl, VecVT, Mask);
13190     unsigned LogicOp = IsFABS ? ISD::AND : ISD::XOR;
13191     return DAG.getNode(ISD::BITCAST, dl, VT,
13192                        DAG.getNode(LogicOp, dl, VecVT, Op0Casted, MaskCasted));
13193   }
13194   // If not vector, then scalar.
13195   unsigned LogicOp = IsFABS ? X86ISD::FAND : X86ISD::FXOR;
13196   return DAG.getNode(LogicOp, dl, VT, Op.getOperand(0), Mask);
13197 }
13198
13199 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
13200   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13201   LLVMContext *Context = DAG.getContext();
13202   SDValue Op0 = Op.getOperand(0);
13203   SDValue Op1 = Op.getOperand(1);
13204   SDLoc dl(Op);
13205   MVT VT = Op.getSimpleValueType();
13206   MVT SrcVT = Op1.getSimpleValueType();
13207
13208   // If second operand is smaller, extend it first.
13209   if (SrcVT.bitsLT(VT)) {
13210     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
13211     SrcVT = VT;
13212   }
13213   // And if it is bigger, shrink it first.
13214   if (SrcVT.bitsGT(VT)) {
13215     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
13216     SrcVT = VT;
13217   }
13218
13219   // At this point the operands and the result should have the same
13220   // type, and that won't be f80 since that is not custom lowered.
13221
13222   // First get the sign bit of second operand.
13223   SmallVector<Constant*,4> CV;
13224   if (SrcVT == MVT::f64) {
13225     const fltSemantics &Sem = APFloat::IEEEdouble;
13226     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
13227     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
13228   } else {
13229     const fltSemantics &Sem = APFloat::IEEEsingle;
13230     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
13231     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
13232     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
13233     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
13234   }
13235   Constant *C = ConstantVector::get(CV);
13236   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
13237   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
13238                               MachinePointerInfo::getConstantPool(),
13239                               false, false, false, 16);
13240   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
13241
13242   // Shift sign bit right or left if the two operands have different types.
13243   if (SrcVT.bitsGT(VT)) {
13244     // Op0 is MVT::f32, Op1 is MVT::f64.
13245     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
13246     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
13247                           DAG.getConstant(32, MVT::i32));
13248     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
13249     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
13250                           DAG.getIntPtrConstant(0));
13251   }
13252
13253   // Clear first operand sign bit.
13254   CV.clear();
13255   if (VT == MVT::f64) {
13256     const fltSemantics &Sem = APFloat::IEEEdouble;
13257     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
13258                                                    APInt(64, ~(1ULL << 63)))));
13259     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
13260   } else {
13261     const fltSemantics &Sem = APFloat::IEEEsingle;
13262     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
13263                                                    APInt(32, ~(1U << 31)))));
13264     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
13265     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
13266     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
13267   }
13268   C = ConstantVector::get(CV);
13269   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
13270   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
13271                               MachinePointerInfo::getConstantPool(),
13272                               false, false, false, 16);
13273   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
13274
13275   // Or the value with the sign bit.
13276   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
13277 }
13278
13279 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
13280   SDValue N0 = Op.getOperand(0);
13281   SDLoc dl(Op);
13282   MVT VT = Op.getSimpleValueType();
13283
13284   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
13285   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
13286                                   DAG.getConstant(1, VT));
13287   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
13288 }
13289
13290 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
13291 //
13292 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
13293                                       SelectionDAG &DAG) {
13294   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
13295
13296   if (!Subtarget->hasSSE41())
13297     return SDValue();
13298
13299   if (!Op->hasOneUse())
13300     return SDValue();
13301
13302   SDNode *N = Op.getNode();
13303   SDLoc DL(N);
13304
13305   SmallVector<SDValue, 8> Opnds;
13306   DenseMap<SDValue, unsigned> VecInMap;
13307   SmallVector<SDValue, 8> VecIns;
13308   EVT VT = MVT::Other;
13309
13310   // Recognize a special case where a vector is casted into wide integer to
13311   // test all 0s.
13312   Opnds.push_back(N->getOperand(0));
13313   Opnds.push_back(N->getOperand(1));
13314
13315   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
13316     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
13317     // BFS traverse all OR'd operands.
13318     if (I->getOpcode() == ISD::OR) {
13319       Opnds.push_back(I->getOperand(0));
13320       Opnds.push_back(I->getOperand(1));
13321       // Re-evaluate the number of nodes to be traversed.
13322       e += 2; // 2 more nodes (LHS and RHS) are pushed.
13323       continue;
13324     }
13325
13326     // Quit if a non-EXTRACT_VECTOR_ELT
13327     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
13328       return SDValue();
13329
13330     // Quit if without a constant index.
13331     SDValue Idx = I->getOperand(1);
13332     if (!isa<ConstantSDNode>(Idx))
13333       return SDValue();
13334
13335     SDValue ExtractedFromVec = I->getOperand(0);
13336     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
13337     if (M == VecInMap.end()) {
13338       VT = ExtractedFromVec.getValueType();
13339       // Quit if not 128/256-bit vector.
13340       if (!VT.is128BitVector() && !VT.is256BitVector())
13341         return SDValue();
13342       // Quit if not the same type.
13343       if (VecInMap.begin() != VecInMap.end() &&
13344           VT != VecInMap.begin()->first.getValueType())
13345         return SDValue();
13346       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
13347       VecIns.push_back(ExtractedFromVec);
13348     }
13349     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
13350   }
13351
13352   assert((VT.is128BitVector() || VT.is256BitVector()) &&
13353          "Not extracted from 128-/256-bit vector.");
13354
13355   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
13356
13357   for (DenseMap<SDValue, unsigned>::const_iterator
13358         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
13359     // Quit if not all elements are used.
13360     if (I->second != FullMask)
13361       return SDValue();
13362   }
13363
13364   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
13365
13366   // Cast all vectors into TestVT for PTEST.
13367   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
13368     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
13369
13370   // If more than one full vectors are evaluated, OR them first before PTEST.
13371   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
13372     // Each iteration will OR 2 nodes and append the result until there is only
13373     // 1 node left, i.e. the final OR'd value of all vectors.
13374     SDValue LHS = VecIns[Slot];
13375     SDValue RHS = VecIns[Slot + 1];
13376     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
13377   }
13378
13379   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
13380                      VecIns.back(), VecIns.back());
13381 }
13382
13383 /// \brief return true if \c Op has a use that doesn't just read flags.
13384 static bool hasNonFlagsUse(SDValue Op) {
13385   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
13386        ++UI) {
13387     SDNode *User = *UI;
13388     unsigned UOpNo = UI.getOperandNo();
13389     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
13390       // Look pass truncate.
13391       UOpNo = User->use_begin().getOperandNo();
13392       User = *User->use_begin();
13393     }
13394
13395     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
13396         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
13397       return true;
13398   }
13399   return false;
13400 }
13401
13402 /// Emit nodes that will be selected as "test Op0,Op0", or something
13403 /// equivalent.
13404 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
13405                                     SelectionDAG &DAG) const {
13406   if (Op.getValueType() == MVT::i1)
13407     // KORTEST instruction should be selected
13408     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13409                        DAG.getConstant(0, Op.getValueType()));
13410
13411   // CF and OF aren't always set the way we want. Determine which
13412   // of these we need.
13413   bool NeedCF = false;
13414   bool NeedOF = false;
13415   switch (X86CC) {
13416   default: break;
13417   case X86::COND_A: case X86::COND_AE:
13418   case X86::COND_B: case X86::COND_BE:
13419     NeedCF = true;
13420     break;
13421   case X86::COND_G: case X86::COND_GE:
13422   case X86::COND_L: case X86::COND_LE:
13423   case X86::COND_O: case X86::COND_NO: {
13424     // Check if we really need to set the
13425     // Overflow flag. If NoSignedWrap is present
13426     // that is not actually needed.
13427     switch (Op->getOpcode()) {
13428     case ISD::ADD:
13429     case ISD::SUB:
13430     case ISD::MUL:
13431     case ISD::SHL: {
13432       const BinaryWithFlagsSDNode *BinNode =
13433           cast<BinaryWithFlagsSDNode>(Op.getNode());
13434       if (BinNode->hasNoSignedWrap())
13435         break;
13436     }
13437     default:
13438       NeedOF = true;
13439       break;
13440     }
13441     break;
13442   }
13443   }
13444   // See if we can use the EFLAGS value from the operand instead of
13445   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
13446   // we prove that the arithmetic won't overflow, we can't use OF or CF.
13447   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
13448     // Emit a CMP with 0, which is the TEST pattern.
13449     //if (Op.getValueType() == MVT::i1)
13450     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
13451     //                     DAG.getConstant(0, MVT::i1));
13452     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13453                        DAG.getConstant(0, Op.getValueType()));
13454   }
13455   unsigned Opcode = 0;
13456   unsigned NumOperands = 0;
13457
13458   // Truncate operations may prevent the merge of the SETCC instruction
13459   // and the arithmetic instruction before it. Attempt to truncate the operands
13460   // of the arithmetic instruction and use a reduced bit-width instruction.
13461   bool NeedTruncation = false;
13462   SDValue ArithOp = Op;
13463   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13464     SDValue Arith = Op->getOperand(0);
13465     // Both the trunc and the arithmetic op need to have one user each.
13466     if (Arith->hasOneUse())
13467       switch (Arith.getOpcode()) {
13468         default: break;
13469         case ISD::ADD:
13470         case ISD::SUB:
13471         case ISD::AND:
13472         case ISD::OR:
13473         case ISD::XOR: {
13474           NeedTruncation = true;
13475           ArithOp = Arith;
13476         }
13477       }
13478   }
13479
13480   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13481   // which may be the result of a CAST.  We use the variable 'Op', which is the
13482   // non-casted variable when we check for possible users.
13483   switch (ArithOp.getOpcode()) {
13484   case ISD::ADD:
13485     // Due to an isel shortcoming, be conservative if this add is likely to be
13486     // selected as part of a load-modify-store instruction. When the root node
13487     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13488     // uses of other nodes in the match, such as the ADD in this case. This
13489     // leads to the ADD being left around and reselected, with the result being
13490     // two adds in the output.  Alas, even if none our users are stores, that
13491     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13492     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13493     // climbing the DAG back to the root, and it doesn't seem to be worth the
13494     // effort.
13495     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13496          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13497       if (UI->getOpcode() != ISD::CopyToReg &&
13498           UI->getOpcode() != ISD::SETCC &&
13499           UI->getOpcode() != ISD::STORE)
13500         goto default_case;
13501
13502     if (ConstantSDNode *C =
13503         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13504       // An add of one will be selected as an INC.
13505       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13506         Opcode = X86ISD::INC;
13507         NumOperands = 1;
13508         break;
13509       }
13510
13511       // An add of negative one (subtract of one) will be selected as a DEC.
13512       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13513         Opcode = X86ISD::DEC;
13514         NumOperands = 1;
13515         break;
13516       }
13517     }
13518
13519     // Otherwise use a regular EFLAGS-setting add.
13520     Opcode = X86ISD::ADD;
13521     NumOperands = 2;
13522     break;
13523   case ISD::SHL:
13524   case ISD::SRL:
13525     // If we have a constant logical shift that's only used in a comparison
13526     // against zero turn it into an equivalent AND. This allows turning it into
13527     // a TEST instruction later.
13528     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13529         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13530       EVT VT = Op.getValueType();
13531       unsigned BitWidth = VT.getSizeInBits();
13532       unsigned ShAmt = Op->getConstantOperandVal(1);
13533       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13534         break;
13535       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13536                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13537                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13538       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13539         break;
13540       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13541                                 DAG.getConstant(Mask, VT));
13542       DAG.ReplaceAllUsesWith(Op, New);
13543       Op = New;
13544     }
13545     break;
13546
13547   case ISD::AND:
13548     // If the primary and result isn't used, don't bother using X86ISD::AND,
13549     // because a TEST instruction will be better.
13550     if (!hasNonFlagsUse(Op))
13551       break;
13552     // FALL THROUGH
13553   case ISD::SUB:
13554   case ISD::OR:
13555   case ISD::XOR:
13556     // Due to the ISEL shortcoming noted above, be conservative if this op is
13557     // likely to be selected as part of a load-modify-store instruction.
13558     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13559            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13560       if (UI->getOpcode() == ISD::STORE)
13561         goto default_case;
13562
13563     // Otherwise use a regular EFLAGS-setting instruction.
13564     switch (ArithOp.getOpcode()) {
13565     default: llvm_unreachable("unexpected operator!");
13566     case ISD::SUB: Opcode = X86ISD::SUB; break;
13567     case ISD::XOR: Opcode = X86ISD::XOR; break;
13568     case ISD::AND: Opcode = X86ISD::AND; break;
13569     case ISD::OR: {
13570       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13571         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13572         if (EFLAGS.getNode())
13573           return EFLAGS;
13574       }
13575       Opcode = X86ISD::OR;
13576       break;
13577     }
13578     }
13579
13580     NumOperands = 2;
13581     break;
13582   case X86ISD::ADD:
13583   case X86ISD::SUB:
13584   case X86ISD::INC:
13585   case X86ISD::DEC:
13586   case X86ISD::OR:
13587   case X86ISD::XOR:
13588   case X86ISD::AND:
13589     return SDValue(Op.getNode(), 1);
13590   default:
13591   default_case:
13592     break;
13593   }
13594
13595   // If we found that truncation is beneficial, perform the truncation and
13596   // update 'Op'.
13597   if (NeedTruncation) {
13598     EVT VT = Op.getValueType();
13599     SDValue WideVal = Op->getOperand(0);
13600     EVT WideVT = WideVal.getValueType();
13601     unsigned ConvertedOp = 0;
13602     // Use a target machine opcode to prevent further DAGCombine
13603     // optimizations that may separate the arithmetic operations
13604     // from the setcc node.
13605     switch (WideVal.getOpcode()) {
13606       default: break;
13607       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13608       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13609       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13610       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13611       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13612     }
13613
13614     if (ConvertedOp) {
13615       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13616       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13617         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13618         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13619         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13620       }
13621     }
13622   }
13623
13624   if (Opcode == 0)
13625     // Emit a CMP with 0, which is the TEST pattern.
13626     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13627                        DAG.getConstant(0, Op.getValueType()));
13628
13629   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13630   SmallVector<SDValue, 4> Ops;
13631   for (unsigned i = 0; i != NumOperands; ++i)
13632     Ops.push_back(Op.getOperand(i));
13633
13634   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13635   DAG.ReplaceAllUsesWith(Op, New);
13636   return SDValue(New.getNode(), 1);
13637 }
13638
13639 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13640 /// equivalent.
13641 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13642                                    SDLoc dl, SelectionDAG &DAG) const {
13643   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13644     if (C->getAPIntValue() == 0)
13645       return EmitTest(Op0, X86CC, dl, DAG);
13646
13647      if (Op0.getValueType() == MVT::i1)
13648        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13649   }
13650  
13651   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13652        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13653     // Do the comparison at i32 if it's smaller, besides the Atom case. 
13654     // This avoids subregister aliasing issues. Keep the smaller reference 
13655     // if we're optimizing for size, however, as that'll allow better folding 
13656     // of memory operations.
13657     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13658         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
13659              AttributeSet::FunctionIndex, Attribute::MinSize) &&
13660         !Subtarget->isAtom()) {
13661       unsigned ExtendOp =
13662           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13663       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13664       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13665     }
13666     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13667     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13668     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13669                               Op0, Op1);
13670     return SDValue(Sub.getNode(), 1);
13671   }
13672   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13673 }
13674
13675 /// Convert a comparison if required by the subtarget.
13676 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13677                                                  SelectionDAG &DAG) const {
13678   // If the subtarget does not support the FUCOMI instruction, floating-point
13679   // comparisons have to be converted.
13680   if (Subtarget->hasCMov() ||
13681       Cmp.getOpcode() != X86ISD::CMP ||
13682       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13683       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13684     return Cmp;
13685
13686   // The instruction selector will select an FUCOM instruction instead of
13687   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13688   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13689   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13690   SDLoc dl(Cmp);
13691   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13692   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13693   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13694                             DAG.getConstant(8, MVT::i8));
13695   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13696   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13697 }
13698
13699 static bool isAllOnes(SDValue V) {
13700   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13701   return C && C->isAllOnesValue();
13702 }
13703
13704 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13705 /// if it's possible.
13706 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13707                                      SDLoc dl, SelectionDAG &DAG) const {
13708   SDValue Op0 = And.getOperand(0);
13709   SDValue Op1 = And.getOperand(1);
13710   if (Op0.getOpcode() == ISD::TRUNCATE)
13711     Op0 = Op0.getOperand(0);
13712   if (Op1.getOpcode() == ISD::TRUNCATE)
13713     Op1 = Op1.getOperand(0);
13714
13715   SDValue LHS, RHS;
13716   if (Op1.getOpcode() == ISD::SHL)
13717     std::swap(Op0, Op1);
13718   if (Op0.getOpcode() == ISD::SHL) {
13719     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13720       if (And00C->getZExtValue() == 1) {
13721         // If we looked past a truncate, check that it's only truncating away
13722         // known zeros.
13723         unsigned BitWidth = Op0.getValueSizeInBits();
13724         unsigned AndBitWidth = And.getValueSizeInBits();
13725         if (BitWidth > AndBitWidth) {
13726           APInt Zeros, Ones;
13727           DAG.computeKnownBits(Op0, Zeros, Ones);
13728           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13729             return SDValue();
13730         }
13731         LHS = Op1;
13732         RHS = Op0.getOperand(1);
13733       }
13734   } else if (Op1.getOpcode() == ISD::Constant) {
13735     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13736     uint64_t AndRHSVal = AndRHS->getZExtValue();
13737     SDValue AndLHS = Op0;
13738
13739     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13740       LHS = AndLHS.getOperand(0);
13741       RHS = AndLHS.getOperand(1);
13742     }
13743
13744     // Use BT if the immediate can't be encoded in a TEST instruction.
13745     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13746       LHS = AndLHS;
13747       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
13748     }
13749   }
13750
13751   if (LHS.getNode()) {
13752     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13753     // instruction.  Since the shift amount is in-range-or-undefined, we know
13754     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13755     // the encoding for the i16 version is larger than the i32 version.
13756     // Also promote i16 to i32 for performance / code size reason.
13757     if (LHS.getValueType() == MVT::i8 ||
13758         LHS.getValueType() == MVT::i16)
13759       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13760
13761     // If the operand types disagree, extend the shift amount to match.  Since
13762     // BT ignores high bits (like shifts) we can use anyextend.
13763     if (LHS.getValueType() != RHS.getValueType())
13764       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13765
13766     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13767     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13768     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13769                        DAG.getConstant(Cond, MVT::i8), BT);
13770   }
13771
13772   return SDValue();
13773 }
13774
13775 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13776 /// mask CMPs.
13777 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13778                               SDValue &Op1) {
13779   unsigned SSECC;
13780   bool Swap = false;
13781
13782   // SSE Condition code mapping:
13783   //  0 - EQ
13784   //  1 - LT
13785   //  2 - LE
13786   //  3 - UNORD
13787   //  4 - NEQ
13788   //  5 - NLT
13789   //  6 - NLE
13790   //  7 - ORD
13791   switch (SetCCOpcode) {
13792   default: llvm_unreachable("Unexpected SETCC condition");
13793   case ISD::SETOEQ:
13794   case ISD::SETEQ:  SSECC = 0; break;
13795   case ISD::SETOGT:
13796   case ISD::SETGT:  Swap = true; // Fallthrough
13797   case ISD::SETLT:
13798   case ISD::SETOLT: SSECC = 1; break;
13799   case ISD::SETOGE:
13800   case ISD::SETGE:  Swap = true; // Fallthrough
13801   case ISD::SETLE:
13802   case ISD::SETOLE: SSECC = 2; break;
13803   case ISD::SETUO:  SSECC = 3; break;
13804   case ISD::SETUNE:
13805   case ISD::SETNE:  SSECC = 4; break;
13806   case ISD::SETULE: Swap = true; // Fallthrough
13807   case ISD::SETUGE: SSECC = 5; break;
13808   case ISD::SETULT: Swap = true; // Fallthrough
13809   case ISD::SETUGT: SSECC = 6; break;
13810   case ISD::SETO:   SSECC = 7; break;
13811   case ISD::SETUEQ:
13812   case ISD::SETONE: SSECC = 8; break;
13813   }
13814   if (Swap)
13815     std::swap(Op0, Op1);
13816
13817   return SSECC;
13818 }
13819
13820 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13821 // ones, and then concatenate the result back.
13822 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13823   MVT VT = Op.getSimpleValueType();
13824
13825   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13826          "Unsupported value type for operation");
13827
13828   unsigned NumElems = VT.getVectorNumElements();
13829   SDLoc dl(Op);
13830   SDValue CC = Op.getOperand(2);
13831
13832   // Extract the LHS vectors
13833   SDValue LHS = Op.getOperand(0);
13834   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13835   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13836
13837   // Extract the RHS vectors
13838   SDValue RHS = Op.getOperand(1);
13839   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13840   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13841
13842   // Issue the operation on the smaller types and concatenate the result back
13843   MVT EltVT = VT.getVectorElementType();
13844   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13845   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13846                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13847                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13848 }
13849
13850 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13851                                      const X86Subtarget *Subtarget) {
13852   SDValue Op0 = Op.getOperand(0);
13853   SDValue Op1 = Op.getOperand(1);
13854   SDValue CC = Op.getOperand(2);
13855   MVT VT = Op.getSimpleValueType();
13856   SDLoc dl(Op);
13857
13858   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13859          Op.getValueType().getScalarType() == MVT::i1 &&
13860          "Cannot set masked compare for this operation");
13861
13862   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13863   unsigned  Opc = 0;
13864   bool Unsigned = false;
13865   bool Swap = false;
13866   unsigned SSECC;
13867   switch (SetCCOpcode) {
13868   default: llvm_unreachable("Unexpected SETCC condition");
13869   case ISD::SETNE:  SSECC = 4; break;
13870   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13871   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13872   case ISD::SETLT:  Swap = true; //fall-through
13873   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13874   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13875   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13876   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13877   case ISD::SETULE: Unsigned = true; //fall-through
13878   case ISD::SETLE:  SSECC = 2; break;
13879   }
13880
13881   if (Swap)
13882     std::swap(Op0, Op1);
13883   if (Opc)
13884     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13885   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13886   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13887                      DAG.getConstant(SSECC, MVT::i8));
13888 }
13889
13890 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13891 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13892 /// return an empty value.
13893 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13894 {
13895   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13896   if (!BV)
13897     return SDValue();
13898
13899   MVT VT = Op1.getSimpleValueType();
13900   MVT EVT = VT.getVectorElementType();
13901   unsigned n = VT.getVectorNumElements();
13902   SmallVector<SDValue, 8> ULTOp1;
13903
13904   for (unsigned i = 0; i < n; ++i) {
13905     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13906     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13907       return SDValue();
13908
13909     // Avoid underflow.
13910     APInt Val = Elt->getAPIntValue();
13911     if (Val == 0)
13912       return SDValue();
13913
13914     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
13915   }
13916
13917   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13918 }
13919
13920 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13921                            SelectionDAG &DAG) {
13922   SDValue Op0 = Op.getOperand(0);
13923   SDValue Op1 = Op.getOperand(1);
13924   SDValue CC = Op.getOperand(2);
13925   MVT VT = Op.getSimpleValueType();
13926   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13927   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13928   SDLoc dl(Op);
13929
13930   if (isFP) {
13931 #ifndef NDEBUG
13932     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13933     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13934 #endif
13935
13936     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13937     unsigned Opc = X86ISD::CMPP;
13938     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13939       assert(VT.getVectorNumElements() <= 16);
13940       Opc = X86ISD::CMPM;
13941     }
13942     // In the two special cases we can't handle, emit two comparisons.
13943     if (SSECC == 8) {
13944       unsigned CC0, CC1;
13945       unsigned CombineOpc;
13946       if (SetCCOpcode == ISD::SETUEQ) {
13947         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13948       } else {
13949         assert(SetCCOpcode == ISD::SETONE);
13950         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13951       }
13952
13953       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13954                                  DAG.getConstant(CC0, MVT::i8));
13955       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13956                                  DAG.getConstant(CC1, MVT::i8));
13957       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13958     }
13959     // Handle all other FP comparisons here.
13960     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13961                        DAG.getConstant(SSECC, MVT::i8));
13962   }
13963
13964   // Break 256-bit integer vector compare into smaller ones.
13965   if (VT.is256BitVector() && !Subtarget->hasInt256())
13966     return Lower256IntVSETCC(Op, DAG);
13967
13968   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13969   EVT OpVT = Op1.getValueType();
13970   if (Subtarget->hasAVX512()) {
13971     if (Op1.getValueType().is512BitVector() ||
13972         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13973         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13974       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13975
13976     // In AVX-512 architecture setcc returns mask with i1 elements,
13977     // But there is no compare instruction for i8 and i16 elements in KNL.
13978     // We are not talking about 512-bit operands in this case, these
13979     // types are illegal.
13980     if (MaskResult &&
13981         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13982          OpVT.getVectorElementType().getSizeInBits() >= 8))
13983       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13984                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13985   }
13986
13987   // We are handling one of the integer comparisons here.  Since SSE only has
13988   // GT and EQ comparisons for integer, swapping operands and multiple
13989   // operations may be required for some comparisons.
13990   unsigned Opc;
13991   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13992   bool Subus = false;
13993
13994   switch (SetCCOpcode) {
13995   default: llvm_unreachable("Unexpected SETCC condition");
13996   case ISD::SETNE:  Invert = true;
13997   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13998   case ISD::SETLT:  Swap = true;
13999   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
14000   case ISD::SETGE:  Swap = true;
14001   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
14002                     Invert = true; break;
14003   case ISD::SETULT: Swap = true;
14004   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
14005                     FlipSigns = true; break;
14006   case ISD::SETUGE: Swap = true;
14007   case ISD::SETULE: Opc = X86ISD::PCMPGT;
14008                     FlipSigns = true; Invert = true; break;
14009   }
14010
14011   // Special case: Use min/max operations for SETULE/SETUGE
14012   MVT VET = VT.getVectorElementType();
14013   bool hasMinMax =
14014        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
14015     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
14016
14017   if (hasMinMax) {
14018     switch (SetCCOpcode) {
14019     default: break;
14020     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
14021     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
14022     }
14023
14024     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
14025   }
14026
14027   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
14028   if (!MinMax && hasSubus) {
14029     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
14030     // Op0 u<= Op1:
14031     //   t = psubus Op0, Op1
14032     //   pcmpeq t, <0..0>
14033     switch (SetCCOpcode) {
14034     default: break;
14035     case ISD::SETULT: {
14036       // If the comparison is against a constant we can turn this into a
14037       // setule.  With psubus, setule does not require a swap.  This is
14038       // beneficial because the constant in the register is no longer
14039       // destructed as the destination so it can be hoisted out of a loop.
14040       // Only do this pre-AVX since vpcmp* is no longer destructive.
14041       if (Subtarget->hasAVX())
14042         break;
14043       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
14044       if (ULEOp1.getNode()) {
14045         Op1 = ULEOp1;
14046         Subus = true; Invert = false; Swap = false;
14047       }
14048       break;
14049     }
14050     // Psubus is better than flip-sign because it requires no inversion.
14051     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
14052     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
14053     }
14054
14055     if (Subus) {
14056       Opc = X86ISD::SUBUS;
14057       FlipSigns = false;
14058     }
14059   }
14060
14061   if (Swap)
14062     std::swap(Op0, Op1);
14063
14064   // Check that the operation in question is available (most are plain SSE2,
14065   // but PCMPGTQ and PCMPEQQ have different requirements).
14066   if (VT == MVT::v2i64) {
14067     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
14068       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
14069
14070       // First cast everything to the right type.
14071       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
14072       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
14073
14074       // Since SSE has no unsigned integer comparisons, we need to flip the sign
14075       // bits of the inputs before performing those operations. The lower
14076       // compare is always unsigned.
14077       SDValue SB;
14078       if (FlipSigns) {
14079         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
14080       } else {
14081         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
14082         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
14083         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
14084                          Sign, Zero, Sign, Zero);
14085       }
14086       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
14087       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
14088
14089       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
14090       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
14091       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
14092
14093       // Create masks for only the low parts/high parts of the 64 bit integers.
14094       static const int MaskHi[] = { 1, 1, 3, 3 };
14095       static const int MaskLo[] = { 0, 0, 2, 2 };
14096       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
14097       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
14098       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
14099
14100       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
14101       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
14102
14103       if (Invert)
14104         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14105
14106       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14107     }
14108
14109     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
14110       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
14111       // pcmpeqd + pshufd + pand.
14112       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
14113
14114       // First cast everything to the right type.
14115       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
14116       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
14117
14118       // Do the compare.
14119       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
14120
14121       // Make sure the lower and upper halves are both all-ones.
14122       static const int Mask[] = { 1, 0, 3, 2 };
14123       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
14124       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
14125
14126       if (Invert)
14127         Result = DAG.getNOT(dl, Result, MVT::v4i32);
14128
14129       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14130     }
14131   }
14132
14133   // Since SSE has no unsigned integer comparisons, we need to flip the sign
14134   // bits of the inputs before performing those operations.
14135   if (FlipSigns) {
14136     EVT EltVT = VT.getVectorElementType();
14137     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
14138     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
14139     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
14140   }
14141
14142   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
14143
14144   // If the logical-not of the result is required, perform that now.
14145   if (Invert)
14146     Result = DAG.getNOT(dl, Result, VT);
14147
14148   if (MinMax)
14149     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
14150
14151   if (Subus)
14152     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
14153                          getZeroVector(VT, Subtarget, DAG, dl));
14154
14155   return Result;
14156 }
14157
14158 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
14159
14160   MVT VT = Op.getSimpleValueType();
14161
14162   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
14163
14164   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
14165          && "SetCC type must be 8-bit or 1-bit integer");
14166   SDValue Op0 = Op.getOperand(0);
14167   SDValue Op1 = Op.getOperand(1);
14168   SDLoc dl(Op);
14169   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
14170
14171   // Optimize to BT if possible.
14172   // Lower (X & (1 << N)) == 0 to BT(X, N).
14173   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
14174   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
14175   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
14176       Op1.getOpcode() == ISD::Constant &&
14177       cast<ConstantSDNode>(Op1)->isNullValue() &&
14178       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14179     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
14180     if (NewSetCC.getNode())
14181       return NewSetCC;
14182   }
14183
14184   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
14185   // these.
14186   if (Op1.getOpcode() == ISD::Constant &&
14187       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
14188        cast<ConstantSDNode>(Op1)->isNullValue()) &&
14189       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14190
14191     // If the input is a setcc, then reuse the input setcc or use a new one with
14192     // the inverted condition.
14193     if (Op0.getOpcode() == X86ISD::SETCC) {
14194       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
14195       bool Invert = (CC == ISD::SETNE) ^
14196         cast<ConstantSDNode>(Op1)->isNullValue();
14197       if (!Invert)
14198         return Op0;
14199
14200       CCode = X86::GetOppositeBranchCondition(CCode);
14201       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14202                                   DAG.getConstant(CCode, MVT::i8),
14203                                   Op0.getOperand(1));
14204       if (VT == MVT::i1)
14205         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14206       return SetCC;
14207     }
14208   }
14209   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
14210       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
14211       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
14212
14213     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
14214     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
14215   }
14216
14217   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
14218   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
14219   if (X86CC == X86::COND_INVALID)
14220     return SDValue();
14221
14222   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
14223   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
14224   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14225                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
14226   if (VT == MVT::i1)
14227     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
14228   return SetCC;
14229 }
14230
14231 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
14232 static bool isX86LogicalCmp(SDValue Op) {
14233   unsigned Opc = Op.getNode()->getOpcode();
14234   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
14235       Opc == X86ISD::SAHF)
14236     return true;
14237   if (Op.getResNo() == 1 &&
14238       (Opc == X86ISD::ADD ||
14239        Opc == X86ISD::SUB ||
14240        Opc == X86ISD::ADC ||
14241        Opc == X86ISD::SBB ||
14242        Opc == X86ISD::SMUL ||
14243        Opc == X86ISD::UMUL ||
14244        Opc == X86ISD::INC ||
14245        Opc == X86ISD::DEC ||
14246        Opc == X86ISD::OR ||
14247        Opc == X86ISD::XOR ||
14248        Opc == X86ISD::AND))
14249     return true;
14250
14251   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
14252     return true;
14253
14254   return false;
14255 }
14256
14257 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
14258   if (V.getOpcode() != ISD::TRUNCATE)
14259     return false;
14260
14261   SDValue VOp0 = V.getOperand(0);
14262   unsigned InBits = VOp0.getValueSizeInBits();
14263   unsigned Bits = V.getValueSizeInBits();
14264   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
14265 }
14266
14267 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
14268   bool addTest = true;
14269   SDValue Cond  = Op.getOperand(0);
14270   SDValue Op1 = Op.getOperand(1);
14271   SDValue Op2 = Op.getOperand(2);
14272   SDLoc DL(Op);
14273   EVT VT = Op1.getValueType();
14274   SDValue CC;
14275
14276   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
14277   // are available. Otherwise fp cmovs get lowered into a less efficient branch
14278   // sequence later on.
14279   if (Cond.getOpcode() == ISD::SETCC &&
14280       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
14281        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
14282       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
14283     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
14284     int SSECC = translateX86FSETCC(
14285         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
14286
14287     if (SSECC != 8) {
14288       if (Subtarget->hasAVX512()) {
14289         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
14290                                   DAG.getConstant(SSECC, MVT::i8));
14291         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
14292       }
14293       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
14294                                 DAG.getConstant(SSECC, MVT::i8));
14295       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
14296       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
14297       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
14298     }
14299   }
14300
14301   if (Cond.getOpcode() == ISD::SETCC) {
14302     SDValue NewCond = LowerSETCC(Cond, DAG);
14303     if (NewCond.getNode())
14304       Cond = NewCond;
14305   }
14306
14307   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14308   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14309   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14310   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14311   if (Cond.getOpcode() == X86ISD::SETCC &&
14312       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14313       isZero(Cond.getOperand(1).getOperand(1))) {
14314     SDValue Cmp = Cond.getOperand(1);
14315
14316     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14317
14318     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14319         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14320       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14321
14322       SDValue CmpOp0 = Cmp.getOperand(0);
14323       // Apply further optimizations for special cases
14324       // (select (x != 0), -1, 0) -> neg & sbb
14325       // (select (x == 0), 0, -1) -> neg & sbb
14326       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14327         if (YC->isNullValue() &&
14328             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14329           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14330           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14331                                     DAG.getConstant(0, CmpOp0.getValueType()),
14332                                     CmpOp0);
14333           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14334                                     DAG.getConstant(X86::COND_B, MVT::i8),
14335                                     SDValue(Neg.getNode(), 1));
14336           return Res;
14337         }
14338
14339       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14340                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
14341       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14342
14343       SDValue Res =   // Res = 0 or -1.
14344         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14345                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
14346
14347       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14348         Res = DAG.getNOT(DL, Res, Res.getValueType());
14349
14350       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14351       if (!N2C || !N2C->isNullValue())
14352         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14353       return Res;
14354     }
14355   }
14356
14357   // Look past (and (setcc_carry (cmp ...)), 1).
14358   if (Cond.getOpcode() == ISD::AND &&
14359       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14360     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14361     if (C && C->getAPIntValue() == 1)
14362       Cond = Cond.getOperand(0);
14363   }
14364
14365   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14366   // setting operand in place of the X86ISD::SETCC.
14367   unsigned CondOpcode = Cond.getOpcode();
14368   if (CondOpcode == X86ISD::SETCC ||
14369       CondOpcode == X86ISD::SETCC_CARRY) {
14370     CC = Cond.getOperand(0);
14371
14372     SDValue Cmp = Cond.getOperand(1);
14373     unsigned Opc = Cmp.getOpcode();
14374     MVT VT = Op.getSimpleValueType();
14375
14376     bool IllegalFPCMov = false;
14377     if (VT.isFloatingPoint() && !VT.isVector() &&
14378         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14379       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14380
14381     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14382         Opc == X86ISD::BT) { // FIXME
14383       Cond = Cmp;
14384       addTest = false;
14385     }
14386   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14387              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14388              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14389               Cond.getOperand(0).getValueType() != MVT::i8)) {
14390     SDValue LHS = Cond.getOperand(0);
14391     SDValue RHS = Cond.getOperand(1);
14392     unsigned X86Opcode;
14393     unsigned X86Cond;
14394     SDVTList VTs;
14395     switch (CondOpcode) {
14396     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14397     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14398     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14399     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14400     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14401     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14402     default: llvm_unreachable("unexpected overflowing operator");
14403     }
14404     if (CondOpcode == ISD::UMULO)
14405       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14406                           MVT::i32);
14407     else
14408       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14409
14410     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14411
14412     if (CondOpcode == ISD::UMULO)
14413       Cond = X86Op.getValue(2);
14414     else
14415       Cond = X86Op.getValue(1);
14416
14417     CC = DAG.getConstant(X86Cond, MVT::i8);
14418     addTest = false;
14419   }
14420
14421   if (addTest) {
14422     // Look pass the truncate if the high bits are known zero.
14423     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14424         Cond = Cond.getOperand(0);
14425
14426     // We know the result of AND is compared against zero. Try to match
14427     // it to BT.
14428     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14429       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14430       if (NewSetCC.getNode()) {
14431         CC = NewSetCC.getOperand(0);
14432         Cond = NewSetCC.getOperand(1);
14433         addTest = false;
14434       }
14435     }
14436   }
14437
14438   if (addTest) {
14439     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
14440     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14441   }
14442
14443   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14444   // a <  b ?  0 : -1 -> RES = setcc_carry
14445   // a >= b ? -1 :  0 -> RES = setcc_carry
14446   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14447   if (Cond.getOpcode() == X86ISD::SUB) {
14448     Cond = ConvertCmpIfNecessary(Cond, DAG);
14449     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14450
14451     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14452         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14453       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14454                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
14455       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14456         return DAG.getNOT(DL, Res, Res.getValueType());
14457       return Res;
14458     }
14459   }
14460
14461   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14462   // widen the cmov and push the truncate through. This avoids introducing a new
14463   // branch during isel and doesn't add any extensions.
14464   if (Op.getValueType() == MVT::i8 &&
14465       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14466     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14467     if (T1.getValueType() == T2.getValueType() &&
14468         // Blacklist CopyFromReg to avoid partial register stalls.
14469         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14470       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14471       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14472       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14473     }
14474   }
14475
14476   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14477   // condition is true.
14478   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14479   SDValue Ops[] = { Op2, Op1, CC, Cond };
14480   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14481 }
14482
14483 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
14484   MVT VT = Op->getSimpleValueType(0);
14485   SDValue In = Op->getOperand(0);
14486   MVT InVT = In.getSimpleValueType();
14487   SDLoc dl(Op);
14488
14489   unsigned int NumElts = VT.getVectorNumElements();
14490   if (NumElts != 8 && NumElts != 16)
14491     return SDValue();
14492
14493   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
14494     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14495
14496   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14497   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14498
14499   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
14500   Constant *C = ConstantInt::get(*DAG.getContext(),
14501     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
14502
14503   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
14504   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
14505   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
14506                           MachinePointerInfo::getConstantPool(),
14507                           false, false, false, Alignment);
14508   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
14509   if (VT.is512BitVector())
14510     return Brcst;
14511   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
14512 }
14513
14514 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14515                                 SelectionDAG &DAG) {
14516   MVT VT = Op->getSimpleValueType(0);
14517   SDValue In = Op->getOperand(0);
14518   MVT InVT = In.getSimpleValueType();
14519   SDLoc dl(Op);
14520
14521   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14522     return LowerSIGN_EXTEND_AVX512(Op, DAG);
14523
14524   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14525       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14526       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14527     return SDValue();
14528
14529   if (Subtarget->hasInt256())
14530     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14531
14532   // Optimize vectors in AVX mode
14533   // Sign extend  v8i16 to v8i32 and
14534   //              v4i32 to v4i64
14535   //
14536   // Divide input vector into two parts
14537   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14538   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14539   // concat the vectors to original VT
14540
14541   unsigned NumElems = InVT.getVectorNumElements();
14542   SDValue Undef = DAG.getUNDEF(InVT);
14543
14544   SmallVector<int,8> ShufMask1(NumElems, -1);
14545   for (unsigned i = 0; i != NumElems/2; ++i)
14546     ShufMask1[i] = i;
14547
14548   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14549
14550   SmallVector<int,8> ShufMask2(NumElems, -1);
14551   for (unsigned i = 0; i != NumElems/2; ++i)
14552     ShufMask2[i] = i + NumElems/2;
14553
14554   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14555
14556   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14557                                 VT.getVectorNumElements()/2);
14558
14559   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14560   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14561
14562   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14563 }
14564
14565 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14566 // may emit an illegal shuffle but the expansion is still better than scalar
14567 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14568 // we'll emit a shuffle and a arithmetic shift.
14569 // TODO: It is possible to support ZExt by zeroing the undef values during
14570 // the shuffle phase or after the shuffle.
14571 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14572                                  SelectionDAG &DAG) {
14573   MVT RegVT = Op.getSimpleValueType();
14574   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14575   assert(RegVT.isInteger() &&
14576          "We only custom lower integer vector sext loads.");
14577
14578   // Nothing useful we can do without SSE2 shuffles.
14579   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14580
14581   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14582   SDLoc dl(Ld);
14583   EVT MemVT = Ld->getMemoryVT();
14584   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14585   unsigned RegSz = RegVT.getSizeInBits();
14586
14587   ISD::LoadExtType Ext = Ld->getExtensionType();
14588
14589   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14590          && "Only anyext and sext are currently implemented.");
14591   assert(MemVT != RegVT && "Cannot extend to the same type");
14592   assert(MemVT.isVector() && "Must load a vector from memory");
14593
14594   unsigned NumElems = RegVT.getVectorNumElements();
14595   unsigned MemSz = MemVT.getSizeInBits();
14596   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14597
14598   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14599     // The only way in which we have a legal 256-bit vector result but not the
14600     // integer 256-bit operations needed to directly lower a sextload is if we
14601     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14602     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14603     // correctly legalized. We do this late to allow the canonical form of
14604     // sextload to persist throughout the rest of the DAG combiner -- it wants
14605     // to fold together any extensions it can, and so will fuse a sign_extend
14606     // of an sextload into a sextload targeting a wider value.
14607     SDValue Load;
14608     if (MemSz == 128) {
14609       // Just switch this to a normal load.
14610       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14611                                        "it must be a legal 128-bit vector "
14612                                        "type!");
14613       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14614                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14615                   Ld->isInvariant(), Ld->getAlignment());
14616     } else {
14617       assert(MemSz < 128 &&
14618              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14619       // Do an sext load to a 128-bit vector type. We want to use the same
14620       // number of elements, but elements half as wide. This will end up being
14621       // recursively lowered by this routine, but will succeed as we definitely
14622       // have all the necessary features if we're using AVX1.
14623       EVT HalfEltVT =
14624           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14625       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14626       Load =
14627           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14628                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14629                          Ld->isNonTemporal(), Ld->isInvariant(),
14630                          Ld->getAlignment());
14631     }
14632
14633     // Replace chain users with the new chain.
14634     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14635     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14636
14637     // Finally, do a normal sign-extend to the desired register.
14638     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14639   }
14640
14641   // All sizes must be a power of two.
14642   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14643          "Non-power-of-two elements are not custom lowered!");
14644
14645   // Attempt to load the original value using scalar loads.
14646   // Find the largest scalar type that divides the total loaded size.
14647   MVT SclrLoadTy = MVT::i8;
14648   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
14649        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
14650     MVT Tp = (MVT::SimpleValueType)tp;
14651     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14652       SclrLoadTy = Tp;
14653     }
14654   }
14655
14656   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14657   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14658       (64 <= MemSz))
14659     SclrLoadTy = MVT::f64;
14660
14661   // Calculate the number of scalar loads that we need to perform
14662   // in order to load our vector from memory.
14663   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14664
14665   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14666          "Can only lower sext loads with a single scalar load!");
14667
14668   unsigned loadRegZize = RegSz;
14669   if (Ext == ISD::SEXTLOAD && RegSz == 256)
14670     loadRegZize /= 2;
14671
14672   // Represent our vector as a sequence of elements which are the
14673   // largest scalar that we can load.
14674   EVT LoadUnitVecVT = EVT::getVectorVT(
14675       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14676
14677   // Represent the data using the same element type that is stored in
14678   // memory. In practice, we ''widen'' MemVT.
14679   EVT WideVecVT =
14680       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14681                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14682
14683   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14684          "Invalid vector type");
14685
14686   // We can't shuffle using an illegal type.
14687   assert(TLI.isTypeLegal(WideVecVT) &&
14688          "We only lower types that form legal widened vector types");
14689
14690   SmallVector<SDValue, 8> Chains;
14691   SDValue Ptr = Ld->getBasePtr();
14692   SDValue Increment =
14693       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
14694   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14695
14696   for (unsigned i = 0; i < NumLoads; ++i) {
14697     // Perform a single load.
14698     SDValue ScalarLoad =
14699         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14700                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14701                     Ld->getAlignment());
14702     Chains.push_back(ScalarLoad.getValue(1));
14703     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14704     // another round of DAGCombining.
14705     if (i == 0)
14706       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14707     else
14708       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14709                         ScalarLoad, DAG.getIntPtrConstant(i));
14710
14711     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14712   }
14713
14714   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14715
14716   // Bitcast the loaded value to a vector of the original element type, in
14717   // the size of the target vector type.
14718   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
14719   unsigned SizeRatio = RegSz / MemSz;
14720
14721   if (Ext == ISD::SEXTLOAD) {
14722     // If we have SSE4.1, we can directly emit a VSEXT node.
14723     if (Subtarget->hasSSE41()) {
14724       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14725       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14726       return Sext;
14727     }
14728
14729     // Otherwise we'll shuffle the small elements in the high bits of the
14730     // larger type and perform an arithmetic shift. If the shift is not legal
14731     // it's better to scalarize.
14732     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14733            "We can't implement a sext load without an arithmetic right shift!");
14734
14735     // Redistribute the loaded elements into the different locations.
14736     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14737     for (unsigned i = 0; i != NumElems; ++i)
14738       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14739
14740     SDValue Shuff = DAG.getVectorShuffle(
14741         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14742
14743     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14744
14745     // Build the arithmetic shift.
14746     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14747                    MemVT.getVectorElementType().getSizeInBits();
14748     Shuff =
14749         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
14750
14751     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14752     return Shuff;
14753   }
14754
14755   // Redistribute the loaded elements into the different locations.
14756   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14757   for (unsigned i = 0; i != NumElems; ++i)
14758     ShuffleVec[i * SizeRatio] = i;
14759
14760   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14761                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14762
14763   // Bitcast to the requested type.
14764   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
14765   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14766   return Shuff;
14767 }
14768
14769 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14770 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14771 // from the AND / OR.
14772 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14773   Opc = Op.getOpcode();
14774   if (Opc != ISD::OR && Opc != ISD::AND)
14775     return false;
14776   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14777           Op.getOperand(0).hasOneUse() &&
14778           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14779           Op.getOperand(1).hasOneUse());
14780 }
14781
14782 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14783 // 1 and that the SETCC node has a single use.
14784 static bool isXor1OfSetCC(SDValue Op) {
14785   if (Op.getOpcode() != ISD::XOR)
14786     return false;
14787   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14788   if (N1C && N1C->getAPIntValue() == 1) {
14789     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14790       Op.getOperand(0).hasOneUse();
14791   }
14792   return false;
14793 }
14794
14795 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14796   bool addTest = true;
14797   SDValue Chain = Op.getOperand(0);
14798   SDValue Cond  = Op.getOperand(1);
14799   SDValue Dest  = Op.getOperand(2);
14800   SDLoc dl(Op);
14801   SDValue CC;
14802   bool Inverted = false;
14803
14804   if (Cond.getOpcode() == ISD::SETCC) {
14805     // Check for setcc([su]{add,sub,mul}o == 0).
14806     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14807         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14808         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14809         Cond.getOperand(0).getResNo() == 1 &&
14810         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14811          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14812          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14813          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14814          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14815          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14816       Inverted = true;
14817       Cond = Cond.getOperand(0);
14818     } else {
14819       SDValue NewCond = LowerSETCC(Cond, DAG);
14820       if (NewCond.getNode())
14821         Cond = NewCond;
14822     }
14823   }
14824 #if 0
14825   // FIXME: LowerXALUO doesn't handle these!!
14826   else if (Cond.getOpcode() == X86ISD::ADD  ||
14827            Cond.getOpcode() == X86ISD::SUB  ||
14828            Cond.getOpcode() == X86ISD::SMUL ||
14829            Cond.getOpcode() == X86ISD::UMUL)
14830     Cond = LowerXALUO(Cond, DAG);
14831 #endif
14832
14833   // Look pass (and (setcc_carry (cmp ...)), 1).
14834   if (Cond.getOpcode() == ISD::AND &&
14835       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14836     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14837     if (C && C->getAPIntValue() == 1)
14838       Cond = Cond.getOperand(0);
14839   }
14840
14841   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14842   // setting operand in place of the X86ISD::SETCC.
14843   unsigned CondOpcode = Cond.getOpcode();
14844   if (CondOpcode == X86ISD::SETCC ||
14845       CondOpcode == X86ISD::SETCC_CARRY) {
14846     CC = Cond.getOperand(0);
14847
14848     SDValue Cmp = Cond.getOperand(1);
14849     unsigned Opc = Cmp.getOpcode();
14850     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14851     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14852       Cond = Cmp;
14853       addTest = false;
14854     } else {
14855       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14856       default: break;
14857       case X86::COND_O:
14858       case X86::COND_B:
14859         // These can only come from an arithmetic instruction with overflow,
14860         // e.g. SADDO, UADDO.
14861         Cond = Cond.getNode()->getOperand(1);
14862         addTest = false;
14863         break;
14864       }
14865     }
14866   }
14867   CondOpcode = Cond.getOpcode();
14868   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14869       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14870       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14871        Cond.getOperand(0).getValueType() != MVT::i8)) {
14872     SDValue LHS = Cond.getOperand(0);
14873     SDValue RHS = Cond.getOperand(1);
14874     unsigned X86Opcode;
14875     unsigned X86Cond;
14876     SDVTList VTs;
14877     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14878     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14879     // X86ISD::INC).
14880     switch (CondOpcode) {
14881     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14882     case ISD::SADDO:
14883       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14884         if (C->isOne()) {
14885           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14886           break;
14887         }
14888       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14889     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14890     case ISD::SSUBO:
14891       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14892         if (C->isOne()) {
14893           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14894           break;
14895         }
14896       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14897     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14898     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14899     default: llvm_unreachable("unexpected overflowing operator");
14900     }
14901     if (Inverted)
14902       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14903     if (CondOpcode == ISD::UMULO)
14904       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14905                           MVT::i32);
14906     else
14907       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14908
14909     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14910
14911     if (CondOpcode == ISD::UMULO)
14912       Cond = X86Op.getValue(2);
14913     else
14914       Cond = X86Op.getValue(1);
14915
14916     CC = DAG.getConstant(X86Cond, MVT::i8);
14917     addTest = false;
14918   } else {
14919     unsigned CondOpc;
14920     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14921       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14922       if (CondOpc == ISD::OR) {
14923         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14924         // two branches instead of an explicit OR instruction with a
14925         // separate test.
14926         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14927             isX86LogicalCmp(Cmp)) {
14928           CC = Cond.getOperand(0).getOperand(0);
14929           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14930                               Chain, Dest, CC, Cmp);
14931           CC = Cond.getOperand(1).getOperand(0);
14932           Cond = Cmp;
14933           addTest = false;
14934         }
14935       } else { // ISD::AND
14936         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14937         // two branches instead of an explicit AND instruction with a
14938         // separate test. However, we only do this if this block doesn't
14939         // have a fall-through edge, because this requires an explicit
14940         // jmp when the condition is false.
14941         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14942             isX86LogicalCmp(Cmp) &&
14943             Op.getNode()->hasOneUse()) {
14944           X86::CondCode CCode =
14945             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14946           CCode = X86::GetOppositeBranchCondition(CCode);
14947           CC = DAG.getConstant(CCode, MVT::i8);
14948           SDNode *User = *Op.getNode()->use_begin();
14949           // Look for an unconditional branch following this conditional branch.
14950           // We need this because we need to reverse the successors in order
14951           // to implement FCMP_OEQ.
14952           if (User->getOpcode() == ISD::BR) {
14953             SDValue FalseBB = User->getOperand(1);
14954             SDNode *NewBR =
14955               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14956             assert(NewBR == User);
14957             (void)NewBR;
14958             Dest = FalseBB;
14959
14960             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14961                                 Chain, Dest, CC, Cmp);
14962             X86::CondCode CCode =
14963               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14964             CCode = X86::GetOppositeBranchCondition(CCode);
14965             CC = DAG.getConstant(CCode, MVT::i8);
14966             Cond = Cmp;
14967             addTest = false;
14968           }
14969         }
14970       }
14971     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14972       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14973       // It should be transformed during dag combiner except when the condition
14974       // is set by a arithmetics with overflow node.
14975       X86::CondCode CCode =
14976         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14977       CCode = X86::GetOppositeBranchCondition(CCode);
14978       CC = DAG.getConstant(CCode, MVT::i8);
14979       Cond = Cond.getOperand(0).getOperand(1);
14980       addTest = false;
14981     } else if (Cond.getOpcode() == ISD::SETCC &&
14982                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14983       // For FCMP_OEQ, we can emit
14984       // two branches instead of an explicit AND instruction with a
14985       // separate test. However, we only do this if this block doesn't
14986       // have a fall-through edge, because this requires an explicit
14987       // jmp when the condition is false.
14988       if (Op.getNode()->hasOneUse()) {
14989         SDNode *User = *Op.getNode()->use_begin();
14990         // Look for an unconditional branch following this conditional branch.
14991         // We need this because we need to reverse the successors in order
14992         // to implement FCMP_OEQ.
14993         if (User->getOpcode() == ISD::BR) {
14994           SDValue FalseBB = User->getOperand(1);
14995           SDNode *NewBR =
14996             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14997           assert(NewBR == User);
14998           (void)NewBR;
14999           Dest = FalseBB;
15000
15001           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15002                                     Cond.getOperand(0), Cond.getOperand(1));
15003           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15004           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15005           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15006                               Chain, Dest, CC, Cmp);
15007           CC = DAG.getConstant(X86::COND_P, MVT::i8);
15008           Cond = Cmp;
15009           addTest = false;
15010         }
15011       }
15012     } else if (Cond.getOpcode() == ISD::SETCC &&
15013                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
15014       // For FCMP_UNE, we can emit
15015       // two branches instead of an explicit AND instruction with a
15016       // separate test. However, we only do this if this block doesn't
15017       // have a fall-through edge, because this requires an explicit
15018       // jmp when the condition is false.
15019       if (Op.getNode()->hasOneUse()) {
15020         SDNode *User = *Op.getNode()->use_begin();
15021         // Look for an unconditional branch following this conditional branch.
15022         // We need this because we need to reverse the successors in order
15023         // to implement FCMP_UNE.
15024         if (User->getOpcode() == ISD::BR) {
15025           SDValue FalseBB = User->getOperand(1);
15026           SDNode *NewBR =
15027             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
15028           assert(NewBR == User);
15029           (void)NewBR;
15030
15031           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
15032                                     Cond.getOperand(0), Cond.getOperand(1));
15033           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
15034           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
15035           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15036                               Chain, Dest, CC, Cmp);
15037           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
15038           Cond = Cmp;
15039           addTest = false;
15040           Dest = FalseBB;
15041         }
15042       }
15043     }
15044   }
15045
15046   if (addTest) {
15047     // Look pass the truncate if the high bits are known zero.
15048     if (isTruncWithZeroHighBitsInput(Cond, DAG))
15049         Cond = Cond.getOperand(0);
15050
15051     // We know the result of AND is compared against zero. Try to match
15052     // it to BT.
15053     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
15054       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
15055       if (NewSetCC.getNode()) {
15056         CC = NewSetCC.getOperand(0);
15057         Cond = NewSetCC.getOperand(1);
15058         addTest = false;
15059       }
15060     }
15061   }
15062
15063   if (addTest) {
15064     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
15065     CC = DAG.getConstant(X86Cond, MVT::i8);
15066     Cond = EmitTest(Cond, X86Cond, dl, DAG);
15067   }
15068   Cond = ConvertCmpIfNecessary(Cond, DAG);
15069   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
15070                      Chain, Dest, CC, Cond);
15071 }
15072
15073 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
15074 // Calls to _alloca are needed to probe the stack when allocating more than 4k
15075 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
15076 // that the guard pages used by the OS virtual memory manager are allocated in
15077 // correct sequence.
15078 SDValue
15079 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
15080                                            SelectionDAG &DAG) const {
15081   MachineFunction &MF = DAG.getMachineFunction();
15082   bool SplitStack = MF.shouldSplitStack();
15083   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
15084                SplitStack;
15085   SDLoc dl(Op);
15086
15087   if (!Lower) {
15088     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15089     SDNode* Node = Op.getNode();
15090
15091     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
15092     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
15093         " not tell us which reg is the stack pointer!");
15094     EVT VT = Node->getValueType(0);
15095     SDValue Tmp1 = SDValue(Node, 0);
15096     SDValue Tmp2 = SDValue(Node, 1);
15097     SDValue Tmp3 = Node->getOperand(2);
15098     SDValue Chain = Tmp1.getOperand(0);
15099
15100     // Chain the dynamic stack allocation so that it doesn't modify the stack
15101     // pointer when other instructions are using the stack.
15102     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
15103         SDLoc(Node));
15104
15105     SDValue Size = Tmp2.getOperand(1);
15106     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
15107     Chain = SP.getValue(1);
15108     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
15109     const TargetFrameLowering &TFI = *DAG.getSubtarget().getFrameLowering();
15110     unsigned StackAlign = TFI.getStackAlignment();
15111     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
15112     if (Align > StackAlign)
15113       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
15114           DAG.getConstant(-(uint64_t)Align, VT));
15115     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
15116
15117     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
15118         DAG.getIntPtrConstant(0, true), SDValue(),
15119         SDLoc(Node));
15120
15121     SDValue Ops[2] = { Tmp1, Tmp2 };
15122     return DAG.getMergeValues(Ops, dl);
15123   }
15124
15125   // Get the inputs.
15126   SDValue Chain = Op.getOperand(0);
15127   SDValue Size  = Op.getOperand(1);
15128   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
15129   EVT VT = Op.getNode()->getValueType(0);
15130
15131   bool Is64Bit = Subtarget->is64Bit();
15132   EVT SPTy = getPointerTy();
15133
15134   if (SplitStack) {
15135     MachineRegisterInfo &MRI = MF.getRegInfo();
15136
15137     if (Is64Bit) {
15138       // The 64 bit implementation of segmented stacks needs to clobber both r10
15139       // r11. This makes it impossible to use it along with nested parameters.
15140       const Function *F = MF.getFunction();
15141
15142       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
15143            I != E; ++I)
15144         if (I->hasNestAttr())
15145           report_fatal_error("Cannot use segmented stacks with functions that "
15146                              "have nested arguments.");
15147     }
15148
15149     const TargetRegisterClass *AddrRegClass =
15150       getRegClassFor(getPointerTy());
15151     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
15152     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
15153     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
15154                                 DAG.getRegister(Vreg, SPTy));
15155     SDValue Ops1[2] = { Value, Chain };
15156     return DAG.getMergeValues(Ops1, dl);
15157   } else {
15158     SDValue Flag;
15159     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
15160
15161     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
15162     Flag = Chain.getValue(1);
15163     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
15164
15165     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
15166
15167     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15168         DAG.getSubtarget().getRegisterInfo());
15169     unsigned SPReg = RegInfo->getStackRegister();
15170     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
15171     Chain = SP.getValue(1);
15172
15173     if (Align) {
15174       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
15175                        DAG.getConstant(-(uint64_t)Align, VT));
15176       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
15177     }
15178
15179     SDValue Ops1[2] = { SP, Chain };
15180     return DAG.getMergeValues(Ops1, dl);
15181   }
15182 }
15183
15184 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
15185   MachineFunction &MF = DAG.getMachineFunction();
15186   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15187
15188   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15189   SDLoc DL(Op);
15190
15191   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
15192     // vastart just stores the address of the VarArgsFrameIndex slot into the
15193     // memory location argument.
15194     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
15195                                    getPointerTy());
15196     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
15197                         MachinePointerInfo(SV), false, false, 0);
15198   }
15199
15200   // __va_list_tag:
15201   //   gp_offset         (0 - 6 * 8)
15202   //   fp_offset         (48 - 48 + 8 * 16)
15203   //   overflow_arg_area (point to parameters coming in memory).
15204   //   reg_save_area
15205   SmallVector<SDValue, 8> MemOps;
15206   SDValue FIN = Op.getOperand(1);
15207   // Store gp_offset
15208   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15209                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15210                                                MVT::i32),
15211                                FIN, MachinePointerInfo(SV), false, false, 0);
15212   MemOps.push_back(Store);
15213
15214   // Store fp_offset
15215   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
15216                     FIN, DAG.getIntPtrConstant(4));
15217   Store = DAG.getStore(Op.getOperand(0), DL,
15218                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
15219                                        MVT::i32),
15220                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15221   MemOps.push_back(Store);
15222
15223   // Store ptr to overflow_arg_area
15224   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
15225                     FIN, DAG.getIntPtrConstant(4));
15226   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
15227                                     getPointerTy());
15228   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15229                        MachinePointerInfo(SV, 8),
15230                        false, false, 0);
15231   MemOps.push_back(Store);
15232
15233   // Store ptr to reg_save_area.
15234   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
15235                     FIN, DAG.getIntPtrConstant(8));
15236   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
15237                                     getPointerTy());
15238   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15239                        MachinePointerInfo(SV, 16), false, false, 0);
15240   MemOps.push_back(Store);
15241   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15242 }
15243
15244 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15245   assert(Subtarget->is64Bit() &&
15246          "LowerVAARG only handles 64-bit va_arg!");
15247   assert((Subtarget->isTargetLinux() ||
15248           Subtarget->isTargetDarwin()) &&
15249           "Unhandled target in LowerVAARG");
15250   assert(Op.getNode()->getNumOperands() == 4);
15251   SDValue Chain = Op.getOperand(0);
15252   SDValue SrcPtr = Op.getOperand(1);
15253   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15254   unsigned Align = Op.getConstantOperandVal(3);
15255   SDLoc dl(Op);
15256
15257   EVT ArgVT = Op.getNode()->getValueType(0);
15258   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15259   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
15260   uint8_t ArgMode;
15261
15262   // Decide which area this value should be read from.
15263   // TODO: Implement the AMD64 ABI in its entirety. This simple
15264   // selection mechanism works only for the basic types.
15265   if (ArgVT == MVT::f80) {
15266     llvm_unreachable("va_arg for f80 not yet implemented");
15267   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15268     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15269   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15270     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15271   } else {
15272     llvm_unreachable("Unhandled argument type in LowerVAARG");
15273   }
15274
15275   if (ArgMode == 2) {
15276     // Sanity Check: Make sure using fp_offset makes sense.
15277     assert(!DAG.getTarget().Options.UseSoftFloat &&
15278            !(DAG.getMachineFunction()
15279                 .getFunction()->getAttributes()
15280                 .hasAttribute(AttributeSet::FunctionIndex,
15281                               Attribute::NoImplicitFloat)) &&
15282            Subtarget->hasSSE1());
15283   }
15284
15285   // Insert VAARG_64 node into the DAG
15286   // VAARG_64 returns two values: Variable Argument Address, Chain
15287   SmallVector<SDValue, 11> InstOps;
15288   InstOps.push_back(Chain);
15289   InstOps.push_back(SrcPtr);
15290   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
15291   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
15292   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
15293   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
15294   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15295                                           VTs, InstOps, MVT::i64,
15296                                           MachinePointerInfo(SV),
15297                                           /*Align=*/0,
15298                                           /*Volatile=*/false,
15299                                           /*ReadMem=*/true,
15300                                           /*WriteMem=*/true);
15301   Chain = VAARG.getValue(1);
15302
15303   // Load the next argument and return it
15304   return DAG.getLoad(ArgVT, dl,
15305                      Chain,
15306                      VAARG,
15307                      MachinePointerInfo(),
15308                      false, false, false, 0);
15309 }
15310
15311 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15312                            SelectionDAG &DAG) {
15313   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15314   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15315   SDValue Chain = Op.getOperand(0);
15316   SDValue DstPtr = Op.getOperand(1);
15317   SDValue SrcPtr = Op.getOperand(2);
15318   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15319   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15320   SDLoc DL(Op);
15321
15322   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15323                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
15324                        false,
15325                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15326 }
15327
15328 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15329 // amount is a constant. Takes immediate version of shift as input.
15330 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15331                                           SDValue SrcOp, uint64_t ShiftAmt,
15332                                           SelectionDAG &DAG) {
15333   MVT ElementType = VT.getVectorElementType();
15334
15335   // Fold this packed shift into its first operand if ShiftAmt is 0.
15336   if (ShiftAmt == 0)
15337     return SrcOp;
15338
15339   // Check for ShiftAmt >= element width
15340   if (ShiftAmt >= ElementType.getSizeInBits()) {
15341     if (Opc == X86ISD::VSRAI)
15342       ShiftAmt = ElementType.getSizeInBits() - 1;
15343     else
15344       return DAG.getConstant(0, VT);
15345   }
15346
15347   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15348          && "Unknown target vector shift-by-constant node");
15349
15350   // Fold this packed vector shift into a build vector if SrcOp is a
15351   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15352   if (VT == SrcOp.getSimpleValueType() &&
15353       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15354     SmallVector<SDValue, 8> Elts;
15355     unsigned NumElts = SrcOp->getNumOperands();
15356     ConstantSDNode *ND;
15357
15358     switch(Opc) {
15359     default: llvm_unreachable(nullptr);
15360     case X86ISD::VSHLI:
15361       for (unsigned i=0; i!=NumElts; ++i) {
15362         SDValue CurrentOp = SrcOp->getOperand(i);
15363         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15364           Elts.push_back(CurrentOp);
15365           continue;
15366         }
15367         ND = cast<ConstantSDNode>(CurrentOp);
15368         const APInt &C = ND->getAPIntValue();
15369         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
15370       }
15371       break;
15372     case X86ISD::VSRLI:
15373       for (unsigned i=0; i!=NumElts; ++i) {
15374         SDValue CurrentOp = SrcOp->getOperand(i);
15375         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15376           Elts.push_back(CurrentOp);
15377           continue;
15378         }
15379         ND = cast<ConstantSDNode>(CurrentOp);
15380         const APInt &C = ND->getAPIntValue();
15381         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
15382       }
15383       break;
15384     case X86ISD::VSRAI:
15385       for (unsigned i=0; i!=NumElts; ++i) {
15386         SDValue CurrentOp = SrcOp->getOperand(i);
15387         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15388           Elts.push_back(CurrentOp);
15389           continue;
15390         }
15391         ND = cast<ConstantSDNode>(CurrentOp);
15392         const APInt &C = ND->getAPIntValue();
15393         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
15394       }
15395       break;
15396     }
15397
15398     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15399   }
15400
15401   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
15402 }
15403
15404 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15405 // may or may not be a constant. Takes immediate version of shift as input.
15406 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15407                                    SDValue SrcOp, SDValue ShAmt,
15408                                    SelectionDAG &DAG) {
15409   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
15410
15411   // Catch shift-by-constant.
15412   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15413     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15414                                       CShAmt->getZExtValue(), DAG);
15415
15416   // Change opcode to non-immediate version
15417   switch (Opc) {
15418     default: llvm_unreachable("Unknown target vector shift node");
15419     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15420     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15421     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15422   }
15423
15424   // Need to build a vector containing shift amount
15425   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
15426   SDValue ShOps[4];
15427   ShOps[0] = ShAmt;
15428   ShOps[1] = DAG.getConstant(0, MVT::i32);
15429   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
15430   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
15431
15432   // The return type has to be a 128-bit type with the same element
15433   // type as the input type.
15434   MVT EltVT = VT.getVectorElementType();
15435   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15436
15437   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
15438   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15439 }
15440
15441 /// \brief Return (vselect \p Mask, \p Op, \p PreservedSrc) along with the
15442 /// necessary casting for \p Mask when lowering masking intrinsics.
15443 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15444                                     SDValue PreservedSrc, SelectionDAG &DAG) {
15445     EVT VT = Op.getValueType();
15446     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15447                                   MVT::i1, VT.getVectorNumElements());
15448     SDLoc dl(Op);
15449
15450     assert(MaskVT.isSimple() && "invalid mask type");
15451     return DAG.getNode(ISD::VSELECT, dl, VT,
15452                        DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask),
15453                        Op, PreservedSrc);
15454 }
15455
15456 static unsigned getOpcodeForFMAIntrinsic(unsigned IntNo) {
15457     switch (IntNo) {
15458     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15459     case Intrinsic::x86_fma_vfmadd_ps:
15460     case Intrinsic::x86_fma_vfmadd_pd:
15461     case Intrinsic::x86_fma_vfmadd_ps_256:
15462     case Intrinsic::x86_fma_vfmadd_pd_256:
15463     case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15464     case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15465       return X86ISD::FMADD;
15466     case Intrinsic::x86_fma_vfmsub_ps:
15467     case Intrinsic::x86_fma_vfmsub_pd:
15468     case Intrinsic::x86_fma_vfmsub_ps_256:
15469     case Intrinsic::x86_fma_vfmsub_pd_256:
15470     case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15471     case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15472       return X86ISD::FMSUB;
15473     case Intrinsic::x86_fma_vfnmadd_ps:
15474     case Intrinsic::x86_fma_vfnmadd_pd:
15475     case Intrinsic::x86_fma_vfnmadd_ps_256:
15476     case Intrinsic::x86_fma_vfnmadd_pd_256:
15477     case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15478     case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15479       return X86ISD::FNMADD;
15480     case Intrinsic::x86_fma_vfnmsub_ps:
15481     case Intrinsic::x86_fma_vfnmsub_pd:
15482     case Intrinsic::x86_fma_vfnmsub_ps_256:
15483     case Intrinsic::x86_fma_vfnmsub_pd_256:
15484     case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15485     case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15486       return X86ISD::FNMSUB;
15487     case Intrinsic::x86_fma_vfmaddsub_ps:
15488     case Intrinsic::x86_fma_vfmaddsub_pd:
15489     case Intrinsic::x86_fma_vfmaddsub_ps_256:
15490     case Intrinsic::x86_fma_vfmaddsub_pd_256:
15491     case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15492     case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15493       return X86ISD::FMADDSUB;
15494     case Intrinsic::x86_fma_vfmsubadd_ps:
15495     case Intrinsic::x86_fma_vfmsubadd_pd:
15496     case Intrinsic::x86_fma_vfmsubadd_ps_256:
15497     case Intrinsic::x86_fma_vfmsubadd_pd_256:
15498     case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15499     case Intrinsic::x86_fma_mask_vfmsubadd_pd_512:
15500       return X86ISD::FMSUBADD;
15501     }
15502 }
15503
15504 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
15505   SDLoc dl(Op);
15506   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15507
15508   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15509   if (IntrData) {
15510     switch(IntrData->Type) {
15511     case INTR_TYPE_1OP:
15512       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15513     case INTR_TYPE_2OP:
15514       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15515         Op.getOperand(2));
15516     case INTR_TYPE_3OP:
15517       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15518         Op.getOperand(2), Op.getOperand(3));
15519     case COMI: { // Comparison intrinsics
15520       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15521       SDValue LHS = Op.getOperand(1);
15522       SDValue RHS = Op.getOperand(2);
15523       unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
15524       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15525       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15526       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15527                                   DAG.getConstant(X86CC, MVT::i8), Cond);
15528       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15529     }
15530     case VSHIFT:
15531       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15532                                  Op.getOperand(1), Op.getOperand(2), DAG);
15533     default:
15534       break;
15535     }
15536   }
15537
15538   switch (IntNo) {
15539   default: return SDValue();    // Don't custom lower most intrinsics.
15540
15541   // Arithmetic intrinsics.
15542   case Intrinsic::x86_sse2_pmulu_dq:
15543   case Intrinsic::x86_avx2_pmulu_dq:
15544     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
15545                        Op.getOperand(1), Op.getOperand(2));
15546
15547   case Intrinsic::x86_sse41_pmuldq:
15548   case Intrinsic::x86_avx2_pmul_dq:
15549     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
15550                        Op.getOperand(1), Op.getOperand(2));
15551
15552   case Intrinsic::x86_sse2_pmulhu_w:
15553   case Intrinsic::x86_avx2_pmulhu_w:
15554     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
15555                        Op.getOperand(1), Op.getOperand(2));
15556
15557   case Intrinsic::x86_sse2_pmulh_w:
15558   case Intrinsic::x86_avx2_pmulh_w:
15559     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
15560                        Op.getOperand(1), Op.getOperand(2));
15561
15562   // SSE/SSE2/AVX floating point max/min intrinsics.
15563   case Intrinsic::x86_sse_max_ps:
15564   case Intrinsic::x86_sse2_max_pd:
15565   case Intrinsic::x86_avx_max_ps_256:
15566   case Intrinsic::x86_avx_max_pd_256:
15567   case Intrinsic::x86_sse_min_ps:
15568   case Intrinsic::x86_sse2_min_pd:
15569   case Intrinsic::x86_avx_min_ps_256:
15570   case Intrinsic::x86_avx_min_pd_256: {
15571     unsigned Opcode;
15572     switch (IntNo) {
15573     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15574     case Intrinsic::x86_sse_max_ps:
15575     case Intrinsic::x86_sse2_max_pd:
15576     case Intrinsic::x86_avx_max_ps_256:
15577     case Intrinsic::x86_avx_max_pd_256:
15578       Opcode = X86ISD::FMAX;
15579       break;
15580     case Intrinsic::x86_sse_min_ps:
15581     case Intrinsic::x86_sse2_min_pd:
15582     case Intrinsic::x86_avx_min_ps_256:
15583     case Intrinsic::x86_avx_min_pd_256:
15584       Opcode = X86ISD::FMIN;
15585       break;
15586     }
15587     return DAG.getNode(Opcode, dl, Op.getValueType(),
15588                        Op.getOperand(1), Op.getOperand(2));
15589   }
15590
15591   // AVX2 variable shift intrinsics
15592   case Intrinsic::x86_avx2_psllv_d:
15593   case Intrinsic::x86_avx2_psllv_q:
15594   case Intrinsic::x86_avx2_psllv_d_256:
15595   case Intrinsic::x86_avx2_psllv_q_256:
15596   case Intrinsic::x86_avx2_psrlv_d:
15597   case Intrinsic::x86_avx2_psrlv_q:
15598   case Intrinsic::x86_avx2_psrlv_d_256:
15599   case Intrinsic::x86_avx2_psrlv_q_256:
15600   case Intrinsic::x86_avx2_psrav_d:
15601   case Intrinsic::x86_avx2_psrav_d_256: {
15602     unsigned Opcode;
15603     switch (IntNo) {
15604     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15605     case Intrinsic::x86_avx2_psllv_d:
15606     case Intrinsic::x86_avx2_psllv_q:
15607     case Intrinsic::x86_avx2_psllv_d_256:
15608     case Intrinsic::x86_avx2_psllv_q_256:
15609       Opcode = ISD::SHL;
15610       break;
15611     case Intrinsic::x86_avx2_psrlv_d:
15612     case Intrinsic::x86_avx2_psrlv_q:
15613     case Intrinsic::x86_avx2_psrlv_d_256:
15614     case Intrinsic::x86_avx2_psrlv_q_256:
15615       Opcode = ISD::SRL;
15616       break;
15617     case Intrinsic::x86_avx2_psrav_d:
15618     case Intrinsic::x86_avx2_psrav_d_256:
15619       Opcode = ISD::SRA;
15620       break;
15621     }
15622     return DAG.getNode(Opcode, dl, Op.getValueType(),
15623                        Op.getOperand(1), Op.getOperand(2));
15624   }
15625
15626   case Intrinsic::x86_sse2_packssdw_128:
15627   case Intrinsic::x86_sse2_packsswb_128:
15628   case Intrinsic::x86_avx2_packssdw:
15629   case Intrinsic::x86_avx2_packsswb:
15630     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
15631                        Op.getOperand(1), Op.getOperand(2));
15632
15633   case Intrinsic::x86_sse2_packuswb_128:
15634   case Intrinsic::x86_sse41_packusdw:
15635   case Intrinsic::x86_avx2_packuswb:
15636   case Intrinsic::x86_avx2_packusdw:
15637     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
15638                        Op.getOperand(1), Op.getOperand(2));
15639
15640   case Intrinsic::x86_ssse3_pshuf_b_128:
15641   case Intrinsic::x86_avx2_pshuf_b:
15642     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
15643                        Op.getOperand(1), Op.getOperand(2));
15644
15645   case Intrinsic::x86_sse2_pshuf_d:
15646     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
15647                        Op.getOperand(1), Op.getOperand(2));
15648
15649   case Intrinsic::x86_sse2_pshufl_w:
15650     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
15651                        Op.getOperand(1), Op.getOperand(2));
15652
15653   case Intrinsic::x86_sse2_pshufh_w:
15654     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
15655                        Op.getOperand(1), Op.getOperand(2));
15656
15657   case Intrinsic::x86_ssse3_psign_b_128:
15658   case Intrinsic::x86_ssse3_psign_w_128:
15659   case Intrinsic::x86_ssse3_psign_d_128:
15660   case Intrinsic::x86_avx2_psign_b:
15661   case Intrinsic::x86_avx2_psign_w:
15662   case Intrinsic::x86_avx2_psign_d:
15663     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
15664                        Op.getOperand(1), Op.getOperand(2));
15665
15666   case Intrinsic::x86_avx2_permd:
15667   case Intrinsic::x86_avx2_permps:
15668     // Operands intentionally swapped. Mask is last operand to intrinsic,
15669     // but second operand for node/instruction.
15670     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15671                        Op.getOperand(2), Op.getOperand(1));
15672
15673   case Intrinsic::x86_avx512_mask_valign_q_512:
15674   case Intrinsic::x86_avx512_mask_valign_d_512:
15675     // Vector source operands are swapped.
15676     return getVectorMaskingNode(DAG.getNode(X86ISD::VALIGN, dl,
15677                                             Op.getValueType(), Op.getOperand(2),
15678                                             Op.getOperand(1),
15679                                             Op.getOperand(3)),
15680                                 Op.getOperand(5), Op.getOperand(4), DAG);
15681
15682   // ptest and testp intrinsics. The intrinsic these come from are designed to
15683   // return an integer value, not just an instruction so lower it to the ptest
15684   // or testp pattern and a setcc for the result.
15685   case Intrinsic::x86_sse41_ptestz:
15686   case Intrinsic::x86_sse41_ptestc:
15687   case Intrinsic::x86_sse41_ptestnzc:
15688   case Intrinsic::x86_avx_ptestz_256:
15689   case Intrinsic::x86_avx_ptestc_256:
15690   case Intrinsic::x86_avx_ptestnzc_256:
15691   case Intrinsic::x86_avx_vtestz_ps:
15692   case Intrinsic::x86_avx_vtestc_ps:
15693   case Intrinsic::x86_avx_vtestnzc_ps:
15694   case Intrinsic::x86_avx_vtestz_pd:
15695   case Intrinsic::x86_avx_vtestc_pd:
15696   case Intrinsic::x86_avx_vtestnzc_pd:
15697   case Intrinsic::x86_avx_vtestz_ps_256:
15698   case Intrinsic::x86_avx_vtestc_ps_256:
15699   case Intrinsic::x86_avx_vtestnzc_ps_256:
15700   case Intrinsic::x86_avx_vtestz_pd_256:
15701   case Intrinsic::x86_avx_vtestc_pd_256:
15702   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15703     bool IsTestPacked = false;
15704     unsigned X86CC;
15705     switch (IntNo) {
15706     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15707     case Intrinsic::x86_avx_vtestz_ps:
15708     case Intrinsic::x86_avx_vtestz_pd:
15709     case Intrinsic::x86_avx_vtestz_ps_256:
15710     case Intrinsic::x86_avx_vtestz_pd_256:
15711       IsTestPacked = true; // Fallthrough
15712     case Intrinsic::x86_sse41_ptestz:
15713     case Intrinsic::x86_avx_ptestz_256:
15714       // ZF = 1
15715       X86CC = X86::COND_E;
15716       break;
15717     case Intrinsic::x86_avx_vtestc_ps:
15718     case Intrinsic::x86_avx_vtestc_pd:
15719     case Intrinsic::x86_avx_vtestc_ps_256:
15720     case Intrinsic::x86_avx_vtestc_pd_256:
15721       IsTestPacked = true; // Fallthrough
15722     case Intrinsic::x86_sse41_ptestc:
15723     case Intrinsic::x86_avx_ptestc_256:
15724       // CF = 1
15725       X86CC = X86::COND_B;
15726       break;
15727     case Intrinsic::x86_avx_vtestnzc_ps:
15728     case Intrinsic::x86_avx_vtestnzc_pd:
15729     case Intrinsic::x86_avx_vtestnzc_ps_256:
15730     case Intrinsic::x86_avx_vtestnzc_pd_256:
15731       IsTestPacked = true; // Fallthrough
15732     case Intrinsic::x86_sse41_ptestnzc:
15733     case Intrinsic::x86_avx_ptestnzc_256:
15734       // ZF and CF = 0
15735       X86CC = X86::COND_A;
15736       break;
15737     }
15738
15739     SDValue LHS = Op.getOperand(1);
15740     SDValue RHS = Op.getOperand(2);
15741     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15742     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15743     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
15744     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15745     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15746   }
15747   case Intrinsic::x86_avx512_kortestz_w:
15748   case Intrinsic::x86_avx512_kortestc_w: {
15749     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15750     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
15751     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
15752     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
15753     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15754     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15755     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15756   }
15757
15758   case Intrinsic::x86_sse42_pcmpistria128:
15759   case Intrinsic::x86_sse42_pcmpestria128:
15760   case Intrinsic::x86_sse42_pcmpistric128:
15761   case Intrinsic::x86_sse42_pcmpestric128:
15762   case Intrinsic::x86_sse42_pcmpistrio128:
15763   case Intrinsic::x86_sse42_pcmpestrio128:
15764   case Intrinsic::x86_sse42_pcmpistris128:
15765   case Intrinsic::x86_sse42_pcmpestris128:
15766   case Intrinsic::x86_sse42_pcmpistriz128:
15767   case Intrinsic::x86_sse42_pcmpestriz128: {
15768     unsigned Opcode;
15769     unsigned X86CC;
15770     switch (IntNo) {
15771     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15772     case Intrinsic::x86_sse42_pcmpistria128:
15773       Opcode = X86ISD::PCMPISTRI;
15774       X86CC = X86::COND_A;
15775       break;
15776     case Intrinsic::x86_sse42_pcmpestria128:
15777       Opcode = X86ISD::PCMPESTRI;
15778       X86CC = X86::COND_A;
15779       break;
15780     case Intrinsic::x86_sse42_pcmpistric128:
15781       Opcode = X86ISD::PCMPISTRI;
15782       X86CC = X86::COND_B;
15783       break;
15784     case Intrinsic::x86_sse42_pcmpestric128:
15785       Opcode = X86ISD::PCMPESTRI;
15786       X86CC = X86::COND_B;
15787       break;
15788     case Intrinsic::x86_sse42_pcmpistrio128:
15789       Opcode = X86ISD::PCMPISTRI;
15790       X86CC = X86::COND_O;
15791       break;
15792     case Intrinsic::x86_sse42_pcmpestrio128:
15793       Opcode = X86ISD::PCMPESTRI;
15794       X86CC = X86::COND_O;
15795       break;
15796     case Intrinsic::x86_sse42_pcmpistris128:
15797       Opcode = X86ISD::PCMPISTRI;
15798       X86CC = X86::COND_S;
15799       break;
15800     case Intrinsic::x86_sse42_pcmpestris128:
15801       Opcode = X86ISD::PCMPESTRI;
15802       X86CC = X86::COND_S;
15803       break;
15804     case Intrinsic::x86_sse42_pcmpistriz128:
15805       Opcode = X86ISD::PCMPISTRI;
15806       X86CC = X86::COND_E;
15807       break;
15808     case Intrinsic::x86_sse42_pcmpestriz128:
15809       Opcode = X86ISD::PCMPESTRI;
15810       X86CC = X86::COND_E;
15811       break;
15812     }
15813     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15814     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15815     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15816     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15817                                 DAG.getConstant(X86CC, MVT::i8),
15818                                 SDValue(PCMP.getNode(), 1));
15819     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15820   }
15821
15822   case Intrinsic::x86_sse42_pcmpistri128:
15823   case Intrinsic::x86_sse42_pcmpestri128: {
15824     unsigned Opcode;
15825     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15826       Opcode = X86ISD::PCMPISTRI;
15827     else
15828       Opcode = X86ISD::PCMPESTRI;
15829
15830     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15831     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15832     return DAG.getNode(Opcode, dl, VTs, NewOps);
15833   }
15834
15835   case Intrinsic::x86_fma_mask_vfmadd_ps_512:
15836   case Intrinsic::x86_fma_mask_vfmadd_pd_512:
15837   case Intrinsic::x86_fma_mask_vfmsub_ps_512:
15838   case Intrinsic::x86_fma_mask_vfmsub_pd_512:
15839   case Intrinsic::x86_fma_mask_vfnmadd_ps_512:
15840   case Intrinsic::x86_fma_mask_vfnmadd_pd_512:
15841   case Intrinsic::x86_fma_mask_vfnmsub_ps_512:
15842   case Intrinsic::x86_fma_mask_vfnmsub_pd_512:
15843   case Intrinsic::x86_fma_mask_vfmaddsub_ps_512:
15844   case Intrinsic::x86_fma_mask_vfmaddsub_pd_512:
15845   case Intrinsic::x86_fma_mask_vfmsubadd_ps_512:
15846   case Intrinsic::x86_fma_mask_vfmsubadd_pd_512: {
15847     auto *SAE = cast<ConstantSDNode>(Op.getOperand(5));
15848     if (SAE->getZExtValue() == X86::STATIC_ROUNDING::CUR_DIRECTION)
15849       return getVectorMaskingNode(DAG.getNode(getOpcodeForFMAIntrinsic(IntNo),
15850                                               dl, Op.getValueType(),
15851                                               Op.getOperand(1),
15852                                               Op.getOperand(2),
15853                                               Op.getOperand(3)),
15854                                   Op.getOperand(4), Op.getOperand(1), DAG);
15855     else
15856       return SDValue();
15857   }
15858
15859   case Intrinsic::x86_fma_vfmadd_ps:
15860   case Intrinsic::x86_fma_vfmadd_pd:
15861   case Intrinsic::x86_fma_vfmsub_ps:
15862   case Intrinsic::x86_fma_vfmsub_pd:
15863   case Intrinsic::x86_fma_vfnmadd_ps:
15864   case Intrinsic::x86_fma_vfnmadd_pd:
15865   case Intrinsic::x86_fma_vfnmsub_ps:
15866   case Intrinsic::x86_fma_vfnmsub_pd:
15867   case Intrinsic::x86_fma_vfmaddsub_ps:
15868   case Intrinsic::x86_fma_vfmaddsub_pd:
15869   case Intrinsic::x86_fma_vfmsubadd_ps:
15870   case Intrinsic::x86_fma_vfmsubadd_pd:
15871   case Intrinsic::x86_fma_vfmadd_ps_256:
15872   case Intrinsic::x86_fma_vfmadd_pd_256:
15873   case Intrinsic::x86_fma_vfmsub_ps_256:
15874   case Intrinsic::x86_fma_vfmsub_pd_256:
15875   case Intrinsic::x86_fma_vfnmadd_ps_256:
15876   case Intrinsic::x86_fma_vfnmadd_pd_256:
15877   case Intrinsic::x86_fma_vfnmsub_ps_256:
15878   case Intrinsic::x86_fma_vfnmsub_pd_256:
15879   case Intrinsic::x86_fma_vfmaddsub_ps_256:
15880   case Intrinsic::x86_fma_vfmaddsub_pd_256:
15881   case Intrinsic::x86_fma_vfmsubadd_ps_256:
15882   case Intrinsic::x86_fma_vfmsubadd_pd_256:
15883     return DAG.getNode(getOpcodeForFMAIntrinsic(IntNo), dl, Op.getValueType(),
15884                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
15885   }
15886 }
15887
15888 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15889                               SDValue Src, SDValue Mask, SDValue Base,
15890                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15891                               const X86Subtarget * Subtarget) {
15892   SDLoc dl(Op);
15893   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15894   assert(C && "Invalid scale type");
15895   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15896   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15897                              Index.getSimpleValueType().getVectorNumElements());
15898   SDValue MaskInReg;
15899   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15900   if (MaskC)
15901     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15902   else
15903     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15904   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15905   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15906   SDValue Segment = DAG.getRegister(0, MVT::i32);
15907   if (Src.getOpcode() == ISD::UNDEF)
15908     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15909   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15910   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15911   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15912   return DAG.getMergeValues(RetOps, dl);
15913 }
15914
15915 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15916                                SDValue Src, SDValue Mask, SDValue Base,
15917                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15918   SDLoc dl(Op);
15919   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15920   assert(C && "Invalid scale type");
15921   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15922   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15923   SDValue Segment = DAG.getRegister(0, MVT::i32);
15924   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15925                              Index.getSimpleValueType().getVectorNumElements());
15926   SDValue MaskInReg;
15927   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15928   if (MaskC)
15929     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15930   else
15931     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15932   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15933   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15934   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15935   return SDValue(Res, 1);
15936 }
15937
15938 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15939                                SDValue Mask, SDValue Base, SDValue Index,
15940                                SDValue ScaleOp, SDValue Chain) {
15941   SDLoc dl(Op);
15942   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15943   assert(C && "Invalid scale type");
15944   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
15945   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
15946   SDValue Segment = DAG.getRegister(0, MVT::i32);
15947   EVT MaskVT =
15948     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15949   SDValue MaskInReg;
15950   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15951   if (MaskC)
15952     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
15953   else
15954     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
15955   //SDVTList VTs = DAG.getVTList(MVT::Other);
15956   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15957   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15958   return SDValue(Res, 0);
15959 }
15960
15961 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15962 // read performance monitor counters (x86_rdpmc).
15963 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15964                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15965                               SmallVectorImpl<SDValue> &Results) {
15966   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15967   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15968   SDValue LO, HI;
15969
15970   // The ECX register is used to select the index of the performance counter
15971   // to read.
15972   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15973                                    N->getOperand(2));
15974   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15975
15976   // Reads the content of a 64-bit performance counter and returns it in the
15977   // registers EDX:EAX.
15978   if (Subtarget->is64Bit()) {
15979     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15980     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15981                             LO.getValue(2));
15982   } else {
15983     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15984     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15985                             LO.getValue(2));
15986   }
15987   Chain = HI.getValue(1);
15988
15989   if (Subtarget->is64Bit()) {
15990     // The EAX register is loaded with the low-order 32 bits. The EDX register
15991     // is loaded with the supported high-order bits of the counter.
15992     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15993                               DAG.getConstant(32, MVT::i8));
15994     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15995     Results.push_back(Chain);
15996     return;
15997   }
15998
15999   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16000   SDValue Ops[] = { LO, HI };
16001   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16002   Results.push_back(Pair);
16003   Results.push_back(Chain);
16004 }
16005
16006 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16007 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16008 // also used to custom lower READCYCLECOUNTER nodes.
16009 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16010                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16011                               SmallVectorImpl<SDValue> &Results) {
16012   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16013   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16014   SDValue LO, HI;
16015
16016   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16017   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16018   // and the EAX register is loaded with the low-order 32 bits.
16019   if (Subtarget->is64Bit()) {
16020     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16021     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16022                             LO.getValue(2));
16023   } else {
16024     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16025     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16026                             LO.getValue(2));
16027   }
16028   SDValue Chain = HI.getValue(1);
16029
16030   if (Opcode == X86ISD::RDTSCP_DAG) {
16031     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16032
16033     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16034     // the ECX register. Add 'ecx' explicitly to the chain.
16035     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16036                                      HI.getValue(2));
16037     // Explicitly store the content of ECX at the location passed in input
16038     // to the 'rdtscp' intrinsic.
16039     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16040                          MachinePointerInfo(), false, false, 0);
16041   }
16042
16043   if (Subtarget->is64Bit()) {
16044     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16045     // the EAX register is loaded with the low-order 32 bits.
16046     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16047                               DAG.getConstant(32, MVT::i8));
16048     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16049     Results.push_back(Chain);
16050     return;
16051   }
16052
16053   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16054   SDValue Ops[] = { LO, HI };
16055   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16056   Results.push_back(Pair);
16057   Results.push_back(Chain);
16058 }
16059
16060 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16061                                      SelectionDAG &DAG) {
16062   SmallVector<SDValue, 2> Results;
16063   SDLoc DL(Op);
16064   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16065                           Results);
16066   return DAG.getMergeValues(Results, DL);
16067 }
16068
16069
16070 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16071                                       SelectionDAG &DAG) {
16072   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16073
16074   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16075   if (!IntrData)
16076     return SDValue();
16077
16078   SDLoc dl(Op);
16079   switch(IntrData->Type) {
16080   default:
16081     llvm_unreachable("Unknown Intrinsic Type");
16082     break;    
16083   case RDSEED:
16084   case RDRAND: {
16085     // Emit the node with the right value type.
16086     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16087     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16088
16089     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16090     // Otherwise return the value from Rand, which is always 0, casted to i32.
16091     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16092                       DAG.getConstant(1, Op->getValueType(1)),
16093                       DAG.getConstant(X86::COND_B, MVT::i32),
16094                       SDValue(Result.getNode(), 1) };
16095     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16096                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16097                                   Ops);
16098
16099     // Return { result, isValid, chain }.
16100     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16101                        SDValue(Result.getNode(), 2));
16102   }
16103   case GATHER: {
16104   //gather(v1, mask, index, base, scale);
16105     SDValue Chain = Op.getOperand(0);
16106     SDValue Src   = Op.getOperand(2);
16107     SDValue Base  = Op.getOperand(3);
16108     SDValue Index = Op.getOperand(4);
16109     SDValue Mask  = Op.getOperand(5);
16110     SDValue Scale = Op.getOperand(6);
16111     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
16112                           Subtarget);
16113   }
16114   case SCATTER: {
16115   //scatter(base, mask, index, v1, scale);
16116     SDValue Chain = Op.getOperand(0);
16117     SDValue Base  = Op.getOperand(2);
16118     SDValue Mask  = Op.getOperand(3);
16119     SDValue Index = Op.getOperand(4);
16120     SDValue Src   = Op.getOperand(5);
16121     SDValue Scale = Op.getOperand(6);
16122     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
16123   }
16124   case PREFETCH: {
16125     SDValue Hint = Op.getOperand(6);
16126     unsigned HintVal;
16127     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
16128         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
16129       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
16130     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16131     SDValue Chain = Op.getOperand(0);
16132     SDValue Mask  = Op.getOperand(2);
16133     SDValue Index = Op.getOperand(3);
16134     SDValue Base  = Op.getOperand(4);
16135     SDValue Scale = Op.getOperand(5);
16136     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16137   }
16138   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16139   case RDTSC: {
16140     SmallVector<SDValue, 2> Results;
16141     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget, Results);
16142     return DAG.getMergeValues(Results, dl);
16143   }
16144   // Read Performance Monitoring Counters.
16145   case RDPMC: {
16146     SmallVector<SDValue, 2> Results;
16147     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16148     return DAG.getMergeValues(Results, dl);
16149   }
16150   // XTEST intrinsics.
16151   case XTEST: {
16152     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16153     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16154     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16155                                 DAG.getConstant(X86::COND_NE, MVT::i8),
16156                                 InTrans);
16157     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16158     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16159                        Ret, SDValue(InTrans.getNode(), 1));
16160   }
16161   // ADC/ADCX/SBB
16162   case ADX: {
16163     SmallVector<SDValue, 2> Results;
16164     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16165     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16166     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16167                                 DAG.getConstant(-1, MVT::i8));
16168     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16169                               Op.getOperand(4), GenCF.getValue(1));
16170     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16171                                  Op.getOperand(5), MachinePointerInfo(),
16172                                  false, false, 0);
16173     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16174                                 DAG.getConstant(X86::COND_B, MVT::i8),
16175                                 Res.getValue(1));
16176     Results.push_back(SetCC);
16177     Results.push_back(Store);
16178     return DAG.getMergeValues(Results, dl);
16179   }
16180   }
16181 }
16182
16183 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16184                                            SelectionDAG &DAG) const {
16185   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16186   MFI->setReturnAddressIsTaken(true);
16187
16188   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16189     return SDValue();
16190
16191   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16192   SDLoc dl(Op);
16193   EVT PtrVT = getPointerTy();
16194
16195   if (Depth > 0) {
16196     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16197     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16198         DAG.getSubtarget().getRegisterInfo());
16199     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
16200     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16201                        DAG.getNode(ISD::ADD, dl, PtrVT,
16202                                    FrameAddr, Offset),
16203                        MachinePointerInfo(), false, false, false, 0);
16204   }
16205
16206   // Just load the return address.
16207   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16208   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16209                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16210 }
16211
16212 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16213   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16214   MFI->setFrameAddressIsTaken(true);
16215
16216   EVT VT = Op.getValueType();
16217   SDLoc dl(Op);  // FIXME probably not meaningful
16218   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16219   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16220       DAG.getSubtarget().getRegisterInfo());
16221   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16222   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16223           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16224          "Invalid Frame Register!");
16225   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16226   while (Depth--)
16227     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16228                             MachinePointerInfo(),
16229                             false, false, false, 0);
16230   return FrameAddr;
16231 }
16232
16233 // FIXME? Maybe this could be a TableGen attribute on some registers and
16234 // this table could be generated automatically from RegInfo.
16235 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
16236                                               EVT VT) const {
16237   unsigned Reg = StringSwitch<unsigned>(RegName)
16238                        .Case("esp", X86::ESP)
16239                        .Case("rsp", X86::RSP)
16240                        .Default(0);
16241   if (Reg)
16242     return Reg;
16243   report_fatal_error("Invalid register name global variable");
16244 }
16245
16246 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16247                                                      SelectionDAG &DAG) const {
16248   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16249       DAG.getSubtarget().getRegisterInfo());
16250   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
16251 }
16252
16253 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16254   SDValue Chain     = Op.getOperand(0);
16255   SDValue Offset    = Op.getOperand(1);
16256   SDValue Handler   = Op.getOperand(2);
16257   SDLoc dl      (Op);
16258
16259   EVT PtrVT = getPointerTy();
16260   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
16261       DAG.getSubtarget().getRegisterInfo());
16262   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16263   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16264           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16265          "Invalid Frame Register!");
16266   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16267   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16268
16269   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16270                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
16271   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16272   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16273                        false, false, 0);
16274   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16275
16276   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16277                      DAG.getRegister(StoreAddrReg, PtrVT));
16278 }
16279
16280 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16281                                                SelectionDAG &DAG) const {
16282   SDLoc DL(Op);
16283   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16284                      DAG.getVTList(MVT::i32, MVT::Other),
16285                      Op.getOperand(0), Op.getOperand(1));
16286 }
16287
16288 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16289                                                 SelectionDAG &DAG) const {
16290   SDLoc DL(Op);
16291   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16292                      Op.getOperand(0), Op.getOperand(1));
16293 }
16294
16295 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16296   return Op.getOperand(0);
16297 }
16298
16299 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16300                                                 SelectionDAG &DAG) const {
16301   SDValue Root = Op.getOperand(0);
16302   SDValue Trmp = Op.getOperand(1); // trampoline
16303   SDValue FPtr = Op.getOperand(2); // nested function
16304   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16305   SDLoc dl (Op);
16306
16307   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16308   const TargetRegisterInfo *TRI = DAG.getSubtarget().getRegisterInfo();
16309
16310   if (Subtarget->is64Bit()) {
16311     SDValue OutChains[6];
16312
16313     // Large code-model.
16314     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16315     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16316
16317     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16318     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16319
16320     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16321
16322     // Load the pointer to the nested function into R11.
16323     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16324     SDValue Addr = Trmp;
16325     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
16326                                 Addr, MachinePointerInfo(TrmpAddr),
16327                                 false, false, 0);
16328
16329     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16330                        DAG.getConstant(2, MVT::i64));
16331     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16332                                 MachinePointerInfo(TrmpAddr, 2),
16333                                 false, false, 2);
16334
16335     // Load the 'nest' parameter value into R10.
16336     // R10 is specified in X86CallingConv.td
16337     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16338     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16339                        DAG.getConstant(10, MVT::i64));
16340     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
16341                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16342                                 false, false, 0);
16343
16344     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16345                        DAG.getConstant(12, MVT::i64));
16346     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16347                                 MachinePointerInfo(TrmpAddr, 12),
16348                                 false, false, 2);
16349
16350     // Jump to the nested function.
16351     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16352     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16353                        DAG.getConstant(20, MVT::i64));
16354     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
16355                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16356                                 false, false, 0);
16357
16358     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16359     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16360                        DAG.getConstant(22, MVT::i64));
16361     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
16362                                 MachinePointerInfo(TrmpAddr, 22),
16363                                 false, false, 0);
16364
16365     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16366   } else {
16367     const Function *Func =
16368       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16369     CallingConv::ID CC = Func->getCallingConv();
16370     unsigned NestReg;
16371
16372     switch (CC) {
16373     default:
16374       llvm_unreachable("Unsupported calling convention");
16375     case CallingConv::C:
16376     case CallingConv::X86_StdCall: {
16377       // Pass 'nest' parameter in ECX.
16378       // Must be kept in sync with X86CallingConv.td
16379       NestReg = X86::ECX;
16380
16381       // Check that ECX wasn't needed by an 'inreg' parameter.
16382       FunctionType *FTy = Func->getFunctionType();
16383       const AttributeSet &Attrs = Func->getAttributes();
16384
16385       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16386         unsigned InRegCount = 0;
16387         unsigned Idx = 1;
16388
16389         for (FunctionType::param_iterator I = FTy->param_begin(),
16390              E = FTy->param_end(); I != E; ++I, ++Idx)
16391           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16392             // FIXME: should only count parameters that are lowered to integers.
16393             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16394
16395         if (InRegCount > 2) {
16396           report_fatal_error("Nest register in use - reduce number of inreg"
16397                              " parameters!");
16398         }
16399       }
16400       break;
16401     }
16402     case CallingConv::X86_FastCall:
16403     case CallingConv::X86_ThisCall:
16404     case CallingConv::Fast:
16405       // Pass 'nest' parameter in EAX.
16406       // Must be kept in sync with X86CallingConv.td
16407       NestReg = X86::EAX;
16408       break;
16409     }
16410
16411     SDValue OutChains[4];
16412     SDValue Addr, Disp;
16413
16414     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16415                        DAG.getConstant(10, MVT::i32));
16416     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16417
16418     // This is storing the opcode for MOV32ri.
16419     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16420     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16421     OutChains[0] = DAG.getStore(Root, dl,
16422                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
16423                                 Trmp, MachinePointerInfo(TrmpAddr),
16424                                 false, false, 0);
16425
16426     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16427                        DAG.getConstant(1, MVT::i32));
16428     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16429                                 MachinePointerInfo(TrmpAddr, 1),
16430                                 false, false, 1);
16431
16432     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16433     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16434                        DAG.getConstant(5, MVT::i32));
16435     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
16436                                 MachinePointerInfo(TrmpAddr, 5),
16437                                 false, false, 1);
16438
16439     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16440                        DAG.getConstant(6, MVT::i32));
16441     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16442                                 MachinePointerInfo(TrmpAddr, 6),
16443                                 false, false, 1);
16444
16445     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16446   }
16447 }
16448
16449 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16450                                             SelectionDAG &DAG) const {
16451   /*
16452    The rounding mode is in bits 11:10 of FPSR, and has the following
16453    settings:
16454      00 Round to nearest
16455      01 Round to -inf
16456      10 Round to +inf
16457      11 Round to 0
16458
16459   FLT_ROUNDS, on the other hand, expects the following:
16460     -1 Undefined
16461      0 Round to 0
16462      1 Round to nearest
16463      2 Round to +inf
16464      3 Round to -inf
16465
16466   To perform the conversion, we do:
16467     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16468   */
16469
16470   MachineFunction &MF = DAG.getMachineFunction();
16471   const TargetMachine &TM = MF.getTarget();
16472   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
16473   unsigned StackAlignment = TFI.getStackAlignment();
16474   MVT VT = Op.getSimpleValueType();
16475   SDLoc DL(Op);
16476
16477   // Save FP Control Word to stack slot
16478   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16479   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16480
16481   MachineMemOperand *MMO =
16482    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16483                            MachineMemOperand::MOStore, 2, 2);
16484
16485   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16486   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16487                                           DAG.getVTList(MVT::Other),
16488                                           Ops, MVT::i16, MMO);
16489
16490   // Load FP Control Word from stack slot
16491   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16492                             MachinePointerInfo(), false, false, false, 0);
16493
16494   // Transform as necessary
16495   SDValue CWD1 =
16496     DAG.getNode(ISD::SRL, DL, MVT::i16,
16497                 DAG.getNode(ISD::AND, DL, MVT::i16,
16498                             CWD, DAG.getConstant(0x800, MVT::i16)),
16499                 DAG.getConstant(11, MVT::i8));
16500   SDValue CWD2 =
16501     DAG.getNode(ISD::SRL, DL, MVT::i16,
16502                 DAG.getNode(ISD::AND, DL, MVT::i16,
16503                             CWD, DAG.getConstant(0x400, MVT::i16)),
16504                 DAG.getConstant(9, MVT::i8));
16505
16506   SDValue RetVal =
16507     DAG.getNode(ISD::AND, DL, MVT::i16,
16508                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16509                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16510                             DAG.getConstant(1, MVT::i16)),
16511                 DAG.getConstant(3, MVT::i16));
16512
16513   return DAG.getNode((VT.getSizeInBits() < 16 ?
16514                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16515 }
16516
16517 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16518   MVT VT = Op.getSimpleValueType();
16519   EVT OpVT = VT;
16520   unsigned NumBits = VT.getSizeInBits();
16521   SDLoc dl(Op);
16522
16523   Op = Op.getOperand(0);
16524   if (VT == MVT::i8) {
16525     // Zero extend to i32 since there is not an i8 bsr.
16526     OpVT = MVT::i32;
16527     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16528   }
16529
16530   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16531   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16532   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16533
16534   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16535   SDValue Ops[] = {
16536     Op,
16537     DAG.getConstant(NumBits+NumBits-1, OpVT),
16538     DAG.getConstant(X86::COND_E, MVT::i8),
16539     Op.getValue(1)
16540   };
16541   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16542
16543   // Finally xor with NumBits-1.
16544   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
16545
16546   if (VT == MVT::i8)
16547     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16548   return Op;
16549 }
16550
16551 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16552   MVT VT = Op.getSimpleValueType();
16553   EVT OpVT = VT;
16554   unsigned NumBits = VT.getSizeInBits();
16555   SDLoc dl(Op);
16556
16557   Op = Op.getOperand(0);
16558   if (VT == MVT::i8) {
16559     // Zero extend to i32 since there is not an i8 bsr.
16560     OpVT = MVT::i32;
16561     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16562   }
16563
16564   // Issue a bsr (scan bits in reverse).
16565   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16566   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16567
16568   // And xor with NumBits-1.
16569   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
16570
16571   if (VT == MVT::i8)
16572     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16573   return Op;
16574 }
16575
16576 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16577   MVT VT = Op.getSimpleValueType();
16578   unsigned NumBits = VT.getSizeInBits();
16579   SDLoc dl(Op);
16580   Op = Op.getOperand(0);
16581
16582   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16583   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16584   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16585
16586   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16587   SDValue Ops[] = {
16588     Op,
16589     DAG.getConstant(NumBits, VT),
16590     DAG.getConstant(X86::COND_E, MVT::i8),
16591     Op.getValue(1)
16592   };
16593   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16594 }
16595
16596 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16597 // ones, and then concatenate the result back.
16598 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16599   MVT VT = Op.getSimpleValueType();
16600
16601   assert(VT.is256BitVector() && VT.isInteger() &&
16602          "Unsupported value type for operation");
16603
16604   unsigned NumElems = VT.getVectorNumElements();
16605   SDLoc dl(Op);
16606
16607   // Extract the LHS vectors
16608   SDValue LHS = Op.getOperand(0);
16609   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16610   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16611
16612   // Extract the RHS vectors
16613   SDValue RHS = Op.getOperand(1);
16614   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16615   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16616
16617   MVT EltVT = VT.getVectorElementType();
16618   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16619
16620   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16621                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16622                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16623 }
16624
16625 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16626   assert(Op.getSimpleValueType().is256BitVector() &&
16627          Op.getSimpleValueType().isInteger() &&
16628          "Only handle AVX 256-bit vector integer operation");
16629   return Lower256IntArith(Op, DAG);
16630 }
16631
16632 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16633   assert(Op.getSimpleValueType().is256BitVector() &&
16634          Op.getSimpleValueType().isInteger() &&
16635          "Only handle AVX 256-bit vector integer operation");
16636   return Lower256IntArith(Op, DAG);
16637 }
16638
16639 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16640                         SelectionDAG &DAG) {
16641   SDLoc dl(Op);
16642   MVT VT = Op.getSimpleValueType();
16643
16644   // Decompose 256-bit ops into smaller 128-bit ops.
16645   if (VT.is256BitVector() && !Subtarget->hasInt256())
16646     return Lower256IntArith(Op, DAG);
16647
16648   SDValue A = Op.getOperand(0);
16649   SDValue B = Op.getOperand(1);
16650
16651   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16652   if (VT == MVT::v4i32) {
16653     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16654            "Should not custom lower when pmuldq is available!");
16655
16656     // Extract the odd parts.
16657     static const int UnpackMask[] = { 1, -1, 3, -1 };
16658     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16659     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16660
16661     // Multiply the even parts.
16662     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16663     // Now multiply odd parts.
16664     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16665
16666     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
16667     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
16668
16669     // Merge the two vectors back together with a shuffle. This expands into 2
16670     // shuffles.
16671     static const int ShufMask[] = { 0, 4, 2, 6 };
16672     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16673   }
16674
16675   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16676          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16677
16678   //  Ahi = psrlqi(a, 32);
16679   //  Bhi = psrlqi(b, 32);
16680   //
16681   //  AloBlo = pmuludq(a, b);
16682   //  AloBhi = pmuludq(a, Bhi);
16683   //  AhiBlo = pmuludq(Ahi, b);
16684
16685   //  AloBhi = psllqi(AloBhi, 32);
16686   //  AhiBlo = psllqi(AhiBlo, 32);
16687   //  return AloBlo + AloBhi + AhiBlo;
16688
16689   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16690   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16691
16692   // Bit cast to 32-bit vectors for MULUDQ
16693   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16694                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16695   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
16696   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
16697   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
16698   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
16699
16700   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16701   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16702   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16703
16704   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16705   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16706
16707   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16708   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16709 }
16710
16711 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16712   assert(Subtarget->isTargetWin64() && "Unexpected target");
16713   EVT VT = Op.getValueType();
16714   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16715          "Unexpected return type for lowering");
16716
16717   RTLIB::Libcall LC;
16718   bool isSigned;
16719   switch (Op->getOpcode()) {
16720   default: llvm_unreachable("Unexpected request for libcall!");
16721   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16722   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16723   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16724   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16725   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16726   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16727   }
16728
16729   SDLoc dl(Op);
16730   SDValue InChain = DAG.getEntryNode();
16731
16732   TargetLowering::ArgListTy Args;
16733   TargetLowering::ArgListEntry Entry;
16734   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16735     EVT ArgVT = Op->getOperand(i).getValueType();
16736     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16737            "Unexpected argument type for lowering");
16738     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16739     Entry.Node = StackPtr;
16740     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16741                            false, false, 16);
16742     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16743     Entry.Ty = PointerType::get(ArgTy,0);
16744     Entry.isSExt = false;
16745     Entry.isZExt = false;
16746     Args.push_back(Entry);
16747   }
16748
16749   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16750                                          getPointerTy());
16751
16752   TargetLowering::CallLoweringInfo CLI(DAG);
16753   CLI.setDebugLoc(dl).setChain(InChain)
16754     .setCallee(getLibcallCallingConv(LC),
16755                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16756                Callee, std::move(Args), 0)
16757     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16758
16759   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16760   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
16761 }
16762
16763 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16764                              SelectionDAG &DAG) {
16765   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16766   EVT VT = Op0.getValueType();
16767   SDLoc dl(Op);
16768
16769   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16770          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16771
16772   // PMULxD operations multiply each even value (starting at 0) of LHS with
16773   // the related value of RHS and produce a widen result.
16774   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16775   // => <2 x i64> <ae|cg>
16776   //
16777   // In other word, to have all the results, we need to perform two PMULxD:
16778   // 1. one with the even values.
16779   // 2. one with the odd values.
16780   // To achieve #2, with need to place the odd values at an even position.
16781   //
16782   // Place the odd value at an even position (basically, shift all values 1
16783   // step to the left):
16784   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16785   // <a|b|c|d> => <b|undef|d|undef>
16786   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16787   // <e|f|g|h> => <f|undef|h|undef>
16788   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16789
16790   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16791   // ints.
16792   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16793   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16794   unsigned Opcode =
16795       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16796   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16797   // => <2 x i64> <ae|cg>
16798   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
16799                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16800   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16801   // => <2 x i64> <bf|dh>
16802   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
16803                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16804
16805   // Shuffle it back into the right order.
16806   SDValue Highs, Lows;
16807   if (VT == MVT::v8i32) {
16808     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16809     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16810     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16811     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16812   } else {
16813     const int HighMask[] = {1, 5, 3, 7};
16814     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16815     const int LowMask[] = {0, 4, 2, 6};
16816     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16817   }
16818
16819   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16820   // unsigned multiply.
16821   if (IsSigned && !Subtarget->hasSSE41()) {
16822     SDValue ShAmt =
16823         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16824     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16825                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16826     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16827                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16828
16829     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16830     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16831   }
16832
16833   // The first result of MUL_LOHI is actually the low value, followed by the
16834   // high value.
16835   SDValue Ops[] = {Lows, Highs};
16836   return DAG.getMergeValues(Ops, dl);
16837 }
16838
16839 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16840                                          const X86Subtarget *Subtarget) {
16841   MVT VT = Op.getSimpleValueType();
16842   SDLoc dl(Op);
16843   SDValue R = Op.getOperand(0);
16844   SDValue Amt = Op.getOperand(1);
16845
16846   // Optimize shl/srl/sra with constant shift amount.
16847   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16848     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16849       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16850
16851       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
16852           (Subtarget->hasInt256() &&
16853            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
16854           (Subtarget->hasAVX512() &&
16855            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
16856         if (Op.getOpcode() == ISD::SHL)
16857           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16858                                             DAG);
16859         if (Op.getOpcode() == ISD::SRL)
16860           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
16861                                             DAG);
16862         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
16863           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
16864                                             DAG);
16865       }
16866
16867       if (VT == MVT::v16i8) {
16868         if (Op.getOpcode() == ISD::SHL) {
16869           // Make a large shift.
16870           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16871                                                    MVT::v8i16, R, ShiftAmt,
16872                                                    DAG);
16873           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16874           // Zero out the rightmost bits.
16875           SmallVector<SDValue, 16> V(16,
16876                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16877                                                      MVT::i8));
16878           return DAG.getNode(ISD::AND, dl, VT, SHL,
16879                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16880         }
16881         if (Op.getOpcode() == ISD::SRL) {
16882           // Make a large shift.
16883           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16884                                                    MVT::v8i16, R, ShiftAmt,
16885                                                    DAG);
16886           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16887           // Zero out the leftmost bits.
16888           SmallVector<SDValue, 16> V(16,
16889                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16890                                                      MVT::i8));
16891           return DAG.getNode(ISD::AND, dl, VT, SRL,
16892                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16893         }
16894         if (Op.getOpcode() == ISD::SRA) {
16895           if (ShiftAmt == 7) {
16896             // R s>> 7  ===  R s< 0
16897             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16898             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16899           }
16900
16901           // R s>> a === ((R u>> a) ^ m) - m
16902           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16903           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
16904                                                          MVT::i8));
16905           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16906           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16907           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16908           return Res;
16909         }
16910         llvm_unreachable("Unknown shift opcode.");
16911       }
16912
16913       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
16914         if (Op.getOpcode() == ISD::SHL) {
16915           // Make a large shift.
16916           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
16917                                                    MVT::v16i16, R, ShiftAmt,
16918                                                    DAG);
16919           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
16920           // Zero out the rightmost bits.
16921           SmallVector<SDValue, 32> V(32,
16922                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
16923                                                      MVT::i8));
16924           return DAG.getNode(ISD::AND, dl, VT, SHL,
16925                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16926         }
16927         if (Op.getOpcode() == ISD::SRL) {
16928           // Make a large shift.
16929           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
16930                                                    MVT::v16i16, R, ShiftAmt,
16931                                                    DAG);
16932           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
16933           // Zero out the leftmost bits.
16934           SmallVector<SDValue, 32> V(32,
16935                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
16936                                                      MVT::i8));
16937           return DAG.getNode(ISD::AND, dl, VT, SRL,
16938                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16939         }
16940         if (Op.getOpcode() == ISD::SRA) {
16941           if (ShiftAmt == 7) {
16942             // R s>> 7  ===  R s< 0
16943             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16944             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16945           }
16946
16947           // R s>> a === ((R u>> a) ^ m) - m
16948           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16949           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
16950                                                          MVT::i8));
16951           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16952           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16953           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16954           return Res;
16955         }
16956         llvm_unreachable("Unknown shift opcode.");
16957       }
16958     }
16959   }
16960
16961   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16962   if (!Subtarget->is64Bit() &&
16963       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16964       Amt.getOpcode() == ISD::BITCAST &&
16965       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16966     Amt = Amt.getOperand(0);
16967     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16968                      VT.getVectorNumElements();
16969     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16970     uint64_t ShiftAmt = 0;
16971     for (unsigned i = 0; i != Ratio; ++i) {
16972       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16973       if (!C)
16974         return SDValue();
16975       // 6 == Log2(64)
16976       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16977     }
16978     // Check remaining shift amounts.
16979     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16980       uint64_t ShAmt = 0;
16981       for (unsigned j = 0; j != Ratio; ++j) {
16982         ConstantSDNode *C =
16983           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16984         if (!C)
16985           return SDValue();
16986         // 6 == Log2(64)
16987         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16988       }
16989       if (ShAmt != ShiftAmt)
16990         return SDValue();
16991     }
16992     switch (Op.getOpcode()) {
16993     default:
16994       llvm_unreachable("Unknown shift opcode!");
16995     case ISD::SHL:
16996       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
16997                                         DAG);
16998     case ISD::SRL:
16999       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
17000                                         DAG);
17001     case ISD::SRA:
17002       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
17003                                         DAG);
17004     }
17005   }
17006
17007   return SDValue();
17008 }
17009
17010 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17011                                         const X86Subtarget* Subtarget) {
17012   MVT VT = Op.getSimpleValueType();
17013   SDLoc dl(Op);
17014   SDValue R = Op.getOperand(0);
17015   SDValue Amt = Op.getOperand(1);
17016
17017   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
17018       VT == MVT::v4i32 || VT == MVT::v8i16 ||
17019       (Subtarget->hasInt256() &&
17020        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
17021         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
17022        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
17023     SDValue BaseShAmt;
17024     EVT EltVT = VT.getVectorElementType();
17025
17026     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17027       unsigned NumElts = VT.getVectorNumElements();
17028       unsigned i, j;
17029       for (i = 0; i != NumElts; ++i) {
17030         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
17031           continue;
17032         break;
17033       }
17034       for (j = i; j != NumElts; ++j) {
17035         SDValue Arg = Amt.getOperand(j);
17036         if (Arg.getOpcode() == ISD::UNDEF) continue;
17037         if (Arg != Amt.getOperand(i))
17038           break;
17039       }
17040       if (i != NumElts && j == NumElts)
17041         BaseShAmt = Amt.getOperand(i);
17042     } else {
17043       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17044         Amt = Amt.getOperand(0);
17045       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
17046                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
17047         SDValue InVec = Amt.getOperand(0);
17048         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17049           unsigned NumElts = InVec.getValueType().getVectorNumElements();
17050           unsigned i = 0;
17051           for (; i != NumElts; ++i) {
17052             SDValue Arg = InVec.getOperand(i);
17053             if (Arg.getOpcode() == ISD::UNDEF) continue;
17054             BaseShAmt = Arg;
17055             break;
17056           }
17057         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17058            if (ConstantSDNode *C =
17059                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17060              unsigned SplatIdx =
17061                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
17062              if (C->getZExtValue() == SplatIdx)
17063                BaseShAmt = InVec.getOperand(1);
17064            }
17065         }
17066         if (!BaseShAmt.getNode())
17067           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
17068                                   DAG.getIntPtrConstant(0));
17069       }
17070     }
17071
17072     if (BaseShAmt.getNode()) {
17073       if (EltVT.bitsGT(MVT::i32))
17074         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
17075       else if (EltVT.bitsLT(MVT::i32))
17076         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17077
17078       switch (Op.getOpcode()) {
17079       default:
17080         llvm_unreachable("Unknown shift opcode!");
17081       case ISD::SHL:
17082         switch (VT.SimpleTy) {
17083         default: return SDValue();
17084         case MVT::v2i64:
17085         case MVT::v4i32:
17086         case MVT::v8i16:
17087         case MVT::v4i64:
17088         case MVT::v8i32:
17089         case MVT::v16i16:
17090         case MVT::v16i32:
17091         case MVT::v8i64:
17092           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
17093         }
17094       case ISD::SRA:
17095         switch (VT.SimpleTy) {
17096         default: return SDValue();
17097         case MVT::v4i32:
17098         case MVT::v8i16:
17099         case MVT::v8i32:
17100         case MVT::v16i16:
17101         case MVT::v16i32:
17102         case MVT::v8i64:
17103           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
17104         }
17105       case ISD::SRL:
17106         switch (VT.SimpleTy) {
17107         default: return SDValue();
17108         case MVT::v2i64:
17109         case MVT::v4i32:
17110         case MVT::v8i16:
17111         case MVT::v4i64:
17112         case MVT::v8i32:
17113         case MVT::v16i16:
17114         case MVT::v16i32:
17115         case MVT::v8i64:
17116           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
17117         }
17118       }
17119     }
17120   }
17121
17122   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17123   if (!Subtarget->is64Bit() &&
17124       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
17125       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
17126       Amt.getOpcode() == ISD::BITCAST &&
17127       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17128     Amt = Amt.getOperand(0);
17129     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17130                      VT.getVectorNumElements();
17131     std::vector<SDValue> Vals(Ratio);
17132     for (unsigned i = 0; i != Ratio; ++i)
17133       Vals[i] = Amt.getOperand(i);
17134     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17135       for (unsigned j = 0; j != Ratio; ++j)
17136         if (Vals[j] != Amt.getOperand(i + j))
17137           return SDValue();
17138     }
17139     switch (Op.getOpcode()) {
17140     default:
17141       llvm_unreachable("Unknown shift opcode!");
17142     case ISD::SHL:
17143       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
17144     case ISD::SRL:
17145       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
17146     case ISD::SRA:
17147       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
17148     }
17149   }
17150
17151   return SDValue();
17152 }
17153
17154 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17155                           SelectionDAG &DAG) {
17156   MVT VT = Op.getSimpleValueType();
17157   SDLoc dl(Op);
17158   SDValue R = Op.getOperand(0);
17159   SDValue Amt = Op.getOperand(1);
17160   SDValue V;
17161
17162   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17163   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17164
17165   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
17166   if (V.getNode())
17167     return V;
17168
17169   V = LowerScalarVariableShift(Op, DAG, Subtarget);
17170   if (V.getNode())
17171       return V;
17172
17173   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
17174     return Op;
17175   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
17176   if (Subtarget->hasInt256()) {
17177     if (Op.getOpcode() == ISD::SRL &&
17178         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
17179          VT == MVT::v4i64 || VT == MVT::v8i32))
17180       return Op;
17181     if (Op.getOpcode() == ISD::SHL &&
17182         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
17183          VT == MVT::v4i64 || VT == MVT::v8i32))
17184       return Op;
17185     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
17186       return Op;
17187   }
17188
17189   // If possible, lower this packed shift into a vector multiply instead of
17190   // expanding it into a sequence of scalar shifts.
17191   // Do this only if the vector shift count is a constant build_vector.
17192   if (Op.getOpcode() == ISD::SHL && 
17193       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17194        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17195       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17196     SmallVector<SDValue, 8> Elts;
17197     EVT SVT = VT.getScalarType();
17198     unsigned SVTBits = SVT.getSizeInBits();
17199     const APInt &One = APInt(SVTBits, 1);
17200     unsigned NumElems = VT.getVectorNumElements();
17201
17202     for (unsigned i=0; i !=NumElems; ++i) {
17203       SDValue Op = Amt->getOperand(i);
17204       if (Op->getOpcode() == ISD::UNDEF) {
17205         Elts.push_back(Op);
17206         continue;
17207       }
17208
17209       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17210       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17211       uint64_t ShAmt = C.getZExtValue();
17212       if (ShAmt >= SVTBits) {
17213         Elts.push_back(DAG.getUNDEF(SVT));
17214         continue;
17215       }
17216       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
17217     }
17218     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17219     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17220   }
17221
17222   // Lower SHL with variable shift amount.
17223   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17224     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
17225
17226     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
17227     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
17228     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17229     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17230   }
17231
17232   // If possible, lower this shift as a sequence of two shifts by
17233   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17234   // Example:
17235   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17236   //
17237   // Could be rewritten as:
17238   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17239   //
17240   // The advantage is that the two shifts from the example would be
17241   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17242   // the vector shift into four scalar shifts plus four pairs of vector
17243   // insert/extract.
17244   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17245       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17246     unsigned TargetOpcode = X86ISD::MOVSS;
17247     bool CanBeSimplified;
17248     // The splat value for the first packed shift (the 'X' from the example).
17249     SDValue Amt1 = Amt->getOperand(0);
17250     // The splat value for the second packed shift (the 'Y' from the example).
17251     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17252                                         Amt->getOperand(2);
17253
17254     // See if it is possible to replace this node with a sequence of
17255     // two shifts followed by a MOVSS/MOVSD
17256     if (VT == MVT::v4i32) {
17257       // Check if it is legal to use a MOVSS.
17258       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17259                         Amt2 == Amt->getOperand(3);
17260       if (!CanBeSimplified) {
17261         // Otherwise, check if we can still simplify this node using a MOVSD.
17262         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17263                           Amt->getOperand(2) == Amt->getOperand(3);
17264         TargetOpcode = X86ISD::MOVSD;
17265         Amt2 = Amt->getOperand(2);
17266       }
17267     } else {
17268       // Do similar checks for the case where the machine value type
17269       // is MVT::v8i16.
17270       CanBeSimplified = Amt1 == Amt->getOperand(1);
17271       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17272         CanBeSimplified = Amt2 == Amt->getOperand(i);
17273
17274       if (!CanBeSimplified) {
17275         TargetOpcode = X86ISD::MOVSD;
17276         CanBeSimplified = true;
17277         Amt2 = Amt->getOperand(4);
17278         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17279           CanBeSimplified = Amt1 == Amt->getOperand(i);
17280         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17281           CanBeSimplified = Amt2 == Amt->getOperand(j);
17282       }
17283     }
17284     
17285     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17286         isa<ConstantSDNode>(Amt2)) {
17287       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17288       EVT CastVT = MVT::v4i32;
17289       SDValue Splat1 = 
17290         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
17291       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17292       SDValue Splat2 = 
17293         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
17294       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17295       if (TargetOpcode == X86ISD::MOVSD)
17296         CastVT = MVT::v2i64;
17297       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
17298       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
17299       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17300                                             BitCast1, DAG);
17301       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
17302     }
17303   }
17304
17305   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
17306     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
17307
17308     // a = a << 5;
17309     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
17310     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
17311
17312     // Turn 'a' into a mask suitable for VSELECT
17313     SDValue VSelM = DAG.getConstant(0x80, VT);
17314     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
17315     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
17316
17317     SDValue CM1 = DAG.getConstant(0x0f, VT);
17318     SDValue CM2 = DAG.getConstant(0x3f, VT);
17319
17320     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
17321     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
17322     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
17323     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
17324     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
17325
17326     // a += a
17327     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
17328     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
17329     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
17330
17331     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
17332     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
17333     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
17334     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
17335     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
17336
17337     // a += a
17338     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
17339     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
17340     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
17341
17342     // return VSELECT(r, r+r, a);
17343     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
17344                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
17345     return R;
17346   }
17347
17348   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17349   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17350   // solution better.
17351   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17352     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
17353     unsigned ExtOpc =
17354         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17355     R = DAG.getNode(ExtOpc, dl, NewVT, R);
17356     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
17357     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17358                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
17359     }
17360
17361   // Decompose 256-bit shifts into smaller 128-bit shifts.
17362   if (VT.is256BitVector()) {
17363     unsigned NumElems = VT.getVectorNumElements();
17364     MVT EltVT = VT.getVectorElementType();
17365     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17366
17367     // Extract the two vectors
17368     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17369     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17370
17371     // Recreate the shift amount vectors
17372     SDValue Amt1, Amt2;
17373     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17374       // Constant shift amount
17375       SmallVector<SDValue, 4> Amt1Csts;
17376       SmallVector<SDValue, 4> Amt2Csts;
17377       for (unsigned i = 0; i != NumElems/2; ++i)
17378         Amt1Csts.push_back(Amt->getOperand(i));
17379       for (unsigned i = NumElems/2; i != NumElems; ++i)
17380         Amt2Csts.push_back(Amt->getOperand(i));
17381
17382       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17383       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17384     } else {
17385       // Variable shift amount
17386       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17387       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17388     }
17389
17390     // Issue new vector shifts for the smaller types
17391     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17392     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17393
17394     // Concatenate the result back
17395     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17396   }
17397
17398   return SDValue();
17399 }
17400
17401 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17402   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17403   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17404   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17405   // has only one use.
17406   SDNode *N = Op.getNode();
17407   SDValue LHS = N->getOperand(0);
17408   SDValue RHS = N->getOperand(1);
17409   unsigned BaseOp = 0;
17410   unsigned Cond = 0;
17411   SDLoc DL(Op);
17412   switch (Op.getOpcode()) {
17413   default: llvm_unreachable("Unknown ovf instruction!");
17414   case ISD::SADDO:
17415     // A subtract of one will be selected as a INC. Note that INC doesn't
17416     // set CF, so we can't do this for UADDO.
17417     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17418       if (C->isOne()) {
17419         BaseOp = X86ISD::INC;
17420         Cond = X86::COND_O;
17421         break;
17422       }
17423     BaseOp = X86ISD::ADD;
17424     Cond = X86::COND_O;
17425     break;
17426   case ISD::UADDO:
17427     BaseOp = X86ISD::ADD;
17428     Cond = X86::COND_B;
17429     break;
17430   case ISD::SSUBO:
17431     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17432     // set CF, so we can't do this for USUBO.
17433     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17434       if (C->isOne()) {
17435         BaseOp = X86ISD::DEC;
17436         Cond = X86::COND_O;
17437         break;
17438       }
17439     BaseOp = X86ISD::SUB;
17440     Cond = X86::COND_O;
17441     break;
17442   case ISD::USUBO:
17443     BaseOp = X86ISD::SUB;
17444     Cond = X86::COND_B;
17445     break;
17446   case ISD::SMULO:
17447     BaseOp = X86ISD::SMUL;
17448     Cond = X86::COND_O;
17449     break;
17450   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17451     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17452                                  MVT::i32);
17453     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17454
17455     SDValue SetCC =
17456       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17457                   DAG.getConstant(X86::COND_O, MVT::i32),
17458                   SDValue(Sum.getNode(), 2));
17459
17460     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17461   }
17462   }
17463
17464   // Also sets EFLAGS.
17465   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17466   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17467
17468   SDValue SetCC =
17469     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17470                 DAG.getConstant(Cond, MVT::i32),
17471                 SDValue(Sum.getNode(), 1));
17472
17473   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17474 }
17475
17476 // Sign extension of the low part of vector elements. This may be used either
17477 // when sign extend instructions are not available or if the vector element
17478 // sizes already match the sign-extended size. If the vector elements are in
17479 // their pre-extended size and sign extend instructions are available, that will
17480 // be handled by LowerSIGN_EXTEND.
17481 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
17482                                                   SelectionDAG &DAG) const {
17483   SDLoc dl(Op);
17484   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
17485   MVT VT = Op.getSimpleValueType();
17486
17487   if (!Subtarget->hasSSE2() || !VT.isVector())
17488     return SDValue();
17489
17490   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
17491                       ExtraVT.getScalarType().getSizeInBits();
17492
17493   switch (VT.SimpleTy) {
17494     default: return SDValue();
17495     case MVT::v8i32:
17496     case MVT::v16i16:
17497       if (!Subtarget->hasFp256())
17498         return SDValue();
17499       if (!Subtarget->hasInt256()) {
17500         // needs to be split
17501         unsigned NumElems = VT.getVectorNumElements();
17502
17503         // Extract the LHS vectors
17504         SDValue LHS = Op.getOperand(0);
17505         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
17506         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
17507
17508         MVT EltVT = VT.getVectorElementType();
17509         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17510
17511         EVT ExtraEltVT = ExtraVT.getVectorElementType();
17512         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
17513         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
17514                                    ExtraNumElems/2);
17515         SDValue Extra = DAG.getValueType(ExtraVT);
17516
17517         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
17518         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
17519
17520         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
17521       }
17522       // fall through
17523     case MVT::v4i32:
17524     case MVT::v8i16: {
17525       SDValue Op0 = Op.getOperand(0);
17526
17527       // This is a sign extension of some low part of vector elements without
17528       // changing the size of the vector elements themselves:
17529       // Shift-Left + Shift-Right-Algebraic.
17530       SDValue Shl = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0,
17531                                                BitsDiff, DAG);
17532       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Shl, BitsDiff,
17533                                         DAG);
17534     }
17535   }
17536 }
17537
17538 /// Returns true if the operand type is exactly twice the native width, and
17539 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17540 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17541 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17542 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17543   const X86Subtarget &Subtarget =
17544       getTargetMachine().getSubtarget<X86Subtarget>();
17545   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17546
17547   if (OpWidth == 64)
17548     return !Subtarget.is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17549   else if (OpWidth == 128)
17550     return Subtarget.hasCmpxchg16b();
17551   else
17552     return false;
17553 }
17554
17555 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17556   return needsCmpXchgNb(SI->getValueOperand()->getType());
17557 }
17558
17559 // Note: this turns large loads into lock cmpxchg8b/16b.
17560 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17561 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17562   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17563   return needsCmpXchgNb(PTy->getElementType());
17564 }
17565
17566 bool X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17567   const X86Subtarget &Subtarget =
17568       getTargetMachine().getSubtarget<X86Subtarget>();
17569   unsigned NativeWidth = Subtarget.is64Bit() ? 64 : 32;
17570   const Type *MemType = AI->getType();
17571
17572   // If the operand is too big, we must see if cmpxchg8/16b is available
17573   // and default to library calls otherwise.
17574   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17575     return needsCmpXchgNb(MemType);
17576
17577   AtomicRMWInst::BinOp Op = AI->getOperation();
17578   switch (Op) {
17579   default:
17580     llvm_unreachable("Unknown atomic operation");
17581   case AtomicRMWInst::Xchg:
17582   case AtomicRMWInst::Add:
17583   case AtomicRMWInst::Sub:
17584     // It's better to use xadd, xsub or xchg for these in all cases.
17585     return false;
17586   case AtomicRMWInst::Or:
17587   case AtomicRMWInst::And:
17588   case AtomicRMWInst::Xor:
17589     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17590     // prefix to a normal instruction for these operations.
17591     return !AI->use_empty();
17592   case AtomicRMWInst::Nand:
17593   case AtomicRMWInst::Max:
17594   case AtomicRMWInst::Min:
17595   case AtomicRMWInst::UMax:
17596   case AtomicRMWInst::UMin:
17597     // These always require a non-trivial set of data operations on x86. We must
17598     // use a cmpxchg loop.
17599     return true;
17600   }
17601 }
17602
17603 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17604                                  SelectionDAG &DAG) {
17605   SDLoc dl(Op);
17606   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17607     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17608   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17609     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17610
17611   // The only fence that needs an instruction is a sequentially-consistent
17612   // cross-thread fence.
17613   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17614     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17615     // no-sse2). There isn't any reason to disable it if the target processor
17616     // supports it.
17617     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
17618       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17619
17620     SDValue Chain = Op.getOperand(0);
17621     SDValue Zero = DAG.getConstant(0, MVT::i32);
17622     SDValue Ops[] = {
17623       DAG.getRegister(X86::ESP, MVT::i32), // Base
17624       DAG.getTargetConstant(1, MVT::i8),   // Scale
17625       DAG.getRegister(0, MVT::i32),        // Index
17626       DAG.getTargetConstant(0, MVT::i32),  // Disp
17627       DAG.getRegister(0, MVT::i32),        // Segment.
17628       Zero,
17629       Chain
17630     };
17631     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17632     return SDValue(Res, 0);
17633   }
17634
17635   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17636   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17637 }
17638
17639 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17640                              SelectionDAG &DAG) {
17641   MVT T = Op.getSimpleValueType();
17642   SDLoc DL(Op);
17643   unsigned Reg = 0;
17644   unsigned size = 0;
17645   switch(T.SimpleTy) {
17646   default: llvm_unreachable("Invalid value type!");
17647   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17648   case MVT::i16: Reg = X86::AX;  size = 2; break;
17649   case MVT::i32: Reg = X86::EAX; size = 4; break;
17650   case MVT::i64:
17651     assert(Subtarget->is64Bit() && "Node not type legal!");
17652     Reg = X86::RAX; size = 8;
17653     break;
17654   }
17655   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17656                                   Op.getOperand(2), SDValue());
17657   SDValue Ops[] = { cpIn.getValue(0),
17658                     Op.getOperand(1),
17659                     Op.getOperand(3),
17660                     DAG.getTargetConstant(size, MVT::i8),
17661                     cpIn.getValue(1) };
17662   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17663   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17664   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17665                                            Ops, T, MMO);
17666
17667   SDValue cpOut =
17668     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17669   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17670                                       MVT::i32, cpOut.getValue(2));
17671   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17672                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
17673
17674   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17675   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17676   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17677   return SDValue();
17678 }
17679
17680 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17681                             SelectionDAG &DAG) {
17682   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17683   MVT DstVT = Op.getSimpleValueType();
17684
17685   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17686     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17687     if (DstVT != MVT::f64)
17688       // This conversion needs to be expanded.
17689       return SDValue();
17690
17691     SDValue InVec = Op->getOperand(0);
17692     SDLoc dl(Op);
17693     unsigned NumElts = SrcVT.getVectorNumElements();
17694     EVT SVT = SrcVT.getVectorElementType();
17695
17696     // Widen the vector in input in the case of MVT::v2i32.
17697     // Example: from MVT::v2i32 to MVT::v4i32.
17698     SmallVector<SDValue, 16> Elts;
17699     for (unsigned i = 0, e = NumElts; i != e; ++i)
17700       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17701                                  DAG.getIntPtrConstant(i)));
17702
17703     // Explicitly mark the extra elements as Undef.
17704     SDValue Undef = DAG.getUNDEF(SVT);
17705     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
17706       Elts.push_back(Undef);
17707
17708     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17709     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17710     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
17711     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17712                        DAG.getIntPtrConstant(0));
17713   }
17714
17715   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17716          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17717   assert((DstVT == MVT::i64 ||
17718           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17719          "Unexpected custom BITCAST");
17720   // i64 <=> MMX conversions are Legal.
17721   if (SrcVT==MVT::i64 && DstVT.isVector())
17722     return Op;
17723   if (DstVT==MVT::i64 && SrcVT.isVector())
17724     return Op;
17725   // MMX <=> MMX conversions are Legal.
17726   if (SrcVT.isVector() && DstVT.isVector())
17727     return Op;
17728   // All other conversions need to be expanded.
17729   return SDValue();
17730 }
17731
17732 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17733   SDNode *Node = Op.getNode();
17734   SDLoc dl(Node);
17735   EVT T = Node->getValueType(0);
17736   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17737                               DAG.getConstant(0, T), Node->getOperand(2));
17738   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17739                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17740                        Node->getOperand(0),
17741                        Node->getOperand(1), negOp,
17742                        cast<AtomicSDNode>(Node)->getMemOperand(),
17743                        cast<AtomicSDNode>(Node)->getOrdering(),
17744                        cast<AtomicSDNode>(Node)->getSynchScope());
17745 }
17746
17747 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17748   SDNode *Node = Op.getNode();
17749   SDLoc dl(Node);
17750   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17751
17752   // Convert seq_cst store -> xchg
17753   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17754   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17755   //        (The only way to get a 16-byte store is cmpxchg16b)
17756   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17757   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17758       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17759     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17760                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17761                                  Node->getOperand(0),
17762                                  Node->getOperand(1), Node->getOperand(2),
17763                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17764                                  cast<AtomicSDNode>(Node)->getOrdering(),
17765                                  cast<AtomicSDNode>(Node)->getSynchScope());
17766     return Swap.getValue(1);
17767   }
17768   // Other atomic stores have a simple pattern.
17769   return Op;
17770 }
17771
17772 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17773   EVT VT = Op.getNode()->getSimpleValueType(0);
17774
17775   // Let legalize expand this if it isn't a legal type yet.
17776   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17777     return SDValue();
17778
17779   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17780
17781   unsigned Opc;
17782   bool ExtraOp = false;
17783   switch (Op.getOpcode()) {
17784   default: llvm_unreachable("Invalid code");
17785   case ISD::ADDC: Opc = X86ISD::ADD; break;
17786   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17787   case ISD::SUBC: Opc = X86ISD::SUB; break;
17788   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17789   }
17790
17791   if (!ExtraOp)
17792     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17793                        Op.getOperand(1));
17794   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17795                      Op.getOperand(1), Op.getOperand(2));
17796 }
17797
17798 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17799                             SelectionDAG &DAG) {
17800   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17801
17802   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17803   // which returns the values as { float, float } (in XMM0) or
17804   // { double, double } (which is returned in XMM0, XMM1).
17805   SDLoc dl(Op);
17806   SDValue Arg = Op.getOperand(0);
17807   EVT ArgVT = Arg.getValueType();
17808   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17809
17810   TargetLowering::ArgListTy Args;
17811   TargetLowering::ArgListEntry Entry;
17812
17813   Entry.Node = Arg;
17814   Entry.Ty = ArgTy;
17815   Entry.isSExt = false;
17816   Entry.isZExt = false;
17817   Args.push_back(Entry);
17818
17819   bool isF64 = ArgVT == MVT::f64;
17820   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
17821   // the small struct {f32, f32} is returned in (eax, edx). For f64,
17822   // the results are returned via SRet in memory.
17823   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
17824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17825   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
17826
17827   Type *RetTy = isF64
17828     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
17829     : (Type*)VectorType::get(ArgTy, 4);
17830
17831   TargetLowering::CallLoweringInfo CLI(DAG);
17832   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
17833     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
17834
17835   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
17836
17837   if (isF64)
17838     // Returned in xmm0 and xmm1.
17839     return CallResult.first;
17840
17841   // Returned in bits 0:31 and 32:64 xmm0.
17842   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17843                                CallResult.first, DAG.getIntPtrConstant(0));
17844   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
17845                                CallResult.first, DAG.getIntPtrConstant(1));
17846   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
17847   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
17848 }
17849
17850 /// LowerOperation - Provide custom lowering hooks for some operations.
17851 ///
17852 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
17853   switch (Op.getOpcode()) {
17854   default: llvm_unreachable("Should not custom lower this!");
17855   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
17856   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
17857   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
17858     return LowerCMP_SWAP(Op, Subtarget, DAG);
17859   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
17860   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
17861   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
17862   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
17863   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
17864   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
17865   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
17866   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
17867   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
17868   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
17869   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
17870   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
17871   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
17872   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
17873   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
17874   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
17875   case ISD::SHL_PARTS:
17876   case ISD::SRA_PARTS:
17877   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
17878   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
17879   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
17880   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
17881   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
17882   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
17883   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
17884   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
17885   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
17886   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
17887   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
17888   case ISD::FABS:
17889   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
17890   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
17891   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
17892   case ISD::SETCC:              return LowerSETCC(Op, DAG);
17893   case ISD::SELECT:             return LowerSELECT(Op, DAG);
17894   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
17895   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
17896   case ISD::VASTART:            return LowerVASTART(Op, DAG);
17897   case ISD::VAARG:              return LowerVAARG(Op, DAG);
17898   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
17899   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
17900   case ISD::INTRINSIC_VOID:
17901   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
17902   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
17903   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
17904   case ISD::FRAME_TO_ARGS_OFFSET:
17905                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
17906   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
17907   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
17908   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
17909   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
17910   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
17911   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
17912   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
17913   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
17914   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
17915   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
17916   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
17917   case ISD::UMUL_LOHI:
17918   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
17919   case ISD::SRA:
17920   case ISD::SRL:
17921   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
17922   case ISD::SADDO:
17923   case ISD::UADDO:
17924   case ISD::SSUBO:
17925   case ISD::USUBO:
17926   case ISD::SMULO:
17927   case ISD::UMULO:              return LowerXALUO(Op, DAG);
17928   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
17929   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
17930   case ISD::ADDC:
17931   case ISD::ADDE:
17932   case ISD::SUBC:
17933   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
17934   case ISD::ADD:                return LowerADD(Op, DAG);
17935   case ISD::SUB:                return LowerSUB(Op, DAG);
17936   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
17937   }
17938 }
17939
17940 /// ReplaceNodeResults - Replace a node with an illegal result type
17941 /// with a new node built out of custom code.
17942 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
17943                                            SmallVectorImpl<SDValue>&Results,
17944                                            SelectionDAG &DAG) const {
17945   SDLoc dl(N);
17946   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17947   switch (N->getOpcode()) {
17948   default:
17949     llvm_unreachable("Do not know how to custom type legalize this operation!");
17950   case ISD::SIGN_EXTEND_INREG:
17951   case ISD::ADDC:
17952   case ISD::ADDE:
17953   case ISD::SUBC:
17954   case ISD::SUBE:
17955     // We don't want to expand or promote these.
17956     return;
17957   case ISD::SDIV:
17958   case ISD::UDIV:
17959   case ISD::SREM:
17960   case ISD::UREM:
17961   case ISD::SDIVREM:
17962   case ISD::UDIVREM: {
17963     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
17964     Results.push_back(V);
17965     return;
17966   }
17967   case ISD::FP_TO_SINT:
17968   case ISD::FP_TO_UINT: {
17969     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
17970
17971     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
17972       return;
17973
17974     std::pair<SDValue,SDValue> Vals =
17975         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
17976     SDValue FIST = Vals.first, StackSlot = Vals.second;
17977     if (FIST.getNode()) {
17978       EVT VT = N->getValueType(0);
17979       // Return a load from the stack slot.
17980       if (StackSlot.getNode())
17981         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
17982                                       MachinePointerInfo(),
17983                                       false, false, false, 0));
17984       else
17985         Results.push_back(FIST);
17986     }
17987     return;
17988   }
17989   case ISD::UINT_TO_FP: {
17990     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17991     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
17992         N->getValueType(0) != MVT::v2f32)
17993       return;
17994     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
17995                                  N->getOperand(0));
17996     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
17997                                      MVT::f64);
17998     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
17999     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18000                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
18001     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
18002     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18003     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18004     return;
18005   }
18006   case ISD::FP_ROUND: {
18007     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18008         return;
18009     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18010     Results.push_back(V);
18011     return;
18012   }
18013   case ISD::INTRINSIC_W_CHAIN: {
18014     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18015     switch (IntNo) {
18016     default : llvm_unreachable("Do not know how to custom type "
18017                                "legalize this intrinsic operation!");
18018     case Intrinsic::x86_rdtsc:
18019       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18020                                      Results);
18021     case Intrinsic::x86_rdtscp:
18022       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18023                                      Results);
18024     case Intrinsic::x86_rdpmc:
18025       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18026     }
18027   }
18028   case ISD::READCYCLECOUNTER: {
18029     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18030                                    Results);
18031   }
18032   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18033     EVT T = N->getValueType(0);
18034     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18035     bool Regs64bit = T == MVT::i128;
18036     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18037     SDValue cpInL, cpInH;
18038     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18039                         DAG.getConstant(0, HalfT));
18040     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18041                         DAG.getConstant(1, HalfT));
18042     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18043                              Regs64bit ? X86::RAX : X86::EAX,
18044                              cpInL, SDValue());
18045     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18046                              Regs64bit ? X86::RDX : X86::EDX,
18047                              cpInH, cpInL.getValue(1));
18048     SDValue swapInL, swapInH;
18049     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18050                           DAG.getConstant(0, HalfT));
18051     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18052                           DAG.getConstant(1, HalfT));
18053     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18054                                Regs64bit ? X86::RBX : X86::EBX,
18055                                swapInL, cpInH.getValue(1));
18056     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18057                                Regs64bit ? X86::RCX : X86::ECX,
18058                                swapInH, swapInL.getValue(1));
18059     SDValue Ops[] = { swapInH.getValue(0),
18060                       N->getOperand(1),
18061                       swapInH.getValue(1) };
18062     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18063     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18064     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18065                                   X86ISD::LCMPXCHG8_DAG;
18066     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18067     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18068                                         Regs64bit ? X86::RAX : X86::EAX,
18069                                         HalfT, Result.getValue(1));
18070     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18071                                         Regs64bit ? X86::RDX : X86::EDX,
18072                                         HalfT, cpOutL.getValue(2));
18073     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18074
18075     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18076                                         MVT::i32, cpOutH.getValue(2));
18077     SDValue Success =
18078         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18079                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
18080     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18081
18082     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18083     Results.push_back(Success);
18084     Results.push_back(EFLAGS.getValue(1));
18085     return;
18086   }
18087   case ISD::ATOMIC_SWAP:
18088   case ISD::ATOMIC_LOAD_ADD:
18089   case ISD::ATOMIC_LOAD_SUB:
18090   case ISD::ATOMIC_LOAD_AND:
18091   case ISD::ATOMIC_LOAD_OR:
18092   case ISD::ATOMIC_LOAD_XOR:
18093   case ISD::ATOMIC_LOAD_NAND:
18094   case ISD::ATOMIC_LOAD_MIN:
18095   case ISD::ATOMIC_LOAD_MAX:
18096   case ISD::ATOMIC_LOAD_UMIN:
18097   case ISD::ATOMIC_LOAD_UMAX:
18098   case ISD::ATOMIC_LOAD: {
18099     // Delegate to generic TypeLegalization. Situations we can really handle
18100     // should have already been dealt with by AtomicExpandPass.cpp.
18101     break;
18102   }
18103   case ISD::BITCAST: {
18104     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18105     EVT DstVT = N->getValueType(0);
18106     EVT SrcVT = N->getOperand(0)->getValueType(0);
18107
18108     if (SrcVT != MVT::f64 ||
18109         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18110       return;
18111
18112     unsigned NumElts = DstVT.getVectorNumElements();
18113     EVT SVT = DstVT.getVectorElementType();
18114     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18115     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18116                                    MVT::v2f64, N->getOperand(0));
18117     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
18118
18119     if (ExperimentalVectorWideningLegalization) {
18120       // If we are legalizing vectors by widening, we already have the desired
18121       // legal vector type, just return it.
18122       Results.push_back(ToVecInt);
18123       return;
18124     }
18125
18126     SmallVector<SDValue, 8> Elts;
18127     for (unsigned i = 0, e = NumElts; i != e; ++i)
18128       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18129                                    ToVecInt, DAG.getIntPtrConstant(i)));
18130
18131     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18132   }
18133   }
18134 }
18135
18136 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18137   switch (Opcode) {
18138   default: return nullptr;
18139   case X86ISD::BSF:                return "X86ISD::BSF";
18140   case X86ISD::BSR:                return "X86ISD::BSR";
18141   case X86ISD::SHLD:               return "X86ISD::SHLD";
18142   case X86ISD::SHRD:               return "X86ISD::SHRD";
18143   case X86ISD::FAND:               return "X86ISD::FAND";
18144   case X86ISD::FANDN:              return "X86ISD::FANDN";
18145   case X86ISD::FOR:                return "X86ISD::FOR";
18146   case X86ISD::FXOR:               return "X86ISD::FXOR";
18147   case X86ISD::FSRL:               return "X86ISD::FSRL";
18148   case X86ISD::FILD:               return "X86ISD::FILD";
18149   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18150   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18151   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18152   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18153   case X86ISD::FLD:                return "X86ISD::FLD";
18154   case X86ISD::FST:                return "X86ISD::FST";
18155   case X86ISD::CALL:               return "X86ISD::CALL";
18156   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18157   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18158   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18159   case X86ISD::BT:                 return "X86ISD::BT";
18160   case X86ISD::CMP:                return "X86ISD::CMP";
18161   case X86ISD::COMI:               return "X86ISD::COMI";
18162   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18163   case X86ISD::CMPM:               return "X86ISD::CMPM";
18164   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18165   case X86ISD::SETCC:              return "X86ISD::SETCC";
18166   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18167   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18168   case X86ISD::CMOV:               return "X86ISD::CMOV";
18169   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18170   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18171   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18172   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18173   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18174   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18175   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18176   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18177   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18178   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18179   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18180   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18181   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18182   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18183   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18184   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
18185   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18186   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18187   case X86ISD::HADD:               return "X86ISD::HADD";
18188   case X86ISD::HSUB:               return "X86ISD::HSUB";
18189   case X86ISD::FHADD:              return "X86ISD::FHADD";
18190   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18191   case X86ISD::UMAX:               return "X86ISD::UMAX";
18192   case X86ISD::UMIN:               return "X86ISD::UMIN";
18193   case X86ISD::SMAX:               return "X86ISD::SMAX";
18194   case X86ISD::SMIN:               return "X86ISD::SMIN";
18195   case X86ISD::FMAX:               return "X86ISD::FMAX";
18196   case X86ISD::FMIN:               return "X86ISD::FMIN";
18197   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18198   case X86ISD::FMINC:              return "X86ISD::FMINC";
18199   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18200   case X86ISD::FRCP:               return "X86ISD::FRCP";
18201   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18202   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18203   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18204   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18205   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18206   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18207   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18208   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18209   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18210   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18211   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18212   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18213   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18214   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18215   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18216   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18217   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18218   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18219   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18220   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18221   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18222   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18223   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18224   case X86ISD::VSHL:               return "X86ISD::VSHL";
18225   case X86ISD::VSRL:               return "X86ISD::VSRL";
18226   case X86ISD::VSRA:               return "X86ISD::VSRA";
18227   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18228   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18229   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18230   case X86ISD::CMPP:               return "X86ISD::CMPP";
18231   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18232   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18233   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18234   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18235   case X86ISD::ADD:                return "X86ISD::ADD";
18236   case X86ISD::SUB:                return "X86ISD::SUB";
18237   case X86ISD::ADC:                return "X86ISD::ADC";
18238   case X86ISD::SBB:                return "X86ISD::SBB";
18239   case X86ISD::SMUL:               return "X86ISD::SMUL";
18240   case X86ISD::UMUL:               return "X86ISD::UMUL";
18241   case X86ISD::INC:                return "X86ISD::INC";
18242   case X86ISD::DEC:                return "X86ISD::DEC";
18243   case X86ISD::OR:                 return "X86ISD::OR";
18244   case X86ISD::XOR:                return "X86ISD::XOR";
18245   case X86ISD::AND:                return "X86ISD::AND";
18246   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18247   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18248   case X86ISD::PTEST:              return "X86ISD::PTEST";
18249   case X86ISD::TESTP:              return "X86ISD::TESTP";
18250   case X86ISD::TESTM:              return "X86ISD::TESTM";
18251   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18252   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18253   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18254   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18255   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18256   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18257   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18258   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18259   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18260   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18261   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18262   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18263   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18264   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18265   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18266   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18267   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18268   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18269   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18270   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18271   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18272   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18273   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18274   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
18275   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18276   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18277   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18278   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18279   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18280   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18281   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18282   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18283   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18284   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18285   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18286   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18287   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18288   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18289   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18290   case X86ISD::SAHF:               return "X86ISD::SAHF";
18291   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18292   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18293   case X86ISD::FMADD:              return "X86ISD::FMADD";
18294   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18295   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18296   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18297   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18298   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18299   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18300   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18301   case X86ISD::XTEST:              return "X86ISD::XTEST";
18302   }
18303 }
18304
18305 // isLegalAddressingMode - Return true if the addressing mode represented
18306 // by AM is legal for this target, for a load/store of the specified type.
18307 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18308                                               Type *Ty) const {
18309   // X86 supports extremely general addressing modes.
18310   CodeModel::Model M = getTargetMachine().getCodeModel();
18311   Reloc::Model R = getTargetMachine().getRelocationModel();
18312
18313   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18314   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18315     return false;
18316
18317   if (AM.BaseGV) {
18318     unsigned GVFlags =
18319       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18320
18321     // If a reference to this global requires an extra load, we can't fold it.
18322     if (isGlobalStubReference(GVFlags))
18323       return false;
18324
18325     // If BaseGV requires a register for the PIC base, we cannot also have a
18326     // BaseReg specified.
18327     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18328       return false;
18329
18330     // If lower 4G is not available, then we must use rip-relative addressing.
18331     if ((M != CodeModel::Small || R != Reloc::Static) &&
18332         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18333       return false;
18334   }
18335
18336   switch (AM.Scale) {
18337   case 0:
18338   case 1:
18339   case 2:
18340   case 4:
18341   case 8:
18342     // These scales always work.
18343     break;
18344   case 3:
18345   case 5:
18346   case 9:
18347     // These scales are formed with basereg+scalereg.  Only accept if there is
18348     // no basereg yet.
18349     if (AM.HasBaseReg)
18350       return false;
18351     break;
18352   default:  // Other stuff never works.
18353     return false;
18354   }
18355
18356   return true;
18357 }
18358
18359 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18360   unsigned Bits = Ty->getScalarSizeInBits();
18361
18362   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18363   // particularly cheaper than those without.
18364   if (Bits == 8)
18365     return false;
18366
18367   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18368   // variable shifts just as cheap as scalar ones.
18369   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18370     return false;
18371
18372   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18373   // fully general vector.
18374   return true;
18375 }
18376
18377 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18378   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18379     return false;
18380   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18381   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18382   return NumBits1 > NumBits2;
18383 }
18384
18385 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18386   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18387     return false;
18388
18389   if (!isTypeLegal(EVT::getEVT(Ty1)))
18390     return false;
18391
18392   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18393
18394   // Assuming the caller doesn't have a zeroext or signext return parameter,
18395   // truncation all the way down to i1 is valid.
18396   return true;
18397 }
18398
18399 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18400   return isInt<32>(Imm);
18401 }
18402
18403 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18404   // Can also use sub to handle negated immediates.
18405   return isInt<32>(Imm);
18406 }
18407
18408 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18409   if (!VT1.isInteger() || !VT2.isInteger())
18410     return false;
18411   unsigned NumBits1 = VT1.getSizeInBits();
18412   unsigned NumBits2 = VT2.getSizeInBits();
18413   return NumBits1 > NumBits2;
18414 }
18415
18416 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18417   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18418   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18419 }
18420
18421 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18422   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18423   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18424 }
18425
18426 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18427   EVT VT1 = Val.getValueType();
18428   if (isZExtFree(VT1, VT2))
18429     return true;
18430
18431   if (Val.getOpcode() != ISD::LOAD)
18432     return false;
18433
18434   if (!VT1.isSimple() || !VT1.isInteger() ||
18435       !VT2.isSimple() || !VT2.isInteger())
18436     return false;
18437
18438   switch (VT1.getSimpleVT().SimpleTy) {
18439   default: break;
18440   case MVT::i8:
18441   case MVT::i16:
18442   case MVT::i32:
18443     // X86 has 8, 16, and 32-bit zero-extending loads.
18444     return true;
18445   }
18446
18447   return false;
18448 }
18449
18450 bool
18451 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18452   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
18453     return false;
18454
18455   VT = VT.getScalarType();
18456
18457   if (!VT.isSimple())
18458     return false;
18459
18460   switch (VT.getSimpleVT().SimpleTy) {
18461   case MVT::f32:
18462   case MVT::f64:
18463     return true;
18464   default:
18465     break;
18466   }
18467
18468   return false;
18469 }
18470
18471 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18472   // i16 instructions are longer (0x66 prefix) and potentially slower.
18473   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18474 }
18475
18476 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18477 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18478 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18479 /// are assumed to be legal.
18480 bool
18481 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18482                                       EVT VT) const {
18483   if (!VT.isSimple())
18484     return false;
18485
18486   MVT SVT = VT.getSimpleVT();
18487
18488   // Very little shuffling can be done for 64-bit vectors right now.
18489   if (VT.getSizeInBits() == 64)
18490     return false;
18491
18492   // If this is a single-input shuffle with no 128 bit lane crossings we can
18493   // lower it into pshufb.
18494   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
18495       (SVT.is256BitVector() && Subtarget->hasInt256())) {
18496     bool isLegal = true;
18497     for (unsigned I = 0, E = M.size(); I != E; ++I) {
18498       if (M[I] >= (int)SVT.getVectorNumElements() ||
18499           ShuffleCrosses128bitLane(SVT, I, M[I])) {
18500         isLegal = false;
18501         break;
18502       }
18503     }
18504     if (isLegal)
18505       return true;
18506   }
18507
18508   // FIXME: blends, shifts.
18509   return (SVT.getVectorNumElements() == 2 ||
18510           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
18511           isMOVLMask(M, SVT) ||
18512           isMOVHLPSMask(M, SVT) ||
18513           isSHUFPMask(M, SVT) ||
18514           isPSHUFDMask(M, SVT) ||
18515           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
18516           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
18517           isPALIGNRMask(M, SVT, Subtarget) ||
18518           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
18519           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
18520           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
18521           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
18522           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
18523 }
18524
18525 bool
18526 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18527                                           EVT VT) const {
18528   if (!VT.isSimple())
18529     return false;
18530
18531   MVT SVT = VT.getSimpleVT();
18532   unsigned NumElts = SVT.getVectorNumElements();
18533   // FIXME: This collection of masks seems suspect.
18534   if (NumElts == 2)
18535     return true;
18536   if (NumElts == 4 && SVT.is128BitVector()) {
18537     return (isMOVLMask(Mask, SVT)  ||
18538             isCommutedMOVLMask(Mask, SVT, true) ||
18539             isSHUFPMask(Mask, SVT) ||
18540             isSHUFPMask(Mask, SVT, /* Commuted */ true));
18541   }
18542   return false;
18543 }
18544
18545 //===----------------------------------------------------------------------===//
18546 //                           X86 Scheduler Hooks
18547 //===----------------------------------------------------------------------===//
18548
18549 /// Utility function to emit xbegin specifying the start of an RTM region.
18550 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18551                                      const TargetInstrInfo *TII) {
18552   DebugLoc DL = MI->getDebugLoc();
18553
18554   const BasicBlock *BB = MBB->getBasicBlock();
18555   MachineFunction::iterator I = MBB;
18556   ++I;
18557
18558   // For the v = xbegin(), we generate
18559   //
18560   // thisMBB:
18561   //  xbegin sinkMBB
18562   //
18563   // mainMBB:
18564   //  eax = -1
18565   //
18566   // sinkMBB:
18567   //  v = eax
18568
18569   MachineBasicBlock *thisMBB = MBB;
18570   MachineFunction *MF = MBB->getParent();
18571   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18572   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18573   MF->insert(I, mainMBB);
18574   MF->insert(I, sinkMBB);
18575
18576   // Transfer the remainder of BB and its successor edges to sinkMBB.
18577   sinkMBB->splice(sinkMBB->begin(), MBB,
18578                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18579   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18580
18581   // thisMBB:
18582   //  xbegin sinkMBB
18583   //  # fallthrough to mainMBB
18584   //  # abortion to sinkMBB
18585   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18586   thisMBB->addSuccessor(mainMBB);
18587   thisMBB->addSuccessor(sinkMBB);
18588
18589   // mainMBB:
18590   //  EAX = -1
18591   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18592   mainMBB->addSuccessor(sinkMBB);
18593
18594   // sinkMBB:
18595   // EAX is live into the sinkMBB
18596   sinkMBB->addLiveIn(X86::EAX);
18597   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18598           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18599     .addReg(X86::EAX);
18600
18601   MI->eraseFromParent();
18602   return sinkMBB;
18603 }
18604
18605 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18606 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18607 // in the .td file.
18608 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18609                                        const TargetInstrInfo *TII) {
18610   unsigned Opc;
18611   switch (MI->getOpcode()) {
18612   default: llvm_unreachable("illegal opcode!");
18613   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18614   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18615   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18616   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18617   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18618   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18619   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18620   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18621   }
18622
18623   DebugLoc dl = MI->getDebugLoc();
18624   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18625
18626   unsigned NumArgs = MI->getNumOperands();
18627   for (unsigned i = 1; i < NumArgs; ++i) {
18628     MachineOperand &Op = MI->getOperand(i);
18629     if (!(Op.isReg() && Op.isImplicit()))
18630       MIB.addOperand(Op);
18631   }
18632   if (MI->hasOneMemOperand())
18633     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18634
18635   BuildMI(*BB, MI, dl,
18636     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18637     .addReg(X86::XMM0);
18638
18639   MI->eraseFromParent();
18640   return BB;
18641 }
18642
18643 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18644 // defs in an instruction pattern
18645 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18646                                        const TargetInstrInfo *TII) {
18647   unsigned Opc;
18648   switch (MI->getOpcode()) {
18649   default: llvm_unreachable("illegal opcode!");
18650   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18651   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18652   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18653   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18654   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18655   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18656   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18657   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18658   }
18659
18660   DebugLoc dl = MI->getDebugLoc();
18661   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18662
18663   unsigned NumArgs = MI->getNumOperands(); // remove the results
18664   for (unsigned i = 1; i < NumArgs; ++i) {
18665     MachineOperand &Op = MI->getOperand(i);
18666     if (!(Op.isReg() && Op.isImplicit()))
18667       MIB.addOperand(Op);
18668   }
18669   if (MI->hasOneMemOperand())
18670     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18671
18672   BuildMI(*BB, MI, dl,
18673     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18674     .addReg(X86::ECX);
18675
18676   MI->eraseFromParent();
18677   return BB;
18678 }
18679
18680 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18681                                        const TargetInstrInfo *TII,
18682                                        const X86Subtarget* Subtarget) {
18683   DebugLoc dl = MI->getDebugLoc();
18684
18685   // Address into RAX/EAX, other two args into ECX, EDX.
18686   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
18687   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
18688   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
18689   for (int i = 0; i < X86::AddrNumOperands; ++i)
18690     MIB.addOperand(MI->getOperand(i));
18691
18692   unsigned ValOps = X86::AddrNumOperands;
18693   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
18694     .addReg(MI->getOperand(ValOps).getReg());
18695   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
18696     .addReg(MI->getOperand(ValOps+1).getReg());
18697
18698   // The instruction doesn't actually take any operands though.
18699   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
18700
18701   MI->eraseFromParent(); // The pseudo is gone now.
18702   return BB;
18703 }
18704
18705 MachineBasicBlock *
18706 X86TargetLowering::EmitVAARG64WithCustomInserter(
18707                    MachineInstr *MI,
18708                    MachineBasicBlock *MBB) const {
18709   // Emit va_arg instruction on X86-64.
18710
18711   // Operands to this pseudo-instruction:
18712   // 0  ) Output        : destination address (reg)
18713   // 1-5) Input         : va_list address (addr, i64mem)
18714   // 6  ) ArgSize       : Size (in bytes) of vararg type
18715   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
18716   // 8  ) Align         : Alignment of type
18717   // 9  ) EFLAGS (implicit-def)
18718
18719   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
18720   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
18721
18722   unsigned DestReg = MI->getOperand(0).getReg();
18723   MachineOperand &Base = MI->getOperand(1);
18724   MachineOperand &Scale = MI->getOperand(2);
18725   MachineOperand &Index = MI->getOperand(3);
18726   MachineOperand &Disp = MI->getOperand(4);
18727   MachineOperand &Segment = MI->getOperand(5);
18728   unsigned ArgSize = MI->getOperand(6).getImm();
18729   unsigned ArgMode = MI->getOperand(7).getImm();
18730   unsigned Align = MI->getOperand(8).getImm();
18731
18732   // Memory Reference
18733   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
18734   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18735   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18736
18737   // Machine Information
18738   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18739   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
18740   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
18741   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
18742   DebugLoc DL = MI->getDebugLoc();
18743
18744   // struct va_list {
18745   //   i32   gp_offset
18746   //   i32   fp_offset
18747   //   i64   overflow_area (address)
18748   //   i64   reg_save_area (address)
18749   // }
18750   // sizeof(va_list) = 24
18751   // alignment(va_list) = 8
18752
18753   unsigned TotalNumIntRegs = 6;
18754   unsigned TotalNumXMMRegs = 8;
18755   bool UseGPOffset = (ArgMode == 1);
18756   bool UseFPOffset = (ArgMode == 2);
18757   unsigned MaxOffset = TotalNumIntRegs * 8 +
18758                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
18759
18760   /* Align ArgSize to a multiple of 8 */
18761   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
18762   bool NeedsAlign = (Align > 8);
18763
18764   MachineBasicBlock *thisMBB = MBB;
18765   MachineBasicBlock *overflowMBB;
18766   MachineBasicBlock *offsetMBB;
18767   MachineBasicBlock *endMBB;
18768
18769   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
18770   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
18771   unsigned OffsetReg = 0;
18772
18773   if (!UseGPOffset && !UseFPOffset) {
18774     // If we only pull from the overflow region, we don't create a branch.
18775     // We don't need to alter control flow.
18776     OffsetDestReg = 0; // unused
18777     OverflowDestReg = DestReg;
18778
18779     offsetMBB = nullptr;
18780     overflowMBB = thisMBB;
18781     endMBB = thisMBB;
18782   } else {
18783     // First emit code to check if gp_offset (or fp_offset) is below the bound.
18784     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
18785     // If not, pull from overflow_area. (branch to overflowMBB)
18786     //
18787     //       thisMBB
18788     //         |     .
18789     //         |        .
18790     //     offsetMBB   overflowMBB
18791     //         |        .
18792     //         |     .
18793     //        endMBB
18794
18795     // Registers for the PHI in endMBB
18796     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
18797     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
18798
18799     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18800     MachineFunction *MF = MBB->getParent();
18801     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18802     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18803     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18804
18805     MachineFunction::iterator MBBIter = MBB;
18806     ++MBBIter;
18807
18808     // Insert the new basic blocks
18809     MF->insert(MBBIter, offsetMBB);
18810     MF->insert(MBBIter, overflowMBB);
18811     MF->insert(MBBIter, endMBB);
18812
18813     // Transfer the remainder of MBB and its successor edges to endMBB.
18814     endMBB->splice(endMBB->begin(), thisMBB,
18815                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
18816     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
18817
18818     // Make offsetMBB and overflowMBB successors of thisMBB
18819     thisMBB->addSuccessor(offsetMBB);
18820     thisMBB->addSuccessor(overflowMBB);
18821
18822     // endMBB is a successor of both offsetMBB and overflowMBB
18823     offsetMBB->addSuccessor(endMBB);
18824     overflowMBB->addSuccessor(endMBB);
18825
18826     // Load the offset value into a register
18827     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18828     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
18829       .addOperand(Base)
18830       .addOperand(Scale)
18831       .addOperand(Index)
18832       .addDisp(Disp, UseFPOffset ? 4 : 0)
18833       .addOperand(Segment)
18834       .setMemRefs(MMOBegin, MMOEnd);
18835
18836     // Check if there is enough room left to pull this argument.
18837     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
18838       .addReg(OffsetReg)
18839       .addImm(MaxOffset + 8 - ArgSizeA8);
18840
18841     // Branch to "overflowMBB" if offset >= max
18842     // Fall through to "offsetMBB" otherwise
18843     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
18844       .addMBB(overflowMBB);
18845   }
18846
18847   // In offsetMBB, emit code to use the reg_save_area.
18848   if (offsetMBB) {
18849     assert(OffsetReg != 0);
18850
18851     // Read the reg_save_area address.
18852     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
18853     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
18854       .addOperand(Base)
18855       .addOperand(Scale)
18856       .addOperand(Index)
18857       .addDisp(Disp, 16)
18858       .addOperand(Segment)
18859       .setMemRefs(MMOBegin, MMOEnd);
18860
18861     // Zero-extend the offset
18862     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
18863       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
18864         .addImm(0)
18865         .addReg(OffsetReg)
18866         .addImm(X86::sub_32bit);
18867
18868     // Add the offset to the reg_save_area to get the final address.
18869     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
18870       .addReg(OffsetReg64)
18871       .addReg(RegSaveReg);
18872
18873     // Compute the offset for the next argument
18874     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
18875     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
18876       .addReg(OffsetReg)
18877       .addImm(UseFPOffset ? 16 : 8);
18878
18879     // Store it back into the va_list.
18880     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
18881       .addOperand(Base)
18882       .addOperand(Scale)
18883       .addOperand(Index)
18884       .addDisp(Disp, UseFPOffset ? 4 : 0)
18885       .addOperand(Segment)
18886       .addReg(NextOffsetReg)
18887       .setMemRefs(MMOBegin, MMOEnd);
18888
18889     // Jump to endMBB
18890     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
18891       .addMBB(endMBB);
18892   }
18893
18894   //
18895   // Emit code to use overflow area
18896   //
18897
18898   // Load the overflow_area address into a register.
18899   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
18900   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
18901     .addOperand(Base)
18902     .addOperand(Scale)
18903     .addOperand(Index)
18904     .addDisp(Disp, 8)
18905     .addOperand(Segment)
18906     .setMemRefs(MMOBegin, MMOEnd);
18907
18908   // If we need to align it, do so. Otherwise, just copy the address
18909   // to OverflowDestReg.
18910   if (NeedsAlign) {
18911     // Align the overflow address
18912     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
18913     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
18914
18915     // aligned_addr = (addr + (align-1)) & ~(align-1)
18916     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
18917       .addReg(OverflowAddrReg)
18918       .addImm(Align-1);
18919
18920     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
18921       .addReg(TmpReg)
18922       .addImm(~(uint64_t)(Align-1));
18923   } else {
18924     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
18925       .addReg(OverflowAddrReg);
18926   }
18927
18928   // Compute the next overflow address after this argument.
18929   // (the overflow address should be kept 8-byte aligned)
18930   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
18931   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
18932     .addReg(OverflowDestReg)
18933     .addImm(ArgSizeA8);
18934
18935   // Store the new overflow address.
18936   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
18937     .addOperand(Base)
18938     .addOperand(Scale)
18939     .addOperand(Index)
18940     .addDisp(Disp, 8)
18941     .addOperand(Segment)
18942     .addReg(NextAddrReg)
18943     .setMemRefs(MMOBegin, MMOEnd);
18944
18945   // If we branched, emit the PHI to the front of endMBB.
18946   if (offsetMBB) {
18947     BuildMI(*endMBB, endMBB->begin(), DL,
18948             TII->get(X86::PHI), DestReg)
18949       .addReg(OffsetDestReg).addMBB(offsetMBB)
18950       .addReg(OverflowDestReg).addMBB(overflowMBB);
18951   }
18952
18953   // Erase the pseudo instruction
18954   MI->eraseFromParent();
18955
18956   return endMBB;
18957 }
18958
18959 MachineBasicBlock *
18960 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
18961                                                  MachineInstr *MI,
18962                                                  MachineBasicBlock *MBB) const {
18963   // Emit code to save XMM registers to the stack. The ABI says that the
18964   // number of registers to save is given in %al, so it's theoretically
18965   // possible to do an indirect jump trick to avoid saving all of them,
18966   // however this code takes a simpler approach and just executes all
18967   // of the stores if %al is non-zero. It's less code, and it's probably
18968   // easier on the hardware branch predictor, and stores aren't all that
18969   // expensive anyway.
18970
18971   // Create the new basic blocks. One block contains all the XMM stores,
18972   // and one block is the final destination regardless of whether any
18973   // stores were performed.
18974   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
18975   MachineFunction *F = MBB->getParent();
18976   MachineFunction::iterator MBBIter = MBB;
18977   ++MBBIter;
18978   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
18979   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
18980   F->insert(MBBIter, XMMSaveMBB);
18981   F->insert(MBBIter, EndMBB);
18982
18983   // Transfer the remainder of MBB and its successor edges to EndMBB.
18984   EndMBB->splice(EndMBB->begin(), MBB,
18985                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18986   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
18987
18988   // The original block will now fall through to the XMM save block.
18989   MBB->addSuccessor(XMMSaveMBB);
18990   // The XMMSaveMBB will fall through to the end block.
18991   XMMSaveMBB->addSuccessor(EndMBB);
18992
18993   // Now add the instructions.
18994   const TargetInstrInfo *TII = MBB->getParent()->getSubtarget().getInstrInfo();
18995   DebugLoc DL = MI->getDebugLoc();
18996
18997   unsigned CountReg = MI->getOperand(0).getReg();
18998   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
18999   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19000
19001   if (!Subtarget->isTargetWin64()) {
19002     // If %al is 0, branch around the XMM save block.
19003     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19004     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
19005     MBB->addSuccessor(EndMBB);
19006   }
19007
19008   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19009   // that was just emitted, but clearly shouldn't be "saved".
19010   assert((MI->getNumOperands() <= 3 ||
19011           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19012           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19013          && "Expected last argument to be EFLAGS");
19014   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19015   // In the XMM save block, save all the XMM argument registers.
19016   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19017     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19018     MachineMemOperand *MMO =
19019       F->getMachineMemOperand(
19020           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19021         MachineMemOperand::MOStore,
19022         /*Size=*/16, /*Align=*/16);
19023     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19024       .addFrameIndex(RegSaveFrameIndex)
19025       .addImm(/*Scale=*/1)
19026       .addReg(/*IndexReg=*/0)
19027       .addImm(/*Disp=*/Offset)
19028       .addReg(/*Segment=*/0)
19029       .addReg(MI->getOperand(i).getReg())
19030       .addMemOperand(MMO);
19031   }
19032
19033   MI->eraseFromParent();   // The pseudo instruction is gone now.
19034
19035   return EndMBB;
19036 }
19037
19038 // The EFLAGS operand of SelectItr might be missing a kill marker
19039 // because there were multiple uses of EFLAGS, and ISel didn't know
19040 // which to mark. Figure out whether SelectItr should have had a
19041 // kill marker, and set it if it should. Returns the correct kill
19042 // marker value.
19043 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19044                                      MachineBasicBlock* BB,
19045                                      const TargetRegisterInfo* TRI) {
19046   // Scan forward through BB for a use/def of EFLAGS.
19047   MachineBasicBlock::iterator miI(std::next(SelectItr));
19048   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19049     const MachineInstr& mi = *miI;
19050     if (mi.readsRegister(X86::EFLAGS))
19051       return false;
19052     if (mi.definesRegister(X86::EFLAGS))
19053       break; // Should have kill-flag - update below.
19054   }
19055
19056   // If we hit the end of the block, check whether EFLAGS is live into a
19057   // successor.
19058   if (miI == BB->end()) {
19059     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19060                                           sEnd = BB->succ_end();
19061          sItr != sEnd; ++sItr) {
19062       MachineBasicBlock* succ = *sItr;
19063       if (succ->isLiveIn(X86::EFLAGS))
19064         return false;
19065     }
19066   }
19067
19068   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19069   // out. SelectMI should have a kill flag on EFLAGS.
19070   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19071   return true;
19072 }
19073
19074 MachineBasicBlock *
19075 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19076                                      MachineBasicBlock *BB) const {
19077   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
19078   DebugLoc DL = MI->getDebugLoc();
19079
19080   // To "insert" a SELECT_CC instruction, we actually have to insert the
19081   // diamond control-flow pattern.  The incoming instruction knows the
19082   // destination vreg to set, the condition code register to branch on, the
19083   // true/false values to select between, and a branch opcode to use.
19084   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19085   MachineFunction::iterator It = BB;
19086   ++It;
19087
19088   //  thisMBB:
19089   //  ...
19090   //   TrueVal = ...
19091   //   cmpTY ccX, r1, r2
19092   //   bCC copy1MBB
19093   //   fallthrough --> copy0MBB
19094   MachineBasicBlock *thisMBB = BB;
19095   MachineFunction *F = BB->getParent();
19096   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19097   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19098   F->insert(It, copy0MBB);
19099   F->insert(It, sinkMBB);
19100
19101   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19102   // live into the sink and copy blocks.
19103   const TargetRegisterInfo *TRI =
19104       BB->getParent()->getSubtarget().getRegisterInfo();
19105   if (!MI->killsRegister(X86::EFLAGS) &&
19106       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
19107     copy0MBB->addLiveIn(X86::EFLAGS);
19108     sinkMBB->addLiveIn(X86::EFLAGS);
19109   }
19110
19111   // Transfer the remainder of BB and its successor edges to sinkMBB.
19112   sinkMBB->splice(sinkMBB->begin(), BB,
19113                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19114   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19115
19116   // Add the true and fallthrough blocks as its successors.
19117   BB->addSuccessor(copy0MBB);
19118   BB->addSuccessor(sinkMBB);
19119
19120   // Create the conditional branch instruction.
19121   unsigned Opc =
19122     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19123   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19124
19125   //  copy0MBB:
19126   //   %FalseValue = ...
19127   //   # fallthrough to sinkMBB
19128   copy0MBB->addSuccessor(sinkMBB);
19129
19130   //  sinkMBB:
19131   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19132   //  ...
19133   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19134           TII->get(X86::PHI), MI->getOperand(0).getReg())
19135     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19136     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19137
19138   MI->eraseFromParent();   // The pseudo instruction is gone now.
19139   return sinkMBB;
19140 }
19141
19142 MachineBasicBlock *
19143 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19144                                         MachineBasicBlock *BB) const {
19145   MachineFunction *MF = BB->getParent();
19146   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
19147   DebugLoc DL = MI->getDebugLoc();
19148   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19149
19150   assert(MF->shouldSplitStack());
19151
19152   const bool Is64Bit = Subtarget->is64Bit();
19153   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19154
19155   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19156   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19157
19158   // BB:
19159   //  ... [Till the alloca]
19160   // If stacklet is not large enough, jump to mallocMBB
19161   //
19162   // bumpMBB:
19163   //  Allocate by subtracting from RSP
19164   //  Jump to continueMBB
19165   //
19166   // mallocMBB:
19167   //  Allocate by call to runtime
19168   //
19169   // continueMBB:
19170   //  ...
19171   //  [rest of original BB]
19172   //
19173
19174   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19175   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19176   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19177
19178   MachineRegisterInfo &MRI = MF->getRegInfo();
19179   const TargetRegisterClass *AddrRegClass =
19180     getRegClassFor(getPointerTy());
19181
19182   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19183     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19184     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19185     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19186     sizeVReg = MI->getOperand(1).getReg(),
19187     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19188
19189   MachineFunction::iterator MBBIter = BB;
19190   ++MBBIter;
19191
19192   MF->insert(MBBIter, bumpMBB);
19193   MF->insert(MBBIter, mallocMBB);
19194   MF->insert(MBBIter, continueMBB);
19195
19196   continueMBB->splice(continueMBB->begin(), BB,
19197                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19198   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19199
19200   // Add code to the main basic block to check if the stack limit has been hit,
19201   // and if so, jump to mallocMBB otherwise to bumpMBB.
19202   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19203   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19204     .addReg(tmpSPVReg).addReg(sizeVReg);
19205   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19206     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19207     .addReg(SPLimitVReg);
19208   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
19209
19210   // bumpMBB simply decreases the stack pointer, since we know the current
19211   // stacklet has enough space.
19212   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19213     .addReg(SPLimitVReg);
19214   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19215     .addReg(SPLimitVReg);
19216   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
19217
19218   // Calls into a routine in libgcc to allocate more space from the heap.
19219   const uint32_t *RegMask = MF->getTarget()
19220                                 .getSubtargetImpl()
19221                                 ->getRegisterInfo()
19222                                 ->getCallPreservedMask(CallingConv::C);
19223   if (IsLP64) {
19224     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19225       .addReg(sizeVReg);
19226     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19227       .addExternalSymbol("__morestack_allocate_stack_space")
19228       .addRegMask(RegMask)
19229       .addReg(X86::RDI, RegState::Implicit)
19230       .addReg(X86::RAX, RegState::ImplicitDefine);
19231   } else if (Is64Bit) {
19232     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19233       .addReg(sizeVReg);
19234     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19235       .addExternalSymbol("__morestack_allocate_stack_space")
19236       .addRegMask(RegMask)
19237       .addReg(X86::EDI, RegState::Implicit)
19238       .addReg(X86::EAX, RegState::ImplicitDefine);
19239   } else {
19240     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19241       .addImm(12);
19242     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19243     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19244       .addExternalSymbol("__morestack_allocate_stack_space")
19245       .addRegMask(RegMask)
19246       .addReg(X86::EAX, RegState::ImplicitDefine);
19247   }
19248
19249   if (!Is64Bit)
19250     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19251       .addImm(16);
19252
19253   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19254     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19255   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
19256
19257   // Set up the CFG correctly.
19258   BB->addSuccessor(bumpMBB);
19259   BB->addSuccessor(mallocMBB);
19260   mallocMBB->addSuccessor(continueMBB);
19261   bumpMBB->addSuccessor(continueMBB);
19262
19263   // Take care of the PHI nodes.
19264   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19265           MI->getOperand(0).getReg())
19266     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19267     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19268
19269   // Delete the original pseudo instruction.
19270   MI->eraseFromParent();
19271
19272   // And we're done.
19273   return continueMBB;
19274 }
19275
19276 MachineBasicBlock *
19277 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19278                                         MachineBasicBlock *BB) const {
19279   const TargetInstrInfo *TII = BB->getParent()->getSubtarget().getInstrInfo();
19280   DebugLoc DL = MI->getDebugLoc();
19281
19282   assert(!Subtarget->isTargetMacho());
19283
19284   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
19285   // non-trivial part is impdef of ESP.
19286
19287   if (Subtarget->isTargetWin64()) {
19288     if (Subtarget->isTargetCygMing()) {
19289       // ___chkstk(Mingw64):
19290       // Clobbers R10, R11, RAX and EFLAGS.
19291       // Updates RSP.
19292       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
19293         .addExternalSymbol("___chkstk")
19294         .addReg(X86::RAX, RegState::Implicit)
19295         .addReg(X86::RSP, RegState::Implicit)
19296         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
19297         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
19298         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
19299     } else {
19300       // __chkstk(MSVCRT): does not update stack pointer.
19301       // Clobbers R10, R11 and EFLAGS.
19302       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
19303         .addExternalSymbol("__chkstk")
19304         .addReg(X86::RAX, RegState::Implicit)
19305         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
19306       // RAX has the offset to be subtracted from RSP.
19307       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
19308         .addReg(X86::RSP)
19309         .addReg(X86::RAX);
19310     }
19311   } else {
19312     const char *StackProbeSymbol =
19313       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
19314
19315     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
19316       .addExternalSymbol(StackProbeSymbol)
19317       .addReg(X86::EAX, RegState::Implicit)
19318       .addReg(X86::ESP, RegState::Implicit)
19319       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
19320       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
19321       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
19322   }
19323
19324   MI->eraseFromParent();   // The pseudo instruction is gone now.
19325   return BB;
19326 }
19327
19328 MachineBasicBlock *
19329 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19330                                       MachineBasicBlock *BB) const {
19331   // This is pretty easy.  We're taking the value that we received from
19332   // our load from the relocation, sticking it in either RDI (x86-64)
19333   // or EAX and doing an indirect call.  The return value will then
19334   // be in the normal return register.
19335   MachineFunction *F = BB->getParent();
19336   const X86InstrInfo *TII =
19337       static_cast<const X86InstrInfo *>(F->getSubtarget().getInstrInfo());
19338   DebugLoc DL = MI->getDebugLoc();
19339
19340   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19341   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19342
19343   // Get a register mask for the lowered call.
19344   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19345   // proper register mask.
19346   const uint32_t *RegMask = F->getTarget()
19347                                 .getSubtargetImpl()
19348                                 ->getRegisterInfo()
19349                                 ->getCallPreservedMask(CallingConv::C);
19350   if (Subtarget->is64Bit()) {
19351     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19352                                       TII->get(X86::MOV64rm), X86::RDI)
19353     .addReg(X86::RIP)
19354     .addImm(0).addReg(0)
19355     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19356                       MI->getOperand(3).getTargetFlags())
19357     .addReg(0);
19358     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19359     addDirectMem(MIB, X86::RDI);
19360     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19361   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19362     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19363                                       TII->get(X86::MOV32rm), X86::EAX)
19364     .addReg(0)
19365     .addImm(0).addReg(0)
19366     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19367                       MI->getOperand(3).getTargetFlags())
19368     .addReg(0);
19369     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19370     addDirectMem(MIB, X86::EAX);
19371     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19372   } else {
19373     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19374                                       TII->get(X86::MOV32rm), X86::EAX)
19375     .addReg(TII->getGlobalBaseReg(F))
19376     .addImm(0).addReg(0)
19377     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19378                       MI->getOperand(3).getTargetFlags())
19379     .addReg(0);
19380     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19381     addDirectMem(MIB, X86::EAX);
19382     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19383   }
19384
19385   MI->eraseFromParent(); // The pseudo instruction is gone now.
19386   return BB;
19387 }
19388
19389 MachineBasicBlock *
19390 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19391                                     MachineBasicBlock *MBB) const {
19392   DebugLoc DL = MI->getDebugLoc();
19393   MachineFunction *MF = MBB->getParent();
19394   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
19395   MachineRegisterInfo &MRI = MF->getRegInfo();
19396
19397   const BasicBlock *BB = MBB->getBasicBlock();
19398   MachineFunction::iterator I = MBB;
19399   ++I;
19400
19401   // Memory Reference
19402   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19403   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19404
19405   unsigned DstReg;
19406   unsigned MemOpndSlot = 0;
19407
19408   unsigned CurOp = 0;
19409
19410   DstReg = MI->getOperand(CurOp++).getReg();
19411   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19412   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19413   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19414   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19415
19416   MemOpndSlot = CurOp;
19417
19418   MVT PVT = getPointerTy();
19419   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19420          "Invalid Pointer Size!");
19421
19422   // For v = setjmp(buf), we generate
19423   //
19424   // thisMBB:
19425   //  buf[LabelOffset] = restoreMBB
19426   //  SjLjSetup restoreMBB
19427   //
19428   // mainMBB:
19429   //  v_main = 0
19430   //
19431   // sinkMBB:
19432   //  v = phi(main, restore)
19433   //
19434   // restoreMBB:
19435   //  v_restore = 1
19436
19437   MachineBasicBlock *thisMBB = MBB;
19438   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19439   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19440   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19441   MF->insert(I, mainMBB);
19442   MF->insert(I, sinkMBB);
19443   MF->push_back(restoreMBB);
19444
19445   MachineInstrBuilder MIB;
19446
19447   // Transfer the remainder of BB and its successor edges to sinkMBB.
19448   sinkMBB->splice(sinkMBB->begin(), MBB,
19449                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19450   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19451
19452   // thisMBB:
19453   unsigned PtrStoreOpc = 0;
19454   unsigned LabelReg = 0;
19455   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19456   Reloc::Model RM = MF->getTarget().getRelocationModel();
19457   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19458                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19459
19460   // Prepare IP either in reg or imm.
19461   if (!UseImmLabel) {
19462     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19463     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19464     LabelReg = MRI.createVirtualRegister(PtrRC);
19465     if (Subtarget->is64Bit()) {
19466       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19467               .addReg(X86::RIP)
19468               .addImm(0)
19469               .addReg(0)
19470               .addMBB(restoreMBB)
19471               .addReg(0);
19472     } else {
19473       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19474       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19475               .addReg(XII->getGlobalBaseReg(MF))
19476               .addImm(0)
19477               .addReg(0)
19478               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19479               .addReg(0);
19480     }
19481   } else
19482     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19483   // Store IP
19484   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19485   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19486     if (i == X86::AddrDisp)
19487       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19488     else
19489       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19490   }
19491   if (!UseImmLabel)
19492     MIB.addReg(LabelReg);
19493   else
19494     MIB.addMBB(restoreMBB);
19495   MIB.setMemRefs(MMOBegin, MMOEnd);
19496   // Setup
19497   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19498           .addMBB(restoreMBB);
19499
19500   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
19501       MF->getSubtarget().getRegisterInfo());
19502   MIB.addRegMask(RegInfo->getNoPreservedMask());
19503   thisMBB->addSuccessor(mainMBB);
19504   thisMBB->addSuccessor(restoreMBB);
19505
19506   // mainMBB:
19507   //  EAX = 0
19508   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19509   mainMBB->addSuccessor(sinkMBB);
19510
19511   // sinkMBB:
19512   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19513           TII->get(X86::PHI), DstReg)
19514     .addReg(mainDstReg).addMBB(mainMBB)
19515     .addReg(restoreDstReg).addMBB(restoreMBB);
19516
19517   // restoreMBB:
19518   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19519   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
19520   restoreMBB->addSuccessor(sinkMBB);
19521
19522   MI->eraseFromParent();
19523   return sinkMBB;
19524 }
19525
19526 MachineBasicBlock *
19527 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19528                                      MachineBasicBlock *MBB) const {
19529   DebugLoc DL = MI->getDebugLoc();
19530   MachineFunction *MF = MBB->getParent();
19531   const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo();
19532   MachineRegisterInfo &MRI = MF->getRegInfo();
19533
19534   // Memory Reference
19535   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19536   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19537
19538   MVT PVT = getPointerTy();
19539   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19540          "Invalid Pointer Size!");
19541
19542   const TargetRegisterClass *RC =
19543     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19544   unsigned Tmp = MRI.createVirtualRegister(RC);
19545   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19546   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
19547       MF->getSubtarget().getRegisterInfo());
19548   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19549   unsigned SP = RegInfo->getStackRegister();
19550
19551   MachineInstrBuilder MIB;
19552
19553   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19554   const int64_t SPOffset = 2 * PVT.getStoreSize();
19555
19556   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19557   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19558
19559   // Reload FP
19560   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19561   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19562     MIB.addOperand(MI->getOperand(i));
19563   MIB.setMemRefs(MMOBegin, MMOEnd);
19564   // Reload IP
19565   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19566   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19567     if (i == X86::AddrDisp)
19568       MIB.addDisp(MI->getOperand(i), LabelOffset);
19569     else
19570       MIB.addOperand(MI->getOperand(i));
19571   }
19572   MIB.setMemRefs(MMOBegin, MMOEnd);
19573   // Reload SP
19574   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19575   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19576     if (i == X86::AddrDisp)
19577       MIB.addDisp(MI->getOperand(i), SPOffset);
19578     else
19579       MIB.addOperand(MI->getOperand(i));
19580   }
19581   MIB.setMemRefs(MMOBegin, MMOEnd);
19582   // Jump
19583   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19584
19585   MI->eraseFromParent();
19586   return MBB;
19587 }
19588
19589 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19590 // accumulator loops. Writing back to the accumulator allows the coalescer
19591 // to remove extra copies in the loop.   
19592 MachineBasicBlock *
19593 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19594                                  MachineBasicBlock *MBB) const {
19595   MachineOperand &AddendOp = MI->getOperand(3);
19596
19597   // Bail out early if the addend isn't a register - we can't switch these.
19598   if (!AddendOp.isReg())
19599     return MBB;
19600
19601   MachineFunction &MF = *MBB->getParent();
19602   MachineRegisterInfo &MRI = MF.getRegInfo();
19603
19604   // Check whether the addend is defined by a PHI:
19605   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
19606   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
19607   if (!AddendDef.isPHI())
19608     return MBB;
19609
19610   // Look for the following pattern:
19611   // loop:
19612   //   %addend = phi [%entry, 0], [%loop, %result]
19613   //   ...
19614   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
19615
19616   // Replace with:
19617   //   loop:
19618   //   %addend = phi [%entry, 0], [%loop, %result]
19619   //   ...
19620   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
19621
19622   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
19623     assert(AddendDef.getOperand(i).isReg());
19624     MachineOperand PHISrcOp = AddendDef.getOperand(i);
19625     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
19626     if (&PHISrcInst == MI) {
19627       // Found a matching instruction.
19628       unsigned NewFMAOpc = 0;
19629       switch (MI->getOpcode()) {
19630         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
19631         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
19632         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
19633         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
19634         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
19635         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
19636         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
19637         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
19638         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
19639         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
19640         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
19641         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
19642         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
19643         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
19644         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
19645         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
19646         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
19647         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
19648         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
19649         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
19650         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
19651         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
19652         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
19653         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
19654         default: llvm_unreachable("Unrecognized FMA variant.");
19655       }
19656
19657       const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
19658       MachineInstrBuilder MIB =
19659         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
19660         .addOperand(MI->getOperand(0))
19661         .addOperand(MI->getOperand(3))
19662         .addOperand(MI->getOperand(2))
19663         .addOperand(MI->getOperand(1));
19664       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
19665       MI->eraseFromParent();
19666     }
19667   }
19668
19669   return MBB;
19670 }
19671
19672 MachineBasicBlock *
19673 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
19674                                                MachineBasicBlock *BB) const {
19675   switch (MI->getOpcode()) {
19676   default: llvm_unreachable("Unexpected instr type to insert");
19677   case X86::TAILJMPd64:
19678   case X86::TAILJMPr64:
19679   case X86::TAILJMPm64:
19680     llvm_unreachable("TAILJMP64 would not be touched here.");
19681   case X86::TCRETURNdi64:
19682   case X86::TCRETURNri64:
19683   case X86::TCRETURNmi64:
19684     return BB;
19685   case X86::WIN_ALLOCA:
19686     return EmitLoweredWinAlloca(MI, BB);
19687   case X86::SEG_ALLOCA_32:
19688   case X86::SEG_ALLOCA_64:
19689     return EmitLoweredSegAlloca(MI, BB);
19690   case X86::TLSCall_32:
19691   case X86::TLSCall_64:
19692     return EmitLoweredTLSCall(MI, BB);
19693   case X86::CMOV_GR8:
19694   case X86::CMOV_FR32:
19695   case X86::CMOV_FR64:
19696   case X86::CMOV_V4F32:
19697   case X86::CMOV_V2F64:
19698   case X86::CMOV_V2I64:
19699   case X86::CMOV_V8F32:
19700   case X86::CMOV_V4F64:
19701   case X86::CMOV_V4I64:
19702   case X86::CMOV_V16F32:
19703   case X86::CMOV_V8F64:
19704   case X86::CMOV_V8I64:
19705   case X86::CMOV_GR16:
19706   case X86::CMOV_GR32:
19707   case X86::CMOV_RFP32:
19708   case X86::CMOV_RFP64:
19709   case X86::CMOV_RFP80:
19710     return EmitLoweredSelect(MI, BB);
19711
19712   case X86::FP32_TO_INT16_IN_MEM:
19713   case X86::FP32_TO_INT32_IN_MEM:
19714   case X86::FP32_TO_INT64_IN_MEM:
19715   case X86::FP64_TO_INT16_IN_MEM:
19716   case X86::FP64_TO_INT32_IN_MEM:
19717   case X86::FP64_TO_INT64_IN_MEM:
19718   case X86::FP80_TO_INT16_IN_MEM:
19719   case X86::FP80_TO_INT32_IN_MEM:
19720   case X86::FP80_TO_INT64_IN_MEM: {
19721     MachineFunction *F = BB->getParent();
19722     const TargetInstrInfo *TII = F->getSubtarget().getInstrInfo();
19723     DebugLoc DL = MI->getDebugLoc();
19724
19725     // Change the floating point control register to use "round towards zero"
19726     // mode when truncating to an integer value.
19727     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
19728     addFrameReference(BuildMI(*BB, MI, DL,
19729                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
19730
19731     // Load the old value of the high byte of the control word...
19732     unsigned OldCW =
19733       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
19734     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
19735                       CWFrameIdx);
19736
19737     // Set the high part to be round to zero...
19738     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
19739       .addImm(0xC7F);
19740
19741     // Reload the modified control word now...
19742     addFrameReference(BuildMI(*BB, MI, DL,
19743                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19744
19745     // Restore the memory image of control word to original value
19746     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
19747       .addReg(OldCW);
19748
19749     // Get the X86 opcode to use.
19750     unsigned Opc;
19751     switch (MI->getOpcode()) {
19752     default: llvm_unreachable("illegal opcode!");
19753     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
19754     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
19755     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
19756     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
19757     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
19758     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
19759     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
19760     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
19761     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
19762     }
19763
19764     X86AddressMode AM;
19765     MachineOperand &Op = MI->getOperand(0);
19766     if (Op.isReg()) {
19767       AM.BaseType = X86AddressMode::RegBase;
19768       AM.Base.Reg = Op.getReg();
19769     } else {
19770       AM.BaseType = X86AddressMode::FrameIndexBase;
19771       AM.Base.FrameIndex = Op.getIndex();
19772     }
19773     Op = MI->getOperand(1);
19774     if (Op.isImm())
19775       AM.Scale = Op.getImm();
19776     Op = MI->getOperand(2);
19777     if (Op.isImm())
19778       AM.IndexReg = Op.getImm();
19779     Op = MI->getOperand(3);
19780     if (Op.isGlobal()) {
19781       AM.GV = Op.getGlobal();
19782     } else {
19783       AM.Disp = Op.getImm();
19784     }
19785     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
19786                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
19787
19788     // Reload the original control word now.
19789     addFrameReference(BuildMI(*BB, MI, DL,
19790                               TII->get(X86::FLDCW16m)), CWFrameIdx);
19791
19792     MI->eraseFromParent();   // The pseudo instruction is gone now.
19793     return BB;
19794   }
19795     // String/text processing lowering.
19796   case X86::PCMPISTRM128REG:
19797   case X86::VPCMPISTRM128REG:
19798   case X86::PCMPISTRM128MEM:
19799   case X86::VPCMPISTRM128MEM:
19800   case X86::PCMPESTRM128REG:
19801   case X86::VPCMPESTRM128REG:
19802   case X86::PCMPESTRM128MEM:
19803   case X86::VPCMPESTRM128MEM:
19804     assert(Subtarget->hasSSE42() &&
19805            "Target must have SSE4.2 or AVX features enabled");
19806     return EmitPCMPSTRM(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19807
19808   // String/text processing lowering.
19809   case X86::PCMPISTRIREG:
19810   case X86::VPCMPISTRIREG:
19811   case X86::PCMPISTRIMEM:
19812   case X86::VPCMPISTRIMEM:
19813   case X86::PCMPESTRIREG:
19814   case X86::VPCMPESTRIREG:
19815   case X86::PCMPESTRIMEM:
19816   case X86::VPCMPESTRIMEM:
19817     assert(Subtarget->hasSSE42() &&
19818            "Target must have SSE4.2 or AVX features enabled");
19819     return EmitPCMPSTRI(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19820
19821   // Thread synchronization.
19822   case X86::MONITOR:
19823     return EmitMonitor(MI, BB, BB->getParent()->getSubtarget().getInstrInfo(),
19824                        Subtarget);
19825
19826   // xbegin
19827   case X86::XBEGIN:
19828     return EmitXBegin(MI, BB, BB->getParent()->getSubtarget().getInstrInfo());
19829
19830   case X86::VASTART_SAVE_XMM_REGS:
19831     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
19832
19833   case X86::VAARG_64:
19834     return EmitVAARG64WithCustomInserter(MI, BB);
19835
19836   case X86::EH_SjLj_SetJmp32:
19837   case X86::EH_SjLj_SetJmp64:
19838     return emitEHSjLjSetJmp(MI, BB);
19839
19840   case X86::EH_SjLj_LongJmp32:
19841   case X86::EH_SjLj_LongJmp64:
19842     return emitEHSjLjLongJmp(MI, BB);
19843
19844   case TargetOpcode::STACKMAP:
19845   case TargetOpcode::PATCHPOINT:
19846     return emitPatchPoint(MI, BB);
19847
19848   case X86::VFMADDPDr213r:
19849   case X86::VFMADDPSr213r:
19850   case X86::VFMADDSDr213r:
19851   case X86::VFMADDSSr213r:
19852   case X86::VFMSUBPDr213r:
19853   case X86::VFMSUBPSr213r:
19854   case X86::VFMSUBSDr213r:
19855   case X86::VFMSUBSSr213r:
19856   case X86::VFNMADDPDr213r:
19857   case X86::VFNMADDPSr213r:
19858   case X86::VFNMADDSDr213r:
19859   case X86::VFNMADDSSr213r:
19860   case X86::VFNMSUBPDr213r:
19861   case X86::VFNMSUBPSr213r:
19862   case X86::VFNMSUBSDr213r:
19863   case X86::VFNMSUBSSr213r:
19864   case X86::VFMADDPDr213rY:
19865   case X86::VFMADDPSr213rY:
19866   case X86::VFMSUBPDr213rY:
19867   case X86::VFMSUBPSr213rY:
19868   case X86::VFNMADDPDr213rY:
19869   case X86::VFNMADDPSr213rY:
19870   case X86::VFNMSUBPDr213rY:
19871   case X86::VFNMSUBPSr213rY:
19872     return emitFMA3Instr(MI, BB);
19873   }
19874 }
19875
19876 //===----------------------------------------------------------------------===//
19877 //                           X86 Optimization Hooks
19878 //===----------------------------------------------------------------------===//
19879
19880 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
19881                                                       APInt &KnownZero,
19882                                                       APInt &KnownOne,
19883                                                       const SelectionDAG &DAG,
19884                                                       unsigned Depth) const {
19885   unsigned BitWidth = KnownZero.getBitWidth();
19886   unsigned Opc = Op.getOpcode();
19887   assert((Opc >= ISD::BUILTIN_OP_END ||
19888           Opc == ISD::INTRINSIC_WO_CHAIN ||
19889           Opc == ISD::INTRINSIC_W_CHAIN ||
19890           Opc == ISD::INTRINSIC_VOID) &&
19891          "Should use MaskedValueIsZero if you don't know whether Op"
19892          " is a target node!");
19893
19894   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
19895   switch (Opc) {
19896   default: break;
19897   case X86ISD::ADD:
19898   case X86ISD::SUB:
19899   case X86ISD::ADC:
19900   case X86ISD::SBB:
19901   case X86ISD::SMUL:
19902   case X86ISD::UMUL:
19903   case X86ISD::INC:
19904   case X86ISD::DEC:
19905   case X86ISD::OR:
19906   case X86ISD::XOR:
19907   case X86ISD::AND:
19908     // These nodes' second result is a boolean.
19909     if (Op.getResNo() == 0)
19910       break;
19911     // Fallthrough
19912   case X86ISD::SETCC:
19913     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
19914     break;
19915   case ISD::INTRINSIC_WO_CHAIN: {
19916     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
19917     unsigned NumLoBits = 0;
19918     switch (IntId) {
19919     default: break;
19920     case Intrinsic::x86_sse_movmsk_ps:
19921     case Intrinsic::x86_avx_movmsk_ps_256:
19922     case Intrinsic::x86_sse2_movmsk_pd:
19923     case Intrinsic::x86_avx_movmsk_pd_256:
19924     case Intrinsic::x86_mmx_pmovmskb:
19925     case Intrinsic::x86_sse2_pmovmskb_128:
19926     case Intrinsic::x86_avx2_pmovmskb: {
19927       // High bits of movmskp{s|d}, pmovmskb are known zero.
19928       switch (IntId) {
19929         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
19930         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
19931         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
19932         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
19933         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
19934         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
19935         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
19936         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
19937       }
19938       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
19939       break;
19940     }
19941     }
19942     break;
19943   }
19944   }
19945 }
19946
19947 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
19948   SDValue Op,
19949   const SelectionDAG &,
19950   unsigned Depth) const {
19951   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
19952   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
19953     return Op.getValueType().getScalarType().getSizeInBits();
19954
19955   // Fallback case.
19956   return 1;
19957 }
19958
19959 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
19960 /// node is a GlobalAddress + offset.
19961 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
19962                                        const GlobalValue* &GA,
19963                                        int64_t &Offset) const {
19964   if (N->getOpcode() == X86ISD::Wrapper) {
19965     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
19966       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
19967       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
19968       return true;
19969     }
19970   }
19971   return TargetLowering::isGAPlusOffset(N, GA, Offset);
19972 }
19973
19974 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
19975 /// same as extracting the high 128-bit part of 256-bit vector and then
19976 /// inserting the result into the low part of a new 256-bit vector
19977 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
19978   EVT VT = SVOp->getValueType(0);
19979   unsigned NumElems = VT.getVectorNumElements();
19980
19981   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
19982   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
19983     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
19984         SVOp->getMaskElt(j) >= 0)
19985       return false;
19986
19987   return true;
19988 }
19989
19990 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
19991 /// same as extracting the low 128-bit part of 256-bit vector and then
19992 /// inserting the result into the high part of a new 256-bit vector
19993 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
19994   EVT VT = SVOp->getValueType(0);
19995   unsigned NumElems = VT.getVectorNumElements();
19996
19997   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
19998   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
19999     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20000         SVOp->getMaskElt(j) >= 0)
20001       return false;
20002
20003   return true;
20004 }
20005
20006 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20007 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20008                                         TargetLowering::DAGCombinerInfo &DCI,
20009                                         const X86Subtarget* Subtarget) {
20010   SDLoc dl(N);
20011   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20012   SDValue V1 = SVOp->getOperand(0);
20013   SDValue V2 = SVOp->getOperand(1);
20014   EVT VT = SVOp->getValueType(0);
20015   unsigned NumElems = VT.getVectorNumElements();
20016
20017   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20018       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20019     //
20020     //                   0,0,0,...
20021     //                      |
20022     //    V      UNDEF    BUILD_VECTOR    UNDEF
20023     //     \      /           \           /
20024     //  CONCAT_VECTOR         CONCAT_VECTOR
20025     //         \                  /
20026     //          \                /
20027     //          RESULT: V + zero extended
20028     //
20029     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20030         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20031         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20032       return SDValue();
20033
20034     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20035       return SDValue();
20036
20037     // To match the shuffle mask, the first half of the mask should
20038     // be exactly the first vector, and all the rest a splat with the
20039     // first element of the second one.
20040     for (unsigned i = 0; i != NumElems/2; ++i)
20041       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20042           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20043         return SDValue();
20044
20045     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20046     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20047       if (Ld->hasNUsesOfValue(1, 0)) {
20048         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20049         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20050         SDValue ResNode =
20051           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20052                                   Ld->getMemoryVT(),
20053                                   Ld->getPointerInfo(),
20054                                   Ld->getAlignment(),
20055                                   false/*isVolatile*/, true/*ReadMem*/,
20056                                   false/*WriteMem*/);
20057
20058         // Make sure the newly-created LOAD is in the same position as Ld in
20059         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20060         // and update uses of Ld's output chain to use the TokenFactor.
20061         if (Ld->hasAnyUseOfValue(1)) {
20062           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20063                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20064           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20065           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20066                                  SDValue(ResNode.getNode(), 1));
20067         }
20068
20069         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
20070       }
20071     }
20072
20073     // Emit a zeroed vector and insert the desired subvector on its
20074     // first half.
20075     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20076     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20077     return DCI.CombineTo(N, InsV);
20078   }
20079
20080   //===--------------------------------------------------------------------===//
20081   // Combine some shuffles into subvector extracts and inserts:
20082   //
20083
20084   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20085   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20086     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20087     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20088     return DCI.CombineTo(N, InsV);
20089   }
20090
20091   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20092   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20093     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20094     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20095     return DCI.CombineTo(N, InsV);
20096   }
20097
20098   return SDValue();
20099 }
20100
20101 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20102 /// possible.
20103 ///
20104 /// This is the leaf of the recursive combinine below. When we have found some
20105 /// chain of single-use x86 shuffle instructions and accumulated the combined
20106 /// shuffle mask represented by them, this will try to pattern match that mask
20107 /// into either a single instruction if there is a special purpose instruction
20108 /// for this operation, or into a PSHUFB instruction which is a fully general
20109 /// instruction but should only be used to replace chains over a certain depth.
20110 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20111                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20112                                    TargetLowering::DAGCombinerInfo &DCI,
20113                                    const X86Subtarget *Subtarget) {
20114   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20115
20116   // Find the operand that enters the chain. Note that multiple uses are OK
20117   // here, we're not going to remove the operand we find.
20118   SDValue Input = Op.getOperand(0);
20119   while (Input.getOpcode() == ISD::BITCAST)
20120     Input = Input.getOperand(0);
20121
20122   MVT VT = Input.getSimpleValueType();
20123   MVT RootVT = Root.getSimpleValueType();
20124   SDLoc DL(Root);
20125
20126   // Just remove no-op shuffle masks.
20127   if (Mask.size() == 1) {
20128     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
20129                   /*AddTo*/ true);
20130     return true;
20131   }
20132
20133   // Use the float domain if the operand type is a floating point type.
20134   bool FloatDomain = VT.isFloatingPoint();
20135
20136   // For floating point shuffles, we don't have free copies in the shuffle
20137   // instructions or the ability to load as part of the instruction, so
20138   // canonicalize their shuffles to UNPCK or MOV variants.
20139   //
20140   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20141   // vectors because it can have a load folded into it that UNPCK cannot. This
20142   // doesn't preclude something switching to the shorter encoding post-RA.
20143   if (FloatDomain) {
20144     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
20145       bool Lo = Mask.equals(0, 0);
20146       unsigned Shuffle;
20147       MVT ShuffleVT;
20148       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20149       // is no slower than UNPCKLPD but has the option to fold the input operand
20150       // into even an unaligned memory load.
20151       if (Lo && Subtarget->hasSSE3()) {
20152         Shuffle = X86ISD::MOVDDUP;
20153         ShuffleVT = MVT::v2f64;
20154       } else {
20155         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20156         // than the UNPCK variants.
20157         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20158         ShuffleVT = MVT::v4f32;
20159       }
20160       if (Depth == 1 && Root->getOpcode() == Shuffle)
20161         return false; // Nothing to do!
20162       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20163       DCI.AddToWorklist(Op.getNode());
20164       if (Shuffle == X86ISD::MOVDDUP)
20165         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20166       else
20167         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20168       DCI.AddToWorklist(Op.getNode());
20169       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20170                     /*AddTo*/ true);
20171       return true;
20172     }
20173     if (Subtarget->hasSSE3() &&
20174         (Mask.equals(0, 0, 2, 2) || Mask.equals(1, 1, 3, 3))) {
20175       bool Lo = Mask.equals(0, 0, 2, 2);
20176       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20177       MVT ShuffleVT = MVT::v4f32;
20178       if (Depth == 1 && Root->getOpcode() == Shuffle)
20179         return false; // Nothing to do!
20180       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20181       DCI.AddToWorklist(Op.getNode());
20182       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20183       DCI.AddToWorklist(Op.getNode());
20184       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20185                     /*AddTo*/ true);
20186       return true;
20187     }
20188     if (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3)) {
20189       bool Lo = Mask.equals(0, 0, 1, 1);
20190       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20191       MVT ShuffleVT = MVT::v4f32;
20192       if (Depth == 1 && Root->getOpcode() == Shuffle)
20193         return false; // Nothing to do!
20194       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20195       DCI.AddToWorklist(Op.getNode());
20196       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20197       DCI.AddToWorklist(Op.getNode());
20198       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20199                     /*AddTo*/ true);
20200       return true;
20201     }
20202   }
20203
20204   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20205   // variants as none of these have single-instruction variants that are
20206   // superior to the UNPCK formulation.
20207   if (!FloatDomain &&
20208       (Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
20209        Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
20210        Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
20211        Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
20212                    15))) {
20213     bool Lo = Mask[0] == 0;
20214     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20215     if (Depth == 1 && Root->getOpcode() == Shuffle)
20216       return false; // Nothing to do!
20217     MVT ShuffleVT;
20218     switch (Mask.size()) {
20219     case 8:
20220       ShuffleVT = MVT::v8i16;
20221       break;
20222     case 16:
20223       ShuffleVT = MVT::v16i8;
20224       break;
20225     default:
20226       llvm_unreachable("Impossible mask size!");
20227     };
20228     Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
20229     DCI.AddToWorklist(Op.getNode());
20230     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20231     DCI.AddToWorklist(Op.getNode());
20232     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20233                   /*AddTo*/ true);
20234     return true;
20235   }
20236
20237   // Don't try to re-form single instruction chains under any circumstances now
20238   // that we've done encoding canonicalization for them.
20239   if (Depth < 2)
20240     return false;
20241
20242   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20243   // can replace them with a single PSHUFB instruction profitably. Intel's
20244   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20245   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20246   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20247     SmallVector<SDValue, 16> PSHUFBMask;
20248     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
20249     int Ratio = 16 / Mask.size();
20250     for (unsigned i = 0; i < 16; ++i) {
20251       if (Mask[i / Ratio] == SM_SentinelUndef) {
20252         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20253         continue;
20254       }
20255       int M = Mask[i / Ratio] != SM_SentinelZero
20256                   ? Ratio * Mask[i / Ratio] + i % Ratio
20257                   : 255;
20258       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
20259     }
20260     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
20261     DCI.AddToWorklist(Op.getNode());
20262     SDValue PSHUFBMaskOp =
20263         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
20264     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20265     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
20266     DCI.AddToWorklist(Op.getNode());
20267     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
20268                   /*AddTo*/ true);
20269     return true;
20270   }
20271
20272   // Failed to find any combines.
20273   return false;
20274 }
20275
20276 /// \brief Fully generic combining of x86 shuffle instructions.
20277 ///
20278 /// This should be the last combine run over the x86 shuffle instructions. Once
20279 /// they have been fully optimized, this will recursively consider all chains
20280 /// of single-use shuffle instructions, build a generic model of the cumulative
20281 /// shuffle operation, and check for simpler instructions which implement this
20282 /// operation. We use this primarily for two purposes:
20283 ///
20284 /// 1) Collapse generic shuffles to specialized single instructions when
20285 ///    equivalent. In most cases, this is just an encoding size win, but
20286 ///    sometimes we will collapse multiple generic shuffles into a single
20287 ///    special-purpose shuffle.
20288 /// 2) Look for sequences of shuffle instructions with 3 or more total
20289 ///    instructions, and replace them with the slightly more expensive SSSE3
20290 ///    PSHUFB instruction if available. We do this as the last combining step
20291 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20292 ///    a suitable short sequence of other instructions. The PHUFB will either
20293 ///    use a register or have to read from memory and so is slightly (but only
20294 ///    slightly) more expensive than the other shuffle instructions.
20295 ///
20296 /// Because this is inherently a quadratic operation (for each shuffle in
20297 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20298 /// This should never be an issue in practice as the shuffle lowering doesn't
20299 /// produce sequences of more than 8 instructions.
20300 ///
20301 /// FIXME: We will currently miss some cases where the redundant shuffling
20302 /// would simplify under the threshold for PSHUFB formation because of
20303 /// combine-ordering. To fix this, we should do the redundant instruction
20304 /// combining in this recursive walk.
20305 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20306                                           ArrayRef<int> RootMask,
20307                                           int Depth, bool HasPSHUFB,
20308                                           SelectionDAG &DAG,
20309                                           TargetLowering::DAGCombinerInfo &DCI,
20310                                           const X86Subtarget *Subtarget) {
20311   // Bound the depth of our recursive combine because this is ultimately
20312   // quadratic in nature.
20313   if (Depth > 8)
20314     return false;
20315
20316   // Directly rip through bitcasts to find the underlying operand.
20317   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20318     Op = Op.getOperand(0);
20319
20320   MVT VT = Op.getSimpleValueType();
20321   if (!VT.isVector())
20322     return false; // Bail if we hit a non-vector.
20323   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
20324   // version should be added.
20325   if (VT.getSizeInBits() != 128)
20326     return false;
20327
20328   assert(Root.getSimpleValueType().isVector() &&
20329          "Shuffles operate on vector types!");
20330   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20331          "Can only combine shuffles of the same vector register size.");
20332
20333   if (!isTargetShuffle(Op.getOpcode()))
20334     return false;
20335   SmallVector<int, 16> OpMask;
20336   bool IsUnary;
20337   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20338   // We only can combine unary shuffles which we can decode the mask for.
20339   if (!HaveMask || !IsUnary)
20340     return false;
20341
20342   assert(VT.getVectorNumElements() == OpMask.size() &&
20343          "Different mask size from vector size!");
20344   assert(((RootMask.size() > OpMask.size() &&
20345            RootMask.size() % OpMask.size() == 0) ||
20346           (OpMask.size() > RootMask.size() &&
20347            OpMask.size() % RootMask.size() == 0) ||
20348           OpMask.size() == RootMask.size()) &&
20349          "The smaller number of elements must divide the larger.");
20350   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20351   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20352   assert(((RootRatio == 1 && OpRatio == 1) ||
20353           (RootRatio == 1) != (OpRatio == 1)) &&
20354          "Must not have a ratio for both incoming and op masks!");
20355
20356   SmallVector<int, 16> Mask;
20357   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20358
20359   // Merge this shuffle operation's mask into our accumulated mask. Note that
20360   // this shuffle's mask will be the first applied to the input, followed by the
20361   // root mask to get us all the way to the root value arrangement. The reason
20362   // for this order is that we are recursing up the operation chain.
20363   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20364     int RootIdx = i / RootRatio;
20365     if (RootMask[RootIdx] < 0) {
20366       // This is a zero or undef lane, we're done.
20367       Mask.push_back(RootMask[RootIdx]);
20368       continue;
20369     }
20370
20371     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20372     int OpIdx = RootMaskedIdx / OpRatio;
20373     if (OpMask[OpIdx] < 0) {
20374       // The incoming lanes are zero or undef, it doesn't matter which ones we
20375       // are using.
20376       Mask.push_back(OpMask[OpIdx]);
20377       continue;
20378     }
20379
20380     // Ok, we have non-zero lanes, map them through.
20381     Mask.push_back(OpMask[OpIdx] * OpRatio +
20382                    RootMaskedIdx % OpRatio);
20383   }
20384
20385   // See if we can recurse into the operand to combine more things.
20386   switch (Op.getOpcode()) {
20387     case X86ISD::PSHUFB:
20388       HasPSHUFB = true;
20389     case X86ISD::PSHUFD:
20390     case X86ISD::PSHUFHW:
20391     case X86ISD::PSHUFLW:
20392       if (Op.getOperand(0).hasOneUse() &&
20393           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20394                                         HasPSHUFB, DAG, DCI, Subtarget))
20395         return true;
20396       break;
20397
20398     case X86ISD::UNPCKL:
20399     case X86ISD::UNPCKH:
20400       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20401       // We can't check for single use, we have to check that this shuffle is the only user.
20402       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20403           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20404                                         HasPSHUFB, DAG, DCI, Subtarget))
20405           return true;
20406       break;
20407   }
20408
20409   // Minor canonicalization of the accumulated shuffle mask to make it easier
20410   // to match below. All this does is detect masks with squential pairs of
20411   // elements, and shrink them to the half-width mask. It does this in a loop
20412   // so it will reduce the size of the mask to the minimal width mask which
20413   // performs an equivalent shuffle.
20414   while (Mask.size() > 1 && canWidenShuffleElements(Mask)) {
20415     for (int i = 0, e = Mask.size() / 2; i < e; ++i)
20416       Mask[i] = Mask[2 * i] / 2;
20417     Mask.resize(Mask.size() / 2);
20418   }
20419
20420   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20421                                 Subtarget);
20422 }
20423
20424 /// \brief Get the PSHUF-style mask from PSHUF node.
20425 ///
20426 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20427 /// PSHUF-style masks that can be reused with such instructions.
20428 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20429   SmallVector<int, 4> Mask;
20430   bool IsUnary;
20431   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
20432   (void)HaveMask;
20433   assert(HaveMask);
20434
20435   switch (N.getOpcode()) {
20436   case X86ISD::PSHUFD:
20437     return Mask;
20438   case X86ISD::PSHUFLW:
20439     Mask.resize(4);
20440     return Mask;
20441   case X86ISD::PSHUFHW:
20442     Mask.erase(Mask.begin(), Mask.begin() + 4);
20443     for (int &M : Mask)
20444       M -= 4;
20445     return Mask;
20446   default:
20447     llvm_unreachable("No valid shuffle instruction found!");
20448   }
20449 }
20450
20451 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20452 ///
20453 /// We walk up the chain and look for a combinable shuffle, skipping over
20454 /// shuffles that we could hoist this shuffle's transformation past without
20455 /// altering anything.
20456 static SDValue
20457 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20458                              SelectionDAG &DAG,
20459                              TargetLowering::DAGCombinerInfo &DCI) {
20460   assert(N.getOpcode() == X86ISD::PSHUFD &&
20461          "Called with something other than an x86 128-bit half shuffle!");
20462   SDLoc DL(N);
20463
20464   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20465   // of the shuffles in the chain so that we can form a fresh chain to replace
20466   // this one.
20467   SmallVector<SDValue, 8> Chain;
20468   SDValue V = N.getOperand(0);
20469   for (; V.hasOneUse(); V = V.getOperand(0)) {
20470     switch (V.getOpcode()) {
20471     default:
20472       return SDValue(); // Nothing combined!
20473
20474     case ISD::BITCAST:
20475       // Skip bitcasts as we always know the type for the target specific
20476       // instructions.
20477       continue;
20478
20479     case X86ISD::PSHUFD:
20480       // Found another dword shuffle.
20481       break;
20482
20483     case X86ISD::PSHUFLW:
20484       // Check that the low words (being shuffled) are the identity in the
20485       // dword shuffle, and the high words are self-contained.
20486       if (Mask[0] != 0 || Mask[1] != 1 ||
20487           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20488         return SDValue();
20489
20490       Chain.push_back(V);
20491       continue;
20492
20493     case X86ISD::PSHUFHW:
20494       // Check that the high words (being shuffled) are the identity in the
20495       // dword shuffle, and the low words are self-contained.
20496       if (Mask[2] != 2 || Mask[3] != 3 ||
20497           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20498         return SDValue();
20499
20500       Chain.push_back(V);
20501       continue;
20502
20503     case X86ISD::UNPCKL:
20504     case X86ISD::UNPCKH:
20505       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20506       // shuffle into a preceding word shuffle.
20507       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
20508         return SDValue();
20509
20510       // Search for a half-shuffle which we can combine with.
20511       unsigned CombineOp =
20512           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20513       if (V.getOperand(0) != V.getOperand(1) ||
20514           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20515         return SDValue();
20516       Chain.push_back(V);
20517       V = V.getOperand(0);
20518       do {
20519         switch (V.getOpcode()) {
20520         default:
20521           return SDValue(); // Nothing to combine.
20522
20523         case X86ISD::PSHUFLW:
20524         case X86ISD::PSHUFHW:
20525           if (V.getOpcode() == CombineOp)
20526             break;
20527
20528           Chain.push_back(V);
20529
20530           // Fallthrough!
20531         case ISD::BITCAST:
20532           V = V.getOperand(0);
20533           continue;
20534         }
20535         break;
20536       } while (V.hasOneUse());
20537       break;
20538     }
20539     // Break out of the loop if we break out of the switch.
20540     break;
20541   }
20542
20543   if (!V.hasOneUse())
20544     // We fell out of the loop without finding a viable combining instruction.
20545     return SDValue();
20546
20547   // Merge this node's mask and our incoming mask.
20548   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20549   for (int &M : Mask)
20550     M = VMask[M];
20551   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20552                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20553
20554   // Rebuild the chain around this new shuffle.
20555   while (!Chain.empty()) {
20556     SDValue W = Chain.pop_back_val();
20557
20558     if (V.getValueType() != W.getOperand(0).getValueType())
20559       V = DAG.getNode(ISD::BITCAST, DL, W.getOperand(0).getValueType(), V);
20560
20561     switch (W.getOpcode()) {
20562     default:
20563       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
20564
20565     case X86ISD::UNPCKL:
20566     case X86ISD::UNPCKH:
20567       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
20568       break;
20569
20570     case X86ISD::PSHUFD:
20571     case X86ISD::PSHUFLW:
20572     case X86ISD::PSHUFHW:
20573       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
20574       break;
20575     }
20576   }
20577   if (V.getValueType() != N.getValueType())
20578     V = DAG.getNode(ISD::BITCAST, DL, N.getValueType(), V);
20579
20580   // Return the new chain to replace N.
20581   return V;
20582 }
20583
20584 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
20585 ///
20586 /// We walk up the chain, skipping shuffles of the other half and looking
20587 /// through shuffles which switch halves trying to find a shuffle of the same
20588 /// pair of dwords.
20589 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
20590                                         SelectionDAG &DAG,
20591                                         TargetLowering::DAGCombinerInfo &DCI) {
20592   assert(
20593       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
20594       "Called with something other than an x86 128-bit half shuffle!");
20595   SDLoc DL(N);
20596   unsigned CombineOpcode = N.getOpcode();
20597
20598   // Walk up a single-use chain looking for a combinable shuffle.
20599   SDValue V = N.getOperand(0);
20600   for (; V.hasOneUse(); V = V.getOperand(0)) {
20601     switch (V.getOpcode()) {
20602     default:
20603       return false; // Nothing combined!
20604
20605     case ISD::BITCAST:
20606       // Skip bitcasts as we always know the type for the target specific
20607       // instructions.
20608       continue;
20609
20610     case X86ISD::PSHUFLW:
20611     case X86ISD::PSHUFHW:
20612       if (V.getOpcode() == CombineOpcode)
20613         break;
20614
20615       // Other-half shuffles are no-ops.
20616       continue;
20617     }
20618     // Break out of the loop if we break out of the switch.
20619     break;
20620   }
20621
20622   if (!V.hasOneUse())
20623     // We fell out of the loop without finding a viable combining instruction.
20624     return false;
20625
20626   // Combine away the bottom node as its shuffle will be accumulated into
20627   // a preceding shuffle.
20628   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20629
20630   // Record the old value.
20631   SDValue Old = V;
20632
20633   // Merge this node's mask and our incoming mask (adjusted to account for all
20634   // the pshufd instructions encountered).
20635   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20636   for (int &M : Mask)
20637     M = VMask[M];
20638   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
20639                   getV4X86ShuffleImm8ForMask(Mask, DAG));
20640
20641   // Check that the shuffles didn't cancel each other out. If not, we need to
20642   // combine to the new one.
20643   if (Old != V)
20644     // Replace the combinable shuffle with the combined one, updating all users
20645     // so that we re-evaluate the chain here.
20646     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
20647
20648   return true;
20649 }
20650
20651 /// \brief Try to combine x86 target specific shuffles.
20652 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
20653                                            TargetLowering::DAGCombinerInfo &DCI,
20654                                            const X86Subtarget *Subtarget) {
20655   SDLoc DL(N);
20656   MVT VT = N.getSimpleValueType();
20657   SmallVector<int, 4> Mask;
20658
20659   switch (N.getOpcode()) {
20660   case X86ISD::PSHUFD:
20661   case X86ISD::PSHUFLW:
20662   case X86ISD::PSHUFHW:
20663     Mask = getPSHUFShuffleMask(N);
20664     assert(Mask.size() == 4);
20665     break;
20666   default:
20667     return SDValue();
20668   }
20669
20670   // Nuke no-op shuffles that show up after combining.
20671   if (isNoopShuffleMask(Mask))
20672     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
20673
20674   // Look for simplifications involving one or two shuffle instructions.
20675   SDValue V = N.getOperand(0);
20676   switch (N.getOpcode()) {
20677   default:
20678     break;
20679   case X86ISD::PSHUFLW:
20680   case X86ISD::PSHUFHW:
20681     assert(VT == MVT::v8i16);
20682     (void)VT;
20683
20684     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
20685       return SDValue(); // We combined away this shuffle, so we're done.
20686
20687     // See if this reduces to a PSHUFD which is no more expensive and can
20688     // combine with more operations.
20689     if (canWidenShuffleElements(Mask)) {
20690       int DMask[] = {-1, -1, -1, -1};
20691       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
20692       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
20693       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
20694       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
20695       DCI.AddToWorklist(V.getNode());
20696       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
20697                       getV4X86ShuffleImm8ForMask(DMask, DAG));
20698       DCI.AddToWorklist(V.getNode());
20699       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
20700     }
20701
20702     // Look for shuffle patterns which can be implemented as a single unpack.
20703     // FIXME: This doesn't handle the location of the PSHUFD generically, and
20704     // only works when we have a PSHUFD followed by two half-shuffles.
20705     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
20706         (V.getOpcode() == X86ISD::PSHUFLW ||
20707          V.getOpcode() == X86ISD::PSHUFHW) &&
20708         V.getOpcode() != N.getOpcode() &&
20709         V.hasOneUse()) {
20710       SDValue D = V.getOperand(0);
20711       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
20712         D = D.getOperand(0);
20713       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
20714         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20715         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
20716         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20717         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
20718         int WordMask[8];
20719         for (int i = 0; i < 4; ++i) {
20720           WordMask[i + NOffset] = Mask[i] + NOffset;
20721           WordMask[i + VOffset] = VMask[i] + VOffset;
20722         }
20723         // Map the word mask through the DWord mask.
20724         int MappedMask[8];
20725         for (int i = 0; i < 8; ++i)
20726           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
20727         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
20728         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
20729         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
20730                        std::begin(UnpackLoMask)) ||
20731             std::equal(std::begin(MappedMask), std::end(MappedMask),
20732                        std::begin(UnpackHiMask))) {
20733           // We can replace all three shuffles with an unpack.
20734           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
20735           DCI.AddToWorklist(V.getNode());
20736           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
20737                                                 : X86ISD::UNPCKH,
20738                              DL, MVT::v8i16, V, V);
20739         }
20740       }
20741     }
20742
20743     break;
20744
20745   case X86ISD::PSHUFD:
20746     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
20747       return NewN;
20748
20749     break;
20750   }
20751
20752   return SDValue();
20753 }
20754
20755 /// \brief Try to combine a shuffle into a target-specific add-sub node.
20756 ///
20757 /// We combine this directly on the abstract vector shuffle nodes so it is
20758 /// easier to generically match. We also insert dummy vector shuffle nodes for
20759 /// the operands which explicitly discard the lanes which are unused by this
20760 /// operation to try to flow through the rest of the combiner the fact that
20761 /// they're unused.
20762 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
20763   SDLoc DL(N);
20764   EVT VT = N->getValueType(0);
20765
20766   // We only handle target-independent shuffles.
20767   // FIXME: It would be easy and harmless to use the target shuffle mask
20768   // extraction tool to support more.
20769   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
20770     return SDValue();
20771
20772   auto *SVN = cast<ShuffleVectorSDNode>(N);
20773   ArrayRef<int> Mask = SVN->getMask();
20774   SDValue V1 = N->getOperand(0);
20775   SDValue V2 = N->getOperand(1);
20776
20777   // We require the first shuffle operand to be the SUB node, and the second to
20778   // be the ADD node.
20779   // FIXME: We should support the commuted patterns.
20780   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
20781     return SDValue();
20782
20783   // If there are other uses of these operations we can't fold them.
20784   if (!V1->hasOneUse() || !V2->hasOneUse())
20785     return SDValue();
20786
20787   // Ensure that both operations have the same operands. Note that we can
20788   // commute the FADD operands.
20789   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
20790   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
20791       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
20792     return SDValue();
20793
20794   // We're looking for blends between FADD and FSUB nodes. We insist on these
20795   // nodes being lined up in a specific expected pattern.
20796   if (!(isShuffleEquivalent(Mask, 0, 3) ||
20797         isShuffleEquivalent(Mask, 0, 5, 2, 7) ||
20798         isShuffleEquivalent(Mask, 0, 9, 2, 11, 4, 13, 6, 15)))
20799     return SDValue();
20800
20801   // Only specific types are legal at this point, assert so we notice if and
20802   // when these change.
20803   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
20804           VT == MVT::v4f64) &&
20805          "Unknown vector type encountered!");
20806
20807   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
20808 }
20809
20810 /// PerformShuffleCombine - Performs several different shuffle combines.
20811 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
20812                                      TargetLowering::DAGCombinerInfo &DCI,
20813                                      const X86Subtarget *Subtarget) {
20814   SDLoc dl(N);
20815   SDValue N0 = N->getOperand(0);
20816   SDValue N1 = N->getOperand(1);
20817   EVT VT = N->getValueType(0);
20818
20819   // Don't create instructions with illegal types after legalize types has run.
20820   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20821   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
20822     return SDValue();
20823
20824   // If we have legalized the vector types, look for blends of FADD and FSUB
20825   // nodes that we can fuse into an ADDSUB node.
20826   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
20827     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
20828       return AddSub;
20829
20830   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
20831   if (Subtarget->hasFp256() && VT.is256BitVector() &&
20832       N->getOpcode() == ISD::VECTOR_SHUFFLE)
20833     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
20834
20835   // During Type Legalization, when promoting illegal vector types,
20836   // the backend might introduce new shuffle dag nodes and bitcasts.
20837   //
20838   // This code performs the following transformation:
20839   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
20840   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
20841   //
20842   // We do this only if both the bitcast and the BINOP dag nodes have
20843   // one use. Also, perform this transformation only if the new binary
20844   // operation is legal. This is to avoid introducing dag nodes that
20845   // potentially need to be further expanded (or custom lowered) into a
20846   // less optimal sequence of dag nodes.
20847   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
20848       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
20849       N0.getOpcode() == ISD::BITCAST) {
20850     SDValue BC0 = N0.getOperand(0);
20851     EVT SVT = BC0.getValueType();
20852     unsigned Opcode = BC0.getOpcode();
20853     unsigned NumElts = VT.getVectorNumElements();
20854     
20855     if (BC0.hasOneUse() && SVT.isVector() &&
20856         SVT.getVectorNumElements() * 2 == NumElts &&
20857         TLI.isOperationLegal(Opcode, VT)) {
20858       bool CanFold = false;
20859       switch (Opcode) {
20860       default : break;
20861       case ISD::ADD :
20862       case ISD::FADD :
20863       case ISD::SUB :
20864       case ISD::FSUB :
20865       case ISD::MUL :
20866       case ISD::FMUL :
20867         CanFold = true;
20868       }
20869
20870       unsigned SVTNumElts = SVT.getVectorNumElements();
20871       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20872       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
20873         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
20874       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
20875         CanFold = SVOp->getMaskElt(i) < 0;
20876
20877       if (CanFold) {
20878         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
20879         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
20880         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
20881         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
20882       }
20883     }
20884   }
20885
20886   // Only handle 128 wide vector from here on.
20887   if (!VT.is128BitVector())
20888     return SDValue();
20889
20890   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
20891   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
20892   // consecutive, non-overlapping, and in the right order.
20893   SmallVector<SDValue, 16> Elts;
20894   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
20895     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
20896
20897   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
20898   if (LD.getNode())
20899     return LD;
20900
20901   if (isTargetShuffle(N->getOpcode())) {
20902     SDValue Shuffle =
20903         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
20904     if (Shuffle.getNode())
20905       return Shuffle;
20906
20907     // Try recursively combining arbitrary sequences of x86 shuffle
20908     // instructions into higher-order shuffles. We do this after combining
20909     // specific PSHUF instruction sequences into their minimal form so that we
20910     // can evaluate how many specialized shuffle instructions are involved in
20911     // a particular chain.
20912     SmallVector<int, 1> NonceMask; // Just a placeholder.
20913     NonceMask.push_back(0);
20914     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
20915                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
20916                                       DCI, Subtarget))
20917       return SDValue(); // This routine will use CombineTo to replace N.
20918   }
20919
20920   return SDValue();
20921 }
20922
20923 /// PerformTruncateCombine - Converts truncate operation to
20924 /// a sequence of vector shuffle operations.
20925 /// It is possible when we truncate 256-bit vector to 128-bit vector
20926 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
20927                                       TargetLowering::DAGCombinerInfo &DCI,
20928                                       const X86Subtarget *Subtarget)  {
20929   return SDValue();
20930 }
20931
20932 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
20933 /// specific shuffle of a load can be folded into a single element load.
20934 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
20935 /// shuffles have been customed lowered so we need to handle those here.
20936 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
20937                                          TargetLowering::DAGCombinerInfo &DCI) {
20938   if (DCI.isBeforeLegalizeOps())
20939     return SDValue();
20940
20941   SDValue InVec = N->getOperand(0);
20942   SDValue EltNo = N->getOperand(1);
20943
20944   if (!isa<ConstantSDNode>(EltNo))
20945     return SDValue();
20946
20947   EVT VT = InVec.getValueType();
20948
20949   if (InVec.getOpcode() == ISD::BITCAST) {
20950     // Don't duplicate a load with other uses.
20951     if (!InVec.hasOneUse())
20952       return SDValue();
20953     EVT BCVT = InVec.getOperand(0).getValueType();
20954     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
20955       return SDValue();
20956     InVec = InVec.getOperand(0);
20957   }
20958
20959   if (!isTargetShuffle(InVec.getOpcode()))
20960     return SDValue();
20961
20962   // Don't duplicate a load with other uses.
20963   if (!InVec.hasOneUse())
20964     return SDValue();
20965
20966   SmallVector<int, 16> ShuffleMask;
20967   bool UnaryShuffle;
20968   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
20969                             UnaryShuffle))
20970     return SDValue();
20971
20972   // Select the input vector, guarding against out of range extract vector.
20973   unsigned NumElems = VT.getVectorNumElements();
20974   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
20975   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
20976   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
20977                                          : InVec.getOperand(1);
20978
20979   // If inputs to shuffle are the same for both ops, then allow 2 uses
20980   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
20981
20982   if (LdNode.getOpcode() == ISD::BITCAST) {
20983     // Don't duplicate a load with other uses.
20984     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
20985       return SDValue();
20986
20987     AllowedUses = 1; // only allow 1 load use if we have a bitcast
20988     LdNode = LdNode.getOperand(0);
20989   }
20990
20991   if (!ISD::isNormalLoad(LdNode.getNode()))
20992     return SDValue();
20993
20994   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
20995
20996   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
20997     return SDValue();
20998
20999   EVT EltVT = N->getValueType(0);
21000   // If there's a bitcast before the shuffle, check if the load type and
21001   // alignment is valid.
21002   unsigned Align = LN0->getAlignment();
21003   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21004   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
21005       EltVT.getTypeForEVT(*DAG.getContext()));
21006
21007   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21008     return SDValue();
21009
21010   // All checks match so transform back to vector_shuffle so that DAG combiner
21011   // can finish the job
21012   SDLoc dl(N);
21013
21014   // Create shuffle node taking into account the case that its a unary shuffle
21015   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
21016   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
21017                                  InVec.getOperand(0), Shuffle,
21018                                  &ShuffleMask[0]);
21019   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
21020   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21021                      EltNo);
21022 }
21023
21024 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21025 /// generation and convert it from being a bunch of shuffles and extracts
21026 /// to a simple store and scalar loads to extract the elements.
21027 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21028                                          TargetLowering::DAGCombinerInfo &DCI) {
21029   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
21030   if (NewOp.getNode())
21031     return NewOp;
21032
21033   SDValue InputVector = N->getOperand(0);
21034
21035   // Detect whether we are trying to convert from mmx to i32 and the bitcast
21036   // from mmx to v2i32 has a single usage.
21037   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
21038       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
21039       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
21040     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21041                        N->getValueType(0),
21042                        InputVector.getNode()->getOperand(0));
21043
21044   // Only operate on vectors of 4 elements, where the alternative shuffling
21045   // gets to be more expensive.
21046   if (InputVector.getValueType() != MVT::v4i32)
21047     return SDValue();
21048
21049   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21050   // single use which is a sign-extend or zero-extend, and all elements are
21051   // used.
21052   SmallVector<SDNode *, 4> Uses;
21053   unsigned ExtractedElements = 0;
21054   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21055        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21056     if (UI.getUse().getResNo() != InputVector.getResNo())
21057       return SDValue();
21058
21059     SDNode *Extract = *UI;
21060     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21061       return SDValue();
21062
21063     if (Extract->getValueType(0) != MVT::i32)
21064       return SDValue();
21065     if (!Extract->hasOneUse())
21066       return SDValue();
21067     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21068         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21069       return SDValue();
21070     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21071       return SDValue();
21072
21073     // Record which element was extracted.
21074     ExtractedElements |=
21075       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21076
21077     Uses.push_back(Extract);
21078   }
21079
21080   // If not all the elements were used, this may not be worthwhile.
21081   if (ExtractedElements != 15)
21082     return SDValue();
21083
21084   // Ok, we've now decided to do the transformation.
21085   SDLoc dl(InputVector);
21086
21087   // Store the value to a temporary stack slot.
21088   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21089   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21090                             MachinePointerInfo(), false, false, 0);
21091
21092   // Replace each use (extract) with a load of the appropriate element.
21093   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21094        UE = Uses.end(); UI != UE; ++UI) {
21095     SDNode *Extract = *UI;
21096
21097     // cOMpute the element's address.
21098     SDValue Idx = Extract->getOperand(1);
21099     unsigned EltSize =
21100         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
21101     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
21102     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21103     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
21104
21105     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21106                                      StackPtr, OffsetVal);
21107
21108     // Load the scalar.
21109     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
21110                                      ScalarAddr, MachinePointerInfo(),
21111                                      false, false, false, 0);
21112
21113     // Replace the exact with the load.
21114     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
21115   }
21116
21117   // The replacement was made in place; don't return anything.
21118   return SDValue();
21119 }
21120
21121 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21122 static std::pair<unsigned, bool>
21123 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21124                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21125   if (!VT.isVector())
21126     return std::make_pair(0, false);
21127
21128   bool NeedSplit = false;
21129   switch (VT.getSimpleVT().SimpleTy) {
21130   default: return std::make_pair(0, false);
21131   case MVT::v32i8:
21132   case MVT::v16i16:
21133   case MVT::v8i32:
21134     if (!Subtarget->hasAVX2())
21135       NeedSplit = true;
21136     if (!Subtarget->hasAVX())
21137       return std::make_pair(0, false);
21138     break;
21139   case MVT::v16i8:
21140   case MVT::v8i16:
21141   case MVT::v4i32:
21142     if (!Subtarget->hasSSE2())
21143       return std::make_pair(0, false);
21144   }
21145
21146   // SSE2 has only a small subset of the operations.
21147   bool hasUnsigned = Subtarget->hasSSE41() ||
21148                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21149   bool hasSigned = Subtarget->hasSSE41() ||
21150                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21151
21152   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21153
21154   unsigned Opc = 0;
21155   // Check for x CC y ? x : y.
21156   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21157       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21158     switch (CC) {
21159     default: break;
21160     case ISD::SETULT:
21161     case ISD::SETULE:
21162       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
21163     case ISD::SETUGT:
21164     case ISD::SETUGE:
21165       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
21166     case ISD::SETLT:
21167     case ISD::SETLE:
21168       Opc = hasSigned ? X86ISD::SMIN : 0; break;
21169     case ISD::SETGT:
21170     case ISD::SETGE:
21171       Opc = hasSigned ? X86ISD::SMAX : 0; break;
21172     }
21173   // Check for x CC y ? y : x -- a min/max with reversed arms.
21174   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21175              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21176     switch (CC) {
21177     default: break;
21178     case ISD::SETULT:
21179     case ISD::SETULE:
21180       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
21181     case ISD::SETUGT:
21182     case ISD::SETUGE:
21183       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
21184     case ISD::SETLT:
21185     case ISD::SETLE:
21186       Opc = hasSigned ? X86ISD::SMAX : 0; break;
21187     case ISD::SETGT:
21188     case ISD::SETGE:
21189       Opc = hasSigned ? X86ISD::SMIN : 0; break;
21190     }
21191   }
21192
21193   return std::make_pair(Opc, NeedSplit);
21194 }
21195
21196 static SDValue
21197 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21198                                       const X86Subtarget *Subtarget) {
21199   SDLoc dl(N);
21200   SDValue Cond = N->getOperand(0);
21201   SDValue LHS = N->getOperand(1);
21202   SDValue RHS = N->getOperand(2);
21203
21204   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21205     SDValue CondSrc = Cond->getOperand(0);
21206     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21207       Cond = CondSrc->getOperand(0);
21208   }
21209
21210   MVT VT = N->getSimpleValueType(0);
21211   MVT EltVT = VT.getVectorElementType();
21212   unsigned NumElems = VT.getVectorNumElements();
21213   // There is no blend with immediate in AVX-512.
21214   if (VT.is512BitVector())
21215     return SDValue();
21216
21217   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
21218     return SDValue();
21219   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
21220     return SDValue();
21221
21222   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21223     return SDValue();
21224
21225   // A vselect where all conditions and data are constants can be optimized into
21226   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21227   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21228       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21229     return SDValue();
21230
21231   unsigned MaskValue = 0;
21232   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21233     return SDValue();
21234
21235   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21236   for (unsigned i = 0; i < NumElems; ++i) {
21237     // Be sure we emit undef where we can.
21238     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21239       ShuffleMask[i] = -1;
21240     else
21241       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21242   }
21243
21244   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21245 }
21246
21247 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21248 /// nodes.
21249 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21250                                     TargetLowering::DAGCombinerInfo &DCI,
21251                                     const X86Subtarget *Subtarget) {
21252   SDLoc DL(N);
21253   SDValue Cond = N->getOperand(0);
21254   // Get the LHS/RHS of the select.
21255   SDValue LHS = N->getOperand(1);
21256   SDValue RHS = N->getOperand(2);
21257   EVT VT = LHS.getValueType();
21258   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21259
21260   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21261   // instructions match the semantics of the common C idiom x<y?x:y but not
21262   // x<=y?x:y, because of how they handle negative zero (which can be
21263   // ignored in unsafe-math mode).
21264   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21265       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
21266       (Subtarget->hasSSE2() ||
21267        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21268     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21269
21270     unsigned Opcode = 0;
21271     // Check for x CC y ? x : y.
21272     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21273         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21274       switch (CC) {
21275       default: break;
21276       case ISD::SETULT:
21277         // Converting this to a min would handle NaNs incorrectly, and swapping
21278         // the operands would cause it to handle comparisons between positive
21279         // and negative zero incorrectly.
21280         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21281           if (!DAG.getTarget().Options.UnsafeFPMath &&
21282               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21283             break;
21284           std::swap(LHS, RHS);
21285         }
21286         Opcode = X86ISD::FMIN;
21287         break;
21288       case ISD::SETOLE:
21289         // Converting this to a min would handle comparisons between positive
21290         // and negative zero incorrectly.
21291         if (!DAG.getTarget().Options.UnsafeFPMath &&
21292             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21293           break;
21294         Opcode = X86ISD::FMIN;
21295         break;
21296       case ISD::SETULE:
21297         // Converting this to a min would handle both negative zeros and NaNs
21298         // incorrectly, but we can swap the operands to fix both.
21299         std::swap(LHS, RHS);
21300       case ISD::SETOLT:
21301       case ISD::SETLT:
21302       case ISD::SETLE:
21303         Opcode = X86ISD::FMIN;
21304         break;
21305
21306       case ISD::SETOGE:
21307         // Converting this to a max would handle comparisons between positive
21308         // and negative zero incorrectly.
21309         if (!DAG.getTarget().Options.UnsafeFPMath &&
21310             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21311           break;
21312         Opcode = X86ISD::FMAX;
21313         break;
21314       case ISD::SETUGT:
21315         // Converting this to a max would handle NaNs incorrectly, and swapping
21316         // the operands would cause it to handle comparisons between positive
21317         // and negative zero incorrectly.
21318         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21319           if (!DAG.getTarget().Options.UnsafeFPMath &&
21320               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21321             break;
21322           std::swap(LHS, RHS);
21323         }
21324         Opcode = X86ISD::FMAX;
21325         break;
21326       case ISD::SETUGE:
21327         // Converting this to a max would handle both negative zeros and NaNs
21328         // incorrectly, but we can swap the operands to fix both.
21329         std::swap(LHS, RHS);
21330       case ISD::SETOGT:
21331       case ISD::SETGT:
21332       case ISD::SETGE:
21333         Opcode = X86ISD::FMAX;
21334         break;
21335       }
21336     // Check for x CC y ? y : x -- a min/max with reversed arms.
21337     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21338                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21339       switch (CC) {
21340       default: break;
21341       case ISD::SETOGE:
21342         // Converting this to a min would handle comparisons between positive
21343         // and negative zero incorrectly, and swapping the operands would
21344         // cause it to handle NaNs incorrectly.
21345         if (!DAG.getTarget().Options.UnsafeFPMath &&
21346             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21347           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21348             break;
21349           std::swap(LHS, RHS);
21350         }
21351         Opcode = X86ISD::FMIN;
21352         break;
21353       case ISD::SETUGT:
21354         // Converting this to a min would handle NaNs incorrectly.
21355         if (!DAG.getTarget().Options.UnsafeFPMath &&
21356             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21357           break;
21358         Opcode = X86ISD::FMIN;
21359         break;
21360       case ISD::SETUGE:
21361         // Converting this to a min would handle both negative zeros and NaNs
21362         // incorrectly, but we can swap the operands to fix both.
21363         std::swap(LHS, RHS);
21364       case ISD::SETOGT:
21365       case ISD::SETGT:
21366       case ISD::SETGE:
21367         Opcode = X86ISD::FMIN;
21368         break;
21369
21370       case ISD::SETULT:
21371         // Converting this to a max would handle NaNs incorrectly.
21372         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21373           break;
21374         Opcode = X86ISD::FMAX;
21375         break;
21376       case ISD::SETOLE:
21377         // Converting this to a max would handle comparisons between positive
21378         // and negative zero incorrectly, and swapping the operands would
21379         // cause it to handle NaNs incorrectly.
21380         if (!DAG.getTarget().Options.UnsafeFPMath &&
21381             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21382           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21383             break;
21384           std::swap(LHS, RHS);
21385         }
21386         Opcode = X86ISD::FMAX;
21387         break;
21388       case ISD::SETULE:
21389         // Converting this to a max would handle both negative zeros and NaNs
21390         // incorrectly, but we can swap the operands to fix both.
21391         std::swap(LHS, RHS);
21392       case ISD::SETOLT:
21393       case ISD::SETLT:
21394       case ISD::SETLE:
21395         Opcode = X86ISD::FMAX;
21396         break;
21397       }
21398     }
21399
21400     if (Opcode)
21401       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21402   }
21403
21404   EVT CondVT = Cond.getValueType();
21405   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21406       CondVT.getVectorElementType() == MVT::i1) {
21407     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21408     // lowering on KNL. In this case we convert it to
21409     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21410     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21411     // Since SKX these selects have a proper lowering.
21412     EVT OpVT = LHS.getValueType();
21413     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21414         (OpVT.getVectorElementType() == MVT::i8 ||
21415          OpVT.getVectorElementType() == MVT::i16) &&
21416         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21417       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21418       DCI.AddToWorklist(Cond.getNode());
21419       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21420     }
21421   }
21422   // If this is a select between two integer constants, try to do some
21423   // optimizations.
21424   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21425     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21426       // Don't do this for crazy integer types.
21427       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21428         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21429         // so that TrueC (the true value) is larger than FalseC.
21430         bool NeedsCondInvert = false;
21431
21432         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21433             // Efficiently invertible.
21434             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21435              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21436               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21437           NeedsCondInvert = true;
21438           std::swap(TrueC, FalseC);
21439         }
21440
21441         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21442         if (FalseC->getAPIntValue() == 0 &&
21443             TrueC->getAPIntValue().isPowerOf2()) {
21444           if (NeedsCondInvert) // Invert the condition if needed.
21445             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21446                                DAG.getConstant(1, Cond.getValueType()));
21447
21448           // Zero extend the condition if needed.
21449           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21450
21451           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21452           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21453                              DAG.getConstant(ShAmt, MVT::i8));
21454         }
21455
21456         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21457         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21458           if (NeedsCondInvert) // Invert the condition if needed.
21459             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21460                                DAG.getConstant(1, Cond.getValueType()));
21461
21462           // Zero extend the condition if needed.
21463           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21464                              FalseC->getValueType(0), Cond);
21465           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21466                              SDValue(FalseC, 0));
21467         }
21468
21469         // Optimize cases that will turn into an LEA instruction.  This requires
21470         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21471         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21472           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21473           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21474
21475           bool isFastMultiplier = false;
21476           if (Diff < 10) {
21477             switch ((unsigned char)Diff) {
21478               default: break;
21479               case 1:  // result = add base, cond
21480               case 2:  // result = lea base(    , cond*2)
21481               case 3:  // result = lea base(cond, cond*2)
21482               case 4:  // result = lea base(    , cond*4)
21483               case 5:  // result = lea base(cond, cond*4)
21484               case 8:  // result = lea base(    , cond*8)
21485               case 9:  // result = lea base(cond, cond*8)
21486                 isFastMultiplier = true;
21487                 break;
21488             }
21489           }
21490
21491           if (isFastMultiplier) {
21492             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
21493             if (NeedsCondInvert) // Invert the condition if needed.
21494               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21495                                  DAG.getConstant(1, Cond.getValueType()));
21496
21497             // Zero extend the condition if needed.
21498             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
21499                                Cond);
21500             // Scale the condition by the difference.
21501             if (Diff != 1)
21502               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
21503                                  DAG.getConstant(Diff, Cond.getValueType()));
21504
21505             // Add the base if non-zero.
21506             if (FalseC->getAPIntValue() != 0)
21507               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21508                                  SDValue(FalseC, 0));
21509             return Cond;
21510           }
21511         }
21512       }
21513   }
21514
21515   // Canonicalize max and min:
21516   // (x > y) ? x : y -> (x >= y) ? x : y
21517   // (x < y) ? x : y -> (x <= y) ? x : y
21518   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
21519   // the need for an extra compare
21520   // against zero. e.g.
21521   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
21522   // subl   %esi, %edi
21523   // testl  %edi, %edi
21524   // movl   $0, %eax
21525   // cmovgl %edi, %eax
21526   // =>
21527   // xorl   %eax, %eax
21528   // subl   %esi, $edi
21529   // cmovsl %eax, %edi
21530   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
21531       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21532       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21533     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21534     switch (CC) {
21535     default: break;
21536     case ISD::SETLT:
21537     case ISD::SETGT: {
21538       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
21539       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
21540                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
21541       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
21542     }
21543     }
21544   }
21545
21546   // Early exit check
21547   if (!TLI.isTypeLegal(VT))
21548     return SDValue();
21549
21550   // Match VSELECTs into subs with unsigned saturation.
21551   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21552       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
21553       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
21554        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
21555     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21556
21557     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
21558     // left side invert the predicate to simplify logic below.
21559     SDValue Other;
21560     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
21561       Other = RHS;
21562       CC = ISD::getSetCCInverse(CC, true);
21563     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
21564       Other = LHS;
21565     }
21566
21567     if (Other.getNode() && Other->getNumOperands() == 2 &&
21568         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
21569       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
21570       SDValue CondRHS = Cond->getOperand(1);
21571
21572       // Look for a general sub with unsigned saturation first.
21573       // x >= y ? x-y : 0 --> subus x, y
21574       // x >  y ? x-y : 0 --> subus x, y
21575       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
21576           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
21577         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
21578
21579       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
21580         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
21581           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
21582             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
21583               // If the RHS is a constant we have to reverse the const
21584               // canonicalization.
21585               // x > C-1 ? x+-C : 0 --> subus x, C
21586               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
21587                   CondRHSConst->getAPIntValue() ==
21588                       (-OpRHSConst->getAPIntValue() - 1))
21589                 return DAG.getNode(
21590                     X86ISD::SUBUS, DL, VT, OpLHS,
21591                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
21592
21593           // Another special case: If C was a sign bit, the sub has been
21594           // canonicalized into a xor.
21595           // FIXME: Would it be better to use computeKnownBits to determine
21596           //        whether it's safe to decanonicalize the xor?
21597           // x s< 0 ? x^C : 0 --> subus x, C
21598           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
21599               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
21600               OpRHSConst->getAPIntValue().isSignBit())
21601             // Note that we have to rebuild the RHS constant here to ensure we
21602             // don't rely on particular values of undef lanes.
21603             return DAG.getNode(
21604                 X86ISD::SUBUS, DL, VT, OpLHS,
21605                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
21606         }
21607     }
21608   }
21609
21610   // Try to match a min/max vector operation.
21611   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
21612     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
21613     unsigned Opc = ret.first;
21614     bool NeedSplit = ret.second;
21615
21616     if (Opc && NeedSplit) {
21617       unsigned NumElems = VT.getVectorNumElements();
21618       // Extract the LHS vectors
21619       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
21620       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
21621
21622       // Extract the RHS vectors
21623       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
21624       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
21625
21626       // Create min/max for each subvector
21627       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
21628       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
21629
21630       // Merge the result
21631       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
21632     } else if (Opc)
21633       return DAG.getNode(Opc, DL, VT, LHS, RHS);
21634   }
21635
21636   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
21637   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
21638       // Check if SETCC has already been promoted
21639       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
21640       // Check that condition value type matches vselect operand type
21641       CondVT == VT) { 
21642
21643     assert(Cond.getValueType().isVector() &&
21644            "vector select expects a vector selector!");
21645
21646     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
21647     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
21648
21649     if (!TValIsAllOnes && !FValIsAllZeros) {
21650       // Try invert the condition if true value is not all 1s and false value
21651       // is not all 0s.
21652       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
21653       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
21654
21655       if (TValIsAllZeros || FValIsAllOnes) {
21656         SDValue CC = Cond.getOperand(2);
21657         ISD::CondCode NewCC =
21658           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
21659                                Cond.getOperand(0).getValueType().isInteger());
21660         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
21661         std::swap(LHS, RHS);
21662         TValIsAllOnes = FValIsAllOnes;
21663         FValIsAllZeros = TValIsAllZeros;
21664       }
21665     }
21666
21667     if (TValIsAllOnes || FValIsAllZeros) {
21668       SDValue Ret;
21669
21670       if (TValIsAllOnes && FValIsAllZeros)
21671         Ret = Cond;
21672       else if (TValIsAllOnes)
21673         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
21674                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
21675       else if (FValIsAllZeros)
21676         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
21677                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
21678
21679       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
21680     }
21681   }
21682
21683   // Try to fold this VSELECT into a MOVSS/MOVSD
21684   if (N->getOpcode() == ISD::VSELECT &&
21685       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
21686     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
21687         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
21688       bool CanFold = false;
21689       unsigned NumElems = Cond.getNumOperands();
21690       SDValue A = LHS;
21691       SDValue B = RHS;
21692       
21693       if (isZero(Cond.getOperand(0))) {
21694         CanFold = true;
21695
21696         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
21697         // fold (vselect <0,-1> -> (movsd A, B)
21698         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
21699           CanFold = isAllOnes(Cond.getOperand(i));
21700       } else if (isAllOnes(Cond.getOperand(0))) {
21701         CanFold = true;
21702         std::swap(A, B);
21703
21704         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
21705         // fold (vselect <-1,0> -> (movsd B, A)
21706         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
21707           CanFold = isZero(Cond.getOperand(i));
21708       }
21709
21710       if (CanFold) {
21711         if (VT == MVT::v4i32 || VT == MVT::v4f32)
21712           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
21713         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
21714       }
21715
21716       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
21717         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
21718         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
21719         //                             (v2i64 (bitcast B)))))
21720         //
21721         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
21722         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
21723         //                             (v2f64 (bitcast B)))))
21724         //
21725         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
21726         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
21727         //                             (v2i64 (bitcast A)))))
21728         //
21729         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
21730         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
21731         //                             (v2f64 (bitcast A)))))
21732
21733         CanFold = (isZero(Cond.getOperand(0)) &&
21734                    isZero(Cond.getOperand(1)) &&
21735                    isAllOnes(Cond.getOperand(2)) &&
21736                    isAllOnes(Cond.getOperand(3)));
21737
21738         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
21739             isAllOnes(Cond.getOperand(1)) &&
21740             isZero(Cond.getOperand(2)) &&
21741             isZero(Cond.getOperand(3))) {
21742           CanFold = true;
21743           std::swap(LHS, RHS);
21744         }
21745
21746         if (CanFold) {
21747           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
21748           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
21749           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
21750           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
21751                                                 NewB, DAG);
21752           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
21753         }
21754       }
21755     }
21756   }
21757
21758   // If we know that this node is legal then we know that it is going to be
21759   // matched by one of the SSE/AVX BLEND instructions. These instructions only
21760   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
21761   // to simplify previous instructions.
21762   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
21763       !DCI.isBeforeLegalize() &&
21764       // We explicitly check against v8i16 and v16i16 because, although
21765       // they're marked as Custom, they might only be legal when Cond is a
21766       // build_vector of constants. This will be taken care in a later
21767       // condition.
21768       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
21769        VT != MVT::v8i16)) {
21770     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
21771
21772     // Don't optimize vector selects that map to mask-registers.
21773     if (BitWidth == 1)
21774       return SDValue();
21775
21776     // Check all uses of that condition operand to check whether it will be
21777     // consumed by non-BLEND instructions, which may depend on all bits are set
21778     // properly.
21779     for (SDNode::use_iterator I = Cond->use_begin(),
21780                               E = Cond->use_end(); I != E; ++I)
21781       if (I->getOpcode() != ISD::VSELECT)
21782         // TODO: Add other opcodes eventually lowered into BLEND.
21783         return SDValue();
21784
21785     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
21786     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
21787
21788     APInt KnownZero, KnownOne;
21789     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
21790                                           DCI.isBeforeLegalizeOps());
21791     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
21792         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
21793       DCI.CommitTargetLoweringOpt(TLO);
21794   }
21795
21796   // We should generate an X86ISD::BLENDI from a vselect if its argument
21797   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
21798   // constants. This specific pattern gets generated when we split a
21799   // selector for a 512 bit vector in a machine without AVX512 (but with
21800   // 256-bit vectors), during legalization:
21801   //
21802   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
21803   //
21804   // Iff we find this pattern and the build_vectors are built from
21805   // constants, we translate the vselect into a shuffle_vector that we
21806   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
21807   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
21808     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
21809     if (Shuffle.getNode())
21810       return Shuffle;
21811   }
21812
21813   return SDValue();
21814 }
21815
21816 // Check whether a boolean test is testing a boolean value generated by
21817 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
21818 // code.
21819 //
21820 // Simplify the following patterns:
21821 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
21822 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
21823 // to (Op EFLAGS Cond)
21824 //
21825 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
21826 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
21827 // to (Op EFLAGS !Cond)
21828 //
21829 // where Op could be BRCOND or CMOV.
21830 //
21831 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
21832   // Quit if not CMP and SUB with its value result used.
21833   if (Cmp.getOpcode() != X86ISD::CMP &&
21834       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
21835       return SDValue();
21836
21837   // Quit if not used as a boolean value.
21838   if (CC != X86::COND_E && CC != X86::COND_NE)
21839     return SDValue();
21840
21841   // Check CMP operands. One of them should be 0 or 1 and the other should be
21842   // an SetCC or extended from it.
21843   SDValue Op1 = Cmp.getOperand(0);
21844   SDValue Op2 = Cmp.getOperand(1);
21845
21846   SDValue SetCC;
21847   const ConstantSDNode* C = nullptr;
21848   bool needOppositeCond = (CC == X86::COND_E);
21849   bool checkAgainstTrue = false; // Is it a comparison against 1?
21850
21851   if ((C = dyn_cast<ConstantSDNode>(Op1)))
21852     SetCC = Op2;
21853   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
21854     SetCC = Op1;
21855   else // Quit if all operands are not constants.
21856     return SDValue();
21857
21858   if (C->getZExtValue() == 1) {
21859     needOppositeCond = !needOppositeCond;
21860     checkAgainstTrue = true;
21861   } else if (C->getZExtValue() != 0)
21862     // Quit if the constant is neither 0 or 1.
21863     return SDValue();
21864
21865   bool truncatedToBoolWithAnd = false;
21866   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
21867   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
21868          SetCC.getOpcode() == ISD::TRUNCATE ||
21869          SetCC.getOpcode() == ISD::AND) {
21870     if (SetCC.getOpcode() == ISD::AND) {
21871       int OpIdx = -1;
21872       ConstantSDNode *CS;
21873       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
21874           CS->getZExtValue() == 1)
21875         OpIdx = 1;
21876       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
21877           CS->getZExtValue() == 1)
21878         OpIdx = 0;
21879       if (OpIdx == -1)
21880         break;
21881       SetCC = SetCC.getOperand(OpIdx);
21882       truncatedToBoolWithAnd = true;
21883     } else
21884       SetCC = SetCC.getOperand(0);
21885   }
21886
21887   switch (SetCC.getOpcode()) {
21888   case X86ISD::SETCC_CARRY:
21889     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
21890     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
21891     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
21892     // truncated to i1 using 'and'.
21893     if (checkAgainstTrue && !truncatedToBoolWithAnd)
21894       break;
21895     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
21896            "Invalid use of SETCC_CARRY!");
21897     // FALL THROUGH
21898   case X86ISD::SETCC:
21899     // Set the condition code or opposite one if necessary.
21900     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
21901     if (needOppositeCond)
21902       CC = X86::GetOppositeBranchCondition(CC);
21903     return SetCC.getOperand(1);
21904   case X86ISD::CMOV: {
21905     // Check whether false/true value has canonical one, i.e. 0 or 1.
21906     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
21907     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
21908     // Quit if true value is not a constant.
21909     if (!TVal)
21910       return SDValue();
21911     // Quit if false value is not a constant.
21912     if (!FVal) {
21913       SDValue Op = SetCC.getOperand(0);
21914       // Skip 'zext' or 'trunc' node.
21915       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
21916           Op.getOpcode() == ISD::TRUNCATE)
21917         Op = Op.getOperand(0);
21918       // A special case for rdrand/rdseed, where 0 is set if false cond is
21919       // found.
21920       if ((Op.getOpcode() != X86ISD::RDRAND &&
21921            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
21922         return SDValue();
21923     }
21924     // Quit if false value is not the constant 0 or 1.
21925     bool FValIsFalse = true;
21926     if (FVal && FVal->getZExtValue() != 0) {
21927       if (FVal->getZExtValue() != 1)
21928         return SDValue();
21929       // If FVal is 1, opposite cond is needed.
21930       needOppositeCond = !needOppositeCond;
21931       FValIsFalse = false;
21932     }
21933     // Quit if TVal is not the constant opposite of FVal.
21934     if (FValIsFalse && TVal->getZExtValue() != 1)
21935       return SDValue();
21936     if (!FValIsFalse && TVal->getZExtValue() != 0)
21937       return SDValue();
21938     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
21939     if (needOppositeCond)
21940       CC = X86::GetOppositeBranchCondition(CC);
21941     return SetCC.getOperand(3);
21942   }
21943   }
21944
21945   return SDValue();
21946 }
21947
21948 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
21949 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
21950                                   TargetLowering::DAGCombinerInfo &DCI,
21951                                   const X86Subtarget *Subtarget) {
21952   SDLoc DL(N);
21953
21954   // If the flag operand isn't dead, don't touch this CMOV.
21955   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
21956     return SDValue();
21957
21958   SDValue FalseOp = N->getOperand(0);
21959   SDValue TrueOp = N->getOperand(1);
21960   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
21961   SDValue Cond = N->getOperand(3);
21962
21963   if (CC == X86::COND_E || CC == X86::COND_NE) {
21964     switch (Cond.getOpcode()) {
21965     default: break;
21966     case X86ISD::BSR:
21967     case X86ISD::BSF:
21968       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
21969       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
21970         return (CC == X86::COND_E) ? FalseOp : TrueOp;
21971     }
21972   }
21973
21974   SDValue Flags;
21975
21976   Flags = checkBoolTestSetCCCombine(Cond, CC);
21977   if (Flags.getNode() &&
21978       // Extra check as FCMOV only supports a subset of X86 cond.
21979       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
21980     SDValue Ops[] = { FalseOp, TrueOp,
21981                       DAG.getConstant(CC, MVT::i8), Flags };
21982     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
21983   }
21984
21985   // If this is a select between two integer constants, try to do some
21986   // optimizations.  Note that the operands are ordered the opposite of SELECT
21987   // operands.
21988   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
21989     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
21990       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
21991       // larger than FalseC (the false value).
21992       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
21993         CC = X86::GetOppositeBranchCondition(CC);
21994         std::swap(TrueC, FalseC);
21995         std::swap(TrueOp, FalseOp);
21996       }
21997
21998       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
21999       // This is efficient for any integer data type (including i8/i16) and
22000       // shift amount.
22001       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22002         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22003                            DAG.getConstant(CC, MVT::i8), Cond);
22004
22005         // Zero extend the condition if needed.
22006         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22007
22008         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22009         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22010                            DAG.getConstant(ShAmt, MVT::i8));
22011         if (N->getNumValues() == 2)  // Dead flag value?
22012           return DCI.CombineTo(N, Cond, SDValue());
22013         return Cond;
22014       }
22015
22016       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22017       // for any integer data type, including i8/i16.
22018       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22019         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22020                            DAG.getConstant(CC, MVT::i8), Cond);
22021
22022         // Zero extend the condition if needed.
22023         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22024                            FalseC->getValueType(0), Cond);
22025         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22026                            SDValue(FalseC, 0));
22027
22028         if (N->getNumValues() == 2)  // Dead flag value?
22029           return DCI.CombineTo(N, Cond, SDValue());
22030         return Cond;
22031       }
22032
22033       // Optimize cases that will turn into an LEA instruction.  This requires
22034       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22035       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22036         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22037         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22038
22039         bool isFastMultiplier = false;
22040         if (Diff < 10) {
22041           switch ((unsigned char)Diff) {
22042           default: break;
22043           case 1:  // result = add base, cond
22044           case 2:  // result = lea base(    , cond*2)
22045           case 3:  // result = lea base(cond, cond*2)
22046           case 4:  // result = lea base(    , cond*4)
22047           case 5:  // result = lea base(cond, cond*4)
22048           case 8:  // result = lea base(    , cond*8)
22049           case 9:  // result = lea base(cond, cond*8)
22050             isFastMultiplier = true;
22051             break;
22052           }
22053         }
22054
22055         if (isFastMultiplier) {
22056           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22057           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22058                              DAG.getConstant(CC, MVT::i8), Cond);
22059           // Zero extend the condition if needed.
22060           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22061                              Cond);
22062           // Scale the condition by the difference.
22063           if (Diff != 1)
22064             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22065                                DAG.getConstant(Diff, Cond.getValueType()));
22066
22067           // Add the base if non-zero.
22068           if (FalseC->getAPIntValue() != 0)
22069             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22070                                SDValue(FalseC, 0));
22071           if (N->getNumValues() == 2)  // Dead flag value?
22072             return DCI.CombineTo(N, Cond, SDValue());
22073           return Cond;
22074         }
22075       }
22076     }
22077   }
22078
22079   // Handle these cases:
22080   //   (select (x != c), e, c) -> select (x != c), e, x),
22081   //   (select (x == c), c, e) -> select (x == c), x, e)
22082   // where the c is an integer constant, and the "select" is the combination
22083   // of CMOV and CMP.
22084   //
22085   // The rationale for this change is that the conditional-move from a constant
22086   // needs two instructions, however, conditional-move from a register needs
22087   // only one instruction.
22088   //
22089   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22090   //  some instruction-combining opportunities. This opt needs to be
22091   //  postponed as late as possible.
22092   //
22093   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22094     // the DCI.xxxx conditions are provided to postpone the optimization as
22095     // late as possible.
22096
22097     ConstantSDNode *CmpAgainst = nullptr;
22098     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22099         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22100         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22101
22102       if (CC == X86::COND_NE &&
22103           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22104         CC = X86::GetOppositeBranchCondition(CC);
22105         std::swap(TrueOp, FalseOp);
22106       }
22107
22108       if (CC == X86::COND_E &&
22109           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22110         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22111                           DAG.getConstant(CC, MVT::i8), Cond };
22112         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22113       }
22114     }
22115   }
22116
22117   return SDValue();
22118 }
22119
22120 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22121                                                 const X86Subtarget *Subtarget) {
22122   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22123   switch (IntNo) {
22124   default: return SDValue();
22125   // SSE/AVX/AVX2 blend intrinsics.
22126   case Intrinsic::x86_avx2_pblendvb:
22127   case Intrinsic::x86_avx2_pblendw:
22128   case Intrinsic::x86_avx2_pblendd_128:
22129   case Intrinsic::x86_avx2_pblendd_256:
22130     // Don't try to simplify this intrinsic if we don't have AVX2.
22131     if (!Subtarget->hasAVX2())
22132       return SDValue();
22133     // FALL-THROUGH
22134   case Intrinsic::x86_avx_blend_pd_256:
22135   case Intrinsic::x86_avx_blend_ps_256:
22136   case Intrinsic::x86_avx_blendv_pd_256:
22137   case Intrinsic::x86_avx_blendv_ps_256:
22138     // Don't try to simplify this intrinsic if we don't have AVX.
22139     if (!Subtarget->hasAVX())
22140       return SDValue();
22141     // FALL-THROUGH
22142   case Intrinsic::x86_sse41_pblendw:
22143   case Intrinsic::x86_sse41_blendpd:
22144   case Intrinsic::x86_sse41_blendps:
22145   case Intrinsic::x86_sse41_blendvps:
22146   case Intrinsic::x86_sse41_blendvpd:
22147   case Intrinsic::x86_sse41_pblendvb: {
22148     SDValue Op0 = N->getOperand(1);
22149     SDValue Op1 = N->getOperand(2);
22150     SDValue Mask = N->getOperand(3);
22151
22152     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22153     if (!Subtarget->hasSSE41())
22154       return SDValue();
22155
22156     // fold (blend A, A, Mask) -> A
22157     if (Op0 == Op1)
22158       return Op0;
22159     // fold (blend A, B, allZeros) -> A
22160     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22161       return Op0;
22162     // fold (blend A, B, allOnes) -> B
22163     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22164       return Op1;
22165     
22166     // Simplify the case where the mask is a constant i32 value.
22167     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22168       if (C->isNullValue())
22169         return Op0;
22170       if (C->isAllOnesValue())
22171         return Op1;
22172     }
22173
22174     return SDValue();
22175   }
22176
22177   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22178   case Intrinsic::x86_sse2_psrai_w:
22179   case Intrinsic::x86_sse2_psrai_d:
22180   case Intrinsic::x86_avx2_psrai_w:
22181   case Intrinsic::x86_avx2_psrai_d:
22182   case Intrinsic::x86_sse2_psra_w:
22183   case Intrinsic::x86_sse2_psra_d:
22184   case Intrinsic::x86_avx2_psra_w:
22185   case Intrinsic::x86_avx2_psra_d: {
22186     SDValue Op0 = N->getOperand(1);
22187     SDValue Op1 = N->getOperand(2);
22188     EVT VT = Op0.getValueType();
22189     assert(VT.isVector() && "Expected a vector type!");
22190
22191     if (isa<BuildVectorSDNode>(Op1))
22192       Op1 = Op1.getOperand(0);
22193
22194     if (!isa<ConstantSDNode>(Op1))
22195       return SDValue();
22196
22197     EVT SVT = VT.getVectorElementType();
22198     unsigned SVTBits = SVT.getSizeInBits();
22199
22200     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22201     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22202     uint64_t ShAmt = C.getZExtValue();
22203
22204     // Don't try to convert this shift into a ISD::SRA if the shift
22205     // count is bigger than or equal to the element size.
22206     if (ShAmt >= SVTBits)
22207       return SDValue();
22208
22209     // Trivial case: if the shift count is zero, then fold this
22210     // into the first operand.
22211     if (ShAmt == 0)
22212       return Op0;
22213
22214     // Replace this packed shift intrinsic with a target independent
22215     // shift dag node.
22216     SDValue Splat = DAG.getConstant(C, VT);
22217     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
22218   }
22219   }
22220 }
22221
22222 /// PerformMulCombine - Optimize a single multiply with constant into two
22223 /// in order to implement it with two cheaper instructions, e.g.
22224 /// LEA + SHL, LEA + LEA.
22225 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22226                                  TargetLowering::DAGCombinerInfo &DCI) {
22227   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22228     return SDValue();
22229
22230   EVT VT = N->getValueType(0);
22231   if (VT != MVT::i64)
22232     return SDValue();
22233
22234   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22235   if (!C)
22236     return SDValue();
22237   uint64_t MulAmt = C->getZExtValue();
22238   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22239     return SDValue();
22240
22241   uint64_t MulAmt1 = 0;
22242   uint64_t MulAmt2 = 0;
22243   if ((MulAmt % 9) == 0) {
22244     MulAmt1 = 9;
22245     MulAmt2 = MulAmt / 9;
22246   } else if ((MulAmt % 5) == 0) {
22247     MulAmt1 = 5;
22248     MulAmt2 = MulAmt / 5;
22249   } else if ((MulAmt % 3) == 0) {
22250     MulAmt1 = 3;
22251     MulAmt2 = MulAmt / 3;
22252   }
22253   if (MulAmt2 &&
22254       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22255     SDLoc DL(N);
22256
22257     if (isPowerOf2_64(MulAmt2) &&
22258         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22259       // If second multiplifer is pow2, issue it first. We want the multiply by
22260       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22261       // is an add.
22262       std::swap(MulAmt1, MulAmt2);
22263
22264     SDValue NewMul;
22265     if (isPowerOf2_64(MulAmt1))
22266       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22267                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
22268     else
22269       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22270                            DAG.getConstant(MulAmt1, VT));
22271
22272     if (isPowerOf2_64(MulAmt2))
22273       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22274                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
22275     else
22276       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22277                            DAG.getConstant(MulAmt2, VT));
22278
22279     // Do not add new nodes to DAG combiner worklist.
22280     DCI.CombineTo(N, NewMul, false);
22281   }
22282   return SDValue();
22283 }
22284
22285 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22286   SDValue N0 = N->getOperand(0);
22287   SDValue N1 = N->getOperand(1);
22288   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22289   EVT VT = N0.getValueType();
22290
22291   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22292   // since the result of setcc_c is all zero's or all ones.
22293   if (VT.isInteger() && !VT.isVector() &&
22294       N1C && N0.getOpcode() == ISD::AND &&
22295       N0.getOperand(1).getOpcode() == ISD::Constant) {
22296     SDValue N00 = N0.getOperand(0);
22297     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22298         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22299           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22300          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22301       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22302       APInt ShAmt = N1C->getAPIntValue();
22303       Mask = Mask.shl(ShAmt);
22304       if (Mask != 0)
22305         return DAG.getNode(ISD::AND, SDLoc(N), VT,
22306                            N00, DAG.getConstant(Mask, VT));
22307     }
22308   }
22309
22310   // Hardware support for vector shifts is sparse which makes us scalarize the
22311   // vector operations in many cases. Also, on sandybridge ADD is faster than
22312   // shl.
22313   // (shl V, 1) -> add V,V
22314   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22315     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22316       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22317       // We shift all of the values by one. In many cases we do not have
22318       // hardware support for this operation. This is better expressed as an ADD
22319       // of two values.
22320       if (N1SplatC->getZExtValue() == 1)
22321         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22322     }
22323
22324   return SDValue();
22325 }
22326
22327 /// \brief Returns a vector of 0s if the node in input is a vector logical
22328 /// shift by a constant amount which is known to be bigger than or equal
22329 /// to the vector element size in bits.
22330 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22331                                       const X86Subtarget *Subtarget) {
22332   EVT VT = N->getValueType(0);
22333
22334   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22335       (!Subtarget->hasInt256() ||
22336        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22337     return SDValue();
22338
22339   SDValue Amt = N->getOperand(1);
22340   SDLoc DL(N);
22341   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22342     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22343       APInt ShiftAmt = AmtSplat->getAPIntValue();
22344       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22345
22346       // SSE2/AVX2 logical shifts always return a vector of 0s
22347       // if the shift amount is bigger than or equal to
22348       // the element size. The constant shift amount will be
22349       // encoded as a 8-bit immediate.
22350       if (ShiftAmt.trunc(8).uge(MaxAmount))
22351         return getZeroVector(VT, Subtarget, DAG, DL);
22352     }
22353
22354   return SDValue();
22355 }
22356
22357 /// PerformShiftCombine - Combine shifts.
22358 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22359                                    TargetLowering::DAGCombinerInfo &DCI,
22360                                    const X86Subtarget *Subtarget) {
22361   if (N->getOpcode() == ISD::SHL) {
22362     SDValue V = PerformSHLCombine(N, DAG);
22363     if (V.getNode()) return V;
22364   }
22365
22366   if (N->getOpcode() != ISD::SRA) {
22367     // Try to fold this logical shift into a zero vector.
22368     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
22369     if (V.getNode()) return V;
22370   }
22371
22372   return SDValue();
22373 }
22374
22375 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22376 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22377 // and friends.  Likewise for OR -> CMPNEQSS.
22378 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22379                             TargetLowering::DAGCombinerInfo &DCI,
22380                             const X86Subtarget *Subtarget) {
22381   unsigned opcode;
22382
22383   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22384   // we're requiring SSE2 for both.
22385   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22386     SDValue N0 = N->getOperand(0);
22387     SDValue N1 = N->getOperand(1);
22388     SDValue CMP0 = N0->getOperand(1);
22389     SDValue CMP1 = N1->getOperand(1);
22390     SDLoc DL(N);
22391
22392     // The SETCCs should both refer to the same CMP.
22393     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22394       return SDValue();
22395
22396     SDValue CMP00 = CMP0->getOperand(0);
22397     SDValue CMP01 = CMP0->getOperand(1);
22398     EVT     VT    = CMP00.getValueType();
22399
22400     if (VT == MVT::f32 || VT == MVT::f64) {
22401       bool ExpectingFlags = false;
22402       // Check for any users that want flags:
22403       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22404            !ExpectingFlags && UI != UE; ++UI)
22405         switch (UI->getOpcode()) {
22406         default:
22407         case ISD::BR_CC:
22408         case ISD::BRCOND:
22409         case ISD::SELECT:
22410           ExpectingFlags = true;
22411           break;
22412         case ISD::CopyToReg:
22413         case ISD::SIGN_EXTEND:
22414         case ISD::ZERO_EXTEND:
22415         case ISD::ANY_EXTEND:
22416           break;
22417         }
22418
22419       if (!ExpectingFlags) {
22420         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22421         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22422
22423         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22424           X86::CondCode tmp = cc0;
22425           cc0 = cc1;
22426           cc1 = tmp;
22427         }
22428
22429         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22430             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22431           // FIXME: need symbolic constants for these magic numbers.
22432           // See X86ATTInstPrinter.cpp:printSSECC().
22433           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22434           if (Subtarget->hasAVX512()) {
22435             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22436                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
22437             if (N->getValueType(0) != MVT::i1)
22438               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
22439                                  FSetCC);
22440             return FSetCC;
22441           }
22442           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
22443                                               CMP00.getValueType(), CMP00, CMP01,
22444                                               DAG.getConstant(x86cc, MVT::i8));
22445
22446           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
22447           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
22448
22449           if (is64BitFP && !Subtarget->is64Bit()) {
22450             // On a 32-bit target, we cannot bitcast the 64-bit float to a
22451             // 64-bit integer, since that's not a legal type. Since
22452             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
22453             // bits, but can do this little dance to extract the lowest 32 bits
22454             // and work with those going forward.
22455             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
22456                                            OnesOrZeroesF);
22457             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
22458                                            Vector64);
22459             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
22460                                         Vector32, DAG.getIntPtrConstant(0));
22461             IntVT = MVT::i32;
22462           }
22463
22464           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
22465           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
22466                                       DAG.getConstant(1, IntVT));
22467           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
22468           return OneBitOfTruth;
22469         }
22470       }
22471     }
22472   }
22473   return SDValue();
22474 }
22475
22476 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
22477 /// so it can be folded inside ANDNP.
22478 static bool CanFoldXORWithAllOnes(const SDNode *N) {
22479   EVT VT = N->getValueType(0);
22480
22481   // Match direct AllOnes for 128 and 256-bit vectors
22482   if (ISD::isBuildVectorAllOnes(N))
22483     return true;
22484
22485   // Look through a bit convert.
22486   if (N->getOpcode() == ISD::BITCAST)
22487     N = N->getOperand(0).getNode();
22488
22489   // Sometimes the operand may come from a insert_subvector building a 256-bit
22490   // allones vector
22491   if (VT.is256BitVector() &&
22492       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
22493     SDValue V1 = N->getOperand(0);
22494     SDValue V2 = N->getOperand(1);
22495
22496     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
22497         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
22498         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
22499         ISD::isBuildVectorAllOnes(V2.getNode()))
22500       return true;
22501   }
22502
22503   return false;
22504 }
22505
22506 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
22507 // register. In most cases we actually compare or select YMM-sized registers
22508 // and mixing the two types creates horrible code. This method optimizes
22509 // some of the transition sequences.
22510 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
22511                                  TargetLowering::DAGCombinerInfo &DCI,
22512                                  const X86Subtarget *Subtarget) {
22513   EVT VT = N->getValueType(0);
22514   if (!VT.is256BitVector())
22515     return SDValue();
22516
22517   assert((N->getOpcode() == ISD::ANY_EXTEND ||
22518           N->getOpcode() == ISD::ZERO_EXTEND ||
22519           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
22520
22521   SDValue Narrow = N->getOperand(0);
22522   EVT NarrowVT = Narrow->getValueType(0);
22523   if (!NarrowVT.is128BitVector())
22524     return SDValue();
22525
22526   if (Narrow->getOpcode() != ISD::XOR &&
22527       Narrow->getOpcode() != ISD::AND &&
22528       Narrow->getOpcode() != ISD::OR)
22529     return SDValue();
22530
22531   SDValue N0  = Narrow->getOperand(0);
22532   SDValue N1  = Narrow->getOperand(1);
22533   SDLoc DL(Narrow);
22534
22535   // The Left side has to be a trunc.
22536   if (N0.getOpcode() != ISD::TRUNCATE)
22537     return SDValue();
22538
22539   // The type of the truncated inputs.
22540   EVT WideVT = N0->getOperand(0)->getValueType(0);
22541   if (WideVT != VT)
22542     return SDValue();
22543
22544   // The right side has to be a 'trunc' or a constant vector.
22545   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
22546   ConstantSDNode *RHSConstSplat = nullptr;
22547   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
22548     RHSConstSplat = RHSBV->getConstantSplatNode();
22549   if (!RHSTrunc && !RHSConstSplat)
22550     return SDValue();
22551
22552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22553
22554   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
22555     return SDValue();
22556
22557   // Set N0 and N1 to hold the inputs to the new wide operation.
22558   N0 = N0->getOperand(0);
22559   if (RHSConstSplat) {
22560     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
22561                      SDValue(RHSConstSplat, 0));
22562     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
22563     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
22564   } else if (RHSTrunc) {
22565     N1 = N1->getOperand(0);
22566   }
22567
22568   // Generate the wide operation.
22569   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
22570   unsigned Opcode = N->getOpcode();
22571   switch (Opcode) {
22572   case ISD::ANY_EXTEND:
22573     return Op;
22574   case ISD::ZERO_EXTEND: {
22575     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
22576     APInt Mask = APInt::getAllOnesValue(InBits);
22577     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
22578     return DAG.getNode(ISD::AND, DL, VT,
22579                        Op, DAG.getConstant(Mask, VT));
22580   }
22581   case ISD::SIGN_EXTEND:
22582     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
22583                        Op, DAG.getValueType(NarrowVT));
22584   default:
22585     llvm_unreachable("Unexpected opcode");
22586   }
22587 }
22588
22589 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
22590                                  TargetLowering::DAGCombinerInfo &DCI,
22591                                  const X86Subtarget *Subtarget) {
22592   EVT VT = N->getValueType(0);
22593   if (DCI.isBeforeLegalizeOps())
22594     return SDValue();
22595
22596   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22597   if (R.getNode())
22598     return R;
22599
22600   // Create BEXTR instructions
22601   // BEXTR is ((X >> imm) & (2**size-1))
22602   if (VT == MVT::i32 || VT == MVT::i64) {
22603     SDValue N0 = N->getOperand(0);
22604     SDValue N1 = N->getOperand(1);
22605     SDLoc DL(N);
22606
22607     // Check for BEXTR.
22608     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
22609         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
22610       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
22611       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22612       if (MaskNode && ShiftNode) {
22613         uint64_t Mask = MaskNode->getZExtValue();
22614         uint64_t Shift = ShiftNode->getZExtValue();
22615         if (isMask_64(Mask)) {
22616           uint64_t MaskSize = CountPopulation_64(Mask);
22617           if (Shift + MaskSize <= VT.getSizeInBits())
22618             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
22619                                DAG.getConstant(Shift | (MaskSize << 8), VT));
22620         }
22621       }
22622     } // BEXTR
22623
22624     return SDValue();
22625   }
22626
22627   // Want to form ANDNP nodes:
22628   // 1) In the hopes of then easily combining them with OR and AND nodes
22629   //    to form PBLEND/PSIGN.
22630   // 2) To match ANDN packed intrinsics
22631   if (VT != MVT::v2i64 && VT != MVT::v4i64)
22632     return SDValue();
22633
22634   SDValue N0 = N->getOperand(0);
22635   SDValue N1 = N->getOperand(1);
22636   SDLoc DL(N);
22637
22638   // Check LHS for vnot
22639   if (N0.getOpcode() == ISD::XOR &&
22640       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
22641       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
22642     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
22643
22644   // Check RHS for vnot
22645   if (N1.getOpcode() == ISD::XOR &&
22646       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
22647       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
22648     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
22649
22650   return SDValue();
22651 }
22652
22653 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
22654                                 TargetLowering::DAGCombinerInfo &DCI,
22655                                 const X86Subtarget *Subtarget) {
22656   if (DCI.isBeforeLegalizeOps())
22657     return SDValue();
22658
22659   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
22660   if (R.getNode())
22661     return R;
22662
22663   SDValue N0 = N->getOperand(0);
22664   SDValue N1 = N->getOperand(1);
22665   EVT VT = N->getValueType(0);
22666
22667   // look for psign/blend
22668   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
22669     if (!Subtarget->hasSSSE3() ||
22670         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
22671       return SDValue();
22672
22673     // Canonicalize pandn to RHS
22674     if (N0.getOpcode() == X86ISD::ANDNP)
22675       std::swap(N0, N1);
22676     // or (and (m, y), (pandn m, x))
22677     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
22678       SDValue Mask = N1.getOperand(0);
22679       SDValue X    = N1.getOperand(1);
22680       SDValue Y;
22681       if (N0.getOperand(0) == Mask)
22682         Y = N0.getOperand(1);
22683       if (N0.getOperand(1) == Mask)
22684         Y = N0.getOperand(0);
22685
22686       // Check to see if the mask appeared in both the AND and ANDNP and
22687       if (!Y.getNode())
22688         return SDValue();
22689
22690       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
22691       // Look through mask bitcast.
22692       if (Mask.getOpcode() == ISD::BITCAST)
22693         Mask = Mask.getOperand(0);
22694       if (X.getOpcode() == ISD::BITCAST)
22695         X = X.getOperand(0);
22696       if (Y.getOpcode() == ISD::BITCAST)
22697         Y = Y.getOperand(0);
22698
22699       EVT MaskVT = Mask.getValueType();
22700
22701       // Validate that the Mask operand is a vector sra node.
22702       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
22703       // there is no psrai.b
22704       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
22705       unsigned SraAmt = ~0;
22706       if (Mask.getOpcode() == ISD::SRA) {
22707         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
22708           if (auto *AmtConst = AmtBV->getConstantSplatNode())
22709             SraAmt = AmtConst->getZExtValue();
22710       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
22711         SDValue SraC = Mask.getOperand(1);
22712         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
22713       }
22714       if ((SraAmt + 1) != EltBits)
22715         return SDValue();
22716
22717       SDLoc DL(N);
22718
22719       // Now we know we at least have a plendvb with the mask val.  See if
22720       // we can form a psignb/w/d.
22721       // psign = x.type == y.type == mask.type && y = sub(0, x);
22722       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
22723           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
22724           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
22725         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
22726                "Unsupported VT for PSIGN");
22727         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
22728         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22729       }
22730       // PBLENDVB only available on SSE 4.1
22731       if (!Subtarget->hasSSE41())
22732         return SDValue();
22733
22734       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
22735
22736       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
22737       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
22738       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
22739       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
22740       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
22741     }
22742   }
22743
22744   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
22745     return SDValue();
22746
22747   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
22748   MachineFunction &MF = DAG.getMachineFunction();
22749   bool OptForSize = MF.getFunction()->getAttributes().
22750     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
22751
22752   // SHLD/SHRD instructions have lower register pressure, but on some
22753   // platforms they have higher latency than the equivalent
22754   // series of shifts/or that would otherwise be generated.
22755   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
22756   // have higher latencies and we are not optimizing for size.
22757   if (!OptForSize && Subtarget->isSHLDSlow())
22758     return SDValue();
22759
22760   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
22761     std::swap(N0, N1);
22762   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
22763     return SDValue();
22764   if (!N0.hasOneUse() || !N1.hasOneUse())
22765     return SDValue();
22766
22767   SDValue ShAmt0 = N0.getOperand(1);
22768   if (ShAmt0.getValueType() != MVT::i8)
22769     return SDValue();
22770   SDValue ShAmt1 = N1.getOperand(1);
22771   if (ShAmt1.getValueType() != MVT::i8)
22772     return SDValue();
22773   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
22774     ShAmt0 = ShAmt0.getOperand(0);
22775   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
22776     ShAmt1 = ShAmt1.getOperand(0);
22777
22778   SDLoc DL(N);
22779   unsigned Opc = X86ISD::SHLD;
22780   SDValue Op0 = N0.getOperand(0);
22781   SDValue Op1 = N1.getOperand(0);
22782   if (ShAmt0.getOpcode() == ISD::SUB) {
22783     Opc = X86ISD::SHRD;
22784     std::swap(Op0, Op1);
22785     std::swap(ShAmt0, ShAmt1);
22786   }
22787
22788   unsigned Bits = VT.getSizeInBits();
22789   if (ShAmt1.getOpcode() == ISD::SUB) {
22790     SDValue Sum = ShAmt1.getOperand(0);
22791     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
22792       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
22793       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
22794         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
22795       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
22796         return DAG.getNode(Opc, DL, VT,
22797                            Op0, Op1,
22798                            DAG.getNode(ISD::TRUNCATE, DL,
22799                                        MVT::i8, ShAmt0));
22800     }
22801   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
22802     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
22803     if (ShAmt0C &&
22804         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
22805       return DAG.getNode(Opc, DL, VT,
22806                          N0.getOperand(0), N1.getOperand(0),
22807                          DAG.getNode(ISD::TRUNCATE, DL,
22808                                        MVT::i8, ShAmt0));
22809   }
22810
22811   return SDValue();
22812 }
22813
22814 // Generate NEG and CMOV for integer abs.
22815 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
22816   EVT VT = N->getValueType(0);
22817
22818   // Since X86 does not have CMOV for 8-bit integer, we don't convert
22819   // 8-bit integer abs to NEG and CMOV.
22820   if (VT.isInteger() && VT.getSizeInBits() == 8)
22821     return SDValue();
22822
22823   SDValue N0 = N->getOperand(0);
22824   SDValue N1 = N->getOperand(1);
22825   SDLoc DL(N);
22826
22827   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
22828   // and change it to SUB and CMOV.
22829   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
22830       N0.getOpcode() == ISD::ADD &&
22831       N0.getOperand(1) == N1 &&
22832       N1.getOpcode() == ISD::SRA &&
22833       N1.getOperand(0) == N0.getOperand(0))
22834     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
22835       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
22836         // Generate SUB & CMOV.
22837         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
22838                                   DAG.getConstant(0, VT), N0.getOperand(0));
22839
22840         SDValue Ops[] = { N0.getOperand(0), Neg,
22841                           DAG.getConstant(X86::COND_GE, MVT::i8),
22842                           SDValue(Neg.getNode(), 1) };
22843         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
22844       }
22845   return SDValue();
22846 }
22847
22848 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
22849 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
22850                                  TargetLowering::DAGCombinerInfo &DCI,
22851                                  const X86Subtarget *Subtarget) {
22852   if (DCI.isBeforeLegalizeOps())
22853     return SDValue();
22854
22855   if (Subtarget->hasCMov()) {
22856     SDValue RV = performIntegerAbsCombine(N, DAG);
22857     if (RV.getNode())
22858       return RV;
22859   }
22860
22861   return SDValue();
22862 }
22863
22864 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
22865 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
22866                                   TargetLowering::DAGCombinerInfo &DCI,
22867                                   const X86Subtarget *Subtarget) {
22868   LoadSDNode *Ld = cast<LoadSDNode>(N);
22869   EVT RegVT = Ld->getValueType(0);
22870   EVT MemVT = Ld->getMemoryVT();
22871   SDLoc dl(Ld);
22872   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22873
22874   // On Sandybridge unaligned 256bit loads are inefficient.
22875   ISD::LoadExtType Ext = Ld->getExtensionType();
22876   unsigned Alignment = Ld->getAlignment();
22877   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
22878   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
22879       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
22880     unsigned NumElems = RegVT.getVectorNumElements();
22881     if (NumElems < 2)
22882       return SDValue();
22883
22884     SDValue Ptr = Ld->getBasePtr();
22885     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
22886
22887     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
22888                                   NumElems/2);
22889     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22890                                 Ld->getPointerInfo(), Ld->isVolatile(),
22891                                 Ld->isNonTemporal(), Ld->isInvariant(),
22892                                 Alignment);
22893     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
22894     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
22895                                 Ld->getPointerInfo(), Ld->isVolatile(),
22896                                 Ld->isNonTemporal(), Ld->isInvariant(),
22897                                 std::min(16U, Alignment));
22898     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
22899                              Load1.getValue(1),
22900                              Load2.getValue(1));
22901
22902     SDValue NewVec = DAG.getUNDEF(RegVT);
22903     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
22904     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
22905     return DCI.CombineTo(N, NewVec, TF, true);
22906   }
22907
22908   return SDValue();
22909 }
22910
22911 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
22912 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
22913                                    const X86Subtarget *Subtarget) {
22914   StoreSDNode *St = cast<StoreSDNode>(N);
22915   EVT VT = St->getValue().getValueType();
22916   EVT StVT = St->getMemoryVT();
22917   SDLoc dl(St);
22918   SDValue StoredVal = St->getOperand(1);
22919   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22920
22921   // If we are saving a concatenation of two XMM registers, perform two stores.
22922   // On Sandy Bridge, 256-bit memory operations are executed by two
22923   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
22924   // memory  operation.
22925   unsigned Alignment = St->getAlignment();
22926   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
22927   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
22928       StVT == VT && !IsAligned) {
22929     unsigned NumElems = VT.getVectorNumElements();
22930     if (NumElems < 2)
22931       return SDValue();
22932
22933     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
22934     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
22935
22936     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
22937     SDValue Ptr0 = St->getBasePtr();
22938     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
22939
22940     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
22941                                 St->getPointerInfo(), St->isVolatile(),
22942                                 St->isNonTemporal(), Alignment);
22943     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
22944                                 St->getPointerInfo(), St->isVolatile(),
22945                                 St->isNonTemporal(),
22946                                 std::min(16U, Alignment));
22947     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
22948   }
22949
22950   // Optimize trunc store (of multiple scalars) to shuffle and store.
22951   // First, pack all of the elements in one place. Next, store to memory
22952   // in fewer chunks.
22953   if (St->isTruncatingStore() && VT.isVector()) {
22954     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22955     unsigned NumElems = VT.getVectorNumElements();
22956     assert(StVT != VT && "Cannot truncate to the same type");
22957     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
22958     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
22959
22960     // From, To sizes and ElemCount must be pow of two
22961     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
22962     // We are going to use the original vector elt for storing.
22963     // Accumulated smaller vector elements must be a multiple of the store size.
22964     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
22965
22966     unsigned SizeRatio  = FromSz / ToSz;
22967
22968     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
22969
22970     // Create a type on which we perform the shuffle
22971     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
22972             StVT.getScalarType(), NumElems*SizeRatio);
22973
22974     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
22975
22976     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
22977     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
22978     for (unsigned i = 0; i != NumElems; ++i)
22979       ShuffleVec[i] = i * SizeRatio;
22980
22981     // Can't shuffle using an illegal type.
22982     if (!TLI.isTypeLegal(WideVecVT))
22983       return SDValue();
22984
22985     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
22986                                          DAG.getUNDEF(WideVecVT),
22987                                          &ShuffleVec[0]);
22988     // At this point all of the data is stored at the bottom of the
22989     // register. We now need to save it to mem.
22990
22991     // Find the largest store unit
22992     MVT StoreType = MVT::i8;
22993     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
22994          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
22995       MVT Tp = (MVT::SimpleValueType)tp;
22996       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
22997         StoreType = Tp;
22998     }
22999
23000     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23001     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23002         (64 <= NumElems * ToSz))
23003       StoreType = MVT::f64;
23004
23005     // Bitcast the original vector into a vector of store-size units
23006     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23007             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23008     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23009     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
23010     SmallVector<SDValue, 8> Chains;
23011     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
23012                                         TLI.getPointerTy());
23013     SDValue Ptr = St->getBasePtr();
23014
23015     // Perform one or more big stores into memory.
23016     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23017       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23018                                    StoreType, ShuffWide,
23019                                    DAG.getIntPtrConstant(i));
23020       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23021                                 St->getPointerInfo(), St->isVolatile(),
23022                                 St->isNonTemporal(), St->getAlignment());
23023       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23024       Chains.push_back(Ch);
23025     }
23026
23027     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23028   }
23029
23030   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23031   // the FP state in cases where an emms may be missing.
23032   // A preferable solution to the general problem is to figure out the right
23033   // places to insert EMMS.  This qualifies as a quick hack.
23034
23035   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23036   if (VT.getSizeInBits() != 64)
23037     return SDValue();
23038
23039   const Function *F = DAG.getMachineFunction().getFunction();
23040   bool NoImplicitFloatOps = F->getAttributes().
23041     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
23042   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
23043                      && Subtarget->hasSSE2();
23044   if ((VT.isVector() ||
23045        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23046       isa<LoadSDNode>(St->getValue()) &&
23047       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23048       St->getChain().hasOneUse() && !St->isVolatile()) {
23049     SDNode* LdVal = St->getValue().getNode();
23050     LoadSDNode *Ld = nullptr;
23051     int TokenFactorIndex = -1;
23052     SmallVector<SDValue, 8> Ops;
23053     SDNode* ChainVal = St->getChain().getNode();
23054     // Must be a store of a load.  We currently handle two cases:  the load
23055     // is a direct child, and it's under an intervening TokenFactor.  It is
23056     // possible to dig deeper under nested TokenFactors.
23057     if (ChainVal == LdVal)
23058       Ld = cast<LoadSDNode>(St->getChain());
23059     else if (St->getValue().hasOneUse() &&
23060              ChainVal->getOpcode() == ISD::TokenFactor) {
23061       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23062         if (ChainVal->getOperand(i).getNode() == LdVal) {
23063           TokenFactorIndex = i;
23064           Ld = cast<LoadSDNode>(St->getValue());
23065         } else
23066           Ops.push_back(ChainVal->getOperand(i));
23067       }
23068     }
23069
23070     if (!Ld || !ISD::isNormalLoad(Ld))
23071       return SDValue();
23072
23073     // If this is not the MMX case, i.e. we are just turning i64 load/store
23074     // into f64 load/store, avoid the transformation if there are multiple
23075     // uses of the loaded value.
23076     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23077       return SDValue();
23078
23079     SDLoc LdDL(Ld);
23080     SDLoc StDL(N);
23081     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23082     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23083     // pair instead.
23084     if (Subtarget->is64Bit() || F64IsLegal) {
23085       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23086       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23087                                   Ld->getPointerInfo(), Ld->isVolatile(),
23088                                   Ld->isNonTemporal(), Ld->isInvariant(),
23089                                   Ld->getAlignment());
23090       SDValue NewChain = NewLd.getValue(1);
23091       if (TokenFactorIndex != -1) {
23092         Ops.push_back(NewChain);
23093         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23094       }
23095       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23096                           St->getPointerInfo(),
23097                           St->isVolatile(), St->isNonTemporal(),
23098                           St->getAlignment());
23099     }
23100
23101     // Otherwise, lower to two pairs of 32-bit loads / stores.
23102     SDValue LoAddr = Ld->getBasePtr();
23103     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23104                                  DAG.getConstant(4, MVT::i32));
23105
23106     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23107                                Ld->getPointerInfo(),
23108                                Ld->isVolatile(), Ld->isNonTemporal(),
23109                                Ld->isInvariant(), Ld->getAlignment());
23110     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23111                                Ld->getPointerInfo().getWithOffset(4),
23112                                Ld->isVolatile(), Ld->isNonTemporal(),
23113                                Ld->isInvariant(),
23114                                MinAlign(Ld->getAlignment(), 4));
23115
23116     SDValue NewChain = LoLd.getValue(1);
23117     if (TokenFactorIndex != -1) {
23118       Ops.push_back(LoLd);
23119       Ops.push_back(HiLd);
23120       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23121     }
23122
23123     LoAddr = St->getBasePtr();
23124     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23125                          DAG.getConstant(4, MVT::i32));
23126
23127     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23128                                 St->getPointerInfo(),
23129                                 St->isVolatile(), St->isNonTemporal(),
23130                                 St->getAlignment());
23131     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23132                                 St->getPointerInfo().getWithOffset(4),
23133                                 St->isVolatile(),
23134                                 St->isNonTemporal(),
23135                                 MinAlign(St->getAlignment(), 4));
23136     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23137   }
23138   return SDValue();
23139 }
23140
23141 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
23142 /// and return the operands for the horizontal operation in LHS and RHS.  A
23143 /// horizontal operation performs the binary operation on successive elements
23144 /// of its first operand, then on successive elements of its second operand,
23145 /// returning the resulting values in a vector.  For example, if
23146 ///   A = < float a0, float a1, float a2, float a3 >
23147 /// and
23148 ///   B = < float b0, float b1, float b2, float b3 >
23149 /// then the result of doing a horizontal operation on A and B is
23150 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23151 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23152 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23153 /// set to A, RHS to B, and the routine returns 'true'.
23154 /// Note that the binary operation should have the property that if one of the
23155 /// operands is UNDEF then the result is UNDEF.
23156 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23157   // Look for the following pattern: if
23158   //   A = < float a0, float a1, float a2, float a3 >
23159   //   B = < float b0, float b1, float b2, float b3 >
23160   // and
23161   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23162   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23163   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23164   // which is A horizontal-op B.
23165
23166   // At least one of the operands should be a vector shuffle.
23167   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23168       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23169     return false;
23170
23171   MVT VT = LHS.getSimpleValueType();
23172
23173   assert((VT.is128BitVector() || VT.is256BitVector()) &&
23174          "Unsupported vector type for horizontal add/sub");
23175
23176   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
23177   // operate independently on 128-bit lanes.
23178   unsigned NumElts = VT.getVectorNumElements();
23179   unsigned NumLanes = VT.getSizeInBits()/128;
23180   unsigned NumLaneElts = NumElts / NumLanes;
23181   assert((NumLaneElts % 2 == 0) &&
23182          "Vector type should have an even number of elements in each lane");
23183   unsigned HalfLaneElts = NumLaneElts/2;
23184
23185   // View LHS in the form
23186   //   LHS = VECTOR_SHUFFLE A, B, LMask
23187   // If LHS is not a shuffle then pretend it is the shuffle
23188   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
23189   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
23190   // type VT.
23191   SDValue A, B;
23192   SmallVector<int, 16> LMask(NumElts);
23193   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23194     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
23195       A = LHS.getOperand(0);
23196     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
23197       B = LHS.getOperand(1);
23198     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
23199     std::copy(Mask.begin(), Mask.end(), LMask.begin());
23200   } else {
23201     if (LHS.getOpcode() != ISD::UNDEF)
23202       A = LHS;
23203     for (unsigned i = 0; i != NumElts; ++i)
23204       LMask[i] = i;
23205   }
23206
23207   // Likewise, view RHS in the form
23208   //   RHS = VECTOR_SHUFFLE C, D, RMask
23209   SDValue C, D;
23210   SmallVector<int, 16> RMask(NumElts);
23211   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
23212     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
23213       C = RHS.getOperand(0);
23214     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
23215       D = RHS.getOperand(1);
23216     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
23217     std::copy(Mask.begin(), Mask.end(), RMask.begin());
23218   } else {
23219     if (RHS.getOpcode() != ISD::UNDEF)
23220       C = RHS;
23221     for (unsigned i = 0; i != NumElts; ++i)
23222       RMask[i] = i;
23223   }
23224
23225   // Check that the shuffles are both shuffling the same vectors.
23226   if (!(A == C && B == D) && !(A == D && B == C))
23227     return false;
23228
23229   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
23230   if (!A.getNode() && !B.getNode())
23231     return false;
23232
23233   // If A and B occur in reverse order in RHS, then "swap" them (which means
23234   // rewriting the mask).
23235   if (A != C)
23236     CommuteVectorShuffleMask(RMask, NumElts);
23237
23238   // At this point LHS and RHS are equivalent to
23239   //   LHS = VECTOR_SHUFFLE A, B, LMask
23240   //   RHS = VECTOR_SHUFFLE A, B, RMask
23241   // Check that the masks correspond to performing a horizontal operation.
23242   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
23243     for (unsigned i = 0; i != NumLaneElts; ++i) {
23244       int LIdx = LMask[i+l], RIdx = RMask[i+l];
23245
23246       // Ignore any UNDEF components.
23247       if (LIdx < 0 || RIdx < 0 ||
23248           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
23249           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
23250         continue;
23251
23252       // Check that successive elements are being operated on.  If not, this is
23253       // not a horizontal operation.
23254       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
23255       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
23256       if (!(LIdx == Index && RIdx == Index + 1) &&
23257           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
23258         return false;
23259     }
23260   }
23261
23262   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
23263   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
23264   return true;
23265 }
23266
23267 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
23268 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
23269                                   const X86Subtarget *Subtarget) {
23270   EVT VT = N->getValueType(0);
23271   SDValue LHS = N->getOperand(0);
23272   SDValue RHS = N->getOperand(1);
23273
23274   // Try to synthesize horizontal adds from adds of shuffles.
23275   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23276        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23277       isHorizontalBinOp(LHS, RHS, true))
23278     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
23279   return SDValue();
23280 }
23281
23282 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
23283 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
23284                                   const X86Subtarget *Subtarget) {
23285   EVT VT = N->getValueType(0);
23286   SDValue LHS = N->getOperand(0);
23287   SDValue RHS = N->getOperand(1);
23288
23289   // Try to synthesize horizontal subs from subs of shuffles.
23290   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
23291        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
23292       isHorizontalBinOp(LHS, RHS, false))
23293     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
23294   return SDValue();
23295 }
23296
23297 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
23298 /// X86ISD::FXOR nodes.
23299 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
23300   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
23301   // F[X]OR(0.0, x) -> x
23302   // F[X]OR(x, 0.0) -> x
23303   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23304     if (C->getValueAPF().isPosZero())
23305       return N->getOperand(1);
23306   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23307     if (C->getValueAPF().isPosZero())
23308       return N->getOperand(0);
23309   return SDValue();
23310 }
23311
23312 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
23313 /// X86ISD::FMAX nodes.
23314 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
23315   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
23316
23317   // Only perform optimizations if UnsafeMath is used.
23318   if (!DAG.getTarget().Options.UnsafeFPMath)
23319     return SDValue();
23320
23321   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
23322   // into FMINC and FMAXC, which are Commutative operations.
23323   unsigned NewOp = 0;
23324   switch (N->getOpcode()) {
23325     default: llvm_unreachable("unknown opcode");
23326     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
23327     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
23328   }
23329
23330   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
23331                      N->getOperand(0), N->getOperand(1));
23332 }
23333
23334 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
23335 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
23336   // FAND(0.0, x) -> 0.0
23337   // FAND(x, 0.0) -> 0.0
23338   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23339     if (C->getValueAPF().isPosZero())
23340       return N->getOperand(0);
23341   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23342     if (C->getValueAPF().isPosZero())
23343       return N->getOperand(1);
23344   return SDValue();
23345 }
23346
23347 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
23348 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
23349   // FANDN(x, 0.0) -> 0.0
23350   // FANDN(0.0, x) -> x
23351   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
23352     if (C->getValueAPF().isPosZero())
23353       return N->getOperand(1);
23354   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
23355     if (C->getValueAPF().isPosZero())
23356       return N->getOperand(1);
23357   return SDValue();
23358 }
23359
23360 static SDValue PerformBTCombine(SDNode *N,
23361                                 SelectionDAG &DAG,
23362                                 TargetLowering::DAGCombinerInfo &DCI) {
23363   // BT ignores high bits in the bit index operand.
23364   SDValue Op1 = N->getOperand(1);
23365   if (Op1.hasOneUse()) {
23366     unsigned BitWidth = Op1.getValueSizeInBits();
23367     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
23368     APInt KnownZero, KnownOne;
23369     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
23370                                           !DCI.isBeforeLegalizeOps());
23371     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23372     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
23373         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
23374       DCI.CommitTargetLoweringOpt(TLO);
23375   }
23376   return SDValue();
23377 }
23378
23379 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
23380   SDValue Op = N->getOperand(0);
23381   if (Op.getOpcode() == ISD::BITCAST)
23382     Op = Op.getOperand(0);
23383   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
23384   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
23385       VT.getVectorElementType().getSizeInBits() ==
23386       OpVT.getVectorElementType().getSizeInBits()) {
23387     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
23388   }
23389   return SDValue();
23390 }
23391
23392 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
23393                                                const X86Subtarget *Subtarget) {
23394   EVT VT = N->getValueType(0);
23395   if (!VT.isVector())
23396     return SDValue();
23397
23398   SDValue N0 = N->getOperand(0);
23399   SDValue N1 = N->getOperand(1);
23400   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
23401   SDLoc dl(N);
23402
23403   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
23404   // both SSE and AVX2 since there is no sign-extended shift right
23405   // operation on a vector with 64-bit elements.
23406   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
23407   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
23408   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
23409       N0.getOpcode() == ISD::SIGN_EXTEND)) {
23410     SDValue N00 = N0.getOperand(0);
23411
23412     // EXTLOAD has a better solution on AVX2,
23413     // it may be replaced with X86ISD::VSEXT node.
23414     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
23415       if (!ISD::isNormalLoad(N00.getNode()))
23416         return SDValue();
23417
23418     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
23419         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
23420                                   N00, N1);
23421       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
23422     }
23423   }
23424   return SDValue();
23425 }
23426
23427 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
23428                                   TargetLowering::DAGCombinerInfo &DCI,
23429                                   const X86Subtarget *Subtarget) {
23430   if (!DCI.isBeforeLegalizeOps())
23431     return SDValue();
23432
23433   if (!Subtarget->hasFp256())
23434     return SDValue();
23435
23436   EVT VT = N->getValueType(0);
23437   if (VT.isVector() && VT.getSizeInBits() == 256) {
23438     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23439     if (R.getNode())
23440       return R;
23441   }
23442
23443   return SDValue();
23444 }
23445
23446 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
23447                                  const X86Subtarget* Subtarget) {
23448   SDLoc dl(N);
23449   EVT VT = N->getValueType(0);
23450
23451   // Let legalize expand this if it isn't a legal type yet.
23452   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
23453     return SDValue();
23454
23455   EVT ScalarVT = VT.getScalarType();
23456   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
23457       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
23458     return SDValue();
23459
23460   SDValue A = N->getOperand(0);
23461   SDValue B = N->getOperand(1);
23462   SDValue C = N->getOperand(2);
23463
23464   bool NegA = (A.getOpcode() == ISD::FNEG);
23465   bool NegB = (B.getOpcode() == ISD::FNEG);
23466   bool NegC = (C.getOpcode() == ISD::FNEG);
23467
23468   // Negative multiplication when NegA xor NegB
23469   bool NegMul = (NegA != NegB);
23470   if (NegA)
23471     A = A.getOperand(0);
23472   if (NegB)
23473     B = B.getOperand(0);
23474   if (NegC)
23475     C = C.getOperand(0);
23476
23477   unsigned Opcode;
23478   if (!NegMul)
23479     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
23480   else
23481     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
23482
23483   return DAG.getNode(Opcode, dl, VT, A, B, C);
23484 }
23485
23486 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
23487                                   TargetLowering::DAGCombinerInfo &DCI,
23488                                   const X86Subtarget *Subtarget) {
23489   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
23490   //           (and (i32 x86isd::setcc_carry), 1)
23491   // This eliminates the zext. This transformation is necessary because
23492   // ISD::SETCC is always legalized to i8.
23493   SDLoc dl(N);
23494   SDValue N0 = N->getOperand(0);
23495   EVT VT = N->getValueType(0);
23496
23497   if (N0.getOpcode() == ISD::AND &&
23498       N0.hasOneUse() &&
23499       N0.getOperand(0).hasOneUse()) {
23500     SDValue N00 = N0.getOperand(0);
23501     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23502       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23503       if (!C || C->getZExtValue() != 1)
23504         return SDValue();
23505       return DAG.getNode(ISD::AND, dl, VT,
23506                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23507                                      N00.getOperand(0), N00.getOperand(1)),
23508                          DAG.getConstant(1, VT));
23509     }
23510   }
23511
23512   if (N0.getOpcode() == ISD::TRUNCATE &&
23513       N0.hasOneUse() &&
23514       N0.getOperand(0).hasOneUse()) {
23515     SDValue N00 = N0.getOperand(0);
23516     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
23517       return DAG.getNode(ISD::AND, dl, VT,
23518                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
23519                                      N00.getOperand(0), N00.getOperand(1)),
23520                          DAG.getConstant(1, VT));
23521     }
23522   }
23523   if (VT.is256BitVector()) {
23524     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
23525     if (R.getNode())
23526       return R;
23527   }
23528
23529   return SDValue();
23530 }
23531
23532 // Optimize x == -y --> x+y == 0
23533 //          x != -y --> x+y != 0
23534 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
23535                                       const X86Subtarget* Subtarget) {
23536   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
23537   SDValue LHS = N->getOperand(0);
23538   SDValue RHS = N->getOperand(1);
23539   EVT VT = N->getValueType(0);
23540   SDLoc DL(N);
23541
23542   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
23543     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
23544       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
23545         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23546                                    LHS.getValueType(), RHS, LHS.getOperand(1));
23547         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23548                             addV, DAG.getConstant(0, addV.getValueType()), CC);
23549       }
23550   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
23551     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
23552       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
23553         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
23554                                    RHS.getValueType(), LHS, RHS.getOperand(1));
23555         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
23556                             addV, DAG.getConstant(0, addV.getValueType()), CC);
23557       }
23558
23559   if (VT.getScalarType() == MVT::i1) {
23560     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
23561       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
23562     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
23563     if (!IsSEXT0 && !IsVZero0)
23564       return SDValue();
23565     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
23566       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
23567     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
23568
23569     if (!IsSEXT1 && !IsVZero1)
23570       return SDValue();
23571
23572     if (IsSEXT0 && IsVZero1) {
23573       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
23574       if (CC == ISD::SETEQ)
23575         return DAG.getNOT(DL, LHS.getOperand(0), VT);
23576       return LHS.getOperand(0);
23577     }
23578     if (IsSEXT1 && IsVZero0) {
23579       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
23580       if (CC == ISD::SETEQ)
23581         return DAG.getNOT(DL, RHS.getOperand(0), VT);
23582       return RHS.getOperand(0);
23583     }
23584   }
23585
23586   return SDValue();
23587 }
23588
23589 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
23590                                       const X86Subtarget *Subtarget) {
23591   SDLoc dl(N);
23592   MVT VT = N->getOperand(1)->getSimpleValueType(0);
23593   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
23594          "X86insertps is only defined for v4x32");
23595
23596   SDValue Ld = N->getOperand(1);
23597   if (MayFoldLoad(Ld)) {
23598     // Extract the countS bits from the immediate so we can get the proper
23599     // address when narrowing the vector load to a specific element.
23600     // When the second source op is a memory address, interps doesn't use
23601     // countS and just gets an f32 from that address.
23602     unsigned DestIndex =
23603         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
23604     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
23605   } else
23606     return SDValue();
23607
23608   // Create this as a scalar to vector to match the instruction pattern.
23609   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
23610   // countS bits are ignored when loading from memory on insertps, which
23611   // means we don't need to explicitly set them to 0.
23612   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
23613                      LoadScalarToVector, N->getOperand(2));
23614 }
23615
23616 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
23617 // as "sbb reg,reg", since it can be extended without zext and produces
23618 // an all-ones bit which is more useful than 0/1 in some cases.
23619 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
23620                                MVT VT) {
23621   if (VT == MVT::i8)
23622     return DAG.getNode(ISD::AND, DL, VT,
23623                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23624                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
23625                        DAG.getConstant(1, VT));
23626   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
23627   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
23628                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
23629                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
23630 }
23631
23632 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
23633 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
23634                                    TargetLowering::DAGCombinerInfo &DCI,
23635                                    const X86Subtarget *Subtarget) {
23636   SDLoc DL(N);
23637   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
23638   SDValue EFLAGS = N->getOperand(1);
23639
23640   if (CC == X86::COND_A) {
23641     // Try to convert COND_A into COND_B in an attempt to facilitate
23642     // materializing "setb reg".
23643     //
23644     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
23645     // cannot take an immediate as its first operand.
23646     //
23647     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
23648         EFLAGS.getValueType().isInteger() &&
23649         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
23650       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
23651                                    EFLAGS.getNode()->getVTList(),
23652                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
23653       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
23654       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
23655     }
23656   }
23657
23658   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
23659   // a zext and produces an all-ones bit which is more useful than 0/1 in some
23660   // cases.
23661   if (CC == X86::COND_B)
23662     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
23663
23664   SDValue Flags;
23665
23666   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23667   if (Flags.getNode()) {
23668     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23669     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
23670   }
23671
23672   return SDValue();
23673 }
23674
23675 // Optimize branch condition evaluation.
23676 //
23677 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
23678                                     TargetLowering::DAGCombinerInfo &DCI,
23679                                     const X86Subtarget *Subtarget) {
23680   SDLoc DL(N);
23681   SDValue Chain = N->getOperand(0);
23682   SDValue Dest = N->getOperand(1);
23683   SDValue EFLAGS = N->getOperand(3);
23684   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
23685
23686   SDValue Flags;
23687
23688   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
23689   if (Flags.getNode()) {
23690     SDValue Cond = DAG.getConstant(CC, MVT::i8);
23691     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
23692                        Flags);
23693   }
23694
23695   return SDValue();
23696 }
23697
23698 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
23699                                                          SelectionDAG &DAG) {
23700   // Take advantage of vector comparisons producing 0 or -1 in each lane to
23701   // optimize away operation when it's from a constant.
23702   //
23703   // The general transformation is:
23704   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
23705   //       AND(VECTOR_CMP(x,y), constant2)
23706   //    constant2 = UNARYOP(constant)
23707
23708   // Early exit if this isn't a vector operation, the operand of the
23709   // unary operation isn't a bitwise AND, or if the sizes of the operations
23710   // aren't the same.
23711   EVT VT = N->getValueType(0);
23712   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
23713       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
23714       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
23715     return SDValue();
23716
23717   // Now check that the other operand of the AND is a constant. We could
23718   // make the transformation for non-constant splats as well, but it's unclear
23719   // that would be a benefit as it would not eliminate any operations, just
23720   // perform one more step in scalar code before moving to the vector unit.
23721   if (BuildVectorSDNode *BV =
23722           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
23723     // Bail out if the vector isn't a constant.
23724     if (!BV->isConstant())
23725       return SDValue();
23726
23727     // Everything checks out. Build up the new and improved node.
23728     SDLoc DL(N);
23729     EVT IntVT = BV->getValueType(0);
23730     // Create a new constant of the appropriate type for the transformed
23731     // DAG.
23732     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
23733     // The AND node needs bitcasts to/from an integer vector type around it.
23734     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
23735     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
23736                                  N->getOperand(0)->getOperand(0), MaskConst);
23737     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
23738     return Res;
23739   }
23740
23741   return SDValue();
23742 }
23743
23744 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
23745                                         const X86TargetLowering *XTLI) {
23746   // First try to optimize away the conversion entirely when it's
23747   // conditionally from a constant. Vectors only.
23748   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
23749   if (Res != SDValue())
23750     return Res;
23751
23752   // Now move on to more general possibilities.
23753   SDValue Op0 = N->getOperand(0);
23754   EVT InVT = Op0->getValueType(0);
23755
23756   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
23757   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
23758     SDLoc dl(N);
23759     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
23760     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
23761     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
23762   }
23763
23764   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
23765   // a 32-bit target where SSE doesn't support i64->FP operations.
23766   if (Op0.getOpcode() == ISD::LOAD) {
23767     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
23768     EVT VT = Ld->getValueType(0);
23769     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
23770         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
23771         !XTLI->getSubtarget()->is64Bit() &&
23772         VT == MVT::i64) {
23773       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
23774                                           Ld->getChain(), Op0, DAG);
23775       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
23776       return FILDChain;
23777     }
23778   }
23779   return SDValue();
23780 }
23781
23782 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
23783 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
23784                                  X86TargetLowering::DAGCombinerInfo &DCI) {
23785   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
23786   // the result is either zero or one (depending on the input carry bit).
23787   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
23788   if (X86::isZeroNode(N->getOperand(0)) &&
23789       X86::isZeroNode(N->getOperand(1)) &&
23790       // We don't have a good way to replace an EFLAGS use, so only do this when
23791       // dead right now.
23792       SDValue(N, 1).use_empty()) {
23793     SDLoc DL(N);
23794     EVT VT = N->getValueType(0);
23795     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
23796     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
23797                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
23798                                            DAG.getConstant(X86::COND_B,MVT::i8),
23799                                            N->getOperand(2)),
23800                                DAG.getConstant(1, VT));
23801     return DCI.CombineTo(N, Res1, CarryOut);
23802   }
23803
23804   return SDValue();
23805 }
23806
23807 // fold (add Y, (sete  X, 0)) -> adc  0, Y
23808 //      (add Y, (setne X, 0)) -> sbb -1, Y
23809 //      (sub (sete  X, 0), Y) -> sbb  0, Y
23810 //      (sub (setne X, 0), Y) -> adc -1, Y
23811 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
23812   SDLoc DL(N);
23813
23814   // Look through ZExts.
23815   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
23816   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
23817     return SDValue();
23818
23819   SDValue SetCC = Ext.getOperand(0);
23820   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
23821     return SDValue();
23822
23823   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
23824   if (CC != X86::COND_E && CC != X86::COND_NE)
23825     return SDValue();
23826
23827   SDValue Cmp = SetCC.getOperand(1);
23828   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
23829       !X86::isZeroNode(Cmp.getOperand(1)) ||
23830       !Cmp.getOperand(0).getValueType().isInteger())
23831     return SDValue();
23832
23833   SDValue CmpOp0 = Cmp.getOperand(0);
23834   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
23835                                DAG.getConstant(1, CmpOp0.getValueType()));
23836
23837   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
23838   if (CC == X86::COND_NE)
23839     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
23840                        DL, OtherVal.getValueType(), OtherVal,
23841                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
23842   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
23843                      DL, OtherVal.getValueType(), OtherVal,
23844                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
23845 }
23846
23847 /// PerformADDCombine - Do target-specific dag combines on integer adds.
23848 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
23849                                  const X86Subtarget *Subtarget) {
23850   EVT VT = N->getValueType(0);
23851   SDValue Op0 = N->getOperand(0);
23852   SDValue Op1 = N->getOperand(1);
23853
23854   // Try to synthesize horizontal adds from adds of shuffles.
23855   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23856        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23857       isHorizontalBinOp(Op0, Op1, true))
23858     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
23859
23860   return OptimizeConditionalInDecrement(N, DAG);
23861 }
23862
23863 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
23864                                  const X86Subtarget *Subtarget) {
23865   SDValue Op0 = N->getOperand(0);
23866   SDValue Op1 = N->getOperand(1);
23867
23868   // X86 can't encode an immediate LHS of a sub. See if we can push the
23869   // negation into a preceding instruction.
23870   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
23871     // If the RHS of the sub is a XOR with one use and a constant, invert the
23872     // immediate. Then add one to the LHS of the sub so we can turn
23873     // X-Y -> X+~Y+1, saving one register.
23874     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
23875         isa<ConstantSDNode>(Op1.getOperand(1))) {
23876       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
23877       EVT VT = Op0.getValueType();
23878       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
23879                                    Op1.getOperand(0),
23880                                    DAG.getConstant(~XorC, VT));
23881       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
23882                          DAG.getConstant(C->getAPIntValue()+1, VT));
23883     }
23884   }
23885
23886   // Try to synthesize horizontal adds from adds of shuffles.
23887   EVT VT = N->getValueType(0);
23888   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
23889        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
23890       isHorizontalBinOp(Op0, Op1, true))
23891     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
23892
23893   return OptimizeConditionalInDecrement(N, DAG);
23894 }
23895
23896 /// performVZEXTCombine - Performs build vector combines
23897 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
23898                                         TargetLowering::DAGCombinerInfo &DCI,
23899                                         const X86Subtarget *Subtarget) {
23900   // (vzext (bitcast (vzext (x)) -> (vzext x)
23901   SDValue In = N->getOperand(0);
23902   while (In.getOpcode() == ISD::BITCAST)
23903     In = In.getOperand(0);
23904
23905   if (In.getOpcode() != X86ISD::VZEXT)
23906     return SDValue();
23907
23908   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
23909                      In.getOperand(0));
23910 }
23911
23912 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
23913                                              DAGCombinerInfo &DCI) const {
23914   SelectionDAG &DAG = DCI.DAG;
23915   switch (N->getOpcode()) {
23916   default: break;
23917   case ISD::EXTRACT_VECTOR_ELT:
23918     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
23919   case ISD::VSELECT:
23920   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
23921   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
23922   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
23923   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
23924   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
23925   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
23926   case ISD::SHL:
23927   case ISD::SRA:
23928   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
23929   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
23930   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
23931   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
23932   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
23933   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
23934   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
23935   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
23936   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
23937   case X86ISD::FXOR:
23938   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
23939   case X86ISD::FMIN:
23940   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
23941   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
23942   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
23943   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
23944   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
23945   case ISD::ANY_EXTEND:
23946   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
23947   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
23948   case ISD::SIGN_EXTEND_INREG:
23949     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
23950   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
23951   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
23952   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
23953   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
23954   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
23955   case X86ISD::SHUFP:       // Handle all target specific shuffles
23956   case X86ISD::PALIGNR:
23957   case X86ISD::UNPCKH:
23958   case X86ISD::UNPCKL:
23959   case X86ISD::MOVHLPS:
23960   case X86ISD::MOVLHPS:
23961   case X86ISD::PSHUFB:
23962   case X86ISD::PSHUFD:
23963   case X86ISD::PSHUFHW:
23964   case X86ISD::PSHUFLW:
23965   case X86ISD::MOVSS:
23966   case X86ISD::MOVSD:
23967   case X86ISD::VPERMILPI:
23968   case X86ISD::VPERM2X128:
23969   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
23970   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
23971   case ISD::INTRINSIC_WO_CHAIN:
23972     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
23973   case X86ISD::INSERTPS:
23974     return PerformINSERTPSCombine(N, DAG, Subtarget);
23975   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
23976   }
23977
23978   return SDValue();
23979 }
23980
23981 /// isTypeDesirableForOp - Return true if the target has native support for
23982 /// the specified value type and it is 'desirable' to use the type for the
23983 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
23984 /// instruction encodings are longer and some i16 instructions are slow.
23985 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
23986   if (!isTypeLegal(VT))
23987     return false;
23988   if (VT != MVT::i16)
23989     return true;
23990
23991   switch (Opc) {
23992   default:
23993     return true;
23994   case ISD::LOAD:
23995   case ISD::SIGN_EXTEND:
23996   case ISD::ZERO_EXTEND:
23997   case ISD::ANY_EXTEND:
23998   case ISD::SHL:
23999   case ISD::SRL:
24000   case ISD::SUB:
24001   case ISD::ADD:
24002   case ISD::MUL:
24003   case ISD::AND:
24004   case ISD::OR:
24005   case ISD::XOR:
24006     return false;
24007   }
24008 }
24009
24010 /// IsDesirableToPromoteOp - This method query the target whether it is
24011 /// beneficial for dag combiner to promote the specified node. If true, it
24012 /// should return the desired promotion type by reference.
24013 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
24014   EVT VT = Op.getValueType();
24015   if (VT != MVT::i16)
24016     return false;
24017
24018   bool Promote = false;
24019   bool Commute = false;
24020   switch (Op.getOpcode()) {
24021   default: break;
24022   case ISD::LOAD: {
24023     LoadSDNode *LD = cast<LoadSDNode>(Op);
24024     // If the non-extending load has a single use and it's not live out, then it
24025     // might be folded.
24026     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
24027                                                      Op.hasOneUse()*/) {
24028       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
24029              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
24030         // The only case where we'd want to promote LOAD (rather then it being
24031         // promoted as an operand is when it's only use is liveout.
24032         if (UI->getOpcode() != ISD::CopyToReg)
24033           return false;
24034       }
24035     }
24036     Promote = true;
24037     break;
24038   }
24039   case ISD::SIGN_EXTEND:
24040   case ISD::ZERO_EXTEND:
24041   case ISD::ANY_EXTEND:
24042     Promote = true;
24043     break;
24044   case ISD::SHL:
24045   case ISD::SRL: {
24046     SDValue N0 = Op.getOperand(0);
24047     // Look out for (store (shl (load), x)).
24048     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
24049       return false;
24050     Promote = true;
24051     break;
24052   }
24053   case ISD::ADD:
24054   case ISD::MUL:
24055   case ISD::AND:
24056   case ISD::OR:
24057   case ISD::XOR:
24058     Commute = true;
24059     // fallthrough
24060   case ISD::SUB: {
24061     SDValue N0 = Op.getOperand(0);
24062     SDValue N1 = Op.getOperand(1);
24063     if (!Commute && MayFoldLoad(N1))
24064       return false;
24065     // Avoid disabling potential load folding opportunities.
24066     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
24067       return false;
24068     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
24069       return false;
24070     Promote = true;
24071   }
24072   }
24073
24074   PVT = MVT::i32;
24075   return Promote;
24076 }
24077
24078 //===----------------------------------------------------------------------===//
24079 //                           X86 Inline Assembly Support
24080 //===----------------------------------------------------------------------===//
24081
24082 namespace {
24083   // Helper to match a string separated by whitespace.
24084   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
24085     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
24086
24087     for (unsigned i = 0, e = args.size(); i != e; ++i) {
24088       StringRef piece(*args[i]);
24089       if (!s.startswith(piece)) // Check if the piece matches.
24090         return false;
24091
24092       s = s.substr(piece.size());
24093       StringRef::size_type pos = s.find_first_not_of(" \t");
24094       if (pos == 0) // We matched a prefix.
24095         return false;
24096
24097       s = s.substr(pos);
24098     }
24099
24100     return s.empty();
24101   }
24102   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
24103 }
24104
24105 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
24106
24107   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
24108     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
24109         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
24110         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
24111
24112       if (AsmPieces.size() == 3)
24113         return true;
24114       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
24115         return true;
24116     }
24117   }
24118   return false;
24119 }
24120
24121 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
24122   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
24123
24124   std::string AsmStr = IA->getAsmString();
24125
24126   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
24127   if (!Ty || Ty->getBitWidth() % 16 != 0)
24128     return false;
24129
24130   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
24131   SmallVector<StringRef, 4> AsmPieces;
24132   SplitString(AsmStr, AsmPieces, ";\n");
24133
24134   switch (AsmPieces.size()) {
24135   default: return false;
24136   case 1:
24137     // FIXME: this should verify that we are targeting a 486 or better.  If not,
24138     // we will turn this bswap into something that will be lowered to logical
24139     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
24140     // lower so don't worry about this.
24141     // bswap $0
24142     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
24143         matchAsm(AsmPieces[0], "bswapl", "$0") ||
24144         matchAsm(AsmPieces[0], "bswapq", "$0") ||
24145         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
24146         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
24147         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
24148       // No need to check constraints, nothing other than the equivalent of
24149       // "=r,0" would be valid here.
24150       return IntrinsicLowering::LowerToByteSwap(CI);
24151     }
24152
24153     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
24154     if (CI->getType()->isIntegerTy(16) &&
24155         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24156         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
24157          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
24158       AsmPieces.clear();
24159       const std::string &ConstraintsStr = IA->getConstraintString();
24160       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24161       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24162       if (clobbersFlagRegisters(AsmPieces))
24163         return IntrinsicLowering::LowerToByteSwap(CI);
24164     }
24165     break;
24166   case 3:
24167     if (CI->getType()->isIntegerTy(32) &&
24168         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
24169         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
24170         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
24171         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
24172       AsmPieces.clear();
24173       const std::string &ConstraintsStr = IA->getConstraintString();
24174       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
24175       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
24176       if (clobbersFlagRegisters(AsmPieces))
24177         return IntrinsicLowering::LowerToByteSwap(CI);
24178     }
24179
24180     if (CI->getType()->isIntegerTy(64)) {
24181       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
24182       if (Constraints.size() >= 2 &&
24183           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
24184           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
24185         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
24186         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
24187             matchAsm(AsmPieces[1], "bswap", "%edx") &&
24188             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
24189           return IntrinsicLowering::LowerToByteSwap(CI);
24190       }
24191     }
24192     break;
24193   }
24194   return false;
24195 }
24196
24197 /// getConstraintType - Given a constraint letter, return the type of
24198 /// constraint it is for this target.
24199 X86TargetLowering::ConstraintType
24200 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
24201   if (Constraint.size() == 1) {
24202     switch (Constraint[0]) {
24203     case 'R':
24204     case 'q':
24205     case 'Q':
24206     case 'f':
24207     case 't':
24208     case 'u':
24209     case 'y':
24210     case 'x':
24211     case 'Y':
24212     case 'l':
24213       return C_RegisterClass;
24214     case 'a':
24215     case 'b':
24216     case 'c':
24217     case 'd':
24218     case 'S':
24219     case 'D':
24220     case 'A':
24221       return C_Register;
24222     case 'I':
24223     case 'J':
24224     case 'K':
24225     case 'L':
24226     case 'M':
24227     case 'N':
24228     case 'G':
24229     case 'C':
24230     case 'e':
24231     case 'Z':
24232       return C_Other;
24233     default:
24234       break;
24235     }
24236   }
24237   return TargetLowering::getConstraintType(Constraint);
24238 }
24239
24240 /// Examine constraint type and operand type and determine a weight value.
24241 /// This object must already have been set up with the operand type
24242 /// and the current alternative constraint selected.
24243 TargetLowering::ConstraintWeight
24244   X86TargetLowering::getSingleConstraintMatchWeight(
24245     AsmOperandInfo &info, const char *constraint) const {
24246   ConstraintWeight weight = CW_Invalid;
24247   Value *CallOperandVal = info.CallOperandVal;
24248     // If we don't have a value, we can't do a match,
24249     // but allow it at the lowest weight.
24250   if (!CallOperandVal)
24251     return CW_Default;
24252   Type *type = CallOperandVal->getType();
24253   // Look at the constraint type.
24254   switch (*constraint) {
24255   default:
24256     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
24257   case 'R':
24258   case 'q':
24259   case 'Q':
24260   case 'a':
24261   case 'b':
24262   case 'c':
24263   case 'd':
24264   case 'S':
24265   case 'D':
24266   case 'A':
24267     if (CallOperandVal->getType()->isIntegerTy())
24268       weight = CW_SpecificReg;
24269     break;
24270   case 'f':
24271   case 't':
24272   case 'u':
24273     if (type->isFloatingPointTy())
24274       weight = CW_SpecificReg;
24275     break;
24276   case 'y':
24277     if (type->isX86_MMXTy() && Subtarget->hasMMX())
24278       weight = CW_SpecificReg;
24279     break;
24280   case 'x':
24281   case 'Y':
24282     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
24283         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
24284       weight = CW_Register;
24285     break;
24286   case 'I':
24287     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
24288       if (C->getZExtValue() <= 31)
24289         weight = CW_Constant;
24290     }
24291     break;
24292   case 'J':
24293     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24294       if (C->getZExtValue() <= 63)
24295         weight = CW_Constant;
24296     }
24297     break;
24298   case 'K':
24299     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24300       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
24301         weight = CW_Constant;
24302     }
24303     break;
24304   case 'L':
24305     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24306       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
24307         weight = CW_Constant;
24308     }
24309     break;
24310   case 'M':
24311     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24312       if (C->getZExtValue() <= 3)
24313         weight = CW_Constant;
24314     }
24315     break;
24316   case 'N':
24317     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24318       if (C->getZExtValue() <= 0xff)
24319         weight = CW_Constant;
24320     }
24321     break;
24322   case 'G':
24323   case 'C':
24324     if (dyn_cast<ConstantFP>(CallOperandVal)) {
24325       weight = CW_Constant;
24326     }
24327     break;
24328   case 'e':
24329     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24330       if ((C->getSExtValue() >= -0x80000000LL) &&
24331           (C->getSExtValue() <= 0x7fffffffLL))
24332         weight = CW_Constant;
24333     }
24334     break;
24335   case 'Z':
24336     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
24337       if (C->getZExtValue() <= 0xffffffff)
24338         weight = CW_Constant;
24339     }
24340     break;
24341   }
24342   return weight;
24343 }
24344
24345 /// LowerXConstraint - try to replace an X constraint, which matches anything,
24346 /// with another that has more specific requirements based on the type of the
24347 /// corresponding operand.
24348 const char *X86TargetLowering::
24349 LowerXConstraint(EVT ConstraintVT) const {
24350   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
24351   // 'f' like normal targets.
24352   if (ConstraintVT.isFloatingPoint()) {
24353     if (Subtarget->hasSSE2())
24354       return "Y";
24355     if (Subtarget->hasSSE1())
24356       return "x";
24357   }
24358
24359   return TargetLowering::LowerXConstraint(ConstraintVT);
24360 }
24361
24362 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
24363 /// vector.  If it is invalid, don't add anything to Ops.
24364 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
24365                                                      std::string &Constraint,
24366                                                      std::vector<SDValue>&Ops,
24367                                                      SelectionDAG &DAG) const {
24368   SDValue Result;
24369
24370   // Only support length 1 constraints for now.
24371   if (Constraint.length() > 1) return;
24372
24373   char ConstraintLetter = Constraint[0];
24374   switch (ConstraintLetter) {
24375   default: break;
24376   case 'I':
24377     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24378       if (C->getZExtValue() <= 31) {
24379         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24380         break;
24381       }
24382     }
24383     return;
24384   case 'J':
24385     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24386       if (C->getZExtValue() <= 63) {
24387         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24388         break;
24389       }
24390     }
24391     return;
24392   case 'K':
24393     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24394       if (isInt<8>(C->getSExtValue())) {
24395         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24396         break;
24397       }
24398     }
24399     return;
24400   case 'N':
24401     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24402       if (C->getZExtValue() <= 255) {
24403         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24404         break;
24405       }
24406     }
24407     return;
24408   case 'e': {
24409     // 32-bit signed value
24410     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24411       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24412                                            C->getSExtValue())) {
24413         // Widen to 64 bits here to get it sign extended.
24414         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
24415         break;
24416       }
24417     // FIXME gcc accepts some relocatable values here too, but only in certain
24418     // memory models; it's complicated.
24419     }
24420     return;
24421   }
24422   case 'Z': {
24423     // 32-bit unsigned value
24424     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
24425       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
24426                                            C->getZExtValue())) {
24427         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
24428         break;
24429       }
24430     }
24431     // FIXME gcc accepts some relocatable values here too, but only in certain
24432     // memory models; it's complicated.
24433     return;
24434   }
24435   case 'i': {
24436     // Literal immediates are always ok.
24437     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
24438       // Widen to 64 bits here to get it sign extended.
24439       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
24440       break;
24441     }
24442
24443     // In any sort of PIC mode addresses need to be computed at runtime by
24444     // adding in a register or some sort of table lookup.  These can't
24445     // be used as immediates.
24446     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
24447       return;
24448
24449     // If we are in non-pic codegen mode, we allow the address of a global (with
24450     // an optional displacement) to be used with 'i'.
24451     GlobalAddressSDNode *GA = nullptr;
24452     int64_t Offset = 0;
24453
24454     // Match either (GA), (GA+C), (GA+C1+C2), etc.
24455     while (1) {
24456       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
24457         Offset += GA->getOffset();
24458         break;
24459       } else if (Op.getOpcode() == ISD::ADD) {
24460         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24461           Offset += C->getZExtValue();
24462           Op = Op.getOperand(0);
24463           continue;
24464         }
24465       } else if (Op.getOpcode() == ISD::SUB) {
24466         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
24467           Offset += -C->getZExtValue();
24468           Op = Op.getOperand(0);
24469           continue;
24470         }
24471       }
24472
24473       // Otherwise, this isn't something we can handle, reject it.
24474       return;
24475     }
24476
24477     const GlobalValue *GV = GA->getGlobal();
24478     // If we require an extra load to get this address, as in PIC mode, we
24479     // can't accept it.
24480     if (isGlobalStubReference(
24481             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
24482       return;
24483
24484     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
24485                                         GA->getValueType(0), Offset);
24486     break;
24487   }
24488   }
24489
24490   if (Result.getNode()) {
24491     Ops.push_back(Result);
24492     return;
24493   }
24494   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
24495 }
24496
24497 std::pair<unsigned, const TargetRegisterClass*>
24498 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
24499                                                 MVT VT) const {
24500   // First, see if this is a constraint that directly corresponds to an LLVM
24501   // register class.
24502   if (Constraint.size() == 1) {
24503     // GCC Constraint Letters
24504     switch (Constraint[0]) {
24505     default: break;
24506       // TODO: Slight differences here in allocation order and leaving
24507       // RIP in the class. Do they matter any more here than they do
24508       // in the normal allocation?
24509     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
24510       if (Subtarget->is64Bit()) {
24511         if (VT == MVT::i32 || VT == MVT::f32)
24512           return std::make_pair(0U, &X86::GR32RegClass);
24513         if (VT == MVT::i16)
24514           return std::make_pair(0U, &X86::GR16RegClass);
24515         if (VT == MVT::i8 || VT == MVT::i1)
24516           return std::make_pair(0U, &X86::GR8RegClass);
24517         if (VT == MVT::i64 || VT == MVT::f64)
24518           return std::make_pair(0U, &X86::GR64RegClass);
24519         break;
24520       }
24521       // 32-bit fallthrough
24522     case 'Q':   // Q_REGS
24523       if (VT == MVT::i32 || VT == MVT::f32)
24524         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
24525       if (VT == MVT::i16)
24526         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
24527       if (VT == MVT::i8 || VT == MVT::i1)
24528         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
24529       if (VT == MVT::i64)
24530         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
24531       break;
24532     case 'r':   // GENERAL_REGS
24533     case 'l':   // INDEX_REGS
24534       if (VT == MVT::i8 || VT == MVT::i1)
24535         return std::make_pair(0U, &X86::GR8RegClass);
24536       if (VT == MVT::i16)
24537         return std::make_pair(0U, &X86::GR16RegClass);
24538       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
24539         return std::make_pair(0U, &X86::GR32RegClass);
24540       return std::make_pair(0U, &X86::GR64RegClass);
24541     case 'R':   // LEGACY_REGS
24542       if (VT == MVT::i8 || VT == MVT::i1)
24543         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
24544       if (VT == MVT::i16)
24545         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
24546       if (VT == MVT::i32 || !Subtarget->is64Bit())
24547         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
24548       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
24549     case 'f':  // FP Stack registers.
24550       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
24551       // value to the correct fpstack register class.
24552       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
24553         return std::make_pair(0U, &X86::RFP32RegClass);
24554       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
24555         return std::make_pair(0U, &X86::RFP64RegClass);
24556       return std::make_pair(0U, &X86::RFP80RegClass);
24557     case 'y':   // MMX_REGS if MMX allowed.
24558       if (!Subtarget->hasMMX()) break;
24559       return std::make_pair(0U, &X86::VR64RegClass);
24560     case 'Y':   // SSE_REGS if SSE2 allowed
24561       if (!Subtarget->hasSSE2()) break;
24562       // FALL THROUGH.
24563     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
24564       if (!Subtarget->hasSSE1()) break;
24565
24566       switch (VT.SimpleTy) {
24567       default: break;
24568       // Scalar SSE types.
24569       case MVT::f32:
24570       case MVT::i32:
24571         return std::make_pair(0U, &X86::FR32RegClass);
24572       case MVT::f64:
24573       case MVT::i64:
24574         return std::make_pair(0U, &X86::FR64RegClass);
24575       // Vector types.
24576       case MVT::v16i8:
24577       case MVT::v8i16:
24578       case MVT::v4i32:
24579       case MVT::v2i64:
24580       case MVT::v4f32:
24581       case MVT::v2f64:
24582         return std::make_pair(0U, &X86::VR128RegClass);
24583       // AVX types.
24584       case MVT::v32i8:
24585       case MVT::v16i16:
24586       case MVT::v8i32:
24587       case MVT::v4i64:
24588       case MVT::v8f32:
24589       case MVT::v4f64:
24590         return std::make_pair(0U, &X86::VR256RegClass);
24591       case MVT::v8f64:
24592       case MVT::v16f32:
24593       case MVT::v16i32:
24594       case MVT::v8i64:
24595         return std::make_pair(0U, &X86::VR512RegClass);
24596       }
24597       break;
24598     }
24599   }
24600
24601   // Use the default implementation in TargetLowering to convert the register
24602   // constraint into a member of a register class.
24603   std::pair<unsigned, const TargetRegisterClass*> Res;
24604   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
24605
24606   // Not found as a standard register?
24607   if (!Res.second) {
24608     // Map st(0) -> st(7) -> ST0
24609     if (Constraint.size() == 7 && Constraint[0] == '{' &&
24610         tolower(Constraint[1]) == 's' &&
24611         tolower(Constraint[2]) == 't' &&
24612         Constraint[3] == '(' &&
24613         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
24614         Constraint[5] == ')' &&
24615         Constraint[6] == '}') {
24616
24617       Res.first = X86::FP0+Constraint[4]-'0';
24618       Res.second = &X86::RFP80RegClass;
24619       return Res;
24620     }
24621
24622     // GCC allows "st(0)" to be called just plain "st".
24623     if (StringRef("{st}").equals_lower(Constraint)) {
24624       Res.first = X86::FP0;
24625       Res.second = &X86::RFP80RegClass;
24626       return Res;
24627     }
24628
24629     // flags -> EFLAGS
24630     if (StringRef("{flags}").equals_lower(Constraint)) {
24631       Res.first = X86::EFLAGS;
24632       Res.second = &X86::CCRRegClass;
24633       return Res;
24634     }
24635
24636     // 'A' means EAX + EDX.
24637     if (Constraint == "A") {
24638       Res.first = X86::EAX;
24639       Res.second = &X86::GR32_ADRegClass;
24640       return Res;
24641     }
24642     return Res;
24643   }
24644
24645   // Otherwise, check to see if this is a register class of the wrong value
24646   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
24647   // turn into {ax},{dx}.
24648   if (Res.second->hasType(VT))
24649     return Res;   // Correct type already, nothing to do.
24650
24651   // All of the single-register GCC register classes map their values onto
24652   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
24653   // really want an 8-bit or 32-bit register, map to the appropriate register
24654   // class and return the appropriate register.
24655   if (Res.second == &X86::GR16RegClass) {
24656     if (VT == MVT::i8 || VT == MVT::i1) {
24657       unsigned DestReg = 0;
24658       switch (Res.first) {
24659       default: break;
24660       case X86::AX: DestReg = X86::AL; break;
24661       case X86::DX: DestReg = X86::DL; break;
24662       case X86::CX: DestReg = X86::CL; break;
24663       case X86::BX: DestReg = X86::BL; break;
24664       }
24665       if (DestReg) {
24666         Res.first = DestReg;
24667         Res.second = &X86::GR8RegClass;
24668       }
24669     } else if (VT == MVT::i32 || VT == MVT::f32) {
24670       unsigned DestReg = 0;
24671       switch (Res.first) {
24672       default: break;
24673       case X86::AX: DestReg = X86::EAX; break;
24674       case X86::DX: DestReg = X86::EDX; break;
24675       case X86::CX: DestReg = X86::ECX; break;
24676       case X86::BX: DestReg = X86::EBX; break;
24677       case X86::SI: DestReg = X86::ESI; break;
24678       case X86::DI: DestReg = X86::EDI; break;
24679       case X86::BP: DestReg = X86::EBP; break;
24680       case X86::SP: DestReg = X86::ESP; break;
24681       }
24682       if (DestReg) {
24683         Res.first = DestReg;
24684         Res.second = &X86::GR32RegClass;
24685       }
24686     } else if (VT == MVT::i64 || VT == MVT::f64) {
24687       unsigned DestReg = 0;
24688       switch (Res.first) {
24689       default: break;
24690       case X86::AX: DestReg = X86::RAX; break;
24691       case X86::DX: DestReg = X86::RDX; break;
24692       case X86::CX: DestReg = X86::RCX; break;
24693       case X86::BX: DestReg = X86::RBX; break;
24694       case X86::SI: DestReg = X86::RSI; break;
24695       case X86::DI: DestReg = X86::RDI; break;
24696       case X86::BP: DestReg = X86::RBP; break;
24697       case X86::SP: DestReg = X86::RSP; break;
24698       }
24699       if (DestReg) {
24700         Res.first = DestReg;
24701         Res.second = &X86::GR64RegClass;
24702       }
24703     }
24704   } else if (Res.second == &X86::FR32RegClass ||
24705              Res.second == &X86::FR64RegClass ||
24706              Res.second == &X86::VR128RegClass ||
24707              Res.second == &X86::VR256RegClass ||
24708              Res.second == &X86::FR32XRegClass ||
24709              Res.second == &X86::FR64XRegClass ||
24710              Res.second == &X86::VR128XRegClass ||
24711              Res.second == &X86::VR256XRegClass ||
24712              Res.second == &X86::VR512RegClass) {
24713     // Handle references to XMM physical registers that got mapped into the
24714     // wrong class.  This can happen with constraints like {xmm0} where the
24715     // target independent register mapper will just pick the first match it can
24716     // find, ignoring the required type.
24717
24718     if (VT == MVT::f32 || VT == MVT::i32)
24719       Res.second = &X86::FR32RegClass;
24720     else if (VT == MVT::f64 || VT == MVT::i64)
24721       Res.second = &X86::FR64RegClass;
24722     else if (X86::VR128RegClass.hasType(VT))
24723       Res.second = &X86::VR128RegClass;
24724     else if (X86::VR256RegClass.hasType(VT))
24725       Res.second = &X86::VR256RegClass;
24726     else if (X86::VR512RegClass.hasType(VT))
24727       Res.second = &X86::VR512RegClass;
24728   }
24729
24730   return Res;
24731 }
24732
24733 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
24734                                             Type *Ty) const {
24735   // Scaling factors are not free at all.
24736   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
24737   // will take 2 allocations in the out of order engine instead of 1
24738   // for plain addressing mode, i.e. inst (reg1).
24739   // E.g.,
24740   // vaddps (%rsi,%drx), %ymm0, %ymm1
24741   // Requires two allocations (one for the load, one for the computation)
24742   // whereas:
24743   // vaddps (%rsi), %ymm0, %ymm1
24744   // Requires just 1 allocation, i.e., freeing allocations for other operations
24745   // and having less micro operations to execute.
24746   //
24747   // For some X86 architectures, this is even worse because for instance for
24748   // stores, the complex addressing mode forces the instruction to use the
24749   // "load" ports instead of the dedicated "store" port.
24750   // E.g., on Haswell:
24751   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
24752   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
24753   if (isLegalAddressingMode(AM, Ty))
24754     // Scale represents reg2 * scale, thus account for 1
24755     // as soon as we use a second register.
24756     return AM.Scale != 0;
24757   return -1;
24758 }
24759
24760 bool X86TargetLowering::isTargetFTOL() const {
24761   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
24762 }