Remove the TargetMachine forwards for TargetSubtargetInfo based
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258       TM.getSubtarget<X86Subtarget>().getRegisterInfo();
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
523     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
524   }
525
526   // There's never any support for operations beyond MVT::f32.
527   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
528   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
529   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
530   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
531
532   setLoadExtAction(ISD::EXTLOAD, MVT::f16, Expand);
533   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
534   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
535   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
536
537   if (Subtarget->hasPOPCNT()) {
538     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
539   } else {
540     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
541     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
542     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
543     if (Subtarget->is64Bit())
544       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
545   }
546
547   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
548
549   if (!Subtarget->hasMOVBE())
550     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
551
552   // These should be promoted to a larger select which is supported.
553   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
554   // X86 wants to expand cmov itself.
555   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
556   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
557   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
558   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
559   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
560   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
561   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
562   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
563   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
564   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
565   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
566   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
567   if (Subtarget->is64Bit()) {
568     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
569     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
570   }
571   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
572   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
573   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
574   // support continuation, user-level threading, and etc.. As a result, no
575   // other SjLj exception interfaces are implemented and please don't build
576   // your own exception handling based on them.
577   // LLVM/Clang supports zero-cost DWARF exception handling.
578   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
579   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
580
581   // Darwin ABI issue.
582   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
583   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
584   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
585   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
586   if (Subtarget->is64Bit())
587     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
588   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
589   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
592     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
593     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
594     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
595     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
596   }
597   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
598   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
599   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
600   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
601   if (Subtarget->is64Bit()) {
602     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
603     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
604     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
605   }
606
607   if (Subtarget->hasSSE1())
608     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
609
610   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
611
612   // Expand certain atomics
613   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
614     MVT VT = IntVTs[i];
615     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
616     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
617     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
618   }
619
620   if (Subtarget->hasCmpxchg16b()) {
621     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
622   }
623
624   // FIXME - use subtarget debug flags
625   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
626       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
627     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
628   }
629
630   if (Subtarget->is64Bit()) {
631     setExceptionPointerRegister(X86::RAX);
632     setExceptionSelectorRegister(X86::RDX);
633   } else {
634     setExceptionPointerRegister(X86::EAX);
635     setExceptionSelectorRegister(X86::EDX);
636   }
637   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
638   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
639
640   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
641   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
642
643   setOperationAction(ISD::TRAP, MVT::Other, Legal);
644   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
645
646   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
647   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
648   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
649   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
650     // TargetInfo::X86_64ABIBuiltinVaList
651     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
652     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
653   } else {
654     // TargetInfo::CharPtrBuiltinVaList
655     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
656     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
657   }
658
659   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
660   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
661
662   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
663                      MVT::i64 : MVT::i32, Custom);
664
665   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
666     // f32 and f64 use SSE.
667     // Set up the FP register classes.
668     addRegisterClass(MVT::f32, &X86::FR32RegClass);
669     addRegisterClass(MVT::f64, &X86::FR64RegClass);
670
671     // Use ANDPD to simulate FABS.
672     setOperationAction(ISD::FABS , MVT::f64, Custom);
673     setOperationAction(ISD::FABS , MVT::f32, Custom);
674
675     // Use XORP to simulate FNEG.
676     setOperationAction(ISD::FNEG , MVT::f64, Custom);
677     setOperationAction(ISD::FNEG , MVT::f32, Custom);
678
679     // Use ANDPD and ORPD to simulate FCOPYSIGN.
680     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
681     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
682
683     // Lower this to FGETSIGNx86 plus an AND.
684     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
685     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
686
687     // We don't support sin/cos/fmod
688     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
689     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
690     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
691     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
692     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
693     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
694
695     // Expand FP immediates into loads from the stack, except for the special
696     // cases we handle.
697     addLegalFPImmediate(APFloat(+0.0)); // xorpd
698     addLegalFPImmediate(APFloat(+0.0f)); // xorps
699   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
700     // Use SSE for f32, x87 for f64.
701     // Set up the FP register classes.
702     addRegisterClass(MVT::f32, &X86::FR32RegClass);
703     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
704
705     // Use ANDPS to simulate FABS.
706     setOperationAction(ISD::FABS , MVT::f32, Custom);
707
708     // Use XORP to simulate FNEG.
709     setOperationAction(ISD::FNEG , MVT::f32, Custom);
710
711     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
712
713     // Use ANDPS and ORPS to simulate FCOPYSIGN.
714     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
715     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
716
717     // We don't support sin/cos/fmod
718     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
719     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
720     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
721
722     // Special cases we handle for FP constants.
723     addLegalFPImmediate(APFloat(+0.0f)); // xorps
724     addLegalFPImmediate(APFloat(+0.0)); // FLD0
725     addLegalFPImmediate(APFloat(+1.0)); // FLD1
726     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
727     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
733     }
734   } else if (!TM.Options.UseSoftFloat) {
735     // f32 and f64 in x87.
736     // Set up the FP register classes.
737     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
738     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
739
740     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
741     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
742     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
743     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
744
745     if (!TM.Options.UnsafeFPMath) {
746       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
747       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
748       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
749       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
750       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
751       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
752     }
753     addLegalFPImmediate(APFloat(+0.0)); // FLD0
754     addLegalFPImmediate(APFloat(+1.0)); // FLD1
755     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
756     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
757     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
758     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
759     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
760     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
761   }
762
763   // We don't support FMA.
764   setOperationAction(ISD::FMA, MVT::f64, Expand);
765   setOperationAction(ISD::FMA, MVT::f32, Expand);
766
767   // Long double always uses X87.
768   if (!TM.Options.UseSoftFloat) {
769     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
770     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
771     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
772     {
773       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
774       addLegalFPImmediate(TmpFlt);  // FLD0
775       TmpFlt.changeSign();
776       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
777
778       bool ignored;
779       APFloat TmpFlt2(+1.0);
780       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
781                       &ignored);
782       addLegalFPImmediate(TmpFlt2);  // FLD1
783       TmpFlt2.changeSign();
784       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
785     }
786
787     if (!TM.Options.UnsafeFPMath) {
788       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
789       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
790       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
791     }
792
793     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
794     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
795     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
796     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
797     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
798     setOperationAction(ISD::FMA, MVT::f80, Expand);
799   }
800
801   // Always use a library call for pow.
802   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
803   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
804   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
805
806   setOperationAction(ISD::FLOG, MVT::f80, Expand);
807   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
808   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
809   setOperationAction(ISD::FEXP, MVT::f80, Expand);
810   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
811
812   // First set operation action for all vector types to either promote
813   // (for widening) or expand (for scalarization). Then we will selectively
814   // turn on ones that can be effectively codegen'd.
815   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
816            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
817     MVT VT = (MVT::SimpleValueType)i;
818     setOperationAction(ISD::ADD , VT, Expand);
819     setOperationAction(ISD::SUB , VT, Expand);
820     setOperationAction(ISD::FADD, VT, Expand);
821     setOperationAction(ISD::FNEG, VT, Expand);
822     setOperationAction(ISD::FSUB, VT, Expand);
823     setOperationAction(ISD::MUL , VT, Expand);
824     setOperationAction(ISD::FMUL, VT, Expand);
825     setOperationAction(ISD::SDIV, VT, Expand);
826     setOperationAction(ISD::UDIV, VT, Expand);
827     setOperationAction(ISD::FDIV, VT, Expand);
828     setOperationAction(ISD::SREM, VT, Expand);
829     setOperationAction(ISD::UREM, VT, Expand);
830     setOperationAction(ISD::LOAD, VT, Expand);
831     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
832     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
833     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
834     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
835     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
836     setOperationAction(ISD::FABS, VT, Expand);
837     setOperationAction(ISD::FSIN, VT, Expand);
838     setOperationAction(ISD::FSINCOS, VT, Expand);
839     setOperationAction(ISD::FCOS, VT, Expand);
840     setOperationAction(ISD::FSINCOS, VT, Expand);
841     setOperationAction(ISD::FREM, VT, Expand);
842     setOperationAction(ISD::FMA,  VT, Expand);
843     setOperationAction(ISD::FPOWI, VT, Expand);
844     setOperationAction(ISD::FSQRT, VT, Expand);
845     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
846     setOperationAction(ISD::FFLOOR, VT, Expand);
847     setOperationAction(ISD::FCEIL, VT, Expand);
848     setOperationAction(ISD::FTRUNC, VT, Expand);
849     setOperationAction(ISD::FRINT, VT, Expand);
850     setOperationAction(ISD::FNEARBYINT, VT, Expand);
851     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
852     setOperationAction(ISD::MULHS, VT, Expand);
853     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
854     setOperationAction(ISD::MULHU, VT, Expand);
855     setOperationAction(ISD::SDIVREM, VT, Expand);
856     setOperationAction(ISD::UDIVREM, VT, Expand);
857     setOperationAction(ISD::FPOW, VT, Expand);
858     setOperationAction(ISD::CTPOP, VT, Expand);
859     setOperationAction(ISD::CTTZ, VT, Expand);
860     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
861     setOperationAction(ISD::CTLZ, VT, Expand);
862     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
863     setOperationAction(ISD::SHL, VT, Expand);
864     setOperationAction(ISD::SRA, VT, Expand);
865     setOperationAction(ISD::SRL, VT, Expand);
866     setOperationAction(ISD::ROTL, VT, Expand);
867     setOperationAction(ISD::ROTR, VT, Expand);
868     setOperationAction(ISD::BSWAP, VT, Expand);
869     setOperationAction(ISD::SETCC, VT, Expand);
870     setOperationAction(ISD::FLOG, VT, Expand);
871     setOperationAction(ISD::FLOG2, VT, Expand);
872     setOperationAction(ISD::FLOG10, VT, Expand);
873     setOperationAction(ISD::FEXP, VT, Expand);
874     setOperationAction(ISD::FEXP2, VT, Expand);
875     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
876     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
877     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
878     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
879     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
880     setOperationAction(ISD::TRUNCATE, VT, Expand);
881     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
882     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
883     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
884     setOperationAction(ISD::VSELECT, VT, Expand);
885     setOperationAction(ISD::SELECT_CC, VT, Expand);
886     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
887              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
888       setTruncStoreAction(VT,
889                           (MVT::SimpleValueType)InnerVT, Expand);
890     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
891     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
892
893     // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like types,
894     // we have to deal with them whether we ask for Expansion or not. Setting
895     // Expand causes its own optimisation problems though, so leave them legal.
896     if (VT.getVectorElementType() == MVT::i1)
897       setLoadExtAction(ISD::EXTLOAD, VT, Expand);
898   }
899
900   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
901   // with -msoft-float, disable use of MMX as well.
902   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
903     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
904     // No operations on x86mmx supported, everything uses intrinsics.
905   }
906
907   // MMX-sized vectors (other than x86mmx) are expected to be expanded
908   // into smaller operations.
909   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
910   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
911   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
912   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
913   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
914   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
915   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
916   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
917   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
918   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
919   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
920   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
921   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
922   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
923   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
924   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
925   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
926   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
927   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
928   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
929   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
930   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
931   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
932   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
933   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
934   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
935   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
936   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
937   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
938
939   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
940     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
941
942     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
943     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
944     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
945     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
946     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
947     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
948     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
949     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
950     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
951     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
952     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
953     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
954   }
955
956   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
957     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
958
959     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
960     // registers cannot be used even for integer operations.
961     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
962     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
963     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
964     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
965
966     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
967     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
968     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
969     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
970     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
971     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
972     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
973     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
974     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
975     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
976     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
977     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
978     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
979     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
980     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
981     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
982     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
983     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
984     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
985     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
986     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
987     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
988
989     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
990     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
991     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
992     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
993
994     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
995     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
1001     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1002       MVT VT = (MVT::SimpleValueType)i;
1003       // Do not attempt to custom lower non-power-of-2 vectors
1004       if (!isPowerOf2_32(VT.getVectorNumElements()))
1005         continue;
1006       // Do not attempt to custom lower non-128-bit vectors
1007       if (!VT.is128BitVector())
1008         continue;
1009       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1010       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1011       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1012     }
1013
1014     // We support custom legalizing of sext and anyext loads for specific
1015     // memory vector types which we can load as a scalar (or sequence of
1016     // scalars) and extend in-register to a legal 128-bit vector type. For sext
1017     // loads these must work with a single scalar load.
1018     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i8, Custom);
1019     if (Subtarget->is64Bit()) {
1020       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, Custom);
1021       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i8, Custom);
1022     }
1023     setLoadExtAction(ISD::EXTLOAD, MVT::v2i8, Custom);
1024     setLoadExtAction(ISD::EXTLOAD, MVT::v2i16, Custom);
1025     setLoadExtAction(ISD::EXTLOAD, MVT::v2i32, Custom);
1026     setLoadExtAction(ISD::EXTLOAD, MVT::v4i8, Custom);
1027     setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, Custom);
1028     setLoadExtAction(ISD::EXTLOAD, MVT::v8i8, Custom);
1029
1030     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
1031     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1032     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1033     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1034     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1035     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1036
1037     if (Subtarget->is64Bit()) {
1038       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1039       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1040     }
1041
1042     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1043     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1044       MVT VT = (MVT::SimpleValueType)i;
1045
1046       // Do not attempt to promote non-128-bit vectors
1047       if (!VT.is128BitVector())
1048         continue;
1049
1050       setOperationAction(ISD::AND,    VT, Promote);
1051       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1052       setOperationAction(ISD::OR,     VT, Promote);
1053       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1054       setOperationAction(ISD::XOR,    VT, Promote);
1055       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1056       setOperationAction(ISD::LOAD,   VT, Promote);
1057       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1058       setOperationAction(ISD::SELECT, VT, Promote);
1059       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1060     }
1061
1062     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1063
1064     // Custom lower v2i64 and v2f64 selects.
1065     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1066     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1067     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1068     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1069
1070     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1071     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1072
1073     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1074     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1075     // As there is no 64-bit GPR available, we need build a special custom
1076     // sequence to convert from v2i32 to v2f32.
1077     if (!Subtarget->is64Bit())
1078       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1079
1080     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1081     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1082
1083     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1084
1085     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1086     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1087     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1088   }
1089
1090   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1091     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1092     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1093     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1094     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1095     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1096     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1097     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1098     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1099     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1100     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1101
1102     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1103     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1104     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1105     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1106     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1107     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1108     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1109     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1110     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1111     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1112
1113     // FIXME: Do we need to handle scalar-to-vector here?
1114     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1115
1116     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1117     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1118     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1119     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1120     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1121     // There is no BLENDI for byte vectors. We don't need to custom lower
1122     // some vselects for now.
1123     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1124
1125     // SSE41 brings specific instructions for doing vector sign extend even in
1126     // cases where we don't have SRA.
1127     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i8, Custom);
1128     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i16, Custom);
1129     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i32, Custom);
1130
1131     // i8 and i16 vectors are custom , because the source register and source
1132     // source memory operand types are not the same width.  f32 vectors are
1133     // custom since the immediate controlling the insert encodes additional
1134     // information.
1135     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1136     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1137     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1138     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1139
1140     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1141     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1142     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1143     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1144
1145     // FIXME: these should be Legal but thats only for the case where
1146     // the index is constant.  For now custom expand to deal with that.
1147     if (Subtarget->is64Bit()) {
1148       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1149       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1150     }
1151   }
1152
1153   if (Subtarget->hasSSE2()) {
1154     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1155     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1156
1157     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1158     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1159
1160     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1161     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1162
1163     // In the customized shift lowering, the legal cases in AVX2 will be
1164     // recognized.
1165     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1166     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1167
1168     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1169     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1170
1171     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1172   }
1173
1174   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1175     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1176     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1177     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1178     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1179     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1180     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1181
1182     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1183     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1184     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1185
1186     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1187     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1188     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1189     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1190     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1191     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1192     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1193     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1194     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1195     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1196     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1197     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1198
1199     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1200     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1201     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1202     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1203     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1204     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1205     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1206     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1207     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1208     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1209     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1210     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1211
1212     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1213     // even though v8i16 is a legal type.
1214     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1215     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1216     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1217
1218     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1219     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1220     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1221
1222     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1223     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1224
1225     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1226
1227     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1228     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1229
1230     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1231     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1232
1233     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1234     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1235
1236     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1237     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1238     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1239     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1240
1241     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1242     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1243     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1244
1245     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1246     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1247     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1248     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1249
1250     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1251     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1252     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1253     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1254     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1255     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1256     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1257     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1258     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1259     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1260     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1261     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1262
1263     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1264       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1265       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1266       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1267       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1268       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1269       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1270     }
1271
1272     if (Subtarget->hasInt256()) {
1273       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1274       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1275       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1276       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1277
1278       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1279       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1280       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1281       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1282
1283       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1284       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1285       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1286       // Don't lower v32i8 because there is no 128-bit byte mul
1287
1288       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1289       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1290       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1291       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1292
1293       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1294       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1295     } else {
1296       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1297       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1298       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1299       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1300
1301       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1302       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1303       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1304       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1305
1306       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1307       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1308       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1309       // Don't lower v32i8 because there is no 128-bit byte mul
1310     }
1311
1312     // In the customized shift lowering, the legal cases in AVX2 will be
1313     // recognized.
1314     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1315     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1316
1317     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1318     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1319
1320     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1321
1322     // Custom lower several nodes for 256-bit types.
1323     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1324              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1325       MVT VT = (MVT::SimpleValueType)i;
1326
1327       // Extract subvector is special because the value type
1328       // (result) is 128-bit but the source is 256-bit wide.
1329       if (VT.is128BitVector())
1330         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1331
1332       // Do not attempt to custom lower other non-256-bit vectors
1333       if (!VT.is256BitVector())
1334         continue;
1335
1336       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1337       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1338       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1339       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1340       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1341       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1342       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1343     }
1344
1345     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1346     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1347       MVT VT = (MVT::SimpleValueType)i;
1348
1349       // Do not attempt to promote non-256-bit vectors
1350       if (!VT.is256BitVector())
1351         continue;
1352
1353       setOperationAction(ISD::AND,    VT, Promote);
1354       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1355       setOperationAction(ISD::OR,     VT, Promote);
1356       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1357       setOperationAction(ISD::XOR,    VT, Promote);
1358       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1359       setOperationAction(ISD::LOAD,   VT, Promote);
1360       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1361       setOperationAction(ISD::SELECT, VT, Promote);
1362       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1363     }
1364   }
1365
1366   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1367     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1368     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1369     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1370     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1371
1372     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1373     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1374     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1375
1376     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1377     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1378     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1379     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1380     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1381     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1382     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1383     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1384     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1385     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1386     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1387
1388     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1389     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1390     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1391     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1392     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1393     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1394
1395     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1396     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1397     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1398     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1399     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1400     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1401     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1402     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1403
1404     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1405     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1406     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1407     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1408     if (Subtarget->is64Bit()) {
1409       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1410       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1411       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1412       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1413     }
1414     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1415     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1416     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1417     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1418     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1419     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1420     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1421     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1422     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1423     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1424
1425     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1426     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1427     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1428     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1429     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1430     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1431     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1432     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1433     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1434     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1435     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1436     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1437     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1438
1439     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1440     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1441     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1442     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1443     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1444     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1445
1446     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1447     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1448
1449     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1450
1451     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1452     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1453     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1454     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1455     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1456     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1457     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1458     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1459     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1460
1461     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1463
1464     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1465     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1466
1467     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1468
1469     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1470     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1471
1472     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1473     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1474
1475     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1476     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1477
1478     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1479     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1480     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1481     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1482     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1483     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1484
1485     if (Subtarget->hasCDI()) {
1486       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1487       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1488     }
1489
1490     // Custom lower several nodes.
1491     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1492              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1493       MVT VT = (MVT::SimpleValueType)i;
1494
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       // Extract subvector is special because the value type
1497       // (result) is 256/128-bit but the source is 512-bit wide.
1498       if (VT.is128BitVector() || VT.is256BitVector())
1499         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1500
1501       if (VT.getVectorElementType() == MVT::i1)
1502         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1503
1504       // Do not attempt to custom lower other non-512-bit vectors
1505       if (!VT.is512BitVector())
1506         continue;
1507
1508       if ( EltSize >= 32) {
1509         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1510         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1511         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1512         setOperationAction(ISD::VSELECT,             VT, Legal);
1513         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1514         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1515         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1516       }
1517     }
1518     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1519       MVT VT = (MVT::SimpleValueType)i;
1520
1521       // Do not attempt to promote non-256-bit vectors
1522       if (!VT.is512BitVector())
1523         continue;
1524
1525       setOperationAction(ISD::SELECT, VT, Promote);
1526       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1527     }
1528   }// has  AVX-512
1529
1530   if (!TM.Options.UseSoftFloat && Subtarget->hasBWI()) {
1531     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1532     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1533   }
1534
1535   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1536   // of this type with custom code.
1537   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1538            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1539     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1540                        Custom);
1541   }
1542
1543   // We want to custom lower some of our intrinsics.
1544   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1545   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1546   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1547   if (!Subtarget->is64Bit())
1548     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1549
1550   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1551   // handle type legalization for these operations here.
1552   //
1553   // FIXME: We really should do custom legalization for addition and
1554   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1555   // than generic legalization for 64-bit multiplication-with-overflow, though.
1556   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1557     // Add/Sub/Mul with overflow operations are custom lowered.
1558     MVT VT = IntVTs[i];
1559     setOperationAction(ISD::SADDO, VT, Custom);
1560     setOperationAction(ISD::UADDO, VT, Custom);
1561     setOperationAction(ISD::SSUBO, VT, Custom);
1562     setOperationAction(ISD::USUBO, VT, Custom);
1563     setOperationAction(ISD::SMULO, VT, Custom);
1564     setOperationAction(ISD::UMULO, VT, Custom);
1565   }
1566
1567   // There are no 8-bit 3-address imul/mul instructions
1568   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1569   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1570
1571   if (!Subtarget->is64Bit()) {
1572     // These libcalls are not available in 32-bit.
1573     setLibcallName(RTLIB::SHL_I128, nullptr);
1574     setLibcallName(RTLIB::SRL_I128, nullptr);
1575     setLibcallName(RTLIB::SRA_I128, nullptr);
1576   }
1577
1578   // Combine sin / cos into one node or libcall if possible.
1579   if (Subtarget->hasSinCos()) {
1580     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1581     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1582     if (Subtarget->isTargetDarwin()) {
1583       // For MacOSX, we don't want to the normal expansion of a libcall to
1584       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1585       // traffic.
1586       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1587       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1588     }
1589   }
1590
1591   if (Subtarget->isTargetWin64()) {
1592     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1593     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1594     setOperationAction(ISD::SREM, MVT::i128, Custom);
1595     setOperationAction(ISD::UREM, MVT::i128, Custom);
1596     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1597     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1598   }
1599
1600   // We have target-specific dag combine patterns for the following nodes:
1601   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1602   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1603   setTargetDAGCombine(ISD::VSELECT);
1604   setTargetDAGCombine(ISD::SELECT);
1605   setTargetDAGCombine(ISD::SHL);
1606   setTargetDAGCombine(ISD::SRA);
1607   setTargetDAGCombine(ISD::SRL);
1608   setTargetDAGCombine(ISD::OR);
1609   setTargetDAGCombine(ISD::AND);
1610   setTargetDAGCombine(ISD::ADD);
1611   setTargetDAGCombine(ISD::FADD);
1612   setTargetDAGCombine(ISD::FSUB);
1613   setTargetDAGCombine(ISD::FMA);
1614   setTargetDAGCombine(ISD::SUB);
1615   setTargetDAGCombine(ISD::LOAD);
1616   setTargetDAGCombine(ISD::STORE);
1617   setTargetDAGCombine(ISD::ZERO_EXTEND);
1618   setTargetDAGCombine(ISD::ANY_EXTEND);
1619   setTargetDAGCombine(ISD::SIGN_EXTEND);
1620   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1621   setTargetDAGCombine(ISD::TRUNCATE);
1622   setTargetDAGCombine(ISD::SINT_TO_FP);
1623   setTargetDAGCombine(ISD::SETCC);
1624   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1625   setTargetDAGCombine(ISD::BUILD_VECTOR);
1626   if (Subtarget->is64Bit())
1627     setTargetDAGCombine(ISD::MUL);
1628   setTargetDAGCombine(ISD::XOR);
1629
1630   computeRegisterProperties();
1631
1632   // On Darwin, -Os means optimize for size without hurting performance,
1633   // do not reduce the limit.
1634   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1635   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1636   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1637   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1638   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1639   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1640   setPrefLoopAlignment(4); // 2^4 bytes.
1641
1642   // Predictable cmov don't hurt on atom because it's in-order.
1643   PredictableSelectIsExpensive = !Subtarget->isAtom();
1644
1645   setPrefFunctionAlignment(4); // 2^4 bytes.
1646 }
1647
1648 // This has so far only been implemented for 64-bit MachO.
1649 bool X86TargetLowering::useLoadStackGuardNode() const {
1650   return Subtarget->getTargetTriple().getObjectFormat() == Triple::MachO &&
1651          Subtarget->is64Bit();
1652 }
1653
1654 TargetLoweringBase::LegalizeTypeAction
1655 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1656   if (ExperimentalVectorWideningLegalization &&
1657       VT.getVectorNumElements() != 1 &&
1658       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1659     return TypeWidenVector;
1660
1661   return TargetLoweringBase::getPreferredVectorAction(VT);
1662 }
1663
1664 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1665   if (!VT.isVector())
1666     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1667
1668   if (Subtarget->hasAVX512())
1669     switch(VT.getVectorNumElements()) {
1670     case  8: return MVT::v8i1;
1671     case 16: return MVT::v16i1;
1672   }
1673
1674   return VT.changeVectorElementTypeToInteger();
1675 }
1676
1677 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1678 /// the desired ByVal argument alignment.
1679 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1680   if (MaxAlign == 16)
1681     return;
1682   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1683     if (VTy->getBitWidth() == 128)
1684       MaxAlign = 16;
1685   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1686     unsigned EltAlign = 0;
1687     getMaxByValAlign(ATy->getElementType(), EltAlign);
1688     if (EltAlign > MaxAlign)
1689       MaxAlign = EltAlign;
1690   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1691     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1692       unsigned EltAlign = 0;
1693       getMaxByValAlign(STy->getElementType(i), EltAlign);
1694       if (EltAlign > MaxAlign)
1695         MaxAlign = EltAlign;
1696       if (MaxAlign == 16)
1697         break;
1698     }
1699   }
1700 }
1701
1702 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1703 /// function arguments in the caller parameter area. For X86, aggregates
1704 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1705 /// are at 4-byte boundaries.
1706 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1707   if (Subtarget->is64Bit()) {
1708     // Max of 8 and alignment of type.
1709     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1710     if (TyAlign > 8)
1711       return TyAlign;
1712     return 8;
1713   }
1714
1715   unsigned Align = 4;
1716   if (Subtarget->hasSSE1())
1717     getMaxByValAlign(Ty, Align);
1718   return Align;
1719 }
1720
1721 /// getOptimalMemOpType - Returns the target specific optimal type for load
1722 /// and store operations as a result of memset, memcpy, and memmove
1723 /// lowering. If DstAlign is zero that means it's safe to destination
1724 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1725 /// means there isn't a need to check it against alignment requirement,
1726 /// probably because the source does not need to be loaded. If 'IsMemset' is
1727 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1728 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1729 /// source is constant so it does not need to be loaded.
1730 /// It returns EVT::Other if the type should be determined using generic
1731 /// target-independent logic.
1732 EVT
1733 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1734                                        unsigned DstAlign, unsigned SrcAlign,
1735                                        bool IsMemset, bool ZeroMemset,
1736                                        bool MemcpyStrSrc,
1737                                        MachineFunction &MF) const {
1738   const Function *F = MF.getFunction();
1739   if ((!IsMemset || ZeroMemset) &&
1740       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1741                                        Attribute::NoImplicitFloat)) {
1742     if (Size >= 16 &&
1743         (Subtarget->isUnalignedMemAccessFast() ||
1744          ((DstAlign == 0 || DstAlign >= 16) &&
1745           (SrcAlign == 0 || SrcAlign >= 16)))) {
1746       if (Size >= 32) {
1747         if (Subtarget->hasInt256())
1748           return MVT::v8i32;
1749         if (Subtarget->hasFp256())
1750           return MVT::v8f32;
1751       }
1752       if (Subtarget->hasSSE2())
1753         return MVT::v4i32;
1754       if (Subtarget->hasSSE1())
1755         return MVT::v4f32;
1756     } else if (!MemcpyStrSrc && Size >= 8 &&
1757                !Subtarget->is64Bit() &&
1758                Subtarget->hasSSE2()) {
1759       // Do not use f64 to lower memcpy if source is string constant. It's
1760       // better to use i32 to avoid the loads.
1761       return MVT::f64;
1762     }
1763   }
1764   if (Subtarget->is64Bit() && Size >= 8)
1765     return MVT::i64;
1766   return MVT::i32;
1767 }
1768
1769 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1770   if (VT == MVT::f32)
1771     return X86ScalarSSEf32;
1772   else if (VT == MVT::f64)
1773     return X86ScalarSSEf64;
1774   return true;
1775 }
1776
1777 bool
1778 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1779                                                   unsigned,
1780                                                   unsigned,
1781                                                   bool *Fast) const {
1782   if (Fast)
1783     *Fast = Subtarget->isUnalignedMemAccessFast();
1784   return true;
1785 }
1786
1787 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1788 /// current function.  The returned value is a member of the
1789 /// MachineJumpTableInfo::JTEntryKind enum.
1790 unsigned X86TargetLowering::getJumpTableEncoding() const {
1791   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1792   // symbol.
1793   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1794       Subtarget->isPICStyleGOT())
1795     return MachineJumpTableInfo::EK_Custom32;
1796
1797   // Otherwise, use the normal jump table encoding heuristics.
1798   return TargetLowering::getJumpTableEncoding();
1799 }
1800
1801 const MCExpr *
1802 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1803                                              const MachineBasicBlock *MBB,
1804                                              unsigned uid,MCContext &Ctx) const{
1805   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1806          Subtarget->isPICStyleGOT());
1807   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1808   // entries.
1809   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1810                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1811 }
1812
1813 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1814 /// jumptable.
1815 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1816                                                     SelectionDAG &DAG) const {
1817   if (!Subtarget->is64Bit())
1818     // This doesn't have SDLoc associated with it, but is not really the
1819     // same as a Register.
1820     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1821   return Table;
1822 }
1823
1824 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1825 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1826 /// MCExpr.
1827 const MCExpr *X86TargetLowering::
1828 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1829                              MCContext &Ctx) const {
1830   // X86-64 uses RIP relative addressing based on the jump table label.
1831   if (Subtarget->isPICStyleRIPRel())
1832     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1833
1834   // Otherwise, the reference is relative to the PIC base.
1835   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1836 }
1837
1838 // FIXME: Why this routine is here? Move to RegInfo!
1839 std::pair<const TargetRegisterClass*, uint8_t>
1840 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1841   const TargetRegisterClass *RRC = nullptr;
1842   uint8_t Cost = 1;
1843   switch (VT.SimpleTy) {
1844   default:
1845     return TargetLowering::findRepresentativeClass(VT);
1846   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1847     RRC = Subtarget->is64Bit() ?
1848       (const TargetRegisterClass*)&X86::GR64RegClass :
1849       (const TargetRegisterClass*)&X86::GR32RegClass;
1850     break;
1851   case MVT::x86mmx:
1852     RRC = &X86::VR64RegClass;
1853     break;
1854   case MVT::f32: case MVT::f64:
1855   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1856   case MVT::v4f32: case MVT::v2f64:
1857   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1858   case MVT::v4f64:
1859     RRC = &X86::VR128RegClass;
1860     break;
1861   }
1862   return std::make_pair(RRC, Cost);
1863 }
1864
1865 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1866                                                unsigned &Offset) const {
1867   if (!Subtarget->isTargetLinux())
1868     return false;
1869
1870   if (Subtarget->is64Bit()) {
1871     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1872     Offset = 0x28;
1873     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1874       AddressSpace = 256;
1875     else
1876       AddressSpace = 257;
1877   } else {
1878     // %gs:0x14 on i386
1879     Offset = 0x14;
1880     AddressSpace = 256;
1881   }
1882   return true;
1883 }
1884
1885 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1886                                             unsigned DestAS) const {
1887   assert(SrcAS != DestAS && "Expected different address spaces!");
1888
1889   return SrcAS < 256 && DestAS < 256;
1890 }
1891
1892 //===----------------------------------------------------------------------===//
1893 //               Return Value Calling Convention Implementation
1894 //===----------------------------------------------------------------------===//
1895
1896 #include "X86GenCallingConv.inc"
1897
1898 bool
1899 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1900                                   MachineFunction &MF, bool isVarArg,
1901                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                         LLVMContext &Context) const {
1903   SmallVector<CCValAssign, 16> RVLocs;
1904   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1905                  RVLocs, Context);
1906   return CCInfo.CheckReturn(Outs, RetCC_X86);
1907 }
1908
1909 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1910   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1911   return ScratchRegs;
1912 }
1913
1914 SDValue
1915 X86TargetLowering::LowerReturn(SDValue Chain,
1916                                CallingConv::ID CallConv, bool isVarArg,
1917                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1918                                const SmallVectorImpl<SDValue> &OutVals,
1919                                SDLoc dl, SelectionDAG &DAG) const {
1920   MachineFunction &MF = DAG.getMachineFunction();
1921   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1922
1923   SmallVector<CCValAssign, 16> RVLocs;
1924   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1925                  RVLocs, *DAG.getContext());
1926   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1927
1928   SDValue Flag;
1929   SmallVector<SDValue, 6> RetOps;
1930   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1931   // Operand #1 = Bytes To Pop
1932   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1933                    MVT::i16));
1934
1935   // Copy the result values into the output registers.
1936   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1937     CCValAssign &VA = RVLocs[i];
1938     assert(VA.isRegLoc() && "Can only return in registers!");
1939     SDValue ValToCopy = OutVals[i];
1940     EVT ValVT = ValToCopy.getValueType();
1941
1942     // Promote values to the appropriate types
1943     if (VA.getLocInfo() == CCValAssign::SExt)
1944       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1945     else if (VA.getLocInfo() == CCValAssign::ZExt)
1946       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1947     else if (VA.getLocInfo() == CCValAssign::AExt)
1948       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1949     else if (VA.getLocInfo() == CCValAssign::BCvt)
1950       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1951
1952     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1953            "Unexpected FP-extend for return value.");  
1954
1955     // If this is x86-64, and we disabled SSE, we can't return FP values,
1956     // or SSE or MMX vectors.
1957     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1958          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1959           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1960       report_fatal_error("SSE register return with SSE disabled");
1961     }
1962     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1963     // llvm-gcc has never done it right and no one has noticed, so this
1964     // should be OK for now.
1965     if (ValVT == MVT::f64 &&
1966         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1967       report_fatal_error("SSE2 register return with SSE2 disabled");
1968
1969     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1970     // the RET instruction and handled by the FP Stackifier.
1971     if (VA.getLocReg() == X86::FP0 ||
1972         VA.getLocReg() == X86::FP1) {
1973       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1974       // change the value to the FP stack register class.
1975       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1976         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1977       RetOps.push_back(ValToCopy);
1978       // Don't emit a copytoreg.
1979       continue;
1980     }
1981
1982     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1983     // which is returned in RAX / RDX.
1984     if (Subtarget->is64Bit()) {
1985       if (ValVT == MVT::x86mmx) {
1986         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1987           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1988           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1989                                   ValToCopy);
1990           // If we don't have SSE2 available, convert to v4f32 so the generated
1991           // register is legal.
1992           if (!Subtarget->hasSSE2())
1993             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1994         }
1995       }
1996     }
1997
1998     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1999     Flag = Chain.getValue(1);
2000     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2001   }
2002
2003   // The x86-64 ABIs require that for returning structs by value we copy
2004   // the sret argument into %rax/%eax (depending on ABI) for the return.
2005   // Win32 requires us to put the sret argument to %eax as well.
2006   // We saved the argument into a virtual register in the entry block,
2007   // so now we copy the value out and into %rax/%eax.
2008   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
2009       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
2010     MachineFunction &MF = DAG.getMachineFunction();
2011     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2012     unsigned Reg = FuncInfo->getSRetReturnReg();
2013     assert(Reg &&
2014            "SRetReturnReg should have been set in LowerFormalArguments().");
2015     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2016
2017     unsigned RetValReg
2018         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2019           X86::RAX : X86::EAX;
2020     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2021     Flag = Chain.getValue(1);
2022
2023     // RAX/EAX now acts like a return value.
2024     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2025   }
2026
2027   RetOps[0] = Chain;  // Update chain.
2028
2029   // Add the flag if we have it.
2030   if (Flag.getNode())
2031     RetOps.push_back(Flag);
2032
2033   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2034 }
2035
2036 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2037   if (N->getNumValues() != 1)
2038     return false;
2039   if (!N->hasNUsesOfValue(1, 0))
2040     return false;
2041
2042   SDValue TCChain = Chain;
2043   SDNode *Copy = *N->use_begin();
2044   if (Copy->getOpcode() == ISD::CopyToReg) {
2045     // If the copy has a glue operand, we conservatively assume it isn't safe to
2046     // perform a tail call.
2047     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2048       return false;
2049     TCChain = Copy->getOperand(0);
2050   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2051     return false;
2052
2053   bool HasRet = false;
2054   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2055        UI != UE; ++UI) {
2056     if (UI->getOpcode() != X86ISD::RET_FLAG)
2057       return false;
2058     HasRet = true;
2059   }
2060
2061   if (!HasRet)
2062     return false;
2063
2064   Chain = TCChain;
2065   return true;
2066 }
2067
2068 MVT
2069 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2070                                             ISD::NodeType ExtendKind) const {
2071   MVT ReturnMVT;
2072   // TODO: Is this also valid on 32-bit?
2073   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2074     ReturnMVT = MVT::i8;
2075   else
2076     ReturnMVT = MVT::i32;
2077
2078   MVT MinVT = getRegisterType(ReturnMVT);
2079   return VT.bitsLT(MinVT) ? MinVT : VT;
2080 }
2081
2082 /// LowerCallResult - Lower the result values of a call into the
2083 /// appropriate copies out of appropriate physical registers.
2084 ///
2085 SDValue
2086 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2087                                    CallingConv::ID CallConv, bool isVarArg,
2088                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2089                                    SDLoc dl, SelectionDAG &DAG,
2090                                    SmallVectorImpl<SDValue> &InVals) const {
2091
2092   // Assign locations to each value returned by this call.
2093   SmallVector<CCValAssign, 16> RVLocs;
2094   bool Is64Bit = Subtarget->is64Bit();
2095   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2096                  DAG.getTarget(), RVLocs, *DAG.getContext());
2097   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2098
2099   // Copy all of the result registers out of their specified physreg.
2100   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2101     CCValAssign &VA = RVLocs[i];
2102     EVT CopyVT = VA.getValVT();
2103
2104     // If this is x86-64, and we disabled SSE, we can't return FP values
2105     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2106         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2107       report_fatal_error("SSE register return with SSE disabled");
2108     }
2109
2110     // If we prefer to use the value in xmm registers, copy it out as f80 and
2111     // use a truncate to move it from fp stack reg to xmm reg.
2112     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2113         isScalarFPTypeInSSEReg(VA.getValVT()))
2114       CopyVT = MVT::f80;
2115
2116     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2117                                CopyVT, InFlag).getValue(1);
2118     SDValue Val = Chain.getValue(0);
2119
2120     if (CopyVT != VA.getValVT())
2121       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2122                         // This truncation won't change the value.
2123                         DAG.getIntPtrConstant(1));
2124
2125     InFlag = Chain.getValue(2);
2126     InVals.push_back(Val);
2127   }
2128
2129   return Chain;
2130 }
2131
2132 //===----------------------------------------------------------------------===//
2133 //                C & StdCall & Fast Calling Convention implementation
2134 //===----------------------------------------------------------------------===//
2135 //  StdCall calling convention seems to be standard for many Windows' API
2136 //  routines and around. It differs from C calling convention just a little:
2137 //  callee should clean up the stack, not caller. Symbols should be also
2138 //  decorated in some fancy way :) It doesn't support any vector arguments.
2139 //  For info on fast calling convention see Fast Calling Convention (tail call)
2140 //  implementation LowerX86_32FastCCCallTo.
2141
2142 /// CallIsStructReturn - Determines whether a call uses struct return
2143 /// semantics.
2144 enum StructReturnType {
2145   NotStructReturn,
2146   RegStructReturn,
2147   StackStructReturn
2148 };
2149 static StructReturnType
2150 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2151   if (Outs.empty())
2152     return NotStructReturn;
2153
2154   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2155   if (!Flags.isSRet())
2156     return NotStructReturn;
2157   if (Flags.isInReg())
2158     return RegStructReturn;
2159   return StackStructReturn;
2160 }
2161
2162 /// ArgsAreStructReturn - Determines whether a function uses struct
2163 /// return semantics.
2164 static StructReturnType
2165 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2166   if (Ins.empty())
2167     return NotStructReturn;
2168
2169   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2170   if (!Flags.isSRet())
2171     return NotStructReturn;
2172   if (Flags.isInReg())
2173     return RegStructReturn;
2174   return StackStructReturn;
2175 }
2176
2177 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2178 /// by "Src" to address "Dst" with size and alignment information specified by
2179 /// the specific parameter attribute. The copy will be passed as a byval
2180 /// function parameter.
2181 static SDValue
2182 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2183                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2184                           SDLoc dl) {
2185   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2186
2187   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2188                        /*isVolatile*/false, /*AlwaysInline=*/true,
2189                        MachinePointerInfo(), MachinePointerInfo());
2190 }
2191
2192 /// IsTailCallConvention - Return true if the calling convention is one that
2193 /// supports tail call optimization.
2194 static bool IsTailCallConvention(CallingConv::ID CC) {
2195   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2196           CC == CallingConv::HiPE);
2197 }
2198
2199 /// \brief Return true if the calling convention is a C calling convention.
2200 static bool IsCCallConvention(CallingConv::ID CC) {
2201   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2202           CC == CallingConv::X86_64_SysV);
2203 }
2204
2205 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2206   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2207     return false;
2208
2209   CallSite CS(CI);
2210   CallingConv::ID CalleeCC = CS.getCallingConv();
2211   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2212     return false;
2213
2214   return true;
2215 }
2216
2217 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2218 /// a tailcall target by changing its ABI.
2219 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2220                                    bool GuaranteedTailCallOpt) {
2221   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2222 }
2223
2224 SDValue
2225 X86TargetLowering::LowerMemArgument(SDValue Chain,
2226                                     CallingConv::ID CallConv,
2227                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2228                                     SDLoc dl, SelectionDAG &DAG,
2229                                     const CCValAssign &VA,
2230                                     MachineFrameInfo *MFI,
2231                                     unsigned i) const {
2232   // Create the nodes corresponding to a load from this parameter slot.
2233   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2234   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2235       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2236   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2237   EVT ValVT;
2238
2239   // If value is passed by pointer we have address passed instead of the value
2240   // itself.
2241   if (VA.getLocInfo() == CCValAssign::Indirect)
2242     ValVT = VA.getLocVT();
2243   else
2244     ValVT = VA.getValVT();
2245
2246   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2247   // changed with more analysis.
2248   // In case of tail call optimization mark all arguments mutable. Since they
2249   // could be overwritten by lowering of arguments in case of a tail call.
2250   if (Flags.isByVal()) {
2251     unsigned Bytes = Flags.getByValSize();
2252     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2253     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2254     return DAG.getFrameIndex(FI, getPointerTy());
2255   } else {
2256     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2257                                     VA.getLocMemOffset(), isImmutable);
2258     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2259     return DAG.getLoad(ValVT, dl, Chain, FIN,
2260                        MachinePointerInfo::getFixedStack(FI),
2261                        false, false, false, 0);
2262   }
2263 }
2264
2265 SDValue
2266 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2267                                         CallingConv::ID CallConv,
2268                                         bool isVarArg,
2269                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2270                                         SDLoc dl,
2271                                         SelectionDAG &DAG,
2272                                         SmallVectorImpl<SDValue> &InVals)
2273                                           const {
2274   MachineFunction &MF = DAG.getMachineFunction();
2275   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2276
2277   const Function* Fn = MF.getFunction();
2278   if (Fn->hasExternalLinkage() &&
2279       Subtarget->isTargetCygMing() &&
2280       Fn->getName() == "main")
2281     FuncInfo->setForceFramePointer(true);
2282
2283   MachineFrameInfo *MFI = MF.getFrameInfo();
2284   bool Is64Bit = Subtarget->is64Bit();
2285   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2286
2287   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2288          "Var args not supported with calling convention fastcc, ghc or hipe");
2289
2290   // Assign locations to all of the incoming arguments.
2291   SmallVector<CCValAssign, 16> ArgLocs;
2292   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2293                  ArgLocs, *DAG.getContext());
2294
2295   // Allocate shadow area for Win64
2296   if (IsWin64)
2297     CCInfo.AllocateStack(32, 8);
2298
2299   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2300
2301   unsigned LastVal = ~0U;
2302   SDValue ArgValue;
2303   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2304     CCValAssign &VA = ArgLocs[i];
2305     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2306     // places.
2307     assert(VA.getValNo() != LastVal &&
2308            "Don't support value assigned to multiple locs yet");
2309     (void)LastVal;
2310     LastVal = VA.getValNo();
2311
2312     if (VA.isRegLoc()) {
2313       EVT RegVT = VA.getLocVT();
2314       const TargetRegisterClass *RC;
2315       if (RegVT == MVT::i32)
2316         RC = &X86::GR32RegClass;
2317       else if (Is64Bit && RegVT == MVT::i64)
2318         RC = &X86::GR64RegClass;
2319       else if (RegVT == MVT::f32)
2320         RC = &X86::FR32RegClass;
2321       else if (RegVT == MVT::f64)
2322         RC = &X86::FR64RegClass;
2323       else if (RegVT.is512BitVector())
2324         RC = &X86::VR512RegClass;
2325       else if (RegVT.is256BitVector())
2326         RC = &X86::VR256RegClass;
2327       else if (RegVT.is128BitVector())
2328         RC = &X86::VR128RegClass;
2329       else if (RegVT == MVT::x86mmx)
2330         RC = &X86::VR64RegClass;
2331       else if (RegVT == MVT::i1)
2332         RC = &X86::VK1RegClass;
2333       else if (RegVT == MVT::v8i1)
2334         RC = &X86::VK8RegClass;
2335       else if (RegVT == MVT::v16i1)
2336         RC = &X86::VK16RegClass;
2337       else if (RegVT == MVT::v32i1)
2338         RC = &X86::VK32RegClass;
2339       else if (RegVT == MVT::v64i1)
2340         RC = &X86::VK64RegClass;
2341       else
2342         llvm_unreachable("Unknown argument type!");
2343
2344       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2345       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2346
2347       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2348       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2349       // right size.
2350       if (VA.getLocInfo() == CCValAssign::SExt)
2351         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2352                                DAG.getValueType(VA.getValVT()));
2353       else if (VA.getLocInfo() == CCValAssign::ZExt)
2354         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2355                                DAG.getValueType(VA.getValVT()));
2356       else if (VA.getLocInfo() == CCValAssign::BCvt)
2357         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2358
2359       if (VA.isExtInLoc()) {
2360         // Handle MMX values passed in XMM regs.
2361         if (RegVT.isVector())
2362           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2363         else
2364           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2365       }
2366     } else {
2367       assert(VA.isMemLoc());
2368       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2369     }
2370
2371     // If value is passed via pointer - do a load.
2372     if (VA.getLocInfo() == CCValAssign::Indirect)
2373       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2374                              MachinePointerInfo(), false, false, false, 0);
2375
2376     InVals.push_back(ArgValue);
2377   }
2378
2379   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2380     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381       // The x86-64 ABIs require that for returning structs by value we copy
2382       // the sret argument into %rax/%eax (depending on ABI) for the return.
2383       // Win32 requires us to put the sret argument to %eax as well.
2384       // Save the argument into a virtual register so that we can access it
2385       // from the return points.
2386       if (Ins[i].Flags.isSRet()) {
2387         unsigned Reg = FuncInfo->getSRetReturnReg();
2388         if (!Reg) {
2389           MVT PtrTy = getPointerTy();
2390           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2391           FuncInfo->setSRetReturnReg(Reg);
2392         }
2393         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2394         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2395         break;
2396       }
2397     }
2398   }
2399
2400   unsigned StackSize = CCInfo.getNextStackOffset();
2401   // Align stack specially for tail calls.
2402   if (FuncIsMadeTailCallSafe(CallConv,
2403                              MF.getTarget().Options.GuaranteedTailCallOpt))
2404     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2405
2406   // If the function takes variable number of arguments, make a frame index for
2407   // the start of the first vararg value... for expansion of llvm.va_start.
2408   if (isVarArg) {
2409     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2410                     CallConv != CallingConv::X86_ThisCall)) {
2411       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2412     }
2413     if (Is64Bit) {
2414       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2415
2416       // FIXME: We should really autogenerate these arrays
2417       static const MCPhysReg GPR64ArgRegsWin64[] = {
2418         X86::RCX, X86::RDX, X86::R8,  X86::R9
2419       };
2420       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2421         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2422       };
2423       static const MCPhysReg XMMArgRegs64Bit[] = {
2424         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2425         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2426       };
2427       const MCPhysReg *GPR64ArgRegs;
2428       unsigned NumXMMRegs = 0;
2429
2430       if (IsWin64) {
2431         // The XMM registers which might contain var arg parameters are shadowed
2432         // in their paired GPR.  So we only need to save the GPR to their home
2433         // slots.
2434         TotalNumIntRegs = 4;
2435         GPR64ArgRegs = GPR64ArgRegsWin64;
2436       } else {
2437         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2438         GPR64ArgRegs = GPR64ArgRegs64Bit;
2439
2440         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2441                                                 TotalNumXMMRegs);
2442       }
2443       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2444                                                        TotalNumIntRegs);
2445
2446       bool NoImplicitFloatOps = Fn->getAttributes().
2447         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2448       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2449              "SSE register cannot be used when SSE is disabled!");
2450       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2451                NoImplicitFloatOps) &&
2452              "SSE register cannot be used when SSE is disabled!");
2453       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2454           !Subtarget->hasSSE1())
2455         // Kernel mode asks for SSE to be disabled, so don't push them
2456         // on the stack.
2457         TotalNumXMMRegs = 0;
2458
2459       if (IsWin64) {
2460         const TargetFrameLowering &TFI =
2461             *MF.getTarget().getSubtargetImpl()->getFrameLowering();
2462         // Get to the caller-allocated home save location.  Add 8 to account
2463         // for the return address.
2464         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2465         FuncInfo->setRegSaveFrameIndex(
2466           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2467         // Fixup to set vararg frame on shadow area (4 x i64).
2468         if (NumIntRegs < 4)
2469           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2470       } else {
2471         // For X86-64, if there are vararg parameters that are passed via
2472         // registers, then we must store them to their spots on the stack so
2473         // they may be loaded by deferencing the result of va_next.
2474         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2475         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2476         FuncInfo->setRegSaveFrameIndex(
2477           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2478                                false));
2479       }
2480
2481       // Store the integer parameter registers.
2482       SmallVector<SDValue, 8> MemOps;
2483       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2484                                         getPointerTy());
2485       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2486       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2487         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2488                                   DAG.getIntPtrConstant(Offset));
2489         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2490                                      &X86::GR64RegClass);
2491         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2492         SDValue Store =
2493           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2494                        MachinePointerInfo::getFixedStack(
2495                          FuncInfo->getRegSaveFrameIndex(), Offset),
2496                        false, false, 0);
2497         MemOps.push_back(Store);
2498         Offset += 8;
2499       }
2500
2501       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2502         // Now store the XMM (fp + vector) parameter registers.
2503         SmallVector<SDValue, 11> SaveXMMOps;
2504         SaveXMMOps.push_back(Chain);
2505
2506         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2507         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2508         SaveXMMOps.push_back(ALVal);
2509
2510         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2511                                FuncInfo->getRegSaveFrameIndex()));
2512         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2513                                FuncInfo->getVarArgsFPOffset()));
2514
2515         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2516           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2517                                        &X86::VR128RegClass);
2518           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2519           SaveXMMOps.push_back(Val);
2520         }
2521         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2522                                      MVT::Other, SaveXMMOps));
2523       }
2524
2525       if (!MemOps.empty())
2526         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2527     }
2528   }
2529
2530   // Some CCs need callee pop.
2531   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2532                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2533     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2534   } else {
2535     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2536     // If this is an sret function, the return should pop the hidden pointer.
2537     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2538         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2539         argsAreStructReturn(Ins) == StackStructReturn)
2540       FuncInfo->setBytesToPopOnReturn(4);
2541   }
2542
2543   if (!Is64Bit) {
2544     // RegSaveFrameIndex is X86-64 only.
2545     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2546     if (CallConv == CallingConv::X86_FastCall ||
2547         CallConv == CallingConv::X86_ThisCall)
2548       // fastcc functions can't have varargs.
2549       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2550   }
2551
2552   FuncInfo->setArgumentStackSize(StackSize);
2553
2554   return Chain;
2555 }
2556
2557 SDValue
2558 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2559                                     SDValue StackPtr, SDValue Arg,
2560                                     SDLoc dl, SelectionDAG &DAG,
2561                                     const CCValAssign &VA,
2562                                     ISD::ArgFlagsTy Flags) const {
2563   unsigned LocMemOffset = VA.getLocMemOffset();
2564   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2565   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2566   if (Flags.isByVal())
2567     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2568
2569   return DAG.getStore(Chain, dl, Arg, PtrOff,
2570                       MachinePointerInfo::getStack(LocMemOffset),
2571                       false, false, 0);
2572 }
2573
2574 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2575 /// optimization is performed and it is required.
2576 SDValue
2577 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2578                                            SDValue &OutRetAddr, SDValue Chain,
2579                                            bool IsTailCall, bool Is64Bit,
2580                                            int FPDiff, SDLoc dl) const {
2581   // Adjust the Return address stack slot.
2582   EVT VT = getPointerTy();
2583   OutRetAddr = getReturnAddressFrameIndex(DAG);
2584
2585   // Load the "old" Return address.
2586   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2587                            false, false, false, 0);
2588   return SDValue(OutRetAddr.getNode(), 1);
2589 }
2590
2591 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2592 /// optimization is performed and it is required (FPDiff!=0).
2593 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2594                                         SDValue Chain, SDValue RetAddrFrIdx,
2595                                         EVT PtrVT, unsigned SlotSize,
2596                                         int FPDiff, SDLoc dl) {
2597   // Store the return address to the appropriate stack slot.
2598   if (!FPDiff) return Chain;
2599   // Calculate the new stack slot for the return address.
2600   int NewReturnAddrFI =
2601     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2602                                          false);
2603   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2604   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2605                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2606                        false, false, 0);
2607   return Chain;
2608 }
2609
2610 SDValue
2611 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2612                              SmallVectorImpl<SDValue> &InVals) const {
2613   SelectionDAG &DAG                     = CLI.DAG;
2614   SDLoc &dl                             = CLI.DL;
2615   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2616   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2617   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2618   SDValue Chain                         = CLI.Chain;
2619   SDValue Callee                        = CLI.Callee;
2620   CallingConv::ID CallConv              = CLI.CallConv;
2621   bool &isTailCall                      = CLI.IsTailCall;
2622   bool isVarArg                         = CLI.IsVarArg;
2623
2624   MachineFunction &MF = DAG.getMachineFunction();
2625   bool Is64Bit        = Subtarget->is64Bit();
2626   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2627   StructReturnType SR = callIsStructReturn(Outs);
2628   bool IsSibcall      = false;
2629
2630   if (MF.getTarget().Options.DisableTailCalls)
2631     isTailCall = false;
2632
2633   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2634   if (IsMustTail) {
2635     // Force this to be a tail call.  The verifier rules are enough to ensure
2636     // that we can lower this successfully without moving the return address
2637     // around.
2638     isTailCall = true;
2639   } else if (isTailCall) {
2640     // Check if it's really possible to do a tail call.
2641     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2642                     isVarArg, SR != NotStructReturn,
2643                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2644                     Outs, OutVals, Ins, DAG);
2645
2646     // Sibcalls are automatically detected tailcalls which do not require
2647     // ABI changes.
2648     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2649       IsSibcall = true;
2650
2651     if (isTailCall)
2652       ++NumTailCalls;
2653   }
2654
2655   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2656          "Var args not supported with calling convention fastcc, ghc or hipe");
2657
2658   // Analyze operands of the call, assigning locations to each operand.
2659   SmallVector<CCValAssign, 16> ArgLocs;
2660   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2661                  ArgLocs, *DAG.getContext());
2662
2663   // Allocate shadow area for Win64
2664   if (IsWin64)
2665     CCInfo.AllocateStack(32, 8);
2666
2667   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2668
2669   // Get a count of how many bytes are to be pushed on the stack.
2670   unsigned NumBytes = CCInfo.getNextStackOffset();
2671   if (IsSibcall)
2672     // This is a sibcall. The memory operands are available in caller's
2673     // own caller's stack.
2674     NumBytes = 0;
2675   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2676            IsTailCallConvention(CallConv))
2677     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2678
2679   int FPDiff = 0;
2680   if (isTailCall && !IsSibcall && !IsMustTail) {
2681     // Lower arguments at fp - stackoffset + fpdiff.
2682     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2683     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2684
2685     FPDiff = NumBytesCallerPushed - NumBytes;
2686
2687     // Set the delta of movement of the returnaddr stackslot.
2688     // But only set if delta is greater than previous delta.
2689     if (FPDiff < X86Info->getTCReturnAddrDelta())
2690       X86Info->setTCReturnAddrDelta(FPDiff);
2691   }
2692
2693   unsigned NumBytesToPush = NumBytes;
2694   unsigned NumBytesToPop = NumBytes;
2695
2696   // If we have an inalloca argument, all stack space has already been allocated
2697   // for us and be right at the top of the stack.  We don't support multiple
2698   // arguments passed in memory when using inalloca.
2699   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2700     NumBytesToPush = 0;
2701     if (!ArgLocs.back().isMemLoc())
2702       report_fatal_error("cannot use inalloca attribute on a register "
2703                          "parameter");
2704     if (ArgLocs.back().getLocMemOffset() != 0)
2705       report_fatal_error("any parameter with the inalloca attribute must be "
2706                          "the only memory argument");
2707   }
2708
2709   if (!IsSibcall)
2710     Chain = DAG.getCALLSEQ_START(
2711         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2712
2713   SDValue RetAddrFrIdx;
2714   // Load return address for tail calls.
2715   if (isTailCall && FPDiff)
2716     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2717                                     Is64Bit, FPDiff, dl);
2718
2719   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2720   SmallVector<SDValue, 8> MemOpChains;
2721   SDValue StackPtr;
2722
2723   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2724   // of tail call optimization arguments are handle later.
2725   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
2726       DAG.getTarget().getSubtargetImpl()->getRegisterInfo());
2727   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2728     // Skip inalloca arguments, they have already been written.
2729     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2730     if (Flags.isInAlloca())
2731       continue;
2732
2733     CCValAssign &VA = ArgLocs[i];
2734     EVT RegVT = VA.getLocVT();
2735     SDValue Arg = OutVals[i];
2736     bool isByVal = Flags.isByVal();
2737
2738     // Promote the value if needed.
2739     switch (VA.getLocInfo()) {
2740     default: llvm_unreachable("Unknown loc info!");
2741     case CCValAssign::Full: break;
2742     case CCValAssign::SExt:
2743       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2744       break;
2745     case CCValAssign::ZExt:
2746       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2747       break;
2748     case CCValAssign::AExt:
2749       if (RegVT.is128BitVector()) {
2750         // Special case: passing MMX values in XMM registers.
2751         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2752         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2753         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2754       } else
2755         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2756       break;
2757     case CCValAssign::BCvt:
2758       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2759       break;
2760     case CCValAssign::Indirect: {
2761       // Store the argument.
2762       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2763       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2764       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2765                            MachinePointerInfo::getFixedStack(FI),
2766                            false, false, 0);
2767       Arg = SpillSlot;
2768       break;
2769     }
2770     }
2771
2772     if (VA.isRegLoc()) {
2773       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2774       if (isVarArg && IsWin64) {
2775         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2776         // shadow reg if callee is a varargs function.
2777         unsigned ShadowReg = 0;
2778         switch (VA.getLocReg()) {
2779         case X86::XMM0: ShadowReg = X86::RCX; break;
2780         case X86::XMM1: ShadowReg = X86::RDX; break;
2781         case X86::XMM2: ShadowReg = X86::R8; break;
2782         case X86::XMM3: ShadowReg = X86::R9; break;
2783         }
2784         if (ShadowReg)
2785           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2786       }
2787     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2788       assert(VA.isMemLoc());
2789       if (!StackPtr.getNode())
2790         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2791                                       getPointerTy());
2792       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2793                                              dl, DAG, VA, Flags));
2794     }
2795   }
2796
2797   if (!MemOpChains.empty())
2798     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2799
2800   if (Subtarget->isPICStyleGOT()) {
2801     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2802     // GOT pointer.
2803     if (!isTailCall) {
2804       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2805                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2806     } else {
2807       // If we are tail calling and generating PIC/GOT style code load the
2808       // address of the callee into ECX. The value in ecx is used as target of
2809       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2810       // for tail calls on PIC/GOT architectures. Normally we would just put the
2811       // address of GOT into ebx and then call target@PLT. But for tail calls
2812       // ebx would be restored (since ebx is callee saved) before jumping to the
2813       // target@PLT.
2814
2815       // Note: The actual moving to ECX is done further down.
2816       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2817       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2818           !G->getGlobal()->hasProtectedVisibility())
2819         Callee = LowerGlobalAddress(Callee, DAG);
2820       else if (isa<ExternalSymbolSDNode>(Callee))
2821         Callee = LowerExternalSymbol(Callee, DAG);
2822     }
2823   }
2824
2825   if (Is64Bit && isVarArg && !IsWin64) {
2826     // From AMD64 ABI document:
2827     // For calls that may call functions that use varargs or stdargs
2828     // (prototype-less calls or calls to functions containing ellipsis (...) in
2829     // the declaration) %al is used as hidden argument to specify the number
2830     // of SSE registers used. The contents of %al do not need to match exactly
2831     // the number of registers, but must be an ubound on the number of SSE
2832     // registers used and is in the range 0 - 8 inclusive.
2833
2834     // Count the number of XMM registers allocated.
2835     static const MCPhysReg XMMArgRegs[] = {
2836       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2837       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2838     };
2839     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2840     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2841            && "SSE registers cannot be used when SSE is disabled");
2842
2843     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2844                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2845   }
2846
2847   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2848   // don't need this because the eligibility check rejects calls that require
2849   // shuffling arguments passed in memory.
2850   if (!IsSibcall && isTailCall) {
2851     // Force all the incoming stack arguments to be loaded from the stack
2852     // before any new outgoing arguments are stored to the stack, because the
2853     // outgoing stack slots may alias the incoming argument stack slots, and
2854     // the alias isn't otherwise explicit. This is slightly more conservative
2855     // than necessary, because it means that each store effectively depends
2856     // on every argument instead of just those arguments it would clobber.
2857     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2858
2859     SmallVector<SDValue, 8> MemOpChains2;
2860     SDValue FIN;
2861     int FI = 0;
2862     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2863       CCValAssign &VA = ArgLocs[i];
2864       if (VA.isRegLoc())
2865         continue;
2866       assert(VA.isMemLoc());
2867       SDValue Arg = OutVals[i];
2868       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2869       // Skip inalloca arguments.  They don't require any work.
2870       if (Flags.isInAlloca())
2871         continue;
2872       // Create frame index.
2873       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2874       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2875       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2876       FIN = DAG.getFrameIndex(FI, getPointerTy());
2877
2878       if (Flags.isByVal()) {
2879         // Copy relative to framepointer.
2880         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2881         if (!StackPtr.getNode())
2882           StackPtr = DAG.getCopyFromReg(Chain, dl,
2883                                         RegInfo->getStackRegister(),
2884                                         getPointerTy());
2885         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2886
2887         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2888                                                          ArgChain,
2889                                                          Flags, DAG, dl));
2890       } else {
2891         // Store relative to framepointer.
2892         MemOpChains2.push_back(
2893           DAG.getStore(ArgChain, dl, Arg, FIN,
2894                        MachinePointerInfo::getFixedStack(FI),
2895                        false, false, 0));
2896       }
2897     }
2898
2899     if (!MemOpChains2.empty())
2900       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2901
2902     // Store the return address to the appropriate stack slot.
2903     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2904                                      getPointerTy(), RegInfo->getSlotSize(),
2905                                      FPDiff, dl);
2906   }
2907
2908   // Build a sequence of copy-to-reg nodes chained together with token chain
2909   // and flag operands which copy the outgoing args into registers.
2910   SDValue InFlag;
2911   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2912     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2913                              RegsToPass[i].second, InFlag);
2914     InFlag = Chain.getValue(1);
2915   }
2916
2917   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2918     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2919     // In the 64-bit large code model, we have to make all calls
2920     // through a register, since the call instruction's 32-bit
2921     // pc-relative offset may not be large enough to hold the whole
2922     // address.
2923   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2924     // If the callee is a GlobalAddress node (quite common, every direct call
2925     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2926     // it.
2927
2928     // We should use extra load for direct calls to dllimported functions in
2929     // non-JIT mode.
2930     const GlobalValue *GV = G->getGlobal();
2931     if (!GV->hasDLLImportStorageClass()) {
2932       unsigned char OpFlags = 0;
2933       bool ExtraLoad = false;
2934       unsigned WrapperKind = ISD::DELETED_NODE;
2935
2936       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2937       // external symbols most go through the PLT in PIC mode.  If the symbol
2938       // has hidden or protected visibility, or if it is static or local, then
2939       // we don't need to use the PLT - we can directly call it.
2940       if (Subtarget->isTargetELF() &&
2941           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2942           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2943         OpFlags = X86II::MO_PLT;
2944       } else if (Subtarget->isPICStyleStubAny() &&
2945                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2946                  (!Subtarget->getTargetTriple().isMacOSX() ||
2947                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2948         // PC-relative references to external symbols should go through $stub,
2949         // unless we're building with the leopard linker or later, which
2950         // automatically synthesizes these stubs.
2951         OpFlags = X86II::MO_DARWIN_STUB;
2952       } else if (Subtarget->isPICStyleRIPRel() &&
2953                  isa<Function>(GV) &&
2954                  cast<Function>(GV)->getAttributes().
2955                    hasAttribute(AttributeSet::FunctionIndex,
2956                                 Attribute::NonLazyBind)) {
2957         // If the function is marked as non-lazy, generate an indirect call
2958         // which loads from the GOT directly. This avoids runtime overhead
2959         // at the cost of eager binding (and one extra byte of encoding).
2960         OpFlags = X86II::MO_GOTPCREL;
2961         WrapperKind = X86ISD::WrapperRIP;
2962         ExtraLoad = true;
2963       }
2964
2965       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2966                                           G->getOffset(), OpFlags);
2967
2968       // Add a wrapper if needed.
2969       if (WrapperKind != ISD::DELETED_NODE)
2970         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2971       // Add extra indirection if needed.
2972       if (ExtraLoad)
2973         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2974                              MachinePointerInfo::getGOT(),
2975                              false, false, false, 0);
2976     }
2977   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2978     unsigned char OpFlags = 0;
2979
2980     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2981     // external symbols should go through the PLT.
2982     if (Subtarget->isTargetELF() &&
2983         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2984       OpFlags = X86II::MO_PLT;
2985     } else if (Subtarget->isPICStyleStubAny() &&
2986                (!Subtarget->getTargetTriple().isMacOSX() ||
2987                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2988       // PC-relative references to external symbols should go through $stub,
2989       // unless we're building with the leopard linker or later, which
2990       // automatically synthesizes these stubs.
2991       OpFlags = X86II::MO_DARWIN_STUB;
2992     }
2993
2994     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2995                                          OpFlags);
2996   }
2997
2998   // Returns a chain & a flag for retval copy to use.
2999   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3000   SmallVector<SDValue, 8> Ops;
3001
3002   if (!IsSibcall && isTailCall) {
3003     Chain = DAG.getCALLSEQ_END(Chain,
3004                                DAG.getIntPtrConstant(NumBytesToPop, true),
3005                                DAG.getIntPtrConstant(0, true), InFlag, dl);
3006     InFlag = Chain.getValue(1);
3007   }
3008
3009   Ops.push_back(Chain);
3010   Ops.push_back(Callee);
3011
3012   if (isTailCall)
3013     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
3014
3015   // Add argument registers to the end of the list so that they are known live
3016   // into the call.
3017   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3018     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3019                                   RegsToPass[i].second.getValueType()));
3020
3021   // Add a register mask operand representing the call-preserved registers.
3022   const TargetRegisterInfo *TRI =
3023       DAG.getTarget().getSubtargetImpl()->getRegisterInfo();
3024   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3025   assert(Mask && "Missing call preserved mask for calling convention");
3026   Ops.push_back(DAG.getRegisterMask(Mask));
3027
3028   if (InFlag.getNode())
3029     Ops.push_back(InFlag);
3030
3031   if (isTailCall) {
3032     // We used to do:
3033     //// If this is the first return lowered for this function, add the regs
3034     //// to the liveout set for the function.
3035     // This isn't right, although it's probably harmless on x86; liveouts
3036     // should be computed from returns not tail calls.  Consider a void
3037     // function making a tail call to a function returning int.
3038     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3039   }
3040
3041   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3042   InFlag = Chain.getValue(1);
3043
3044   // Create the CALLSEQ_END node.
3045   unsigned NumBytesForCalleeToPop;
3046   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3047                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3048     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3049   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3050            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3051            SR == StackStructReturn)
3052     // If this is a call to a struct-return function, the callee
3053     // pops the hidden struct pointer, so we have to push it back.
3054     // This is common for Darwin/X86, Linux & Mingw32 targets.
3055     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3056     NumBytesForCalleeToPop = 4;
3057   else
3058     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3059
3060   // Returns a flag for retval copy to use.
3061   if (!IsSibcall) {
3062     Chain = DAG.getCALLSEQ_END(Chain,
3063                                DAG.getIntPtrConstant(NumBytesToPop, true),
3064                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3065                                                      true),
3066                                InFlag, dl);
3067     InFlag = Chain.getValue(1);
3068   }
3069
3070   // Handle result values, copying them out of physregs into vregs that we
3071   // return.
3072   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3073                          Ins, dl, DAG, InVals);
3074 }
3075
3076 //===----------------------------------------------------------------------===//
3077 //                Fast Calling Convention (tail call) implementation
3078 //===----------------------------------------------------------------------===//
3079
3080 //  Like std call, callee cleans arguments, convention except that ECX is
3081 //  reserved for storing the tail called function address. Only 2 registers are
3082 //  free for argument passing (inreg). Tail call optimization is performed
3083 //  provided:
3084 //                * tailcallopt is enabled
3085 //                * caller/callee are fastcc
3086 //  On X86_64 architecture with GOT-style position independent code only local
3087 //  (within module) calls are supported at the moment.
3088 //  To keep the stack aligned according to platform abi the function
3089 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3090 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3091 //  If a tail called function callee has more arguments than the caller the
3092 //  caller needs to make sure that there is room to move the RETADDR to. This is
3093 //  achieved by reserving an area the size of the argument delta right after the
3094 //  original RETADDR, but before the saved framepointer or the spilled registers
3095 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3096 //  stack layout:
3097 //    arg1
3098 //    arg2
3099 //    RETADDR
3100 //    [ new RETADDR
3101 //      move area ]
3102 //    (possible EBP)
3103 //    ESI
3104 //    EDI
3105 //    local1 ..
3106
3107 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3108 /// for a 16 byte align requirement.
3109 unsigned
3110 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3111                                                SelectionDAG& DAG) const {
3112   MachineFunction &MF = DAG.getMachineFunction();
3113   const TargetMachine &TM = MF.getTarget();
3114   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3115       TM.getSubtargetImpl()->getRegisterInfo());
3116   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
3117   unsigned StackAlignment = TFI.getStackAlignment();
3118   uint64_t AlignMask = StackAlignment - 1;
3119   int64_t Offset = StackSize;
3120   unsigned SlotSize = RegInfo->getSlotSize();
3121   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3122     // Number smaller than 12 so just add the difference.
3123     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3124   } else {
3125     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3126     Offset = ((~AlignMask) & Offset) + StackAlignment +
3127       (StackAlignment-SlotSize);
3128   }
3129   return Offset;
3130 }
3131
3132 /// MatchingStackOffset - Return true if the given stack call argument is
3133 /// already available in the same position (relatively) of the caller's
3134 /// incoming argument stack.
3135 static
3136 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3137                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3138                          const X86InstrInfo *TII) {
3139   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3140   int FI = INT_MAX;
3141   if (Arg.getOpcode() == ISD::CopyFromReg) {
3142     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3143     if (!TargetRegisterInfo::isVirtualRegister(VR))
3144       return false;
3145     MachineInstr *Def = MRI->getVRegDef(VR);
3146     if (!Def)
3147       return false;
3148     if (!Flags.isByVal()) {
3149       if (!TII->isLoadFromStackSlot(Def, FI))
3150         return false;
3151     } else {
3152       unsigned Opcode = Def->getOpcode();
3153       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3154           Def->getOperand(1).isFI()) {
3155         FI = Def->getOperand(1).getIndex();
3156         Bytes = Flags.getByValSize();
3157       } else
3158         return false;
3159     }
3160   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3161     if (Flags.isByVal())
3162       // ByVal argument is passed in as a pointer but it's now being
3163       // dereferenced. e.g.
3164       // define @foo(%struct.X* %A) {
3165       //   tail call @bar(%struct.X* byval %A)
3166       // }
3167       return false;
3168     SDValue Ptr = Ld->getBasePtr();
3169     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3170     if (!FINode)
3171       return false;
3172     FI = FINode->getIndex();
3173   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3174     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3175     FI = FINode->getIndex();
3176     Bytes = Flags.getByValSize();
3177   } else
3178     return false;
3179
3180   assert(FI != INT_MAX);
3181   if (!MFI->isFixedObjectIndex(FI))
3182     return false;
3183   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3184 }
3185
3186 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3187 /// for tail call optimization. Targets which want to do tail call
3188 /// optimization should implement this function.
3189 bool
3190 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3191                                                      CallingConv::ID CalleeCC,
3192                                                      bool isVarArg,
3193                                                      bool isCalleeStructRet,
3194                                                      bool isCallerStructRet,
3195                                                      Type *RetTy,
3196                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3197                                     const SmallVectorImpl<SDValue> &OutVals,
3198                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3199                                                      SelectionDAG &DAG) const {
3200   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3201     return false;
3202
3203   // If -tailcallopt is specified, make fastcc functions tail-callable.
3204   const MachineFunction &MF = DAG.getMachineFunction();
3205   const Function *CallerF = MF.getFunction();
3206
3207   // If the function return type is x86_fp80 and the callee return type is not,
3208   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3209   // perform a tailcall optimization here.
3210   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3211     return false;
3212
3213   CallingConv::ID CallerCC = CallerF->getCallingConv();
3214   bool CCMatch = CallerCC == CalleeCC;
3215   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3216   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3217
3218   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3219     if (IsTailCallConvention(CalleeCC) && CCMatch)
3220       return true;
3221     return false;
3222   }
3223
3224   // Look for obvious safe cases to perform tail call optimization that do not
3225   // require ABI changes. This is what gcc calls sibcall.
3226
3227   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3228   // emit a special epilogue.
3229   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3230       DAG.getTarget().getSubtargetImpl()->getRegisterInfo());
3231   if (RegInfo->needsStackRealignment(MF))
3232     return false;
3233
3234   // Also avoid sibcall optimization if either caller or callee uses struct
3235   // return semantics.
3236   if (isCalleeStructRet || isCallerStructRet)
3237     return false;
3238
3239   // An stdcall/thiscall caller is expected to clean up its arguments; the
3240   // callee isn't going to do that.
3241   // FIXME: this is more restrictive than needed. We could produce a tailcall
3242   // when the stack adjustment matches. For example, with a thiscall that takes
3243   // only one argument.
3244   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3245                    CallerCC == CallingConv::X86_ThisCall))
3246     return false;
3247
3248   // Do not sibcall optimize vararg calls unless all arguments are passed via
3249   // registers.
3250   if (isVarArg && !Outs.empty()) {
3251
3252     // Optimizing for varargs on Win64 is unlikely to be safe without
3253     // additional testing.
3254     if (IsCalleeWin64 || IsCallerWin64)
3255       return false;
3256
3257     SmallVector<CCValAssign, 16> ArgLocs;
3258     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3259                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3260
3261     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3262     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3263       if (!ArgLocs[i].isRegLoc())
3264         return false;
3265   }
3266
3267   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3268   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3269   // this into a sibcall.
3270   bool Unused = false;
3271   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3272     if (!Ins[i].Used) {
3273       Unused = true;
3274       break;
3275     }
3276   }
3277   if (Unused) {
3278     SmallVector<CCValAssign, 16> RVLocs;
3279     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3280                    DAG.getTarget(), RVLocs, *DAG.getContext());
3281     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3282     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3283       CCValAssign &VA = RVLocs[i];
3284       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3285         return false;
3286     }
3287   }
3288
3289   // If the calling conventions do not match, then we'd better make sure the
3290   // results are returned in the same way as what the caller expects.
3291   if (!CCMatch) {
3292     SmallVector<CCValAssign, 16> RVLocs1;
3293     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3294                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3295     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3296
3297     SmallVector<CCValAssign, 16> RVLocs2;
3298     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3299                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3300     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3301
3302     if (RVLocs1.size() != RVLocs2.size())
3303       return false;
3304     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3305       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3306         return false;
3307       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3308         return false;
3309       if (RVLocs1[i].isRegLoc()) {
3310         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3311           return false;
3312       } else {
3313         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3314           return false;
3315       }
3316     }
3317   }
3318
3319   // If the callee takes no arguments then go on to check the results of the
3320   // call.
3321   if (!Outs.empty()) {
3322     // Check if stack adjustment is needed. For now, do not do this if any
3323     // argument is passed on the stack.
3324     SmallVector<CCValAssign, 16> ArgLocs;
3325     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3326                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3327
3328     // Allocate shadow area for Win64
3329     if (IsCalleeWin64)
3330       CCInfo.AllocateStack(32, 8);
3331
3332     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3333     if (CCInfo.getNextStackOffset()) {
3334       MachineFunction &MF = DAG.getMachineFunction();
3335       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3336         return false;
3337
3338       // Check if the arguments are already laid out in the right way as
3339       // the caller's fixed stack objects.
3340       MachineFrameInfo *MFI = MF.getFrameInfo();
3341       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3342       const X86InstrInfo *TII = static_cast<const X86InstrInfo *>(
3343           DAG.getTarget().getSubtargetImpl()->getInstrInfo());
3344       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3345         CCValAssign &VA = ArgLocs[i];
3346         SDValue Arg = OutVals[i];
3347         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3348         if (VA.getLocInfo() == CCValAssign::Indirect)
3349           return false;
3350         if (!VA.isRegLoc()) {
3351           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3352                                    MFI, MRI, TII))
3353             return false;
3354         }
3355       }
3356     }
3357
3358     // If the tailcall address may be in a register, then make sure it's
3359     // possible to register allocate for it. In 32-bit, the call address can
3360     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3361     // callee-saved registers are restored. These happen to be the same
3362     // registers used to pass 'inreg' arguments so watch out for those.
3363     if (!Subtarget->is64Bit() &&
3364         ((!isa<GlobalAddressSDNode>(Callee) &&
3365           !isa<ExternalSymbolSDNode>(Callee)) ||
3366          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3367       unsigned NumInRegs = 0;
3368       // In PIC we need an extra register to formulate the address computation
3369       // for the callee.
3370       unsigned MaxInRegs =
3371         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3372
3373       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3374         CCValAssign &VA = ArgLocs[i];
3375         if (!VA.isRegLoc())
3376           continue;
3377         unsigned Reg = VA.getLocReg();
3378         switch (Reg) {
3379         default: break;
3380         case X86::EAX: case X86::EDX: case X86::ECX:
3381           if (++NumInRegs == MaxInRegs)
3382             return false;
3383           break;
3384         }
3385       }
3386     }
3387   }
3388
3389   return true;
3390 }
3391
3392 FastISel *
3393 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3394                                   const TargetLibraryInfo *libInfo) const {
3395   return X86::createFastISel(funcInfo, libInfo);
3396 }
3397
3398 //===----------------------------------------------------------------------===//
3399 //                           Other Lowering Hooks
3400 //===----------------------------------------------------------------------===//
3401
3402 static bool MayFoldLoad(SDValue Op) {
3403   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3404 }
3405
3406 static bool MayFoldIntoStore(SDValue Op) {
3407   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3408 }
3409
3410 static bool isTargetShuffle(unsigned Opcode) {
3411   switch(Opcode) {
3412   default: return false;
3413   case X86ISD::PSHUFB:
3414   case X86ISD::PSHUFD:
3415   case X86ISD::PSHUFHW:
3416   case X86ISD::PSHUFLW:
3417   case X86ISD::SHUFP:
3418   case X86ISD::PALIGNR:
3419   case X86ISD::MOVLHPS:
3420   case X86ISD::MOVLHPD:
3421   case X86ISD::MOVHLPS:
3422   case X86ISD::MOVLPS:
3423   case X86ISD::MOVLPD:
3424   case X86ISD::MOVSHDUP:
3425   case X86ISD::MOVSLDUP:
3426   case X86ISD::MOVDDUP:
3427   case X86ISD::MOVSS:
3428   case X86ISD::MOVSD:
3429   case X86ISD::UNPCKL:
3430   case X86ISD::UNPCKH:
3431   case X86ISD::VPERMILP:
3432   case X86ISD::VPERM2X128:
3433   case X86ISD::VPERMI:
3434     return true;
3435   }
3436 }
3437
3438 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3439                                     SDValue V1, SelectionDAG &DAG) {
3440   switch(Opc) {
3441   default: llvm_unreachable("Unknown x86 shuffle node");
3442   case X86ISD::MOVSHDUP:
3443   case X86ISD::MOVSLDUP:
3444   case X86ISD::MOVDDUP:
3445     return DAG.getNode(Opc, dl, VT, V1);
3446   }
3447 }
3448
3449 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3450                                     SDValue V1, unsigned TargetMask,
3451                                     SelectionDAG &DAG) {
3452   switch(Opc) {
3453   default: llvm_unreachable("Unknown x86 shuffle node");
3454   case X86ISD::PSHUFD:
3455   case X86ISD::PSHUFHW:
3456   case X86ISD::PSHUFLW:
3457   case X86ISD::VPERMILP:
3458   case X86ISD::VPERMI:
3459     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3460   }
3461 }
3462
3463 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3464                                     SDValue V1, SDValue V2, unsigned TargetMask,
3465                                     SelectionDAG &DAG) {
3466   switch(Opc) {
3467   default: llvm_unreachable("Unknown x86 shuffle node");
3468   case X86ISD::PALIGNR:
3469   case X86ISD::SHUFP:
3470   case X86ISD::VPERM2X128:
3471     return DAG.getNode(Opc, dl, VT, V1, V2,
3472                        DAG.getConstant(TargetMask, MVT::i8));
3473   }
3474 }
3475
3476 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3477                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3478   switch(Opc) {
3479   default: llvm_unreachable("Unknown x86 shuffle node");
3480   case X86ISD::MOVLHPS:
3481   case X86ISD::MOVLHPD:
3482   case X86ISD::MOVHLPS:
3483   case X86ISD::MOVLPS:
3484   case X86ISD::MOVLPD:
3485   case X86ISD::MOVSS:
3486   case X86ISD::MOVSD:
3487   case X86ISD::UNPCKL:
3488   case X86ISD::UNPCKH:
3489     return DAG.getNode(Opc, dl, VT, V1, V2);
3490   }
3491 }
3492
3493 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3494   MachineFunction &MF = DAG.getMachineFunction();
3495   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
3496       DAG.getTarget().getSubtargetImpl()->getRegisterInfo());
3497   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3498   int ReturnAddrIndex = FuncInfo->getRAIndex();
3499
3500   if (ReturnAddrIndex == 0) {
3501     // Set up a frame object for the return address.
3502     unsigned SlotSize = RegInfo->getSlotSize();
3503     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3504                                                            -(int64_t)SlotSize,
3505                                                            false);
3506     FuncInfo->setRAIndex(ReturnAddrIndex);
3507   }
3508
3509   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3510 }
3511
3512 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3513                                        bool hasSymbolicDisplacement) {
3514   // Offset should fit into 32 bit immediate field.
3515   if (!isInt<32>(Offset))
3516     return false;
3517
3518   // If we don't have a symbolic displacement - we don't have any extra
3519   // restrictions.
3520   if (!hasSymbolicDisplacement)
3521     return true;
3522
3523   // FIXME: Some tweaks might be needed for medium code model.
3524   if (M != CodeModel::Small && M != CodeModel::Kernel)
3525     return false;
3526
3527   // For small code model we assume that latest object is 16MB before end of 31
3528   // bits boundary. We may also accept pretty large negative constants knowing
3529   // that all objects are in the positive half of address space.
3530   if (M == CodeModel::Small && Offset < 16*1024*1024)
3531     return true;
3532
3533   // For kernel code model we know that all object resist in the negative half
3534   // of 32bits address space. We may not accept negative offsets, since they may
3535   // be just off and we may accept pretty large positive ones.
3536   if (M == CodeModel::Kernel && Offset > 0)
3537     return true;
3538
3539   return false;
3540 }
3541
3542 /// isCalleePop - Determines whether the callee is required to pop its
3543 /// own arguments. Callee pop is necessary to support tail calls.
3544 bool X86::isCalleePop(CallingConv::ID CallingConv,
3545                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3546   if (IsVarArg)
3547     return false;
3548
3549   switch (CallingConv) {
3550   default:
3551     return false;
3552   case CallingConv::X86_StdCall:
3553     return !is64Bit;
3554   case CallingConv::X86_FastCall:
3555     return !is64Bit;
3556   case CallingConv::X86_ThisCall:
3557     return !is64Bit;
3558   case CallingConv::Fast:
3559     return TailCallOpt;
3560   case CallingConv::GHC:
3561     return TailCallOpt;
3562   case CallingConv::HiPE:
3563     return TailCallOpt;
3564   }
3565 }
3566
3567 /// \brief Return true if the condition is an unsigned comparison operation.
3568 static bool isX86CCUnsigned(unsigned X86CC) {
3569   switch (X86CC) {
3570   default: llvm_unreachable("Invalid integer condition!");
3571   case X86::COND_E:     return true;
3572   case X86::COND_G:     return false;
3573   case X86::COND_GE:    return false;
3574   case X86::COND_L:     return false;
3575   case X86::COND_LE:    return false;
3576   case X86::COND_NE:    return true;
3577   case X86::COND_B:     return true;
3578   case X86::COND_A:     return true;
3579   case X86::COND_BE:    return true;
3580   case X86::COND_AE:    return true;
3581   }
3582   llvm_unreachable("covered switch fell through?!");
3583 }
3584
3585 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3586 /// specific condition code, returning the condition code and the LHS/RHS of the
3587 /// comparison to make.
3588 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3589                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3590   if (!isFP) {
3591     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3592       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3593         // X > -1   -> X == 0, jump !sign.
3594         RHS = DAG.getConstant(0, RHS.getValueType());
3595         return X86::COND_NS;
3596       }
3597       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3598         // X < 0   -> X == 0, jump on sign.
3599         return X86::COND_S;
3600       }
3601       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3602         // X < 1   -> X <= 0
3603         RHS = DAG.getConstant(0, RHS.getValueType());
3604         return X86::COND_LE;
3605       }
3606     }
3607
3608     switch (SetCCOpcode) {
3609     default: llvm_unreachable("Invalid integer condition!");
3610     case ISD::SETEQ:  return X86::COND_E;
3611     case ISD::SETGT:  return X86::COND_G;
3612     case ISD::SETGE:  return X86::COND_GE;
3613     case ISD::SETLT:  return X86::COND_L;
3614     case ISD::SETLE:  return X86::COND_LE;
3615     case ISD::SETNE:  return X86::COND_NE;
3616     case ISD::SETULT: return X86::COND_B;
3617     case ISD::SETUGT: return X86::COND_A;
3618     case ISD::SETULE: return X86::COND_BE;
3619     case ISD::SETUGE: return X86::COND_AE;
3620     }
3621   }
3622
3623   // First determine if it is required or is profitable to flip the operands.
3624
3625   // If LHS is a foldable load, but RHS is not, flip the condition.
3626   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3627       !ISD::isNON_EXTLoad(RHS.getNode())) {
3628     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3629     std::swap(LHS, RHS);
3630   }
3631
3632   switch (SetCCOpcode) {
3633   default: break;
3634   case ISD::SETOLT:
3635   case ISD::SETOLE:
3636   case ISD::SETUGT:
3637   case ISD::SETUGE:
3638     std::swap(LHS, RHS);
3639     break;
3640   }
3641
3642   // On a floating point condition, the flags are set as follows:
3643   // ZF  PF  CF   op
3644   //  0 | 0 | 0 | X > Y
3645   //  0 | 0 | 1 | X < Y
3646   //  1 | 0 | 0 | X == Y
3647   //  1 | 1 | 1 | unordered
3648   switch (SetCCOpcode) {
3649   default: llvm_unreachable("Condcode should be pre-legalized away");
3650   case ISD::SETUEQ:
3651   case ISD::SETEQ:   return X86::COND_E;
3652   case ISD::SETOLT:              // flipped
3653   case ISD::SETOGT:
3654   case ISD::SETGT:   return X86::COND_A;
3655   case ISD::SETOLE:              // flipped
3656   case ISD::SETOGE:
3657   case ISD::SETGE:   return X86::COND_AE;
3658   case ISD::SETUGT:              // flipped
3659   case ISD::SETULT:
3660   case ISD::SETLT:   return X86::COND_B;
3661   case ISD::SETUGE:              // flipped
3662   case ISD::SETULE:
3663   case ISD::SETLE:   return X86::COND_BE;
3664   case ISD::SETONE:
3665   case ISD::SETNE:   return X86::COND_NE;
3666   case ISD::SETUO:   return X86::COND_P;
3667   case ISD::SETO:    return X86::COND_NP;
3668   case ISD::SETOEQ:
3669   case ISD::SETUNE:  return X86::COND_INVALID;
3670   }
3671 }
3672
3673 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3674 /// code. Current x86 isa includes the following FP cmov instructions:
3675 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3676 static bool hasFPCMov(unsigned X86CC) {
3677   switch (X86CC) {
3678   default:
3679     return false;
3680   case X86::COND_B:
3681   case X86::COND_BE:
3682   case X86::COND_E:
3683   case X86::COND_P:
3684   case X86::COND_A:
3685   case X86::COND_AE:
3686   case X86::COND_NE:
3687   case X86::COND_NP:
3688     return true;
3689   }
3690 }
3691
3692 /// isFPImmLegal - Returns true if the target can instruction select the
3693 /// specified FP immediate natively. If false, the legalizer will
3694 /// materialize the FP immediate as a load from a constant pool.
3695 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3696   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3697     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3698       return true;
3699   }
3700   return false;
3701 }
3702
3703 /// \brief Returns true if it is beneficial to convert a load of a constant
3704 /// to just the constant itself.
3705 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3706                                                           Type *Ty) const {
3707   assert(Ty->isIntegerTy());
3708
3709   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3710   if (BitSize == 0 || BitSize > 64)
3711     return false;
3712   return true;
3713 }
3714
3715 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3716 /// the specified range (L, H].
3717 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3718   return (Val < 0) || (Val >= Low && Val < Hi);
3719 }
3720
3721 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3722 /// specified value.
3723 static bool isUndefOrEqual(int Val, int CmpVal) {
3724   return (Val < 0 || Val == CmpVal);
3725 }
3726
3727 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3728 /// from position Pos and ending in Pos+Size, falls within the specified
3729 /// sequential range (L, L+Pos]. or is undef.
3730 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3731                                        unsigned Pos, unsigned Size, int Low) {
3732   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3733     if (!isUndefOrEqual(Mask[i], Low))
3734       return false;
3735   return true;
3736 }
3737
3738 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3739 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3740 /// the second operand.
3741 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3742   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3743     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3744   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3745     return (Mask[0] < 2 && Mask[1] < 2);
3746   return false;
3747 }
3748
3749 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3750 /// is suitable for input to PSHUFHW.
3751 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3752   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3753     return false;
3754
3755   // Lower quadword copied in order or undef.
3756   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3757     return false;
3758
3759   // Upper quadword shuffled.
3760   for (unsigned i = 4; i != 8; ++i)
3761     if (!isUndefOrInRange(Mask[i], 4, 8))
3762       return false;
3763
3764   if (VT == MVT::v16i16) {
3765     // Lower quadword copied in order or undef.
3766     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3767       return false;
3768
3769     // Upper quadword shuffled.
3770     for (unsigned i = 12; i != 16; ++i)
3771       if (!isUndefOrInRange(Mask[i], 12, 16))
3772         return false;
3773   }
3774
3775   return true;
3776 }
3777
3778 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3779 /// is suitable for input to PSHUFLW.
3780 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3781   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3782     return false;
3783
3784   // Upper quadword copied in order.
3785   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3786     return false;
3787
3788   // Lower quadword shuffled.
3789   for (unsigned i = 0; i != 4; ++i)
3790     if (!isUndefOrInRange(Mask[i], 0, 4))
3791       return false;
3792
3793   if (VT == MVT::v16i16) {
3794     // Upper quadword copied in order.
3795     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3796       return false;
3797
3798     // Lower quadword shuffled.
3799     for (unsigned i = 8; i != 12; ++i)
3800       if (!isUndefOrInRange(Mask[i], 8, 12))
3801         return false;
3802   }
3803
3804   return true;
3805 }
3806
3807 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3808 /// is suitable for input to PALIGNR.
3809 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3810                           const X86Subtarget *Subtarget) {
3811   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3812       (VT.is256BitVector() && !Subtarget->hasInt256()))
3813     return false;
3814
3815   unsigned NumElts = VT.getVectorNumElements();
3816   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3817   unsigned NumLaneElts = NumElts/NumLanes;
3818
3819   // Do not handle 64-bit element shuffles with palignr.
3820   if (NumLaneElts == 2)
3821     return false;
3822
3823   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3824     unsigned i;
3825     for (i = 0; i != NumLaneElts; ++i) {
3826       if (Mask[i+l] >= 0)
3827         break;
3828     }
3829
3830     // Lane is all undef, go to next lane
3831     if (i == NumLaneElts)
3832       continue;
3833
3834     int Start = Mask[i+l];
3835
3836     // Make sure its in this lane in one of the sources
3837     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3838         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3839       return false;
3840
3841     // If not lane 0, then we must match lane 0
3842     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3843       return false;
3844
3845     // Correct second source to be contiguous with first source
3846     if (Start >= (int)NumElts)
3847       Start -= NumElts - NumLaneElts;
3848
3849     // Make sure we're shifting in the right direction.
3850     if (Start <= (int)(i+l))
3851       return false;
3852
3853     Start -= i;
3854
3855     // Check the rest of the elements to see if they are consecutive.
3856     for (++i; i != NumLaneElts; ++i) {
3857       int Idx = Mask[i+l];
3858
3859       // Make sure its in this lane
3860       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3861           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3862         return false;
3863
3864       // If not lane 0, then we must match lane 0
3865       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3866         return false;
3867
3868       if (Idx >= (int)NumElts)
3869         Idx -= NumElts - NumLaneElts;
3870
3871       if (!isUndefOrEqual(Idx, Start+i))
3872         return false;
3873
3874     }
3875   }
3876
3877   return true;
3878 }
3879
3880 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3881 /// the two vector operands have swapped position.
3882 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3883                                      unsigned NumElems) {
3884   for (unsigned i = 0; i != NumElems; ++i) {
3885     int idx = Mask[i];
3886     if (idx < 0)
3887       continue;
3888     else if (idx < (int)NumElems)
3889       Mask[i] = idx + NumElems;
3890     else
3891       Mask[i] = idx - NumElems;
3892   }
3893 }
3894
3895 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3896 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3897 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3898 /// reverse of what x86 shuffles want.
3899 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3900
3901   unsigned NumElems = VT.getVectorNumElements();
3902   unsigned NumLanes = VT.getSizeInBits()/128;
3903   unsigned NumLaneElems = NumElems/NumLanes;
3904
3905   if (NumLaneElems != 2 && NumLaneElems != 4)
3906     return false;
3907
3908   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3909   bool symetricMaskRequired =
3910     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3911
3912   // VSHUFPSY divides the resulting vector into 4 chunks.
3913   // The sources are also splitted into 4 chunks, and each destination
3914   // chunk must come from a different source chunk.
3915   //
3916   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3917   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3918   //
3919   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3920   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3921   //
3922   // VSHUFPDY divides the resulting vector into 4 chunks.
3923   // The sources are also splitted into 4 chunks, and each destination
3924   // chunk must come from a different source chunk.
3925   //
3926   //  SRC1 =>      X3       X2       X1       X0
3927   //  SRC2 =>      Y3       Y2       Y1       Y0
3928   //
3929   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3930   //
3931   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3932   unsigned HalfLaneElems = NumLaneElems/2;
3933   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3934     for (unsigned i = 0; i != NumLaneElems; ++i) {
3935       int Idx = Mask[i+l];
3936       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3937       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3938         return false;
3939       // For VSHUFPSY, the mask of the second half must be the same as the
3940       // first but with the appropriate offsets. This works in the same way as
3941       // VPERMILPS works with masks.
3942       if (!symetricMaskRequired || Idx < 0)
3943         continue;
3944       if (MaskVal[i] < 0) {
3945         MaskVal[i] = Idx - l;
3946         continue;
3947       }
3948       if ((signed)(Idx - l) != MaskVal[i])
3949         return false;
3950     }
3951   }
3952
3953   return true;
3954 }
3955
3956 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3957 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3958 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3959   if (!VT.is128BitVector())
3960     return false;
3961
3962   unsigned NumElems = VT.getVectorNumElements();
3963
3964   if (NumElems != 4)
3965     return false;
3966
3967   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3968   return isUndefOrEqual(Mask[0], 6) &&
3969          isUndefOrEqual(Mask[1], 7) &&
3970          isUndefOrEqual(Mask[2], 2) &&
3971          isUndefOrEqual(Mask[3], 3);
3972 }
3973
3974 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3975 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3976 /// <2, 3, 2, 3>
3977 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3978   if (!VT.is128BitVector())
3979     return false;
3980
3981   unsigned NumElems = VT.getVectorNumElements();
3982
3983   if (NumElems != 4)
3984     return false;
3985
3986   return isUndefOrEqual(Mask[0], 2) &&
3987          isUndefOrEqual(Mask[1], 3) &&
3988          isUndefOrEqual(Mask[2], 2) &&
3989          isUndefOrEqual(Mask[3], 3);
3990 }
3991
3992 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3993 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3994 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3995   if (!VT.is128BitVector())
3996     return false;
3997
3998   unsigned NumElems = VT.getVectorNumElements();
3999
4000   if (NumElems != 2 && NumElems != 4)
4001     return false;
4002
4003   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4004     if (!isUndefOrEqual(Mask[i], i + NumElems))
4005       return false;
4006
4007   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4008     if (!isUndefOrEqual(Mask[i], i))
4009       return false;
4010
4011   return true;
4012 }
4013
4014 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
4015 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
4016 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
4017   if (!VT.is128BitVector())
4018     return false;
4019
4020   unsigned NumElems = VT.getVectorNumElements();
4021
4022   if (NumElems != 2 && NumElems != 4)
4023     return false;
4024
4025   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4026     if (!isUndefOrEqual(Mask[i], i))
4027       return false;
4028
4029   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4030     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
4031       return false;
4032
4033   return true;
4034 }
4035
4036 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
4037 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
4038 /// i. e: If all but one element come from the same vector.
4039 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
4040   // TODO: Deal with AVX's VINSERTPS
4041   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
4042     return false;
4043
4044   unsigned CorrectPosV1 = 0;
4045   unsigned CorrectPosV2 = 0;
4046   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
4047     if (Mask[i] == -1) {
4048       ++CorrectPosV1;
4049       ++CorrectPosV2;
4050       continue;
4051     }
4052
4053     if (Mask[i] == i)
4054       ++CorrectPosV1;
4055     else if (Mask[i] == i + 4)
4056       ++CorrectPosV2;
4057   }
4058
4059   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4060     // We have 3 elements (undefs count as elements from any vector) from one
4061     // vector, and one from another.
4062     return true;
4063
4064   return false;
4065 }
4066
4067 //
4068 // Some special combinations that can be optimized.
4069 //
4070 static
4071 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4072                                SelectionDAG &DAG) {
4073   MVT VT = SVOp->getSimpleValueType(0);
4074   SDLoc dl(SVOp);
4075
4076   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4077     return SDValue();
4078
4079   ArrayRef<int> Mask = SVOp->getMask();
4080
4081   // These are the special masks that may be optimized.
4082   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4083   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4084   bool MatchEvenMask = true;
4085   bool MatchOddMask  = true;
4086   for (int i=0; i<8; ++i) {
4087     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4088       MatchEvenMask = false;
4089     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4090       MatchOddMask = false;
4091   }
4092
4093   if (!MatchEvenMask && !MatchOddMask)
4094     return SDValue();
4095
4096   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4097
4098   SDValue Op0 = SVOp->getOperand(0);
4099   SDValue Op1 = SVOp->getOperand(1);
4100
4101   if (MatchEvenMask) {
4102     // Shift the second operand right to 32 bits.
4103     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4104     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4105   } else {
4106     // Shift the first operand left to 32 bits.
4107     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4108     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4109   }
4110   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4111   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4112 }
4113
4114 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4115 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4116 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4117                          bool HasInt256, bool V2IsSplat = false) {
4118
4119   assert(VT.getSizeInBits() >= 128 &&
4120          "Unsupported vector type for unpckl");
4121
4122   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4123   unsigned NumLanes;
4124   unsigned NumOf256BitLanes;
4125   unsigned NumElts = VT.getVectorNumElements();
4126   if (VT.is256BitVector()) {
4127     if (NumElts != 4 && NumElts != 8 &&
4128         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4129     return false;
4130     NumLanes = 2;
4131     NumOf256BitLanes = 1;
4132   } else if (VT.is512BitVector()) {
4133     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4134            "Unsupported vector type for unpckh");
4135     NumLanes = 2;
4136     NumOf256BitLanes = 2;
4137   } else {
4138     NumLanes = 1;
4139     NumOf256BitLanes = 1;
4140   }
4141
4142   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4143   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4144
4145   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4146     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4147       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4148         int BitI  = Mask[l256*NumEltsInStride+l+i];
4149         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4150         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4151           return false;
4152         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4153           return false;
4154         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4155           return false;
4156       }
4157     }
4158   }
4159   return true;
4160 }
4161
4162 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4163 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4164 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4165                          bool HasInt256, bool V2IsSplat = false) {
4166   assert(VT.getSizeInBits() >= 128 &&
4167          "Unsupported vector type for unpckh");
4168
4169   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4170   unsigned NumLanes;
4171   unsigned NumOf256BitLanes;
4172   unsigned NumElts = VT.getVectorNumElements();
4173   if (VT.is256BitVector()) {
4174     if (NumElts != 4 && NumElts != 8 &&
4175         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4176     return false;
4177     NumLanes = 2;
4178     NumOf256BitLanes = 1;
4179   } else if (VT.is512BitVector()) {
4180     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4181            "Unsupported vector type for unpckh");
4182     NumLanes = 2;
4183     NumOf256BitLanes = 2;
4184   } else {
4185     NumLanes = 1;
4186     NumOf256BitLanes = 1;
4187   }
4188
4189   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4190   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4191
4192   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4193     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4194       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4195         int BitI  = Mask[l256*NumEltsInStride+l+i];
4196         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4197         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4198           return false;
4199         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4200           return false;
4201         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4202           return false;
4203       }
4204     }
4205   }
4206   return true;
4207 }
4208
4209 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4210 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4211 /// <0, 0, 1, 1>
4212 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4213   unsigned NumElts = VT.getVectorNumElements();
4214   bool Is256BitVec = VT.is256BitVector();
4215
4216   if (VT.is512BitVector())
4217     return false;
4218   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4219          "Unsupported vector type for unpckh");
4220
4221   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4222       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4223     return false;
4224
4225   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4226   // FIXME: Need a better way to get rid of this, there's no latency difference
4227   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4228   // the former later. We should also remove the "_undef" special mask.
4229   if (NumElts == 4 && Is256BitVec)
4230     return false;
4231
4232   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4233   // independently on 128-bit lanes.
4234   unsigned NumLanes = VT.getSizeInBits()/128;
4235   unsigned NumLaneElts = NumElts/NumLanes;
4236
4237   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4238     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4239       int BitI  = Mask[l+i];
4240       int BitI1 = Mask[l+i+1];
4241
4242       if (!isUndefOrEqual(BitI, j))
4243         return false;
4244       if (!isUndefOrEqual(BitI1, j))
4245         return false;
4246     }
4247   }
4248
4249   return true;
4250 }
4251
4252 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4253 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4254 /// <2, 2, 3, 3>
4255 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4256   unsigned NumElts = VT.getVectorNumElements();
4257
4258   if (VT.is512BitVector())
4259     return false;
4260
4261   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4262          "Unsupported vector type for unpckh");
4263
4264   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4265       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4266     return false;
4267
4268   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4269   // independently on 128-bit lanes.
4270   unsigned NumLanes = VT.getSizeInBits()/128;
4271   unsigned NumLaneElts = NumElts/NumLanes;
4272
4273   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4274     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4275       int BitI  = Mask[l+i];
4276       int BitI1 = Mask[l+i+1];
4277       if (!isUndefOrEqual(BitI, j))
4278         return false;
4279       if (!isUndefOrEqual(BitI1, j))
4280         return false;
4281     }
4282   }
4283   return true;
4284 }
4285
4286 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4287 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4288 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4289   if (!VT.is512BitVector())
4290     return false;
4291
4292   unsigned NumElts = VT.getVectorNumElements();
4293   unsigned HalfSize = NumElts/2;
4294   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4295     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4296       *Imm = 1;
4297       return true;
4298     }
4299   }
4300   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4301     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4302       *Imm = 0;
4303       return true;
4304     }
4305   }
4306   return false;
4307 }
4308
4309 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4310 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4311 /// MOVSD, and MOVD, i.e. setting the lowest element.
4312 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4313   if (VT.getVectorElementType().getSizeInBits() < 32)
4314     return false;
4315   if (!VT.is128BitVector())
4316     return false;
4317
4318   unsigned NumElts = VT.getVectorNumElements();
4319
4320   if (!isUndefOrEqual(Mask[0], NumElts))
4321     return false;
4322
4323   for (unsigned i = 1; i != NumElts; ++i)
4324     if (!isUndefOrEqual(Mask[i], i))
4325       return false;
4326
4327   return true;
4328 }
4329
4330 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4331 /// as permutations between 128-bit chunks or halves. As an example: this
4332 /// shuffle bellow:
4333 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4334 /// The first half comes from the second half of V1 and the second half from the
4335 /// the second half of V2.
4336 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4337   if (!HasFp256 || !VT.is256BitVector())
4338     return false;
4339
4340   // The shuffle result is divided into half A and half B. In total the two
4341   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4342   // B must come from C, D, E or F.
4343   unsigned HalfSize = VT.getVectorNumElements()/2;
4344   bool MatchA = false, MatchB = false;
4345
4346   // Check if A comes from one of C, D, E, F.
4347   for (unsigned Half = 0; Half != 4; ++Half) {
4348     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4349       MatchA = true;
4350       break;
4351     }
4352   }
4353
4354   // Check if B comes from one of C, D, E, F.
4355   for (unsigned Half = 0; Half != 4; ++Half) {
4356     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4357       MatchB = true;
4358       break;
4359     }
4360   }
4361
4362   return MatchA && MatchB;
4363 }
4364
4365 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4366 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4367 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4368   MVT VT = SVOp->getSimpleValueType(0);
4369
4370   unsigned HalfSize = VT.getVectorNumElements()/2;
4371
4372   unsigned FstHalf = 0, SndHalf = 0;
4373   for (unsigned i = 0; i < HalfSize; ++i) {
4374     if (SVOp->getMaskElt(i) > 0) {
4375       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4376       break;
4377     }
4378   }
4379   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4380     if (SVOp->getMaskElt(i) > 0) {
4381       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4382       break;
4383     }
4384   }
4385
4386   return (FstHalf | (SndHalf << 4));
4387 }
4388
4389 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4390 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4391   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4392   if (EltSize < 32)
4393     return false;
4394
4395   unsigned NumElts = VT.getVectorNumElements();
4396   Imm8 = 0;
4397   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4398     for (unsigned i = 0; i != NumElts; ++i) {
4399       if (Mask[i] < 0)
4400         continue;
4401       Imm8 |= Mask[i] << (i*2);
4402     }
4403     return true;
4404   }
4405
4406   unsigned LaneSize = 4;
4407   SmallVector<int, 4> MaskVal(LaneSize, -1);
4408
4409   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4410     for (unsigned i = 0; i != LaneSize; ++i) {
4411       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4412         return false;
4413       if (Mask[i+l] < 0)
4414         continue;
4415       if (MaskVal[i] < 0) {
4416         MaskVal[i] = Mask[i+l] - l;
4417         Imm8 |= MaskVal[i] << (i*2);
4418         continue;
4419       }
4420       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4421         return false;
4422     }
4423   }
4424   return true;
4425 }
4426
4427 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4428 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4429 /// Note that VPERMIL mask matching is different depending whether theunderlying
4430 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4431 /// to the same elements of the low, but to the higher half of the source.
4432 /// In VPERMILPD the two lanes could be shuffled independently of each other
4433 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4434 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4435   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4436   if (VT.getSizeInBits() < 256 || EltSize < 32)
4437     return false;
4438   bool symetricMaskRequired = (EltSize == 32);
4439   unsigned NumElts = VT.getVectorNumElements();
4440
4441   unsigned NumLanes = VT.getSizeInBits()/128;
4442   unsigned LaneSize = NumElts/NumLanes;
4443   // 2 or 4 elements in one lane
4444
4445   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4446   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4447     for (unsigned i = 0; i != LaneSize; ++i) {
4448       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4449         return false;
4450       if (symetricMaskRequired) {
4451         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4452           ExpectedMaskVal[i] = Mask[i+l] - l;
4453           continue;
4454         }
4455         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4456           return false;
4457       }
4458     }
4459   }
4460   return true;
4461 }
4462
4463 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4464 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4465 /// element of vector 2 and the other elements to come from vector 1 in order.
4466 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4467                                bool V2IsSplat = false, bool V2IsUndef = false) {
4468   if (!VT.is128BitVector())
4469     return false;
4470
4471   unsigned NumOps = VT.getVectorNumElements();
4472   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4473     return false;
4474
4475   if (!isUndefOrEqual(Mask[0], 0))
4476     return false;
4477
4478   for (unsigned i = 1; i != NumOps; ++i)
4479     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4480           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4481           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4482       return false;
4483
4484   return true;
4485 }
4486
4487 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4488 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4489 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4490 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4491                            const X86Subtarget *Subtarget) {
4492   if (!Subtarget->hasSSE3())
4493     return false;
4494
4495   unsigned NumElems = VT.getVectorNumElements();
4496
4497   if ((VT.is128BitVector() && NumElems != 4) ||
4498       (VT.is256BitVector() && NumElems != 8) ||
4499       (VT.is512BitVector() && NumElems != 16))
4500     return false;
4501
4502   // "i+1" is the value the indexed mask element must have
4503   for (unsigned i = 0; i != NumElems; i += 2)
4504     if (!isUndefOrEqual(Mask[i], i+1) ||
4505         !isUndefOrEqual(Mask[i+1], i+1))
4506       return false;
4507
4508   return true;
4509 }
4510
4511 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4512 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4513 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4514 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4515                            const X86Subtarget *Subtarget) {
4516   if (!Subtarget->hasSSE3())
4517     return false;
4518
4519   unsigned NumElems = VT.getVectorNumElements();
4520
4521   if ((VT.is128BitVector() && NumElems != 4) ||
4522       (VT.is256BitVector() && NumElems != 8) ||
4523       (VT.is512BitVector() && NumElems != 16))
4524     return false;
4525
4526   // "i" is the value the indexed mask element must have
4527   for (unsigned i = 0; i != NumElems; i += 2)
4528     if (!isUndefOrEqual(Mask[i], i) ||
4529         !isUndefOrEqual(Mask[i+1], i))
4530       return false;
4531
4532   return true;
4533 }
4534
4535 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4536 /// specifies a shuffle of elements that is suitable for input to 256-bit
4537 /// version of MOVDDUP.
4538 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4539   if (!HasFp256 || !VT.is256BitVector())
4540     return false;
4541
4542   unsigned NumElts = VT.getVectorNumElements();
4543   if (NumElts != 4)
4544     return false;
4545
4546   for (unsigned i = 0; i != NumElts/2; ++i)
4547     if (!isUndefOrEqual(Mask[i], 0))
4548       return false;
4549   for (unsigned i = NumElts/2; i != NumElts; ++i)
4550     if (!isUndefOrEqual(Mask[i], NumElts/2))
4551       return false;
4552   return true;
4553 }
4554
4555 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4556 /// specifies a shuffle of elements that is suitable for input to 128-bit
4557 /// version of MOVDDUP.
4558 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4559   if (!VT.is128BitVector())
4560     return false;
4561
4562   unsigned e = VT.getVectorNumElements() / 2;
4563   for (unsigned i = 0; i != e; ++i)
4564     if (!isUndefOrEqual(Mask[i], i))
4565       return false;
4566   for (unsigned i = 0; i != e; ++i)
4567     if (!isUndefOrEqual(Mask[e+i], i))
4568       return false;
4569   return true;
4570 }
4571
4572 /// isVEXTRACTIndex - Return true if the specified
4573 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4574 /// suitable for instruction that extract 128 or 256 bit vectors
4575 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4576   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4577   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4578     return false;
4579
4580   // The index should be aligned on a vecWidth-bit boundary.
4581   uint64_t Index =
4582     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4583
4584   MVT VT = N->getSimpleValueType(0);
4585   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4586   bool Result = (Index * ElSize) % vecWidth == 0;
4587
4588   return Result;
4589 }
4590
4591 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4592 /// operand specifies a subvector insert that is suitable for input to
4593 /// insertion of 128 or 256-bit subvectors
4594 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4595   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4596   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4597     return false;
4598   // The index should be aligned on a vecWidth-bit boundary.
4599   uint64_t Index =
4600     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4601
4602   MVT VT = N->getSimpleValueType(0);
4603   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4604   bool Result = (Index * ElSize) % vecWidth == 0;
4605
4606   return Result;
4607 }
4608
4609 bool X86::isVINSERT128Index(SDNode *N) {
4610   return isVINSERTIndex(N, 128);
4611 }
4612
4613 bool X86::isVINSERT256Index(SDNode *N) {
4614   return isVINSERTIndex(N, 256);
4615 }
4616
4617 bool X86::isVEXTRACT128Index(SDNode *N) {
4618   return isVEXTRACTIndex(N, 128);
4619 }
4620
4621 bool X86::isVEXTRACT256Index(SDNode *N) {
4622   return isVEXTRACTIndex(N, 256);
4623 }
4624
4625 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4626 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4627 /// Handles 128-bit and 256-bit.
4628 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4629   MVT VT = N->getSimpleValueType(0);
4630
4631   assert((VT.getSizeInBits() >= 128) &&
4632          "Unsupported vector type for PSHUF/SHUFP");
4633
4634   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4635   // independently on 128-bit lanes.
4636   unsigned NumElts = VT.getVectorNumElements();
4637   unsigned NumLanes = VT.getSizeInBits()/128;
4638   unsigned NumLaneElts = NumElts/NumLanes;
4639
4640   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4641          "Only supports 2, 4 or 8 elements per lane");
4642
4643   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4644   unsigned Mask = 0;
4645   for (unsigned i = 0; i != NumElts; ++i) {
4646     int Elt = N->getMaskElt(i);
4647     if (Elt < 0) continue;
4648     Elt &= NumLaneElts - 1;
4649     unsigned ShAmt = (i << Shift) % 8;
4650     Mask |= Elt << ShAmt;
4651   }
4652
4653   return Mask;
4654 }
4655
4656 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4657 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4658 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4659   MVT VT = N->getSimpleValueType(0);
4660
4661   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4662          "Unsupported vector type for PSHUFHW");
4663
4664   unsigned NumElts = VT.getVectorNumElements();
4665
4666   unsigned Mask = 0;
4667   for (unsigned l = 0; l != NumElts; l += 8) {
4668     // 8 nodes per lane, but we only care about the last 4.
4669     for (unsigned i = 0; i < 4; ++i) {
4670       int Elt = N->getMaskElt(l+i+4);
4671       if (Elt < 0) continue;
4672       Elt &= 0x3; // only 2-bits.
4673       Mask |= Elt << (i * 2);
4674     }
4675   }
4676
4677   return Mask;
4678 }
4679
4680 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4681 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4682 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4683   MVT VT = N->getSimpleValueType(0);
4684
4685   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4686          "Unsupported vector type for PSHUFHW");
4687
4688   unsigned NumElts = VT.getVectorNumElements();
4689
4690   unsigned Mask = 0;
4691   for (unsigned l = 0; l != NumElts; l += 8) {
4692     // 8 nodes per lane, but we only care about the first 4.
4693     for (unsigned i = 0; i < 4; ++i) {
4694       int Elt = N->getMaskElt(l+i);
4695       if (Elt < 0) continue;
4696       Elt &= 0x3; // only 2-bits
4697       Mask |= Elt << (i * 2);
4698     }
4699   }
4700
4701   return Mask;
4702 }
4703
4704 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4705 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4706 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4707   MVT VT = SVOp->getSimpleValueType(0);
4708   unsigned EltSize = VT.is512BitVector() ? 1 :
4709     VT.getVectorElementType().getSizeInBits() >> 3;
4710
4711   unsigned NumElts = VT.getVectorNumElements();
4712   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4713   unsigned NumLaneElts = NumElts/NumLanes;
4714
4715   int Val = 0;
4716   unsigned i;
4717   for (i = 0; i != NumElts; ++i) {
4718     Val = SVOp->getMaskElt(i);
4719     if (Val >= 0)
4720       break;
4721   }
4722   if (Val >= (int)NumElts)
4723     Val -= NumElts - NumLaneElts;
4724
4725   assert(Val - i > 0 && "PALIGNR imm should be positive");
4726   return (Val - i) * EltSize;
4727 }
4728
4729 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4730   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4731   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4732     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4733
4734   uint64_t Index =
4735     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4736
4737   MVT VecVT = N->getOperand(0).getSimpleValueType();
4738   MVT ElVT = VecVT.getVectorElementType();
4739
4740   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4741   return Index / NumElemsPerChunk;
4742 }
4743
4744 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4745   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4746   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4747     llvm_unreachable("Illegal insert subvector for VINSERT");
4748
4749   uint64_t Index =
4750     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4751
4752   MVT VecVT = N->getSimpleValueType(0);
4753   MVT ElVT = VecVT.getVectorElementType();
4754
4755   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4756   return Index / NumElemsPerChunk;
4757 }
4758
4759 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4760 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4761 /// and VINSERTI128 instructions.
4762 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4763   return getExtractVEXTRACTImmediate(N, 128);
4764 }
4765
4766 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4767 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4768 /// and VINSERTI64x4 instructions.
4769 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4770   return getExtractVEXTRACTImmediate(N, 256);
4771 }
4772
4773 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4774 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4775 /// and VINSERTI128 instructions.
4776 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4777   return getInsertVINSERTImmediate(N, 128);
4778 }
4779
4780 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4781 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4782 /// and VINSERTI64x4 instructions.
4783 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4784   return getInsertVINSERTImmediate(N, 256);
4785 }
4786
4787 /// isZero - Returns true if Elt is a constant integer zero
4788 static bool isZero(SDValue V) {
4789   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4790   return C && C->isNullValue();
4791 }
4792
4793 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4794 /// constant +0.0.
4795 bool X86::isZeroNode(SDValue Elt) {
4796   if (isZero(Elt))
4797     return true;
4798   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4799     return CFP->getValueAPF().isPosZero();
4800   return false;
4801 }
4802
4803 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4804 /// match movhlps. The lower half elements should come from upper half of
4805 /// V1 (and in order), and the upper half elements should come from the upper
4806 /// half of V2 (and in order).
4807 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4808   if (!VT.is128BitVector())
4809     return false;
4810   if (VT.getVectorNumElements() != 4)
4811     return false;
4812   for (unsigned i = 0, e = 2; i != e; ++i)
4813     if (!isUndefOrEqual(Mask[i], i+2))
4814       return false;
4815   for (unsigned i = 2; i != 4; ++i)
4816     if (!isUndefOrEqual(Mask[i], i+4))
4817       return false;
4818   return true;
4819 }
4820
4821 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4822 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4823 /// required.
4824 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4825   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4826     return false;
4827   N = N->getOperand(0).getNode();
4828   if (!ISD::isNON_EXTLoad(N))
4829     return false;
4830   if (LD)
4831     *LD = cast<LoadSDNode>(N);
4832   return true;
4833 }
4834
4835 // Test whether the given value is a vector value which will be legalized
4836 // into a load.
4837 static bool WillBeConstantPoolLoad(SDNode *N) {
4838   if (N->getOpcode() != ISD::BUILD_VECTOR)
4839     return false;
4840
4841   // Check for any non-constant elements.
4842   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4843     switch (N->getOperand(i).getNode()->getOpcode()) {
4844     case ISD::UNDEF:
4845     case ISD::ConstantFP:
4846     case ISD::Constant:
4847       break;
4848     default:
4849       return false;
4850     }
4851
4852   // Vectors of all-zeros and all-ones are materialized with special
4853   // instructions rather than being loaded.
4854   return !ISD::isBuildVectorAllZeros(N) &&
4855          !ISD::isBuildVectorAllOnes(N);
4856 }
4857
4858 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4859 /// match movlp{s|d}. The lower half elements should come from lower half of
4860 /// V1 (and in order), and the upper half elements should come from the upper
4861 /// half of V2 (and in order). And since V1 will become the source of the
4862 /// MOVLP, it must be either a vector load or a scalar load to vector.
4863 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4864                                ArrayRef<int> Mask, MVT VT) {
4865   if (!VT.is128BitVector())
4866     return false;
4867
4868   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4869     return false;
4870   // Is V2 is a vector load, don't do this transformation. We will try to use
4871   // load folding shufps op.
4872   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4873     return false;
4874
4875   unsigned NumElems = VT.getVectorNumElements();
4876
4877   if (NumElems != 2 && NumElems != 4)
4878     return false;
4879   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4880     if (!isUndefOrEqual(Mask[i], i))
4881       return false;
4882   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4883     if (!isUndefOrEqual(Mask[i], i+NumElems))
4884       return false;
4885   return true;
4886 }
4887
4888 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4889 /// to an zero vector.
4890 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4891 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4892   SDValue V1 = N->getOperand(0);
4893   SDValue V2 = N->getOperand(1);
4894   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4895   for (unsigned i = 0; i != NumElems; ++i) {
4896     int Idx = N->getMaskElt(i);
4897     if (Idx >= (int)NumElems) {
4898       unsigned Opc = V2.getOpcode();
4899       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4900         continue;
4901       if (Opc != ISD::BUILD_VECTOR ||
4902           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4903         return false;
4904     } else if (Idx >= 0) {
4905       unsigned Opc = V1.getOpcode();
4906       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4907         continue;
4908       if (Opc != ISD::BUILD_VECTOR ||
4909           !X86::isZeroNode(V1.getOperand(Idx)))
4910         return false;
4911     }
4912   }
4913   return true;
4914 }
4915
4916 /// getZeroVector - Returns a vector of specified type with all zero elements.
4917 ///
4918 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4919                              SelectionDAG &DAG, SDLoc dl) {
4920   assert(VT.isVector() && "Expected a vector type");
4921
4922   // Always build SSE zero vectors as <4 x i32> bitcasted
4923   // to their dest type. This ensures they get CSE'd.
4924   SDValue Vec;
4925   if (VT.is128BitVector()) {  // SSE
4926     if (Subtarget->hasSSE2()) {  // SSE2
4927       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4928       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4929     } else { // SSE1
4930       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4931       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4932     }
4933   } else if (VT.is256BitVector()) { // AVX
4934     if (Subtarget->hasInt256()) { // AVX2
4935       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4936       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4937       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4938     } else {
4939       // 256-bit logic and arithmetic instructions in AVX are all
4940       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4941       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4942       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4943       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4944     }
4945   } else if (VT.is512BitVector()) { // AVX-512
4946       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4947       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4948                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4949       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4950   } else if (VT.getScalarType() == MVT::i1) {
4951     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4952     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4953     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4954     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4955   } else
4956     llvm_unreachable("Unexpected vector type");
4957
4958   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4959 }
4960
4961 /// getOnesVector - Returns a vector of specified type with all bits set.
4962 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4963 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4964 /// Then bitcast to their original type, ensuring they get CSE'd.
4965 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4966                              SDLoc dl) {
4967   assert(VT.isVector() && "Expected a vector type");
4968
4969   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4970   SDValue Vec;
4971   if (VT.is256BitVector()) {
4972     if (HasInt256) { // AVX2
4973       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4974       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4975     } else { // AVX
4976       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4977       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4978     }
4979   } else if (VT.is128BitVector()) {
4980     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4981   } else
4982     llvm_unreachable("Unexpected vector type");
4983
4984   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4985 }
4986
4987 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4988 /// that point to V2 points to its first element.
4989 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4990   for (unsigned i = 0; i != NumElems; ++i) {
4991     if (Mask[i] > (int)NumElems) {
4992       Mask[i] = NumElems;
4993     }
4994   }
4995 }
4996
4997 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4998 /// operation of specified width.
4999 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
5000                        SDValue V2) {
5001   unsigned NumElems = VT.getVectorNumElements();
5002   SmallVector<int, 8> Mask;
5003   Mask.push_back(NumElems);
5004   for (unsigned i = 1; i != NumElems; ++i)
5005     Mask.push_back(i);
5006   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5007 }
5008
5009 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
5010 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5011                           SDValue V2) {
5012   unsigned NumElems = VT.getVectorNumElements();
5013   SmallVector<int, 8> Mask;
5014   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5015     Mask.push_back(i);
5016     Mask.push_back(i + NumElems);
5017   }
5018   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5019 }
5020
5021 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5022 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5023                           SDValue V2) {
5024   unsigned NumElems = VT.getVectorNumElements();
5025   SmallVector<int, 8> Mask;
5026   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5027     Mask.push_back(i + Half);
5028     Mask.push_back(i + NumElems + Half);
5029   }
5030   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5031 }
5032
5033 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5034 // a generic shuffle instruction because the target has no such instructions.
5035 // Generate shuffles which repeat i16 and i8 several times until they can be
5036 // represented by v4f32 and then be manipulated by target suported shuffles.
5037 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5038   MVT VT = V.getSimpleValueType();
5039   int NumElems = VT.getVectorNumElements();
5040   SDLoc dl(V);
5041
5042   while (NumElems > 4) {
5043     if (EltNo < NumElems/2) {
5044       V = getUnpackl(DAG, dl, VT, V, V);
5045     } else {
5046       V = getUnpackh(DAG, dl, VT, V, V);
5047       EltNo -= NumElems/2;
5048     }
5049     NumElems >>= 1;
5050   }
5051   return V;
5052 }
5053
5054 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5055 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5056   MVT VT = V.getSimpleValueType();
5057   SDLoc dl(V);
5058
5059   if (VT.is128BitVector()) {
5060     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5061     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5062     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5063                              &SplatMask[0]);
5064   } else if (VT.is256BitVector()) {
5065     // To use VPERMILPS to splat scalars, the second half of indicies must
5066     // refer to the higher part, which is a duplication of the lower one,
5067     // because VPERMILPS can only handle in-lane permutations.
5068     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5069                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5070
5071     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5072     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5073                              &SplatMask[0]);
5074   } else
5075     llvm_unreachable("Vector size not supported");
5076
5077   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5078 }
5079
5080 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5081 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5082   MVT SrcVT = SV->getSimpleValueType(0);
5083   SDValue V1 = SV->getOperand(0);
5084   SDLoc dl(SV);
5085
5086   int EltNo = SV->getSplatIndex();
5087   int NumElems = SrcVT.getVectorNumElements();
5088   bool Is256BitVec = SrcVT.is256BitVector();
5089
5090   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5091          "Unknown how to promote splat for type");
5092
5093   // Extract the 128-bit part containing the splat element and update
5094   // the splat element index when it refers to the higher register.
5095   if (Is256BitVec) {
5096     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5097     if (EltNo >= NumElems/2)
5098       EltNo -= NumElems/2;
5099   }
5100
5101   // All i16 and i8 vector types can't be used directly by a generic shuffle
5102   // instruction because the target has no such instruction. Generate shuffles
5103   // which repeat i16 and i8 several times until they fit in i32, and then can
5104   // be manipulated by target suported shuffles.
5105   MVT EltVT = SrcVT.getVectorElementType();
5106   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5107     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5108
5109   // Recreate the 256-bit vector and place the same 128-bit vector
5110   // into the low and high part. This is necessary because we want
5111   // to use VPERM* to shuffle the vectors
5112   if (Is256BitVec) {
5113     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5114   }
5115
5116   return getLegalSplat(DAG, V1, EltNo);
5117 }
5118
5119 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5120 /// vector of zero or undef vector.  This produces a shuffle where the low
5121 /// element of V2 is swizzled into the zero/undef vector, landing at element
5122 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5123 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5124                                            bool IsZero,
5125                                            const X86Subtarget *Subtarget,
5126                                            SelectionDAG &DAG) {
5127   MVT VT = V2.getSimpleValueType();
5128   SDValue V1 = IsZero
5129     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5130   unsigned NumElems = VT.getVectorNumElements();
5131   SmallVector<int, 16> MaskVec;
5132   for (unsigned i = 0; i != NumElems; ++i)
5133     // If this is the insertion idx, put the low elt of V2 here.
5134     MaskVec.push_back(i == Idx ? NumElems : i);
5135   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5136 }
5137
5138 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5139 /// target specific opcode. Returns true if the Mask could be calculated. Sets
5140 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
5141 /// shuffles which use a single input multiple times, and in those cases it will
5142 /// adjust the mask to only have indices within that single input.
5143 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5144                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5145   unsigned NumElems = VT.getVectorNumElements();
5146   SDValue ImmN;
5147
5148   IsUnary = false;
5149   bool IsFakeUnary = false;
5150   switch(N->getOpcode()) {
5151   case X86ISD::SHUFP:
5152     ImmN = N->getOperand(N->getNumOperands()-1);
5153     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5154     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5155     break;
5156   case X86ISD::UNPCKH:
5157     DecodeUNPCKHMask(VT, Mask);
5158     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5159     break;
5160   case X86ISD::UNPCKL:
5161     DecodeUNPCKLMask(VT, Mask);
5162     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5163     break;
5164   case X86ISD::MOVHLPS:
5165     DecodeMOVHLPSMask(NumElems, Mask);
5166     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5167     break;
5168   case X86ISD::MOVLHPS:
5169     DecodeMOVLHPSMask(NumElems, Mask);
5170     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
5171     break;
5172   case X86ISD::PALIGNR:
5173     ImmN = N->getOperand(N->getNumOperands()-1);
5174     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5175     break;
5176   case X86ISD::PSHUFD:
5177   case X86ISD::VPERMILP:
5178     ImmN = N->getOperand(N->getNumOperands()-1);
5179     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5180     IsUnary = true;
5181     break;
5182   case X86ISD::PSHUFHW:
5183     ImmN = N->getOperand(N->getNumOperands()-1);
5184     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5185     IsUnary = true;
5186     break;
5187   case X86ISD::PSHUFLW:
5188     ImmN = N->getOperand(N->getNumOperands()-1);
5189     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5190     IsUnary = true;
5191     break;
5192   case X86ISD::PSHUFB: {
5193     IsUnary = true;
5194     SDValue MaskNode = N->getOperand(1);
5195     while (MaskNode->getOpcode() == ISD::BITCAST)
5196       MaskNode = MaskNode->getOperand(0);
5197
5198     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
5199       // If we have a build-vector, then things are easy.
5200       EVT VT = MaskNode.getValueType();
5201       assert(VT.isVector() &&
5202              "Can't produce a non-vector with a build_vector!");
5203       if (!VT.isInteger())
5204         return false;
5205
5206       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
5207
5208       SmallVector<uint64_t, 32> RawMask;
5209       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
5210         auto *CN = dyn_cast<ConstantSDNode>(MaskNode->getOperand(i));
5211         if (!CN)
5212           return false;
5213         APInt MaskElement = CN->getAPIntValue();
5214
5215         // We now have to decode the element which could be any integer size and
5216         // extract each byte of it.
5217         for (int j = 0; j < NumBytesPerElement; ++j) {
5218           // Note that this is x86 and so always little endian: the low byte is
5219           // the first byte of the mask.
5220           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
5221           MaskElement = MaskElement.lshr(8);
5222         }
5223       }
5224       DecodePSHUFBMask(RawMask, Mask);
5225       break;
5226     }
5227
5228     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
5229     if (!MaskLoad)
5230       return false;
5231
5232     SDValue Ptr = MaskLoad->getBasePtr();
5233     if (Ptr->getOpcode() == X86ISD::Wrapper)
5234       Ptr = Ptr->getOperand(0);
5235
5236     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
5237     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
5238       return false;
5239
5240     if (auto *C = dyn_cast<ConstantDataSequential>(MaskCP->getConstVal())) {
5241       // FIXME: Support AVX-512 here.
5242       if (!C->getType()->isVectorTy() ||
5243           (C->getNumElements() != 16 && C->getNumElements() != 32))
5244         return false;
5245
5246       assert(C->getType()->isVectorTy() && "Expected a vector constant.");
5247       DecodePSHUFBMask(C, Mask);
5248       break;
5249     }
5250
5251     return false;
5252   }
5253   case X86ISD::VPERMI:
5254     ImmN = N->getOperand(N->getNumOperands()-1);
5255     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5256     IsUnary = true;
5257     break;
5258   case X86ISD::MOVSS:
5259   case X86ISD::MOVSD: {
5260     // The index 0 always comes from the first element of the second source,
5261     // this is why MOVSS and MOVSD are used in the first place. The other
5262     // elements come from the other positions of the first source vector
5263     Mask.push_back(NumElems);
5264     for (unsigned i = 1; i != NumElems; ++i) {
5265       Mask.push_back(i);
5266     }
5267     break;
5268   }
5269   case X86ISD::VPERM2X128:
5270     ImmN = N->getOperand(N->getNumOperands()-1);
5271     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5272     if (Mask.empty()) return false;
5273     break;
5274   case X86ISD::MOVDDUP:
5275   case X86ISD::MOVLHPD:
5276   case X86ISD::MOVLPD:
5277   case X86ISD::MOVLPS:
5278   case X86ISD::MOVSHDUP:
5279   case X86ISD::MOVSLDUP:
5280     // Not yet implemented
5281     return false;
5282   default: llvm_unreachable("unknown target shuffle node");
5283   }
5284
5285   // If we have a fake unary shuffle, the shuffle mask is spread across two
5286   // inputs that are actually the same node. Re-map the mask to always point
5287   // into the first input.
5288   if (IsFakeUnary)
5289     for (int &M : Mask)
5290       if (M >= (int)Mask.size())
5291         M -= Mask.size();
5292
5293   return true;
5294 }
5295
5296 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5297 /// element of the result of the vector shuffle.
5298 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5299                                    unsigned Depth) {
5300   if (Depth == 6)
5301     return SDValue();  // Limit search depth.
5302
5303   SDValue V = SDValue(N, 0);
5304   EVT VT = V.getValueType();
5305   unsigned Opcode = V.getOpcode();
5306
5307   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5308   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5309     int Elt = SV->getMaskElt(Index);
5310
5311     if (Elt < 0)
5312       return DAG.getUNDEF(VT.getVectorElementType());
5313
5314     unsigned NumElems = VT.getVectorNumElements();
5315     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5316                                          : SV->getOperand(1);
5317     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5318   }
5319
5320   // Recurse into target specific vector shuffles to find scalars.
5321   if (isTargetShuffle(Opcode)) {
5322     MVT ShufVT = V.getSimpleValueType();
5323     unsigned NumElems = ShufVT.getVectorNumElements();
5324     SmallVector<int, 16> ShuffleMask;
5325     bool IsUnary;
5326
5327     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5328       return SDValue();
5329
5330     int Elt = ShuffleMask[Index];
5331     if (Elt < 0)
5332       return DAG.getUNDEF(ShufVT.getVectorElementType());
5333
5334     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5335                                          : N->getOperand(1);
5336     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5337                                Depth+1);
5338   }
5339
5340   // Actual nodes that may contain scalar elements
5341   if (Opcode == ISD::BITCAST) {
5342     V = V.getOperand(0);
5343     EVT SrcVT = V.getValueType();
5344     unsigned NumElems = VT.getVectorNumElements();
5345
5346     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5347       return SDValue();
5348   }
5349
5350   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5351     return (Index == 0) ? V.getOperand(0)
5352                         : DAG.getUNDEF(VT.getVectorElementType());
5353
5354   if (V.getOpcode() == ISD::BUILD_VECTOR)
5355     return V.getOperand(Index);
5356
5357   return SDValue();
5358 }
5359
5360 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5361 /// shuffle operation which come from a consecutively from a zero. The
5362 /// search can start in two different directions, from left or right.
5363 /// We count undefs as zeros until PreferredNum is reached.
5364 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5365                                          unsigned NumElems, bool ZerosFromLeft,
5366                                          SelectionDAG &DAG,
5367                                          unsigned PreferredNum = -1U) {
5368   unsigned NumZeros = 0;
5369   for (unsigned i = 0; i != NumElems; ++i) {
5370     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5371     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5372     if (!Elt.getNode())
5373       break;
5374
5375     if (X86::isZeroNode(Elt))
5376       ++NumZeros;
5377     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5378       NumZeros = std::min(NumZeros + 1, PreferredNum);
5379     else
5380       break;
5381   }
5382
5383   return NumZeros;
5384 }
5385
5386 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5387 /// correspond consecutively to elements from one of the vector operands,
5388 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5389 static
5390 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5391                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5392                               unsigned NumElems, unsigned &OpNum) {
5393   bool SeenV1 = false;
5394   bool SeenV2 = false;
5395
5396   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5397     int Idx = SVOp->getMaskElt(i);
5398     // Ignore undef indicies
5399     if (Idx < 0)
5400       continue;
5401
5402     if (Idx < (int)NumElems)
5403       SeenV1 = true;
5404     else
5405       SeenV2 = true;
5406
5407     // Only accept consecutive elements from the same vector
5408     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5409       return false;
5410   }
5411
5412   OpNum = SeenV1 ? 0 : 1;
5413   return true;
5414 }
5415
5416 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5417 /// logical left shift of a vector.
5418 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5419                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5420   unsigned NumElems =
5421     SVOp->getSimpleValueType(0).getVectorNumElements();
5422   unsigned NumZeros = getNumOfConsecutiveZeros(
5423       SVOp, NumElems, false /* check zeros from right */, DAG,
5424       SVOp->getMaskElt(0));
5425   unsigned OpSrc;
5426
5427   if (!NumZeros)
5428     return false;
5429
5430   // Considering the elements in the mask that are not consecutive zeros,
5431   // check if they consecutively come from only one of the source vectors.
5432   //
5433   //               V1 = {X, A, B, C}     0
5434   //                         \  \  \    /
5435   //   vector_shuffle V1, V2 <1, 2, 3, X>
5436   //
5437   if (!isShuffleMaskConsecutive(SVOp,
5438             0,                   // Mask Start Index
5439             NumElems-NumZeros,   // Mask End Index(exclusive)
5440             NumZeros,            // Where to start looking in the src vector
5441             NumElems,            // Number of elements in vector
5442             OpSrc))              // Which source operand ?
5443     return false;
5444
5445   isLeft = false;
5446   ShAmt = NumZeros;
5447   ShVal = SVOp->getOperand(OpSrc);
5448   return true;
5449 }
5450
5451 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5452 /// logical left shift of a vector.
5453 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5454                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5455   unsigned NumElems =
5456     SVOp->getSimpleValueType(0).getVectorNumElements();
5457   unsigned NumZeros = getNumOfConsecutiveZeros(
5458       SVOp, NumElems, true /* check zeros from left */, DAG,
5459       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5460   unsigned OpSrc;
5461
5462   if (!NumZeros)
5463     return false;
5464
5465   // Considering the elements in the mask that are not consecutive zeros,
5466   // check if they consecutively come from only one of the source vectors.
5467   //
5468   //                           0    { A, B, X, X } = V2
5469   //                          / \    /  /
5470   //   vector_shuffle V1, V2 <X, X, 4, 5>
5471   //
5472   if (!isShuffleMaskConsecutive(SVOp,
5473             NumZeros,     // Mask Start Index
5474             NumElems,     // Mask End Index(exclusive)
5475             0,            // Where to start looking in the src vector
5476             NumElems,     // Number of elements in vector
5477             OpSrc))       // Which source operand ?
5478     return false;
5479
5480   isLeft = true;
5481   ShAmt = NumZeros;
5482   ShVal = SVOp->getOperand(OpSrc);
5483   return true;
5484 }
5485
5486 /// isVectorShift - Returns true if the shuffle can be implemented as a
5487 /// logical left or right shift of a vector.
5488 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5489                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5490   // Although the logic below support any bitwidth size, there are no
5491   // shift instructions which handle more than 128-bit vectors.
5492   if (!SVOp->getSimpleValueType(0).is128BitVector())
5493     return false;
5494
5495   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5496       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5497     return true;
5498
5499   return false;
5500 }
5501
5502 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5503 ///
5504 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5505                                        unsigned NumNonZero, unsigned NumZero,
5506                                        SelectionDAG &DAG,
5507                                        const X86Subtarget* Subtarget,
5508                                        const TargetLowering &TLI) {
5509   if (NumNonZero > 8)
5510     return SDValue();
5511
5512   SDLoc dl(Op);
5513   SDValue V;
5514   bool First = true;
5515   for (unsigned i = 0; i < 16; ++i) {
5516     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5517     if (ThisIsNonZero && First) {
5518       if (NumZero)
5519         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5520       else
5521         V = DAG.getUNDEF(MVT::v8i16);
5522       First = false;
5523     }
5524
5525     if ((i & 1) != 0) {
5526       SDValue ThisElt, LastElt;
5527       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5528       if (LastIsNonZero) {
5529         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5530                               MVT::i16, Op.getOperand(i-1));
5531       }
5532       if (ThisIsNonZero) {
5533         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5534         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5535                               ThisElt, DAG.getConstant(8, MVT::i8));
5536         if (LastIsNonZero)
5537           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5538       } else
5539         ThisElt = LastElt;
5540
5541       if (ThisElt.getNode())
5542         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5543                         DAG.getIntPtrConstant(i/2));
5544     }
5545   }
5546
5547   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5548 }
5549
5550 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5551 ///
5552 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5553                                      unsigned NumNonZero, unsigned NumZero,
5554                                      SelectionDAG &DAG,
5555                                      const X86Subtarget* Subtarget,
5556                                      const TargetLowering &TLI) {
5557   if (NumNonZero > 4)
5558     return SDValue();
5559
5560   SDLoc dl(Op);
5561   SDValue V;
5562   bool First = true;
5563   for (unsigned i = 0; i < 8; ++i) {
5564     bool isNonZero = (NonZeros & (1 << i)) != 0;
5565     if (isNonZero) {
5566       if (First) {
5567         if (NumZero)
5568           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5569         else
5570           V = DAG.getUNDEF(MVT::v8i16);
5571         First = false;
5572       }
5573       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5574                       MVT::v8i16, V, Op.getOperand(i),
5575                       DAG.getIntPtrConstant(i));
5576     }
5577   }
5578
5579   return V;
5580 }
5581
5582 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5583 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5584                                      unsigned NonZeros, unsigned NumNonZero,
5585                                      unsigned NumZero, SelectionDAG &DAG,
5586                                      const X86Subtarget *Subtarget,
5587                                      const TargetLowering &TLI) {
5588   // We know there's at least one non-zero element
5589   unsigned FirstNonZeroIdx = 0;
5590   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5591   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5592          X86::isZeroNode(FirstNonZero)) {
5593     ++FirstNonZeroIdx;
5594     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5595   }
5596
5597   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5598       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5599     return SDValue();
5600
5601   SDValue V = FirstNonZero.getOperand(0);
5602   MVT VVT = V.getSimpleValueType();
5603   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5604     return SDValue();
5605
5606   unsigned FirstNonZeroDst =
5607       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5608   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5609   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5610   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5611
5612   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5613     SDValue Elem = Op.getOperand(Idx);
5614     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5615       continue;
5616
5617     // TODO: What else can be here? Deal with it.
5618     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5619       return SDValue();
5620
5621     // TODO: Some optimizations are still possible here
5622     // ex: Getting one element from a vector, and the rest from another.
5623     if (Elem.getOperand(0) != V)
5624       return SDValue();
5625
5626     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5627     if (Dst == Idx)
5628       ++CorrectIdx;
5629     else if (IncorrectIdx == -1U) {
5630       IncorrectIdx = Idx;
5631       IncorrectDst = Dst;
5632     } else
5633       // There was already one element with an incorrect index.
5634       // We can't optimize this case to an insertps.
5635       return SDValue();
5636   }
5637
5638   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5639     SDLoc dl(Op);
5640     EVT VT = Op.getSimpleValueType();
5641     unsigned ElementMoveMask = 0;
5642     if (IncorrectIdx == -1U)
5643       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5644     else
5645       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5646
5647     SDValue InsertpsMask =
5648         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5649     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5650   }
5651
5652   return SDValue();
5653 }
5654
5655 /// getVShift - Return a vector logical shift node.
5656 ///
5657 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5658                          unsigned NumBits, SelectionDAG &DAG,
5659                          const TargetLowering &TLI, SDLoc dl) {
5660   assert(VT.is128BitVector() && "Unknown type for VShift");
5661   EVT ShVT = MVT::v2i64;
5662   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5663   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5664   return DAG.getNode(ISD::BITCAST, dl, VT,
5665                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5666                              DAG.getConstant(NumBits,
5667                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5668 }
5669
5670 static SDValue
5671 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5672
5673   // Check if the scalar load can be widened into a vector load. And if
5674   // the address is "base + cst" see if the cst can be "absorbed" into
5675   // the shuffle mask.
5676   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5677     SDValue Ptr = LD->getBasePtr();
5678     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5679       return SDValue();
5680     EVT PVT = LD->getValueType(0);
5681     if (PVT != MVT::i32 && PVT != MVT::f32)
5682       return SDValue();
5683
5684     int FI = -1;
5685     int64_t Offset = 0;
5686     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5687       FI = FINode->getIndex();
5688       Offset = 0;
5689     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5690                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5691       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5692       Offset = Ptr.getConstantOperandVal(1);
5693       Ptr = Ptr.getOperand(0);
5694     } else {
5695       return SDValue();
5696     }
5697
5698     // FIXME: 256-bit vector instructions don't require a strict alignment,
5699     // improve this code to support it better.
5700     unsigned RequiredAlign = VT.getSizeInBits()/8;
5701     SDValue Chain = LD->getChain();
5702     // Make sure the stack object alignment is at least 16 or 32.
5703     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5704     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5705       if (MFI->isFixedObjectIndex(FI)) {
5706         // Can't change the alignment. FIXME: It's possible to compute
5707         // the exact stack offset and reference FI + adjust offset instead.
5708         // If someone *really* cares about this. That's the way to implement it.
5709         return SDValue();
5710       } else {
5711         MFI->setObjectAlignment(FI, RequiredAlign);
5712       }
5713     }
5714
5715     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5716     // Ptr + (Offset & ~15).
5717     if (Offset < 0)
5718       return SDValue();
5719     if ((Offset % RequiredAlign) & 3)
5720       return SDValue();
5721     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5722     if (StartOffset)
5723       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5724                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5725
5726     int EltNo = (Offset - StartOffset) >> 2;
5727     unsigned NumElems = VT.getVectorNumElements();
5728
5729     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5730     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5731                              LD->getPointerInfo().getWithOffset(StartOffset),
5732                              false, false, false, 0);
5733
5734     SmallVector<int, 8> Mask;
5735     for (unsigned i = 0; i != NumElems; ++i)
5736       Mask.push_back(EltNo);
5737
5738     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5739   }
5740
5741   return SDValue();
5742 }
5743
5744 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5745 /// vector of type 'VT', see if the elements can be replaced by a single large
5746 /// load which has the same value as a build_vector whose operands are 'elts'.
5747 ///
5748 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5749 ///
5750 /// FIXME: we'd also like to handle the case where the last elements are zero
5751 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5752 /// There's even a handy isZeroNode for that purpose.
5753 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5754                                         SDLoc &DL, SelectionDAG &DAG,
5755                                         bool isAfterLegalize) {
5756   EVT EltVT = VT.getVectorElementType();
5757   unsigned NumElems = Elts.size();
5758
5759   LoadSDNode *LDBase = nullptr;
5760   unsigned LastLoadedElt = -1U;
5761
5762   // For each element in the initializer, see if we've found a load or an undef.
5763   // If we don't find an initial load element, or later load elements are
5764   // non-consecutive, bail out.
5765   for (unsigned i = 0; i < NumElems; ++i) {
5766     SDValue Elt = Elts[i];
5767
5768     if (!Elt.getNode() ||
5769         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5770       return SDValue();
5771     if (!LDBase) {
5772       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5773         return SDValue();
5774       LDBase = cast<LoadSDNode>(Elt.getNode());
5775       LastLoadedElt = i;
5776       continue;
5777     }
5778     if (Elt.getOpcode() == ISD::UNDEF)
5779       continue;
5780
5781     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5782     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5783       return SDValue();
5784     LastLoadedElt = i;
5785   }
5786
5787   // If we have found an entire vector of loads and undefs, then return a large
5788   // load of the entire vector width starting at the base pointer.  If we found
5789   // consecutive loads for the low half, generate a vzext_load node.
5790   if (LastLoadedElt == NumElems - 1) {
5791
5792     if (isAfterLegalize &&
5793         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5794       return SDValue();
5795
5796     SDValue NewLd = SDValue();
5797
5798     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5799       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5800                           LDBase->getPointerInfo(),
5801                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5802                           LDBase->isInvariant(), 0);
5803     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5804                         LDBase->getPointerInfo(),
5805                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5806                         LDBase->isInvariant(), LDBase->getAlignment());
5807
5808     if (LDBase->hasAnyUseOfValue(1)) {
5809       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5810                                      SDValue(LDBase, 1),
5811                                      SDValue(NewLd.getNode(), 1));
5812       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5813       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5814                              SDValue(NewLd.getNode(), 1));
5815     }
5816
5817     return NewLd;
5818   }
5819   if (NumElems == 4 && LastLoadedElt == 1 &&
5820       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5821     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5822     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5823     SDValue ResNode =
5824         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5825                                 LDBase->getPointerInfo(),
5826                                 LDBase->getAlignment(),
5827                                 false/*isVolatile*/, true/*ReadMem*/,
5828                                 false/*WriteMem*/);
5829
5830     // Make sure the newly-created LOAD is in the same position as LDBase in
5831     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5832     // update uses of LDBase's output chain to use the TokenFactor.
5833     if (LDBase->hasAnyUseOfValue(1)) {
5834       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5835                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5836       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5837       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5838                              SDValue(ResNode.getNode(), 1));
5839     }
5840
5841     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5842   }
5843   return SDValue();
5844 }
5845
5846 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5847 /// to generate a splat value for the following cases:
5848 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5849 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5850 /// a scalar load, or a constant.
5851 /// The VBROADCAST node is returned when a pattern is found,
5852 /// or SDValue() otherwise.
5853 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5854                                     SelectionDAG &DAG) {
5855   if (!Subtarget->hasFp256())
5856     return SDValue();
5857
5858   MVT VT = Op.getSimpleValueType();
5859   SDLoc dl(Op);
5860
5861   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5862          "Unsupported vector type for broadcast.");
5863
5864   SDValue Ld;
5865   bool ConstSplatVal;
5866
5867   switch (Op.getOpcode()) {
5868     default:
5869       // Unknown pattern found.
5870       return SDValue();
5871
5872     case ISD::BUILD_VECTOR: {
5873       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5874       BitVector UndefElements;
5875       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5876
5877       // We need a splat of a single value to use broadcast, and it doesn't
5878       // make any sense if the value is only in one element of the vector.
5879       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5880         return SDValue();
5881
5882       Ld = Splat;
5883       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5884                        Ld.getOpcode() == ISD::ConstantFP);
5885
5886       // Make sure that all of the users of a non-constant load are from the
5887       // BUILD_VECTOR node.
5888       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5889         return SDValue();
5890       break;
5891     }
5892
5893     case ISD::VECTOR_SHUFFLE: {
5894       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5895
5896       // Shuffles must have a splat mask where the first element is
5897       // broadcasted.
5898       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5899         return SDValue();
5900
5901       SDValue Sc = Op.getOperand(0);
5902       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5903           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5904
5905         if (!Subtarget->hasInt256())
5906           return SDValue();
5907
5908         // Use the register form of the broadcast instruction available on AVX2.
5909         if (VT.getSizeInBits() >= 256)
5910           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5911         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5912       }
5913
5914       Ld = Sc.getOperand(0);
5915       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5916                        Ld.getOpcode() == ISD::ConstantFP);
5917
5918       // The scalar_to_vector node and the suspected
5919       // load node must have exactly one user.
5920       // Constants may have multiple users.
5921
5922       // AVX-512 has register version of the broadcast
5923       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5924         Ld.getValueType().getSizeInBits() >= 32;
5925       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5926           !hasRegVer))
5927         return SDValue();
5928       break;
5929     }
5930   }
5931
5932   bool IsGE256 = (VT.getSizeInBits() >= 256);
5933
5934   // Handle the broadcasting a single constant scalar from the constant pool
5935   // into a vector. On Sandybridge it is still better to load a constant vector
5936   // from the constant pool and not to broadcast it from a scalar.
5937   if (ConstSplatVal && Subtarget->hasInt256()) {
5938     EVT CVT = Ld.getValueType();
5939     assert(!CVT.isVector() && "Must not broadcast a vector type");
5940     unsigned ScalarSize = CVT.getSizeInBits();
5941
5942     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5943       const Constant *C = nullptr;
5944       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5945         C = CI->getConstantIntValue();
5946       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5947         C = CF->getConstantFPValue();
5948
5949       assert(C && "Invalid constant type");
5950
5951       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5952       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5953       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5954       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5955                        MachinePointerInfo::getConstantPool(),
5956                        false, false, false, Alignment);
5957
5958       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5959     }
5960   }
5961
5962   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5963   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5964
5965   // Handle AVX2 in-register broadcasts.
5966   if (!IsLoad && Subtarget->hasInt256() &&
5967       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5968     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5969
5970   // The scalar source must be a normal load.
5971   if (!IsLoad)
5972     return SDValue();
5973
5974   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5975     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5976
5977   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5978   // double since there is no vbroadcastsd xmm
5979   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5980     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5981       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5982   }
5983
5984   // Unsupported broadcast.
5985   return SDValue();
5986 }
5987
5988 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5989 /// underlying vector and index.
5990 ///
5991 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5992 /// index.
5993 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5994                                          SDValue ExtIdx) {
5995   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5996   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5997     return Idx;
5998
5999   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
6000   // lowered this:
6001   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
6002   // to:
6003   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
6004   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
6005   //                           undef)
6006   //                       Constant<0>)
6007   // In this case the vector is the extract_subvector expression and the index
6008   // is 2, as specified by the shuffle.
6009   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
6010   SDValue ShuffleVec = SVOp->getOperand(0);
6011   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
6012   assert(ShuffleVecVT.getVectorElementType() ==
6013          ExtractedFromVec.getSimpleValueType().getVectorElementType());
6014
6015   int ShuffleIdx = SVOp->getMaskElt(Idx);
6016   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
6017     ExtractedFromVec = ShuffleVec;
6018     return ShuffleIdx;
6019   }
6020   return Idx;
6021 }
6022
6023 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
6024   MVT VT = Op.getSimpleValueType();
6025
6026   // Skip if insert_vec_elt is not supported.
6027   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6028   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
6029     return SDValue();
6030
6031   SDLoc DL(Op);
6032   unsigned NumElems = Op.getNumOperands();
6033
6034   SDValue VecIn1;
6035   SDValue VecIn2;
6036   SmallVector<unsigned, 4> InsertIndices;
6037   SmallVector<int, 8> Mask(NumElems, -1);
6038
6039   for (unsigned i = 0; i != NumElems; ++i) {
6040     unsigned Opc = Op.getOperand(i).getOpcode();
6041
6042     if (Opc == ISD::UNDEF)
6043       continue;
6044
6045     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
6046       // Quit if more than 1 elements need inserting.
6047       if (InsertIndices.size() > 1)
6048         return SDValue();
6049
6050       InsertIndices.push_back(i);
6051       continue;
6052     }
6053
6054     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
6055     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
6056     // Quit if non-constant index.
6057     if (!isa<ConstantSDNode>(ExtIdx))
6058       return SDValue();
6059     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
6060
6061     // Quit if extracted from vector of different type.
6062     if (ExtractedFromVec.getValueType() != VT)
6063       return SDValue();
6064
6065     if (!VecIn1.getNode())
6066       VecIn1 = ExtractedFromVec;
6067     else if (VecIn1 != ExtractedFromVec) {
6068       if (!VecIn2.getNode())
6069         VecIn2 = ExtractedFromVec;
6070       else if (VecIn2 != ExtractedFromVec)
6071         // Quit if more than 2 vectors to shuffle
6072         return SDValue();
6073     }
6074
6075     if (ExtractedFromVec == VecIn1)
6076       Mask[i] = Idx;
6077     else if (ExtractedFromVec == VecIn2)
6078       Mask[i] = Idx + NumElems;
6079   }
6080
6081   if (!VecIn1.getNode())
6082     return SDValue();
6083
6084   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6085   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
6086   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
6087     unsigned Idx = InsertIndices[i];
6088     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
6089                      DAG.getIntPtrConstant(Idx));
6090   }
6091
6092   return NV;
6093 }
6094
6095 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6096 SDValue
6097 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6098
6099   MVT VT = Op.getSimpleValueType();
6100   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6101          "Unexpected type in LowerBUILD_VECTORvXi1!");
6102
6103   SDLoc dl(Op);
6104   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6105     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6106     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6107     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6108   }
6109
6110   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6111     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6112     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6113     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6114   }
6115
6116   bool AllContants = true;
6117   uint64_t Immediate = 0;
6118   int NonConstIdx = -1;
6119   bool IsSplat = true;
6120   unsigned NumNonConsts = 0;
6121   unsigned NumConsts = 0;
6122   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6123     SDValue In = Op.getOperand(idx);
6124     if (In.getOpcode() == ISD::UNDEF)
6125       continue;
6126     if (!isa<ConstantSDNode>(In)) {
6127       AllContants = false;
6128       NonConstIdx = idx;
6129       NumNonConsts++;
6130     }
6131     else {
6132       NumConsts++;
6133       if (cast<ConstantSDNode>(In)->getZExtValue())
6134       Immediate |= (1ULL << idx);
6135     }
6136     if (In != Op.getOperand(0))
6137       IsSplat = false;
6138   }
6139
6140   if (AllContants) {
6141     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6142       DAG.getConstant(Immediate, MVT::i16));
6143     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6144                        DAG.getIntPtrConstant(0));
6145   }
6146
6147   if (NumNonConsts == 1 && NonConstIdx != 0) {
6148     SDValue DstVec;
6149     if (NumConsts) {
6150       SDValue VecAsImm = DAG.getConstant(Immediate,
6151                                          MVT::getIntegerVT(VT.getSizeInBits()));
6152       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6153     }
6154     else 
6155       DstVec = DAG.getUNDEF(VT);
6156     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6157                        Op.getOperand(NonConstIdx),
6158                        DAG.getIntPtrConstant(NonConstIdx));
6159   }
6160   if (!IsSplat && (NonConstIdx != 0))
6161     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6162   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6163   SDValue Select;
6164   if (IsSplat)
6165     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6166                           DAG.getConstant(-1, SelectVT),
6167                           DAG.getConstant(0, SelectVT));
6168   else
6169     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6170                          DAG.getConstant((Immediate | 1), SelectVT),
6171                          DAG.getConstant(Immediate, SelectVT));
6172   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6173 }
6174
6175 /// \brief Return true if \p N implements a horizontal binop and return the
6176 /// operands for the horizontal binop into V0 and V1.
6177 /// 
6178 /// This is a helper function of PerformBUILD_VECTORCombine.
6179 /// This function checks that the build_vector \p N in input implements a
6180 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6181 /// operation to match.
6182 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6183 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6184 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6185 /// arithmetic sub.
6186 ///
6187 /// This function only analyzes elements of \p N whose indices are
6188 /// in range [BaseIdx, LastIdx).
6189 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6190                               SelectionDAG &DAG,
6191                               unsigned BaseIdx, unsigned LastIdx,
6192                               SDValue &V0, SDValue &V1) {
6193   EVT VT = N->getValueType(0);
6194
6195   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6196   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6197          "Invalid Vector in input!");
6198   
6199   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6200   bool CanFold = true;
6201   unsigned ExpectedVExtractIdx = BaseIdx;
6202   unsigned NumElts = LastIdx - BaseIdx;
6203   V0 = DAG.getUNDEF(VT);
6204   V1 = DAG.getUNDEF(VT);
6205
6206   // Check if N implements a horizontal binop.
6207   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6208     SDValue Op = N->getOperand(i + BaseIdx);
6209
6210     // Skip UNDEFs.
6211     if (Op->getOpcode() == ISD::UNDEF) {
6212       // Update the expected vector extract index.
6213       if (i * 2 == NumElts)
6214         ExpectedVExtractIdx = BaseIdx;
6215       ExpectedVExtractIdx += 2;
6216       continue;
6217     }
6218
6219     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6220
6221     if (!CanFold)
6222       break;
6223
6224     SDValue Op0 = Op.getOperand(0);
6225     SDValue Op1 = Op.getOperand(1);
6226
6227     // Try to match the following pattern:
6228     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6229     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6230         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6231         Op0.getOperand(0) == Op1.getOperand(0) &&
6232         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6233         isa<ConstantSDNode>(Op1.getOperand(1)));
6234     if (!CanFold)
6235       break;
6236
6237     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6238     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6239
6240     if (i * 2 < NumElts) {
6241       if (V0.getOpcode() == ISD::UNDEF)
6242         V0 = Op0.getOperand(0);
6243     } else {
6244       if (V1.getOpcode() == ISD::UNDEF)
6245         V1 = Op0.getOperand(0);
6246       if (i * 2 == NumElts)
6247         ExpectedVExtractIdx = BaseIdx;
6248     }
6249
6250     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6251     if (I0 == ExpectedVExtractIdx)
6252       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6253     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6254       // Try to match the following dag sequence:
6255       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6256       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6257     } else
6258       CanFold = false;
6259
6260     ExpectedVExtractIdx += 2;
6261   }
6262
6263   return CanFold;
6264 }
6265
6266 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6267 /// a concat_vector. 
6268 ///
6269 /// This is a helper function of PerformBUILD_VECTORCombine.
6270 /// This function expects two 256-bit vectors called V0 and V1.
6271 /// At first, each vector is split into two separate 128-bit vectors.
6272 /// Then, the resulting 128-bit vectors are used to implement two
6273 /// horizontal binary operations. 
6274 ///
6275 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6276 ///
6277 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6278 /// the two new horizontal binop.
6279 /// When Mode is set, the first horizontal binop dag node would take as input
6280 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6281 /// horizontal binop dag node would take as input the lower 128-bit of V1
6282 /// and the upper 128-bit of V1.
6283 ///   Example:
6284 ///     HADD V0_LO, V0_HI
6285 ///     HADD V1_LO, V1_HI
6286 ///
6287 /// Otherwise, the first horizontal binop dag node takes as input the lower
6288 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6289 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6290 ///   Example:
6291 ///     HADD V0_LO, V1_LO
6292 ///     HADD V0_HI, V1_HI
6293 ///
6294 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6295 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6296 /// the upper 128-bits of the result.
6297 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6298                                      SDLoc DL, SelectionDAG &DAG,
6299                                      unsigned X86Opcode, bool Mode,
6300                                      bool isUndefLO, bool isUndefHI) {
6301   EVT VT = V0.getValueType();
6302   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6303          "Invalid nodes in input!");
6304
6305   unsigned NumElts = VT.getVectorNumElements();
6306   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6307   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6308   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6309   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6310   EVT NewVT = V0_LO.getValueType();
6311
6312   SDValue LO = DAG.getUNDEF(NewVT);
6313   SDValue HI = DAG.getUNDEF(NewVT);
6314
6315   if (Mode) {
6316     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6317     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6318       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6319     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6320       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6321   } else {
6322     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6323     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6324                        V1_LO->getOpcode() != ISD::UNDEF))
6325       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6326
6327     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6328                        V1_HI->getOpcode() != ISD::UNDEF))
6329       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6330   }
6331
6332   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6333 }
6334
6335 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6336 /// sequence of 'vadd + vsub + blendi'.
6337 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6338                            const X86Subtarget *Subtarget) {
6339   SDLoc DL(BV);
6340   EVT VT = BV->getValueType(0);
6341   unsigned NumElts = VT.getVectorNumElements();
6342   SDValue InVec0 = DAG.getUNDEF(VT);
6343   SDValue InVec1 = DAG.getUNDEF(VT);
6344
6345   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6346           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6347
6348   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6349   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6350   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6351     return SDValue();
6352
6353   // Odd-numbered elements in the input build vector are obtained from
6354   // adding two integer/float elements.
6355   // Even-numbered elements in the input build vector are obtained from
6356   // subtracting two integer/float elements.
6357   unsigned ExpectedOpcode = ISD::FSUB;
6358   unsigned NextExpectedOpcode = ISD::FADD;
6359   bool AddFound = false;
6360   bool SubFound = false;
6361
6362   for (unsigned i = 0, e = NumElts; i != e; i++) {
6363     SDValue Op = BV->getOperand(i);
6364       
6365     // Skip 'undef' values.
6366     unsigned Opcode = Op.getOpcode();
6367     if (Opcode == ISD::UNDEF) {
6368       std::swap(ExpectedOpcode, NextExpectedOpcode);
6369       continue;
6370     }
6371       
6372     // Early exit if we found an unexpected opcode.
6373     if (Opcode != ExpectedOpcode)
6374       return SDValue();
6375
6376     SDValue Op0 = Op.getOperand(0);
6377     SDValue Op1 = Op.getOperand(1);
6378
6379     // Try to match the following pattern:
6380     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6381     // Early exit if we cannot match that sequence.
6382     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6383         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6384         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6385         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6386         Op0.getOperand(1) != Op1.getOperand(1))
6387       return SDValue();
6388
6389     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6390     if (I0 != i)
6391       return SDValue();
6392
6393     // We found a valid add/sub node. Update the information accordingly.
6394     if (i & 1)
6395       AddFound = true;
6396     else
6397       SubFound = true;
6398
6399     // Update InVec0 and InVec1.
6400     if (InVec0.getOpcode() == ISD::UNDEF)
6401       InVec0 = Op0.getOperand(0);
6402     if (InVec1.getOpcode() == ISD::UNDEF)
6403       InVec1 = Op1.getOperand(0);
6404
6405     // Make sure that operands in input to each add/sub node always
6406     // come from a same pair of vectors.
6407     if (InVec0 != Op0.getOperand(0)) {
6408       if (ExpectedOpcode == ISD::FSUB)
6409         return SDValue();
6410
6411       // FADD is commutable. Try to commute the operands
6412       // and then test again.
6413       std::swap(Op0, Op1);
6414       if (InVec0 != Op0.getOperand(0))
6415         return SDValue();
6416     }
6417
6418     if (InVec1 != Op1.getOperand(0))
6419       return SDValue();
6420
6421     // Update the pair of expected opcodes.
6422     std::swap(ExpectedOpcode, NextExpectedOpcode);
6423   }
6424
6425   // Don't try to fold this build_vector into a VSELECT if it has
6426   // too many UNDEF operands.
6427   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6428       InVec1.getOpcode() != ISD::UNDEF) {
6429     // Emit a sequence of vector add and sub followed by a VSELECT.
6430     // The new VSELECT will be lowered into a BLENDI.
6431     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6432     // and emit a single ADDSUB instruction.
6433     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6434     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6435
6436     // Construct the VSELECT mask.
6437     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6438     EVT SVT = MaskVT.getVectorElementType();
6439     unsigned SVTBits = SVT.getSizeInBits();
6440     SmallVector<SDValue, 8> Ops;
6441
6442     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6443       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6444                             APInt::getAllOnesValue(SVTBits);
6445       SDValue Constant = DAG.getConstant(Value, SVT);
6446       Ops.push_back(Constant);
6447     }
6448
6449     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6450     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6451   }
6452   
6453   return SDValue();
6454 }
6455
6456 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6457                                           const X86Subtarget *Subtarget) {
6458   SDLoc DL(N);
6459   EVT VT = N->getValueType(0);
6460   unsigned NumElts = VT.getVectorNumElements();
6461   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6462   SDValue InVec0, InVec1;
6463
6464   // Try to match an ADDSUB.
6465   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6466       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6467     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6468     if (Value.getNode())
6469       return Value;
6470   }
6471
6472   // Try to match horizontal ADD/SUB.
6473   unsigned NumUndefsLO = 0;
6474   unsigned NumUndefsHI = 0;
6475   unsigned Half = NumElts/2;
6476
6477   // Count the number of UNDEF operands in the build_vector in input.
6478   for (unsigned i = 0, e = Half; i != e; ++i)
6479     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6480       NumUndefsLO++;
6481
6482   for (unsigned i = Half, e = NumElts; i != e; ++i)
6483     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6484       NumUndefsHI++;
6485
6486   // Early exit if this is either a build_vector of all UNDEFs or all the
6487   // operands but one are UNDEF.
6488   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6489     return SDValue();
6490
6491   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6492     // Try to match an SSE3 float HADD/HSUB.
6493     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6494       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6495     
6496     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6497       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6498   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6499     // Try to match an SSSE3 integer HADD/HSUB.
6500     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6501       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6502     
6503     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6504       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6505   }
6506   
6507   if (!Subtarget->hasAVX())
6508     return SDValue();
6509
6510   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6511     // Try to match an AVX horizontal add/sub of packed single/double
6512     // precision floating point values from 256-bit vectors.
6513     SDValue InVec2, InVec3;
6514     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6515         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6516         ((InVec0.getOpcode() == ISD::UNDEF ||
6517           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6518         ((InVec1.getOpcode() == ISD::UNDEF ||
6519           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6520       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6521
6522     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6523         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6524         ((InVec0.getOpcode() == ISD::UNDEF ||
6525           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6526         ((InVec1.getOpcode() == ISD::UNDEF ||
6527           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6528       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6529   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6530     // Try to match an AVX2 horizontal add/sub of signed integers.
6531     SDValue InVec2, InVec3;
6532     unsigned X86Opcode;
6533     bool CanFold = true;
6534
6535     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6536         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6537         ((InVec0.getOpcode() == ISD::UNDEF ||
6538           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6539         ((InVec1.getOpcode() == ISD::UNDEF ||
6540           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6541       X86Opcode = X86ISD::HADD;
6542     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6543         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6544         ((InVec0.getOpcode() == ISD::UNDEF ||
6545           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6546         ((InVec1.getOpcode() == ISD::UNDEF ||
6547           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6548       X86Opcode = X86ISD::HSUB;
6549     else
6550       CanFold = false;
6551
6552     if (CanFold) {
6553       // Fold this build_vector into a single horizontal add/sub.
6554       // Do this only if the target has AVX2.
6555       if (Subtarget->hasAVX2())
6556         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6557  
6558       // Do not try to expand this build_vector into a pair of horizontal
6559       // add/sub if we can emit a pair of scalar add/sub.
6560       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6561         return SDValue();
6562
6563       // Convert this build_vector into a pair of horizontal binop followed by
6564       // a concat vector.
6565       bool isUndefLO = NumUndefsLO == Half;
6566       bool isUndefHI = NumUndefsHI == Half;
6567       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6568                                    isUndefLO, isUndefHI);
6569     }
6570   }
6571
6572   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6573        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6574     unsigned X86Opcode;
6575     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6576       X86Opcode = X86ISD::HADD;
6577     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6578       X86Opcode = X86ISD::HSUB;
6579     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6580       X86Opcode = X86ISD::FHADD;
6581     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6582       X86Opcode = X86ISD::FHSUB;
6583     else
6584       return SDValue();
6585
6586     // Don't try to expand this build_vector into a pair of horizontal add/sub
6587     // if we can simply emit a pair of scalar add/sub.
6588     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6589       return SDValue();
6590
6591     // Convert this build_vector into two horizontal add/sub followed by
6592     // a concat vector.
6593     bool isUndefLO = NumUndefsLO == Half;
6594     bool isUndefHI = NumUndefsHI == Half;
6595     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6596                                  isUndefLO, isUndefHI);
6597   }
6598
6599   return SDValue();
6600 }
6601
6602 SDValue
6603 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6604   SDLoc dl(Op);
6605
6606   MVT VT = Op.getSimpleValueType();
6607   MVT ExtVT = VT.getVectorElementType();
6608   unsigned NumElems = Op.getNumOperands();
6609
6610   // Generate vectors for predicate vectors.
6611   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6612     return LowerBUILD_VECTORvXi1(Op, DAG);
6613
6614   // Vectors containing all zeros can be matched by pxor and xorps later
6615   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6616     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6617     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6618     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6619       return Op;
6620
6621     return getZeroVector(VT, Subtarget, DAG, dl);
6622   }
6623
6624   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6625   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6626   // vpcmpeqd on 256-bit vectors.
6627   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6628     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6629       return Op;
6630
6631     if (!VT.is512BitVector())
6632       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6633   }
6634
6635   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6636   if (Broadcast.getNode())
6637     return Broadcast;
6638
6639   unsigned EVTBits = ExtVT.getSizeInBits();
6640
6641   unsigned NumZero  = 0;
6642   unsigned NumNonZero = 0;
6643   unsigned NonZeros = 0;
6644   bool IsAllConstants = true;
6645   SmallSet<SDValue, 8> Values;
6646   for (unsigned i = 0; i < NumElems; ++i) {
6647     SDValue Elt = Op.getOperand(i);
6648     if (Elt.getOpcode() == ISD::UNDEF)
6649       continue;
6650     Values.insert(Elt);
6651     if (Elt.getOpcode() != ISD::Constant &&
6652         Elt.getOpcode() != ISD::ConstantFP)
6653       IsAllConstants = false;
6654     if (X86::isZeroNode(Elt))
6655       NumZero++;
6656     else {
6657       NonZeros |= (1 << i);
6658       NumNonZero++;
6659     }
6660   }
6661
6662   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6663   if (NumNonZero == 0)
6664     return DAG.getUNDEF(VT);
6665
6666   // Special case for single non-zero, non-undef, element.
6667   if (NumNonZero == 1) {
6668     unsigned Idx = countTrailingZeros(NonZeros);
6669     SDValue Item = Op.getOperand(Idx);
6670
6671     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6672     // the value are obviously zero, truncate the value to i32 and do the
6673     // insertion that way.  Only do this if the value is non-constant or if the
6674     // value is a constant being inserted into element 0.  It is cheaper to do
6675     // a constant pool load than it is to do a movd + shuffle.
6676     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6677         (!IsAllConstants || Idx == 0)) {
6678       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6679         // Handle SSE only.
6680         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6681         EVT VecVT = MVT::v4i32;
6682         unsigned VecElts = 4;
6683
6684         // Truncate the value (which may itself be a constant) to i32, and
6685         // convert it to a vector with movd (S2V+shuffle to zero extend).
6686         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6687         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6688         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6689
6690         // Now we have our 32-bit value zero extended in the low element of
6691         // a vector.  If Idx != 0, swizzle it into place.
6692         if (Idx != 0) {
6693           SmallVector<int, 4> Mask;
6694           Mask.push_back(Idx);
6695           for (unsigned i = 1; i != VecElts; ++i)
6696             Mask.push_back(i);
6697           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6698                                       &Mask[0]);
6699         }
6700         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6701       }
6702     }
6703
6704     // If we have a constant or non-constant insertion into the low element of
6705     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6706     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6707     // depending on what the source datatype is.
6708     if (Idx == 0) {
6709       if (NumZero == 0)
6710         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6711
6712       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6713           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6714         if (VT.is256BitVector() || VT.is512BitVector()) {
6715           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6716           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6717                              Item, DAG.getIntPtrConstant(0));
6718         }
6719         assert(VT.is128BitVector() && "Expected an SSE value type!");
6720         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6721         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6722         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6723       }
6724
6725       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6726         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6727         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6728         if (VT.is256BitVector()) {
6729           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6730           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6731         } else {
6732           assert(VT.is128BitVector() && "Expected an SSE value type!");
6733           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6734         }
6735         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6736       }
6737     }
6738
6739     // Is it a vector logical left shift?
6740     if (NumElems == 2 && Idx == 1 &&
6741         X86::isZeroNode(Op.getOperand(0)) &&
6742         !X86::isZeroNode(Op.getOperand(1))) {
6743       unsigned NumBits = VT.getSizeInBits();
6744       return getVShift(true, VT,
6745                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6746                                    VT, Op.getOperand(1)),
6747                        NumBits/2, DAG, *this, dl);
6748     }
6749
6750     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6751       return SDValue();
6752
6753     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6754     // is a non-constant being inserted into an element other than the low one,
6755     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6756     // movd/movss) to move this into the low element, then shuffle it into
6757     // place.
6758     if (EVTBits == 32) {
6759       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6760
6761       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6762       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6763       SmallVector<int, 8> MaskVec;
6764       for (unsigned i = 0; i != NumElems; ++i)
6765         MaskVec.push_back(i == Idx ? 0 : 1);
6766       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6767     }
6768   }
6769
6770   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6771   if (Values.size() == 1) {
6772     if (EVTBits == 32) {
6773       // Instead of a shuffle like this:
6774       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6775       // Check if it's possible to issue this instead.
6776       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6777       unsigned Idx = countTrailingZeros(NonZeros);
6778       SDValue Item = Op.getOperand(Idx);
6779       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6780         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6781     }
6782     return SDValue();
6783   }
6784
6785   // A vector full of immediates; various special cases are already
6786   // handled, so this is best done with a single constant-pool load.
6787   if (IsAllConstants)
6788     return SDValue();
6789
6790   // For AVX-length vectors, build the individual 128-bit pieces and use
6791   // shuffles to put them in place.
6792   if (VT.is256BitVector() || VT.is512BitVector()) {
6793     SmallVector<SDValue, 64> V;
6794     for (unsigned i = 0; i != NumElems; ++i)
6795       V.push_back(Op.getOperand(i));
6796
6797     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6798
6799     // Build both the lower and upper subvector.
6800     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6801                                 makeArrayRef(&V[0], NumElems/2));
6802     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6803                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6804
6805     // Recreate the wider vector with the lower and upper part.
6806     if (VT.is256BitVector())
6807       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6808     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6809   }
6810
6811   // Let legalizer expand 2-wide build_vectors.
6812   if (EVTBits == 64) {
6813     if (NumNonZero == 1) {
6814       // One half is zero or undef.
6815       unsigned Idx = countTrailingZeros(NonZeros);
6816       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6817                                  Op.getOperand(Idx));
6818       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6819     }
6820     return SDValue();
6821   }
6822
6823   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6824   if (EVTBits == 8 && NumElems == 16) {
6825     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6826                                         Subtarget, *this);
6827     if (V.getNode()) return V;
6828   }
6829
6830   if (EVTBits == 16 && NumElems == 8) {
6831     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6832                                       Subtarget, *this);
6833     if (V.getNode()) return V;
6834   }
6835
6836   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6837   if (EVTBits == 32 && NumElems == 4) {
6838     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6839                                       NumZero, DAG, Subtarget, *this);
6840     if (V.getNode())
6841       return V;
6842   }
6843
6844   // If element VT is == 32 bits, turn it into a number of shuffles.
6845   SmallVector<SDValue, 8> V(NumElems);
6846   if (NumElems == 4 && NumZero > 0) {
6847     for (unsigned i = 0; i < 4; ++i) {
6848       bool isZero = !(NonZeros & (1 << i));
6849       if (isZero)
6850         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6851       else
6852         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6853     }
6854
6855     for (unsigned i = 0; i < 2; ++i) {
6856       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6857         default: break;
6858         case 0:
6859           V[i] = V[i*2];  // Must be a zero vector.
6860           break;
6861         case 1:
6862           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6863           break;
6864         case 2:
6865           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6866           break;
6867         case 3:
6868           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6869           break;
6870       }
6871     }
6872
6873     bool Reverse1 = (NonZeros & 0x3) == 2;
6874     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6875     int MaskVec[] = {
6876       Reverse1 ? 1 : 0,
6877       Reverse1 ? 0 : 1,
6878       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6879       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6880     };
6881     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6882   }
6883
6884   if (Values.size() > 1 && VT.is128BitVector()) {
6885     // Check for a build vector of consecutive loads.
6886     for (unsigned i = 0; i < NumElems; ++i)
6887       V[i] = Op.getOperand(i);
6888
6889     // Check for elements which are consecutive loads.
6890     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6891     if (LD.getNode())
6892       return LD;
6893
6894     // Check for a build vector from mostly shuffle plus few inserting.
6895     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6896     if (Sh.getNode())
6897       return Sh;
6898
6899     // For SSE 4.1, use insertps to put the high elements into the low element.
6900     if (getSubtarget()->hasSSE41()) {
6901       SDValue Result;
6902       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6903         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6904       else
6905         Result = DAG.getUNDEF(VT);
6906
6907       for (unsigned i = 1; i < NumElems; ++i) {
6908         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6909         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6910                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6911       }
6912       return Result;
6913     }
6914
6915     // Otherwise, expand into a number of unpckl*, start by extending each of
6916     // our (non-undef) elements to the full vector width with the element in the
6917     // bottom slot of the vector (which generates no code for SSE).
6918     for (unsigned i = 0; i < NumElems; ++i) {
6919       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6920         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6921       else
6922         V[i] = DAG.getUNDEF(VT);
6923     }
6924
6925     // Next, we iteratively mix elements, e.g. for v4f32:
6926     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6927     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6928     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6929     unsigned EltStride = NumElems >> 1;
6930     while (EltStride != 0) {
6931       for (unsigned i = 0; i < EltStride; ++i) {
6932         // If V[i+EltStride] is undef and this is the first round of mixing,
6933         // then it is safe to just drop this shuffle: V[i] is already in the
6934         // right place, the one element (since it's the first round) being
6935         // inserted as undef can be dropped.  This isn't safe for successive
6936         // rounds because they will permute elements within both vectors.
6937         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6938             EltStride == NumElems/2)
6939           continue;
6940
6941         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6942       }
6943       EltStride >>= 1;
6944     }
6945     return V[0];
6946   }
6947   return SDValue();
6948 }
6949
6950 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6951 // to create 256-bit vectors from two other 128-bit ones.
6952 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6953   SDLoc dl(Op);
6954   MVT ResVT = Op.getSimpleValueType();
6955
6956   assert((ResVT.is256BitVector() ||
6957           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6958
6959   SDValue V1 = Op.getOperand(0);
6960   SDValue V2 = Op.getOperand(1);
6961   unsigned NumElems = ResVT.getVectorNumElements();
6962   if(ResVT.is256BitVector())
6963     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6964
6965   if (Op.getNumOperands() == 4) {
6966     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6967                                 ResVT.getVectorNumElements()/2);
6968     SDValue V3 = Op.getOperand(2);
6969     SDValue V4 = Op.getOperand(3);
6970     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6971       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6972   }
6973   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6974 }
6975
6976 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6977   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6978   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6979          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6980           Op.getNumOperands() == 4)));
6981
6982   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6983   // from two other 128-bit ones.
6984
6985   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6986   return LowerAVXCONCAT_VECTORS(Op, DAG);
6987 }
6988
6989
6990 //===----------------------------------------------------------------------===//
6991 // Vector shuffle lowering
6992 //
6993 // This is an experimental code path for lowering vector shuffles on x86. It is
6994 // designed to handle arbitrary vector shuffles and blends, gracefully
6995 // degrading performance as necessary. It works hard to recognize idiomatic
6996 // shuffles and lower them to optimal instruction patterns without leaving
6997 // a framework that allows reasonably efficient handling of all vector shuffle
6998 // patterns.
6999 //===----------------------------------------------------------------------===//
7000
7001 /// \brief Tiny helper function to identify a no-op mask.
7002 ///
7003 /// This is a somewhat boring predicate function. It checks whether the mask
7004 /// array input, which is assumed to be a single-input shuffle mask of the kind
7005 /// used by the X86 shuffle instructions (not a fully general
7006 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
7007 /// in-place shuffle are 'no-op's.
7008 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
7009   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7010     if (Mask[i] != -1 && Mask[i] != i)
7011       return false;
7012   return true;
7013 }
7014
7015 /// \brief Helper function to classify a mask as a single-input mask.
7016 ///
7017 /// This isn't a generic single-input test because in the vector shuffle
7018 /// lowering we canonicalize single inputs to be the first input operand. This
7019 /// means we can more quickly test for a single input by only checking whether
7020 /// an input from the second operand exists. We also assume that the size of
7021 /// mask corresponds to the size of the input vectors which isn't true in the
7022 /// fully general case.
7023 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
7024   for (int M : Mask)
7025     if (M >= (int)Mask.size())
7026       return false;
7027   return true;
7028 }
7029
7030 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
7031 ///
7032 /// This helper function produces an 8-bit shuffle immediate corresponding to
7033 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
7034 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
7035 /// example.
7036 ///
7037 /// NB: We rely heavily on "undef" masks preserving the input lane.
7038 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
7039                                           SelectionDAG &DAG) {
7040   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
7041   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
7042   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
7043   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
7044   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
7045
7046   unsigned Imm = 0;
7047   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
7048   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
7049   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
7050   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
7051   return DAG.getConstant(Imm, MVT::i8);
7052 }
7053
7054 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7055 ///
7056 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7057 /// support for floating point shuffles but not integer shuffles. These
7058 /// instructions will incur a domain crossing penalty on some chips though so
7059 /// it is better to avoid lowering through this for integer vectors where
7060 /// possible.
7061 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7062                                        const X86Subtarget *Subtarget,
7063                                        SelectionDAG &DAG) {
7064   SDLoc DL(Op);
7065   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7066   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7067   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7069   ArrayRef<int> Mask = SVOp->getMask();
7070   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7071
7072   if (isSingleInputShuffleMask(Mask)) {
7073     // Straight shuffle of a single input vector. Simulate this by using the
7074     // single input as both of the "inputs" to this instruction..
7075     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7076     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
7077                        DAG.getConstant(SHUFPDMask, MVT::i8));
7078   }
7079   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7080   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7081
7082   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7083   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
7084                      DAG.getConstant(SHUFPDMask, MVT::i8));
7085 }
7086
7087 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7088 ///
7089 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7090 /// the integer unit to minimize domain crossing penalties. However, for blends
7091 /// it falls back to the floating point shuffle operation with appropriate bit
7092 /// casting.
7093 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7094                                        const X86Subtarget *Subtarget,
7095                                        SelectionDAG &DAG) {
7096   SDLoc DL(Op);
7097   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7098   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7099   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7100   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7101   ArrayRef<int> Mask = SVOp->getMask();
7102   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7103
7104   if (isSingleInputShuffleMask(Mask)) {
7105     // Straight shuffle of a single input vector. For everything from SSE2
7106     // onward this has a single fast instruction with no scary immediates.
7107     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7108     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7109     int WidenedMask[4] = {
7110         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7111         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7112     return DAG.getNode(
7113         ISD::BITCAST, DL, MVT::v2i64,
7114         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7115                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7116   }
7117
7118   // We implement this with SHUFPD which is pretty lame because it will likely
7119   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7120   // However, all the alternatives are still more cycles and newer chips don't
7121   // have this problem. It would be really nice if x86 had better shuffles here.
7122   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7123   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7124   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7125                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7126 }
7127
7128 /// \brief Lower 4-lane 32-bit floating point shuffles.
7129 ///
7130 /// Uses instructions exclusively from the floating point unit to minimize
7131 /// domain crossing penalties, as these are sufficient to implement all v4f32
7132 /// shuffles.
7133 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7134                                        const X86Subtarget *Subtarget,
7135                                        SelectionDAG &DAG) {
7136   SDLoc DL(Op);
7137   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7138   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7139   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7140   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7141   ArrayRef<int> Mask = SVOp->getMask();
7142   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7143
7144   SDValue LowV = V1, HighV = V2;
7145   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7146
7147   int NumV2Elements =
7148       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7149
7150   if (NumV2Elements == 0)
7151     // Straight shuffle of a single input vector. We pass the input vector to
7152     // both operands to simulate this with a SHUFPS.
7153     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7154                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7155
7156   if (NumV2Elements == 1) {
7157     int V2Index =
7158         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7159         Mask.begin();
7160     // Compute the index adjacent to V2Index and in the same half by toggling
7161     // the low bit.
7162     int V2AdjIndex = V2Index ^ 1;
7163
7164     if (Mask[V2AdjIndex] == -1) {
7165       // Handles all the cases where we have a single V2 element and an undef.
7166       // This will only ever happen in the high lanes because we commute the
7167       // vector otherwise.
7168       if (V2Index < 2)
7169         std::swap(LowV, HighV);
7170       NewMask[V2Index] -= 4;
7171     } else {
7172       // Handle the case where the V2 element ends up adjacent to a V1 element.
7173       // To make this work, blend them together as the first step.
7174       int V1Index = V2AdjIndex;
7175       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7176       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7177                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7178
7179       // Now proceed to reconstruct the final blend as we have the necessary
7180       // high or low half formed.
7181       if (V2Index < 2) {
7182         LowV = V2;
7183         HighV = V1;
7184       } else {
7185         HighV = V2;
7186       }
7187       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7188       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7189     }
7190   } else if (NumV2Elements == 2) {
7191     if (Mask[0] < 4 && Mask[1] < 4) {
7192       // Handle the easy case where we have V1 in the low lanes and V2 in the
7193       // high lanes. We never see this reversed because we sort the shuffle.
7194       NewMask[2] -= 4;
7195       NewMask[3] -= 4;
7196     } else {
7197       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7198       // trying to place elements directly, just blend them and set up the final
7199       // shuffle to place them.
7200
7201       // The first two blend mask elements are for V1, the second two are for
7202       // V2.
7203       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7204                           Mask[2] < 4 ? Mask[2] : Mask[3],
7205                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7206                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7207       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7208                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7209
7210       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7211       // a blend.
7212       LowV = HighV = V1;
7213       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7214       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7215       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7216       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7217     }
7218   }
7219   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7220                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7221 }
7222
7223 /// \brief Lower 4-lane i32 vector shuffles.
7224 ///
7225 /// We try to handle these with integer-domain shuffles where we can, but for
7226 /// blends we use the floating point domain blend instructions.
7227 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7228                                        const X86Subtarget *Subtarget,
7229                                        SelectionDAG &DAG) {
7230   SDLoc DL(Op);
7231   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7232   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7233   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7234   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7235   ArrayRef<int> Mask = SVOp->getMask();
7236   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7237
7238   if (isSingleInputShuffleMask(Mask))
7239     // Straight shuffle of a single input vector. For everything from SSE2
7240     // onward this has a single fast instruction with no scary immediates.
7241     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7242                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7243
7244   // We implement this with SHUFPS because it can blend from two vectors.
7245   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7246   // up the inputs, bypassing domain shift penalties that we would encur if we
7247   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7248   // relevant.
7249   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7250                      DAG.getVectorShuffle(
7251                          MVT::v4f32, DL,
7252                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7253                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7254 }
7255
7256 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7257 /// shuffle lowering, and the most complex part.
7258 ///
7259 /// The lowering strategy is to try to form pairs of input lanes which are
7260 /// targeted at the same half of the final vector, and then use a dword shuffle
7261 /// to place them onto the right half, and finally unpack the paired lanes into
7262 /// their final position.
7263 ///
7264 /// The exact breakdown of how to form these dword pairs and align them on the
7265 /// correct sides is really tricky. See the comments within the function for
7266 /// more of the details.
7267 static SDValue lowerV8I16SingleInputVectorShuffle(
7268     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7269     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7270   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7271   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7272   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7273
7274   SmallVector<int, 4> LoInputs;
7275   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7276                [](int M) { return M >= 0; });
7277   std::sort(LoInputs.begin(), LoInputs.end());
7278   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7279   SmallVector<int, 4> HiInputs;
7280   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7281                [](int M) { return M >= 0; });
7282   std::sort(HiInputs.begin(), HiInputs.end());
7283   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7284   int NumLToL =
7285       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7286   int NumHToL = LoInputs.size() - NumLToL;
7287   int NumLToH =
7288       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7289   int NumHToH = HiInputs.size() - NumLToH;
7290   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7291   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7292   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7293   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7294
7295   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7296   // such inputs we can swap two of the dwords across the half mark and end up
7297   // with <=2 inputs to each half in each half. Once there, we can fall through
7298   // to the generic code below. For example:
7299   //
7300   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7301   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7302   //
7303   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7304   // and 2-2.
7305   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7306                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7307     // Compute the index of dword with only one word among the three inputs in
7308     // a half by taking the sum of the half with three inputs and subtracting
7309     // the sum of the actual three inputs. The difference is the remaining
7310     // slot.
7311     int DWordA = (ThreeInputHalfSum -
7312                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7313                  2;
7314     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7315
7316     int PSHUFDMask[] = {0, 1, 2, 3};
7317     PSHUFDMask[DWordA] = DWordB;
7318     PSHUFDMask[DWordB] = DWordA;
7319     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7320                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7321                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7322                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7323
7324     // Adjust the mask to match the new locations of A and B.
7325     for (int &M : Mask)
7326       if (M != -1 && M/2 == DWordA)
7327         M = 2 * DWordB + M % 2;
7328       else if (M != -1 && M/2 == DWordB)
7329         M = 2 * DWordA + M % 2;
7330
7331     // Recurse back into this routine to re-compute state now that this isn't
7332     // a 3 and 1 problem.
7333     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7334                                 Mask);
7335   };
7336   if (NumLToL == 3 && NumHToL == 1)
7337     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7338   else if (NumLToL == 1 && NumHToL == 3)
7339     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7340   else if (NumLToH == 1 && NumHToH == 3)
7341     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7342   else if (NumLToH == 3 && NumHToH == 1)
7343     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7344
7345   // At this point there are at most two inputs to the low and high halves from
7346   // each half. That means the inputs can always be grouped into dwords and
7347   // those dwords can then be moved to the correct half with a dword shuffle.
7348   // We use at most one low and one high word shuffle to collect these paired
7349   // inputs into dwords, and finally a dword shuffle to place them.
7350   int PSHUFLMask[4] = {-1, -1, -1, -1};
7351   int PSHUFHMask[4] = {-1, -1, -1, -1};
7352   int PSHUFDMask[4] = {-1, -1, -1, -1};
7353
7354   // First fix the masks for all the inputs that are staying in their
7355   // original halves. This will then dictate the targets of the cross-half
7356   // shuffles.
7357   auto fixInPlaceInputs = [&PSHUFDMask](
7358       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7359       MutableArrayRef<int> HalfMask, int HalfOffset) {
7360     if (InPlaceInputs.empty())
7361       return;
7362     if (InPlaceInputs.size() == 1) {
7363       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7364           InPlaceInputs[0] - HalfOffset;
7365       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7366       return;
7367     }
7368
7369     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7370     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7371         InPlaceInputs[0] - HalfOffset;
7372     // Put the second input next to the first so that they are packed into
7373     // a dword. We find the adjacent index by toggling the low bit.
7374     int AdjIndex = InPlaceInputs[0] ^ 1;
7375     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7376     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7377     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7378   };
7379   if (!HToLInputs.empty())
7380     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7381   if (!LToHInputs.empty())
7382     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7383
7384   // Now gather the cross-half inputs and place them into a free dword of
7385   // their target half.
7386   // FIXME: This operation could almost certainly be simplified dramatically to
7387   // look more like the 3-1 fixing operation.
7388   auto moveInputsToRightHalf = [&PSHUFDMask](
7389       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7390       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7391       int SourceOffset, int DestOffset) {
7392     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7393       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7394     };
7395     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7396                                                int Word) {
7397       int LowWord = Word & ~1;
7398       int HighWord = Word | 1;
7399       return isWordClobbered(SourceHalfMask, LowWord) ||
7400              isWordClobbered(SourceHalfMask, HighWord);
7401     };
7402
7403     if (IncomingInputs.empty())
7404       return;
7405
7406     if (ExistingInputs.empty()) {
7407       // Map any dwords with inputs from them into the right half.
7408       for (int Input : IncomingInputs) {
7409         // If the source half mask maps over the inputs, turn those into
7410         // swaps and use the swapped lane.
7411         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7412           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7413             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7414                 Input - SourceOffset;
7415             // We have to swap the uses in our half mask in one sweep.
7416             for (int &M : HalfMask)
7417               if (M == SourceHalfMask[Input - SourceOffset])
7418                 M = Input;
7419               else if (M == Input)
7420                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7421           } else {
7422             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7423                        Input - SourceOffset &&
7424                    "Previous placement doesn't match!");
7425           }
7426           // Note that this correctly re-maps both when we do a swap and when
7427           // we observe the other side of the swap above. We rely on that to
7428           // avoid swapping the members of the input list directly.
7429           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7430         }
7431
7432         // Map the input's dword into the correct half.
7433         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7434           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7435         else
7436           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7437                      Input / 2 &&
7438                  "Previous placement doesn't match!");
7439       }
7440
7441       // And just directly shift any other-half mask elements to be same-half
7442       // as we will have mirrored the dword containing the element into the
7443       // same position within that half.
7444       for (int &M : HalfMask)
7445         if (M >= SourceOffset && M < SourceOffset + 4) {
7446           M = M - SourceOffset + DestOffset;
7447           assert(M >= 0 && "This should never wrap below zero!");
7448         }
7449       return;
7450     }
7451
7452     // Ensure we have the input in a viable dword of its current half. This
7453     // is particularly tricky because the original position may be clobbered
7454     // by inputs being moved and *staying* in that half.
7455     if (IncomingInputs.size() == 1) {
7456       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7457         int InputFixed = std::find(std::begin(SourceHalfMask),
7458                                    std::end(SourceHalfMask), -1) -
7459                          std::begin(SourceHalfMask) + SourceOffset;
7460         SourceHalfMask[InputFixed - SourceOffset] =
7461             IncomingInputs[0] - SourceOffset;
7462         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7463                      InputFixed);
7464         IncomingInputs[0] = InputFixed;
7465       }
7466     } else if (IncomingInputs.size() == 2) {
7467       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7468           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7469         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7470         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7471                "Not all dwords can be clobbered!");
7472         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7473         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7474         for (int &M : HalfMask)
7475           if (M == IncomingInputs[0])
7476             M = SourceDWordBase + SourceOffset;
7477           else if (M == IncomingInputs[1])
7478             M = SourceDWordBase + 1 + SourceOffset;
7479         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7480         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7481       }
7482     } else {
7483       llvm_unreachable("Unhandled input size!");
7484     }
7485
7486     // Now hoist the DWord down to the right half.
7487     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7488     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7489     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7490     for (int Input : IncomingInputs)
7491       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7492                    FreeDWord * 2 + Input % 2);
7493   };
7494   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7495                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7496   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7497                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7498
7499   // Now enact all the shuffles we've computed to move the inputs into their
7500   // target half.
7501   if (!isNoopShuffleMask(PSHUFLMask))
7502     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7503                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7504   if (!isNoopShuffleMask(PSHUFHMask))
7505     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7506                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7507   if (!isNoopShuffleMask(PSHUFDMask))
7508     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7509                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7510                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7511                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7512
7513   // At this point, each half should contain all its inputs, and we can then
7514   // just shuffle them into their final position.
7515   assert(std::count_if(LoMask.begin(), LoMask.end(),
7516                        [](int M) { return M >= 4; }) == 0 &&
7517          "Failed to lift all the high half inputs to the low mask!");
7518   assert(std::count_if(HiMask.begin(), HiMask.end(),
7519                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7520          "Failed to lift all the low half inputs to the high mask!");
7521
7522   // Do a half shuffle for the low mask.
7523   if (!isNoopShuffleMask(LoMask))
7524     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7525                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7526
7527   // Do a half shuffle with the high mask after shifting its values down.
7528   for (int &M : HiMask)
7529     if (M >= 0)
7530       M -= 4;
7531   if (!isNoopShuffleMask(HiMask))
7532     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7533                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7534
7535   return V;
7536 }
7537
7538 /// \brief Detect whether the mask pattern should be lowered through
7539 /// interleaving.
7540 ///
7541 /// This essentially tests whether viewing the mask as an interleaving of two
7542 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7543 /// lowering it through interleaving is a significantly better strategy.
7544 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7545   int NumEvenInputs[2] = {0, 0};
7546   int NumOddInputs[2] = {0, 0};
7547   int NumLoInputs[2] = {0, 0};
7548   int NumHiInputs[2] = {0, 0};
7549   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7550     if (Mask[i] < 0)
7551       continue;
7552
7553     int InputIdx = Mask[i] >= Size;
7554
7555     if (i < Size / 2)
7556       ++NumLoInputs[InputIdx];
7557     else
7558       ++NumHiInputs[InputIdx];
7559
7560     if ((i % 2) == 0)
7561       ++NumEvenInputs[InputIdx];
7562     else
7563       ++NumOddInputs[InputIdx];
7564   }
7565
7566   // The minimum number of cross-input results for both the interleaved and
7567   // split cases. If interleaving results in fewer cross-input results, return
7568   // true.
7569   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7570                                     NumEvenInputs[0] + NumOddInputs[1]);
7571   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7572                               NumLoInputs[0] + NumHiInputs[1]);
7573   return InterleavedCrosses < SplitCrosses;
7574 }
7575
7576 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7577 ///
7578 /// This strategy only works when the inputs from each vector fit into a single
7579 /// half of that vector, and generally there are not so many inputs as to leave
7580 /// the in-place shuffles required highly constrained (and thus expensive). It
7581 /// shifts all the inputs into a single side of both input vectors and then
7582 /// uses an unpack to interleave these inputs in a single vector. At that
7583 /// point, we will fall back on the generic single input shuffle lowering.
7584 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7585                                                  SDValue V2,
7586                                                  MutableArrayRef<int> Mask,
7587                                                  const X86Subtarget *Subtarget,
7588                                                  SelectionDAG &DAG) {
7589   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7590   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7591   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7592   for (int i = 0; i < 8; ++i)
7593     if (Mask[i] >= 0 && Mask[i] < 4)
7594       LoV1Inputs.push_back(i);
7595     else if (Mask[i] >= 4 && Mask[i] < 8)
7596       HiV1Inputs.push_back(i);
7597     else if (Mask[i] >= 8 && Mask[i] < 12)
7598       LoV2Inputs.push_back(i);
7599     else if (Mask[i] >= 12)
7600       HiV2Inputs.push_back(i);
7601
7602   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7603   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7604   (void)NumV1Inputs;
7605   (void)NumV2Inputs;
7606   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7607   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7608   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7609
7610   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7611                      HiV1Inputs.size() + HiV2Inputs.size();
7612
7613   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7614                               ArrayRef<int> HiInputs, bool MoveToLo,
7615                               int MaskOffset) {
7616     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7617     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7618     if (BadInputs.empty())
7619       return V;
7620
7621     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7622     int MoveOffset = MoveToLo ? 0 : 4;
7623
7624     if (GoodInputs.empty()) {
7625       for (int BadInput : BadInputs) {
7626         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7627         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7628       }
7629     } else {
7630       if (GoodInputs.size() == 2) {
7631         // If the low inputs are spread across two dwords, pack them into
7632         // a single dword.
7633         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7634             Mask[GoodInputs[0]] - MaskOffset;
7635         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7636             Mask[GoodInputs[1]] - MaskOffset;
7637         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7638         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7639       } else {
7640         // Otherwise pin the low inputs.
7641         for (int GoodInput : GoodInputs)
7642           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7643       }
7644
7645       int MoveMaskIdx =
7646           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7647           std::begin(MoveMask);
7648       assert(MoveMaskIdx >= MoveOffset && "Established above");
7649
7650       if (BadInputs.size() == 2) {
7651         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7652         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7653         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7654             Mask[BadInputs[0]] - MaskOffset;
7655         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7656             Mask[BadInputs[1]] - MaskOffset;
7657         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7658         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7659       } else {
7660         assert(BadInputs.size() == 1 && "All sizes handled");
7661         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7662         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7663       }
7664     }
7665
7666     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7667                                 MoveMask);
7668   };
7669   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7670                         /*MaskOffset*/ 0);
7671   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7672                         /*MaskOffset*/ 8);
7673
7674   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7675   // cross-half traffic in the final shuffle.
7676
7677   // Munge the mask to be a single-input mask after the unpack merges the
7678   // results.
7679   for (int &M : Mask)
7680     if (M != -1)
7681       M = 2 * (M % 4) + (M / 8);
7682
7683   return DAG.getVectorShuffle(
7684       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7685                                   DL, MVT::v8i16, V1, V2),
7686       DAG.getUNDEF(MVT::v8i16), Mask);
7687 }
7688
7689 /// \brief Generic lowering of 8-lane i16 shuffles.
7690 ///
7691 /// This handles both single-input shuffles and combined shuffle/blends with
7692 /// two inputs. The single input shuffles are immediately delegated to
7693 /// a dedicated lowering routine.
7694 ///
7695 /// The blends are lowered in one of three fundamental ways. If there are few
7696 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7697 /// of the input is significantly cheaper when lowered as an interleaving of
7698 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7699 /// halves of the inputs separately (making them have relatively few inputs)
7700 /// and then concatenate them.
7701 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7702                                        const X86Subtarget *Subtarget,
7703                                        SelectionDAG &DAG) {
7704   SDLoc DL(Op);
7705   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7706   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7707   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7708   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7709   ArrayRef<int> OrigMask = SVOp->getMask();
7710   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7711                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7712   MutableArrayRef<int> Mask(MaskStorage);
7713
7714   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7715
7716   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7717   auto isV2 = [](int M) { return M >= 8; };
7718
7719   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7720   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7721
7722   if (NumV2Inputs == 0)
7723     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7724
7725   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7726                             "to be V1-input shuffles.");
7727
7728   if (NumV1Inputs + NumV2Inputs <= 4)
7729     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7730
7731   // Check whether an interleaving lowering is likely to be more efficient.
7732   // This isn't perfect but it is a strong heuristic that tends to work well on
7733   // the kinds of shuffles that show up in practice.
7734   //
7735   // FIXME: Handle 1x, 2x, and 4x interleaving.
7736   if (shouldLowerAsInterleaving(Mask)) {
7737     // FIXME: Figure out whether we should pack these into the low or high
7738     // halves.
7739
7740     int EMask[8], OMask[8];
7741     for (int i = 0; i < 4; ++i) {
7742       EMask[i] = Mask[2*i];
7743       OMask[i] = Mask[2*i + 1];
7744       EMask[i + 4] = -1;
7745       OMask[i + 4] = -1;
7746     }
7747
7748     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7749     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7750
7751     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7752   }
7753
7754   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7755   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7756
7757   for (int i = 0; i < 4; ++i) {
7758     LoBlendMask[i] = Mask[i];
7759     HiBlendMask[i] = Mask[i + 4];
7760   }
7761
7762   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7763   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7764   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7765   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7766
7767   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7768                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7769 }
7770
7771 /// \brief Check whether a compaction lowering can be done by dropping even
7772 /// elements and compute how many times even elements must be dropped.
7773 ///
7774 /// This handles shuffles which take every Nth element where N is a power of
7775 /// two. Example shuffle masks:
7776 ///
7777 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
7778 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
7779 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
7780 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
7781 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
7782 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
7783 ///
7784 /// Any of these lanes can of course be undef.
7785 ///
7786 /// This routine only supports N <= 3.
7787 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
7788 /// for larger N.
7789 ///
7790 /// \returns N above, or the number of times even elements must be dropped if
7791 /// there is such a number. Otherwise returns zero.
7792 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
7793   // Figure out whether we're looping over two inputs or just one.
7794   bool IsSingleInput = isSingleInputShuffleMask(Mask);
7795
7796   // The modulus for the shuffle vector entries is based on whether this is
7797   // a single input or not.
7798   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
7799   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
7800          "We should only be called with masks with a power-of-2 size!");
7801
7802   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
7803
7804   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
7805   // and 2^3 simultaneously. This is because we may have ambiguity with
7806   // partially undef inputs.
7807   bool ViableForN[3] = {true, true, true};
7808
7809   for (int i = 0, e = Mask.size(); i < e; ++i) {
7810     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
7811     // want.
7812     if (Mask[i] == -1)
7813       continue;
7814
7815     bool IsAnyViable = false;
7816     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7817       if (ViableForN[j]) {
7818         uint64_t N = j + 1;
7819
7820         // The shuffle mask must be equal to (i * 2^N) % M.
7821         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
7822           IsAnyViable = true;
7823         else
7824           ViableForN[j] = false;
7825       }
7826     // Early exit if we exhaust the possible powers of two.
7827     if (!IsAnyViable)
7828       break;
7829   }
7830
7831   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
7832     if (ViableForN[j])
7833       return j + 1;
7834
7835   // Return 0 as there is no viable power of two.
7836   return 0;
7837 }
7838
7839 /// \brief Generic lowering of v16i8 shuffles.
7840 ///
7841 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7842 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7843 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7844 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7845 /// back together.
7846 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7847                                        const X86Subtarget *Subtarget,
7848                                        SelectionDAG &DAG) {
7849   SDLoc DL(Op);
7850   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7851   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7852   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7853   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7854   ArrayRef<int> OrigMask = SVOp->getMask();
7855   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7856   int MaskStorage[16] = {
7857       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7858       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7859       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7860       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7861   MutableArrayRef<int> Mask(MaskStorage);
7862   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7863   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7864
7865   // For single-input shuffles, there are some nicer lowering tricks we can use.
7866   if (isSingleInputShuffleMask(Mask)) {
7867     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7868     // Notably, this handles splat and partial-splat shuffles more efficiently.
7869     // However, it only makes sense if the pre-duplication shuffle simplifies
7870     // things significantly. Currently, this means we need to be able to
7871     // express the pre-duplication shuffle as an i16 shuffle.
7872     //
7873     // FIXME: We should check for other patterns which can be widened into an
7874     // i16 shuffle as well.
7875     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7876       for (int i = 0; i < 16; i += 2) {
7877         if (Mask[i] != Mask[i + 1])
7878           return false;
7879       }
7880       return true;
7881     };
7882     auto tryToWidenViaDuplication = [&]() -> SDValue {
7883       if (!canWidenViaDuplication(Mask))
7884         return SDValue();
7885       SmallVector<int, 4> LoInputs;
7886       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7887                    [](int M) { return M >= 0 && M < 8; });
7888       std::sort(LoInputs.begin(), LoInputs.end());
7889       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7890                      LoInputs.end());
7891       SmallVector<int, 4> HiInputs;
7892       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7893                    [](int M) { return M >= 8; });
7894       std::sort(HiInputs.begin(), HiInputs.end());
7895       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7896                      HiInputs.end());
7897
7898       bool TargetLo = LoInputs.size() >= HiInputs.size();
7899       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7900       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7901
7902       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7903       SmallDenseMap<int, int, 8> LaneMap;
7904       for (int I : InPlaceInputs) {
7905         PreDupI16Shuffle[I/2] = I/2;
7906         LaneMap[I] = I;
7907       }
7908       int j = TargetLo ? 0 : 4, je = j + 4;
7909       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
7910         // Check if j is already a shuffle of this input. This happens when
7911         // there are two adjacent bytes after we move the low one.
7912         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
7913           // If we haven't yet mapped the input, search for a slot into which
7914           // we can map it.
7915           while (j < je && PreDupI16Shuffle[j] != -1)
7916             ++j;
7917
7918           if (j == je)
7919             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
7920             return SDValue();
7921
7922           // Map this input with the i16 shuffle.
7923           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
7924         }
7925
7926         // Update the lane map based on the mapping we ended up with.
7927         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
7928       }
7929       V1 = DAG.getNode(
7930           ISD::BITCAST, DL, MVT::v16i8,
7931           DAG.getVectorShuffle(MVT::v8i16, DL,
7932                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7933                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
7934
7935       // Unpack the bytes to form the i16s that will be shuffled into place.
7936       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7937                        MVT::v16i8, V1, V1);
7938
7939       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7940       for (int i = 0; i < 16; i += 2) {
7941         if (Mask[i] != -1)
7942           PostDupI16Shuffle[i / 2] = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
7943         assert(PostDupI16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7944       }
7945       return DAG.getNode(
7946           ISD::BITCAST, DL, MVT::v16i8,
7947           DAG.getVectorShuffle(MVT::v8i16, DL,
7948                                DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7949                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
7950     };
7951     if (SDValue V = tryToWidenViaDuplication())
7952       return V;
7953   }
7954
7955   // Check whether an interleaving lowering is likely to be more efficient.
7956   // This isn't perfect but it is a strong heuristic that tends to work well on
7957   // the kinds of shuffles that show up in practice.
7958   //
7959   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7960   if (shouldLowerAsInterleaving(Mask)) {
7961     // FIXME: Figure out whether we should pack these into the low or high
7962     // halves.
7963
7964     int EMask[16], OMask[16];
7965     for (int i = 0; i < 8; ++i) {
7966       EMask[i] = Mask[2*i];
7967       OMask[i] = Mask[2*i + 1];
7968       EMask[i + 8] = -1;
7969       OMask[i + 8] = -1;
7970     }
7971
7972     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7973     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7974
7975     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7976   }
7977
7978   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
7979   // with PSHUFB. It is important to do this before we attempt to generate any
7980   // blends but after all of the single-input lowerings. If the single input
7981   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
7982   // want to preserve that and we can DAG combine any longer sequences into
7983   // a PSHUFB in the end. But once we start blending from multiple inputs,
7984   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
7985   // and there are *very* few patterns that would actually be faster than the
7986   // PSHUFB approach because of its ability to zero lanes.
7987   //
7988   // FIXME: The only exceptions to the above are blends which are exact
7989   // interleavings with direct instructions supporting them. We currently don't
7990   // handle those well here.
7991   if (Subtarget->hasSSSE3()) {
7992     SDValue V1Mask[16];
7993     SDValue V2Mask[16];
7994     for (int i = 0; i < 16; ++i)
7995       if (Mask[i] == -1) {
7996         V1Mask[i] = V2Mask[i] = DAG.getConstant(0x80, MVT::i8);
7997       } else {
7998         V1Mask[i] = DAG.getConstant(Mask[i] < 16 ? Mask[i] : 0x80, MVT::i8);
7999         V2Mask[i] =
8000             DAG.getConstant(Mask[i] < 16 ? 0x80 : Mask[i] - 16, MVT::i8);
8001       }
8002     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V1,
8003                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8004     if (isSingleInputShuffleMask(Mask))
8005       return V1; // Single inputs are easy.
8006
8007     // Otherwise, blend the two.
8008     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, V2,
8009                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8010     return DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8011   }
8012
8013   // Check whether a compaction lowering can be done. This handles shuffles
8014   // which take every Nth element for some even N. See the helper function for
8015   // details.
8016   //
8017   // We special case these as they can be particularly efficiently handled with
8018   // the PACKUSB instruction on x86 and they show up in common patterns of
8019   // rearranging bytes to truncate wide elements.
8020   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8021     // NumEvenDrops is the power of two stride of the elements. Another way of
8022     // thinking about it is that we need to drop the even elements this many
8023     // times to get the original input.
8024     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8025
8026     // First we need to zero all the dropped bytes.
8027     assert(NumEvenDrops <= 3 &&
8028            "No support for dropping even elements more than 3 times.");
8029     // We use the mask type to pick which bytes are preserved based on how many
8030     // elements are dropped.
8031     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8032     SDValue ByteClearMask =
8033         DAG.getNode(ISD::BITCAST, DL, MVT::v16i8,
8034                     DAG.getConstant(0xFF, MaskVTs[NumEvenDrops - 1]));
8035     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8036     if (!IsSingleInput)
8037       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8038
8039     // Now pack things back together.
8040     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1);
8041     V2 = IsSingleInput ? V1 : DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V2);
8042     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8043     for (int i = 1; i < NumEvenDrops; ++i) {
8044       Result = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, Result);
8045       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8046     }
8047
8048     return Result;
8049   }
8050
8051   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8052   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8053   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8054   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8055
8056   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
8057                             MutableArrayRef<int> V1HalfBlendMask,
8058                             MutableArrayRef<int> V2HalfBlendMask) {
8059     for (int i = 0; i < 8; ++i)
8060       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
8061         V1HalfBlendMask[i] = HalfMask[i];
8062         HalfMask[i] = i;
8063       } else if (HalfMask[i] >= 16) {
8064         V2HalfBlendMask[i] = HalfMask[i] - 16;
8065         HalfMask[i] = i + 8;
8066       }
8067   };
8068   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
8069   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
8070
8071   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8072
8073   auto buildLoAndHiV8s = [&](SDValue V, MutableArrayRef<int> LoBlendMask,
8074                              MutableArrayRef<int> HiBlendMask) {
8075     SDValue V1, V2;
8076     // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8077     // them out and avoid using UNPCK{L,H} to extract the elements of V as
8078     // i16s.
8079     if (std::none_of(LoBlendMask.begin(), LoBlendMask.end(),
8080                      [](int M) { return M >= 0 && M % 2 == 1; }) &&
8081         std::none_of(HiBlendMask.begin(), HiBlendMask.end(),
8082                      [](int M) { return M >= 0 && M % 2 == 1; })) {
8083       // Use a mask to drop the high bytes.
8084       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
8085       V1 = DAG.getNode(ISD::AND, DL, MVT::v8i16, V1,
8086                        DAG.getConstant(0x00FF, MVT::v8i16));
8087
8088       // This will be a single vector shuffle instead of a blend so nuke V2.
8089       V2 = DAG.getUNDEF(MVT::v8i16);
8090
8091       // Squash the masks to point directly into V1.
8092       for (int &M : LoBlendMask)
8093         if (M >= 0)
8094           M /= 2;
8095       for (int &M : HiBlendMask)
8096         if (M >= 0)
8097           M /= 2;
8098     } else {
8099       // Otherwise just unpack the low half of V into V1 and the high half into
8100       // V2 so that we can blend them as i16s.
8101       V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8102                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8103       V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
8104                        DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8105     }
8106
8107     SDValue BlendedLo = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
8108     SDValue BlendedHi = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
8109     return std::make_pair(BlendedLo, BlendedHi);
8110   };
8111   SDValue V1Lo, V1Hi, V2Lo, V2Hi;
8112   std::tie(V1Lo, V1Hi) = buildLoAndHiV8s(V1, V1LoBlendMask, V1HiBlendMask);
8113   std::tie(V2Lo, V2Hi) = buildLoAndHiV8s(V2, V2LoBlendMask, V2HiBlendMask);
8114
8115   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
8116   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
8117
8118   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8119 }
8120
8121 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8122 ///
8123 /// This routine breaks down the specific type of 128-bit shuffle and
8124 /// dispatches to the lowering routines accordingly.
8125 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8126                                         MVT VT, const X86Subtarget *Subtarget,
8127                                         SelectionDAG &DAG) {
8128   switch (VT.SimpleTy) {
8129   case MVT::v2i64:
8130     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8131   case MVT::v2f64:
8132     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
8133   case MVT::v4i32:
8134     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8135   case MVT::v4f32:
8136     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
8137   case MVT::v8i16:
8138     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
8139   case MVT::v16i8:
8140     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
8141
8142   default:
8143     llvm_unreachable("Unimplemented!");
8144   }
8145 }
8146
8147 /// \brief Tiny helper function to test whether adjacent masks are sequential.
8148 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
8149   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8150     if (Mask[i] + 1 != Mask[i+1])
8151       return false;
8152
8153   return true;
8154 }
8155
8156 /// \brief Top-level lowering for x86 vector shuffles.
8157 ///
8158 /// This handles decomposition, canonicalization, and lowering of all x86
8159 /// vector shuffles. Most of the specific lowering strategies are encapsulated
8160 /// above in helper routines. The canonicalization attempts to widen shuffles
8161 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
8162 /// s.t. only one of the two inputs needs to be tested, etc.
8163 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8164                                   SelectionDAG &DAG) {
8165   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8166   ArrayRef<int> Mask = SVOp->getMask();
8167   SDValue V1 = Op.getOperand(0);
8168   SDValue V2 = Op.getOperand(1);
8169   MVT VT = Op.getSimpleValueType();
8170   int NumElements = VT.getVectorNumElements();
8171   SDLoc dl(Op);
8172
8173   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8174
8175   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8176   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8177   if (V1IsUndef && V2IsUndef)
8178     return DAG.getUNDEF(VT);
8179
8180   // When we create a shuffle node we put the UNDEF node to second operand,
8181   // but in some cases the first operand may be transformed to UNDEF.
8182   // In this case we should just commute the node.
8183   if (V1IsUndef)
8184     return DAG.getCommutedVectorShuffle(*SVOp);
8185
8186   // Check for non-undef masks pointing at an undef vector and make the masks
8187   // undef as well. This makes it easier to match the shuffle based solely on
8188   // the mask.
8189   if (V2IsUndef)
8190     for (int M : Mask)
8191       if (M >= NumElements) {
8192         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
8193         for (int &M : NewMask)
8194           if (M >= NumElements)
8195             M = -1;
8196         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
8197       }
8198
8199   // For integer vector shuffles, try to collapse them into a shuffle of fewer
8200   // lanes but wider integers. We cap this to not form integers larger than i64
8201   // but it might be interesting to form i128 integers to handle flipping the
8202   // low and high halves of AVX 256-bit vectors.
8203   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
8204       areAdjacentMasksSequential(Mask)) {
8205     SmallVector<int, 8> NewMask;
8206     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
8207       NewMask.push_back(Mask[i] / 2);
8208     MVT NewVT =
8209         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
8210                          VT.getVectorNumElements() / 2);
8211     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
8212     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
8213     return DAG.getNode(ISD::BITCAST, dl, VT,
8214                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
8215   }
8216
8217   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
8218   for (int M : SVOp->getMask())
8219     if (M < 0)
8220       ++NumUndefElements;
8221     else if (M < NumElements)
8222       ++NumV1Elements;
8223     else
8224       ++NumV2Elements;
8225
8226   // Commute the shuffle as needed such that more elements come from V1 than
8227   // V2. This allows us to match the shuffle pattern strictly on how many
8228   // elements come from V1 without handling the symmetric cases.
8229   if (NumV2Elements > NumV1Elements)
8230     return DAG.getCommutedVectorShuffle(*SVOp);
8231
8232   // When the number of V1 and V2 elements are the same, try to minimize the
8233   // number of uses of V2 in the low half of the vector.
8234   if (NumV1Elements == NumV2Elements) {
8235     int LowV1Elements = 0, LowV2Elements = 0;
8236     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8237       if (M >= NumElements)
8238         ++LowV2Elements;
8239       else if (M >= 0)
8240         ++LowV1Elements;
8241     if (LowV2Elements > LowV1Elements)
8242       return DAG.getCommutedVectorShuffle(*SVOp);
8243   }
8244
8245   // For each vector width, delegate to a specialized lowering routine.
8246   if (VT.getSizeInBits() == 128)
8247     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8248
8249   llvm_unreachable("Unimplemented!");
8250 }
8251
8252
8253 //===----------------------------------------------------------------------===//
8254 // Legacy vector shuffle lowering
8255 //
8256 // This code is the legacy code handling vector shuffles until the above
8257 // replaces its functionality and performance.
8258 //===----------------------------------------------------------------------===//
8259
8260 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8261                         bool hasInt256, unsigned *MaskOut = nullptr) {
8262   MVT EltVT = VT.getVectorElementType();
8263
8264   // There is no blend with immediate in AVX-512.
8265   if (VT.is512BitVector())
8266     return false;
8267
8268   if (!hasSSE41 || EltVT == MVT::i8)
8269     return false;
8270   if (!hasInt256 && VT == MVT::v16i16)
8271     return false;
8272
8273   unsigned MaskValue = 0;
8274   unsigned NumElems = VT.getVectorNumElements();
8275   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8276   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8277   unsigned NumElemsInLane = NumElems / NumLanes;
8278
8279   // Blend for v16i16 should be symetric for the both lanes.
8280   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8281
8282     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8283     int EltIdx = MaskVals[i];
8284
8285     if ((EltIdx < 0 || EltIdx == (int)i) &&
8286         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8287       continue;
8288
8289     if (((unsigned)EltIdx == (i + NumElems)) &&
8290         (SndLaneEltIdx < 0 ||
8291          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8292       MaskValue |= (1 << i);
8293     else
8294       return false;
8295   }
8296
8297   if (MaskOut)
8298     *MaskOut = MaskValue;
8299   return true;
8300 }
8301
8302 // Try to lower a shuffle node into a simple blend instruction.
8303 // This function assumes isBlendMask returns true for this
8304 // SuffleVectorSDNode
8305 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8306                                           unsigned MaskValue,
8307                                           const X86Subtarget *Subtarget,
8308                                           SelectionDAG &DAG) {
8309   MVT VT = SVOp->getSimpleValueType(0);
8310   MVT EltVT = VT.getVectorElementType();
8311   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8312                      Subtarget->hasInt256() && "Trying to lower a "
8313                                                "VECTOR_SHUFFLE to a Blend but "
8314                                                "with the wrong mask"));
8315   SDValue V1 = SVOp->getOperand(0);
8316   SDValue V2 = SVOp->getOperand(1);
8317   SDLoc dl(SVOp);
8318   unsigned NumElems = VT.getVectorNumElements();
8319
8320   // Convert i32 vectors to floating point if it is not AVX2.
8321   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8322   MVT BlendVT = VT;
8323   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8324     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8325                                NumElems);
8326     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8327     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8328   }
8329
8330   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8331                             DAG.getConstant(MaskValue, MVT::i32));
8332   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8333 }
8334
8335 /// In vector type \p VT, return true if the element at index \p InputIdx
8336 /// falls on a different 128-bit lane than \p OutputIdx.
8337 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8338                                      unsigned OutputIdx) {
8339   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8340   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8341 }
8342
8343 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8344 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8345 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8346 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8347 /// zero.
8348 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8349                          SelectionDAG &DAG) {
8350   MVT VT = V1.getSimpleValueType();
8351   assert(VT.is128BitVector() || VT.is256BitVector());
8352
8353   MVT EltVT = VT.getVectorElementType();
8354   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8355   unsigned NumElts = VT.getVectorNumElements();
8356
8357   SmallVector<SDValue, 32> PshufbMask;
8358   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8359     int InputIdx = MaskVals[OutputIdx];
8360     unsigned InputByteIdx;
8361
8362     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8363       InputByteIdx = 0x80;
8364     else {
8365       // Cross lane is not allowed.
8366       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8367         return SDValue();
8368       InputByteIdx = InputIdx * EltSizeInBytes;
8369       // Index is an byte offset within the 128-bit lane.
8370       InputByteIdx &= 0xf;
8371     }
8372
8373     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8374       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8375       if (InputByteIdx != 0x80)
8376         ++InputByteIdx;
8377     }
8378   }
8379
8380   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8381   if (ShufVT != VT)
8382     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8383   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8384                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8385 }
8386
8387 // v8i16 shuffles - Prefer shuffles in the following order:
8388 // 1. [all]   pshuflw, pshufhw, optional move
8389 // 2. [ssse3] 1 x pshufb
8390 // 3. [ssse3] 2 x pshufb + 1 x por
8391 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8392 static SDValue
8393 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8394                          SelectionDAG &DAG) {
8395   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8396   SDValue V1 = SVOp->getOperand(0);
8397   SDValue V2 = SVOp->getOperand(1);
8398   SDLoc dl(SVOp);
8399   SmallVector<int, 8> MaskVals;
8400
8401   // Determine if more than 1 of the words in each of the low and high quadwords
8402   // of the result come from the same quadword of one of the two inputs.  Undef
8403   // mask values count as coming from any quadword, for better codegen.
8404   //
8405   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8406   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8407   unsigned LoQuad[] = { 0, 0, 0, 0 };
8408   unsigned HiQuad[] = { 0, 0, 0, 0 };
8409   // Indices of quads used.
8410   std::bitset<4> InputQuads;
8411   for (unsigned i = 0; i < 8; ++i) {
8412     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8413     int EltIdx = SVOp->getMaskElt(i);
8414     MaskVals.push_back(EltIdx);
8415     if (EltIdx < 0) {
8416       ++Quad[0];
8417       ++Quad[1];
8418       ++Quad[2];
8419       ++Quad[3];
8420       continue;
8421     }
8422     ++Quad[EltIdx / 4];
8423     InputQuads.set(EltIdx / 4);
8424   }
8425
8426   int BestLoQuad = -1;
8427   unsigned MaxQuad = 1;
8428   for (unsigned i = 0; i < 4; ++i) {
8429     if (LoQuad[i] > MaxQuad) {
8430       BestLoQuad = i;
8431       MaxQuad = LoQuad[i];
8432     }
8433   }
8434
8435   int BestHiQuad = -1;
8436   MaxQuad = 1;
8437   for (unsigned i = 0; i < 4; ++i) {
8438     if (HiQuad[i] > MaxQuad) {
8439       BestHiQuad = i;
8440       MaxQuad = HiQuad[i];
8441     }
8442   }
8443
8444   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8445   // of the two input vectors, shuffle them into one input vector so only a
8446   // single pshufb instruction is necessary. If there are more than 2 input
8447   // quads, disable the next transformation since it does not help SSSE3.
8448   bool V1Used = InputQuads[0] || InputQuads[1];
8449   bool V2Used = InputQuads[2] || InputQuads[3];
8450   if (Subtarget->hasSSSE3()) {
8451     if (InputQuads.count() == 2 && V1Used && V2Used) {
8452       BestLoQuad = InputQuads[0] ? 0 : 1;
8453       BestHiQuad = InputQuads[2] ? 2 : 3;
8454     }
8455     if (InputQuads.count() > 2) {
8456       BestLoQuad = -1;
8457       BestHiQuad = -1;
8458     }
8459   }
8460
8461   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8462   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8463   // words from all 4 input quadwords.
8464   SDValue NewV;
8465   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8466     int MaskV[] = {
8467       BestLoQuad < 0 ? 0 : BestLoQuad,
8468       BestHiQuad < 0 ? 1 : BestHiQuad
8469     };
8470     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8471                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8472                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8473     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8474
8475     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8476     // source words for the shuffle, to aid later transformations.
8477     bool AllWordsInNewV = true;
8478     bool InOrder[2] = { true, true };
8479     for (unsigned i = 0; i != 8; ++i) {
8480       int idx = MaskVals[i];
8481       if (idx != (int)i)
8482         InOrder[i/4] = false;
8483       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8484         continue;
8485       AllWordsInNewV = false;
8486       break;
8487     }
8488
8489     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8490     if (AllWordsInNewV) {
8491       for (int i = 0; i != 8; ++i) {
8492         int idx = MaskVals[i];
8493         if (idx < 0)
8494           continue;
8495         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8496         if ((idx != i) && idx < 4)
8497           pshufhw = false;
8498         if ((idx != i) && idx > 3)
8499           pshuflw = false;
8500       }
8501       V1 = NewV;
8502       V2Used = false;
8503       BestLoQuad = 0;
8504       BestHiQuad = 1;
8505     }
8506
8507     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8508     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8509     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8510       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8511       unsigned TargetMask = 0;
8512       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8513                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8514       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8515       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8516                              getShufflePSHUFLWImmediate(SVOp);
8517       V1 = NewV.getOperand(0);
8518       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8519     }
8520   }
8521
8522   // Promote splats to a larger type which usually leads to more efficient code.
8523   // FIXME: Is this true if pshufb is available?
8524   if (SVOp->isSplat())
8525     return PromoteSplat(SVOp, DAG);
8526
8527   // If we have SSSE3, and all words of the result are from 1 input vector,
8528   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8529   // is present, fall back to case 4.
8530   if (Subtarget->hasSSSE3()) {
8531     SmallVector<SDValue,16> pshufbMask;
8532
8533     // If we have elements from both input vectors, set the high bit of the
8534     // shuffle mask element to zero out elements that come from V2 in the V1
8535     // mask, and elements that come from V1 in the V2 mask, so that the two
8536     // results can be OR'd together.
8537     bool TwoInputs = V1Used && V2Used;
8538     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8539     if (!TwoInputs)
8540       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8541
8542     // Calculate the shuffle mask for the second input, shuffle it, and
8543     // OR it with the first shuffled input.
8544     CommuteVectorShuffleMask(MaskVals, 8);
8545     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8546     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8547     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8548   }
8549
8550   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8551   // and update MaskVals with new element order.
8552   std::bitset<8> InOrder;
8553   if (BestLoQuad >= 0) {
8554     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8555     for (int i = 0; i != 4; ++i) {
8556       int idx = MaskVals[i];
8557       if (idx < 0) {
8558         InOrder.set(i);
8559       } else if ((idx / 4) == BestLoQuad) {
8560         MaskV[i] = idx & 3;
8561         InOrder.set(i);
8562       }
8563     }
8564     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8565                                 &MaskV[0]);
8566
8567     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8568       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8569       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8570                                   NewV.getOperand(0),
8571                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8572     }
8573   }
8574
8575   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8576   // and update MaskVals with the new element order.
8577   if (BestHiQuad >= 0) {
8578     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8579     for (unsigned i = 4; i != 8; ++i) {
8580       int idx = MaskVals[i];
8581       if (idx < 0) {
8582         InOrder.set(i);
8583       } else if ((idx / 4) == BestHiQuad) {
8584         MaskV[i] = (idx & 3) + 4;
8585         InOrder.set(i);
8586       }
8587     }
8588     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8589                                 &MaskV[0]);
8590
8591     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8592       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8593       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8594                                   NewV.getOperand(0),
8595                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8596     }
8597   }
8598
8599   // In case BestHi & BestLo were both -1, which means each quadword has a word
8600   // from each of the four input quadwords, calculate the InOrder bitvector now
8601   // before falling through to the insert/extract cleanup.
8602   if (BestLoQuad == -1 && BestHiQuad == -1) {
8603     NewV = V1;
8604     for (int i = 0; i != 8; ++i)
8605       if (MaskVals[i] < 0 || MaskVals[i] == i)
8606         InOrder.set(i);
8607   }
8608
8609   // The other elements are put in the right place using pextrw and pinsrw.
8610   for (unsigned i = 0; i != 8; ++i) {
8611     if (InOrder[i])
8612       continue;
8613     int EltIdx = MaskVals[i];
8614     if (EltIdx < 0)
8615       continue;
8616     SDValue ExtOp = (EltIdx < 8) ?
8617       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8618                   DAG.getIntPtrConstant(EltIdx)) :
8619       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8620                   DAG.getIntPtrConstant(EltIdx - 8));
8621     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8622                        DAG.getIntPtrConstant(i));
8623   }
8624   return NewV;
8625 }
8626
8627 /// \brief v16i16 shuffles
8628 ///
8629 /// FIXME: We only support generation of a single pshufb currently.  We can
8630 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8631 /// well (e.g 2 x pshufb + 1 x por).
8632 static SDValue
8633 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8634   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8635   SDValue V1 = SVOp->getOperand(0);
8636   SDValue V2 = SVOp->getOperand(1);
8637   SDLoc dl(SVOp);
8638
8639   if (V2.getOpcode() != ISD::UNDEF)
8640     return SDValue();
8641
8642   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8643   return getPSHUFB(MaskVals, V1, dl, DAG);
8644 }
8645
8646 // v16i8 shuffles - Prefer shuffles in the following order:
8647 // 1. [ssse3] 1 x pshufb
8648 // 2. [ssse3] 2 x pshufb + 1 x por
8649 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8650 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8651                                         const X86Subtarget* Subtarget,
8652                                         SelectionDAG &DAG) {
8653   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8654   SDValue V1 = SVOp->getOperand(0);
8655   SDValue V2 = SVOp->getOperand(1);
8656   SDLoc dl(SVOp);
8657   ArrayRef<int> MaskVals = SVOp->getMask();
8658
8659   // Promote splats to a larger type which usually leads to more efficient code.
8660   // FIXME: Is this true if pshufb is available?
8661   if (SVOp->isSplat())
8662     return PromoteSplat(SVOp, DAG);
8663
8664   // If we have SSSE3, case 1 is generated when all result bytes come from
8665   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8666   // present, fall back to case 3.
8667
8668   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8669   if (Subtarget->hasSSSE3()) {
8670     SmallVector<SDValue,16> pshufbMask;
8671
8672     // If all result elements are from one input vector, then only translate
8673     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8674     //
8675     // Otherwise, we have elements from both input vectors, and must zero out
8676     // elements that come from V2 in the first mask, and V1 in the second mask
8677     // so that we can OR them together.
8678     for (unsigned i = 0; i != 16; ++i) {
8679       int EltIdx = MaskVals[i];
8680       if (EltIdx < 0 || EltIdx >= 16)
8681         EltIdx = 0x80;
8682       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8683     }
8684     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8685                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8686                                  MVT::v16i8, pshufbMask));
8687
8688     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8689     // the 2nd operand if it's undefined or zero.
8690     if (V2.getOpcode() == ISD::UNDEF ||
8691         ISD::isBuildVectorAllZeros(V2.getNode()))
8692       return V1;
8693
8694     // Calculate the shuffle mask for the second input, shuffle it, and
8695     // OR it with the first shuffled input.
8696     pshufbMask.clear();
8697     for (unsigned i = 0; i != 16; ++i) {
8698       int EltIdx = MaskVals[i];
8699       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8700       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8701     }
8702     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8703                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8704                                  MVT::v16i8, pshufbMask));
8705     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8706   }
8707
8708   // No SSSE3 - Calculate in place words and then fix all out of place words
8709   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8710   // the 16 different words that comprise the two doublequadword input vectors.
8711   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8712   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8713   SDValue NewV = V1;
8714   for (int i = 0; i != 8; ++i) {
8715     int Elt0 = MaskVals[i*2];
8716     int Elt1 = MaskVals[i*2+1];
8717
8718     // This word of the result is all undef, skip it.
8719     if (Elt0 < 0 && Elt1 < 0)
8720       continue;
8721
8722     // This word of the result is already in the correct place, skip it.
8723     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8724       continue;
8725
8726     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8727     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8728     SDValue InsElt;
8729
8730     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8731     // using a single extract together, load it and store it.
8732     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8733       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8734                            DAG.getIntPtrConstant(Elt1 / 2));
8735       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8736                         DAG.getIntPtrConstant(i));
8737       continue;
8738     }
8739
8740     // If Elt1 is defined, extract it from the appropriate source.  If the
8741     // source byte is not also odd, shift the extracted word left 8 bits
8742     // otherwise clear the bottom 8 bits if we need to do an or.
8743     if (Elt1 >= 0) {
8744       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8745                            DAG.getIntPtrConstant(Elt1 / 2));
8746       if ((Elt1 & 1) == 0)
8747         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8748                              DAG.getConstant(8,
8749                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8750       else if (Elt0 >= 0)
8751         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8752                              DAG.getConstant(0xFF00, MVT::i16));
8753     }
8754     // If Elt0 is defined, extract it from the appropriate source.  If the
8755     // source byte is not also even, shift the extracted word right 8 bits. If
8756     // Elt1 was also defined, OR the extracted values together before
8757     // inserting them in the result.
8758     if (Elt0 >= 0) {
8759       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8760                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8761       if ((Elt0 & 1) != 0)
8762         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8763                               DAG.getConstant(8,
8764                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8765       else if (Elt1 >= 0)
8766         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8767                              DAG.getConstant(0x00FF, MVT::i16));
8768       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8769                          : InsElt0;
8770     }
8771     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8772                        DAG.getIntPtrConstant(i));
8773   }
8774   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8775 }
8776
8777 // v32i8 shuffles - Translate to VPSHUFB if possible.
8778 static
8779 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8780                                  const X86Subtarget *Subtarget,
8781                                  SelectionDAG &DAG) {
8782   MVT VT = SVOp->getSimpleValueType(0);
8783   SDValue V1 = SVOp->getOperand(0);
8784   SDValue V2 = SVOp->getOperand(1);
8785   SDLoc dl(SVOp);
8786   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8787
8788   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8789   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8790   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8791
8792   // VPSHUFB may be generated if
8793   // (1) one of input vector is undefined or zeroinitializer.
8794   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8795   // And (2) the mask indexes don't cross the 128-bit lane.
8796   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8797       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8798     return SDValue();
8799
8800   if (V1IsAllZero && !V2IsAllZero) {
8801     CommuteVectorShuffleMask(MaskVals, 32);
8802     V1 = V2;
8803   }
8804   return getPSHUFB(MaskVals, V1, dl, DAG);
8805 }
8806
8807 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8808 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8809 /// done when every pair / quad of shuffle mask elements point to elements in
8810 /// the right sequence. e.g.
8811 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8812 static
8813 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8814                                  SelectionDAG &DAG) {
8815   MVT VT = SVOp->getSimpleValueType(0);
8816   SDLoc dl(SVOp);
8817   unsigned NumElems = VT.getVectorNumElements();
8818   MVT NewVT;
8819   unsigned Scale;
8820   switch (VT.SimpleTy) {
8821   default: llvm_unreachable("Unexpected!");
8822   case MVT::v2i64:
8823   case MVT::v2f64:
8824            return SDValue(SVOp, 0);
8825   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8826   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8827   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8828   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8829   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8830   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8831   }
8832
8833   SmallVector<int, 8> MaskVec;
8834   for (unsigned i = 0; i != NumElems; i += Scale) {
8835     int StartIdx = -1;
8836     for (unsigned j = 0; j != Scale; ++j) {
8837       int EltIdx = SVOp->getMaskElt(i+j);
8838       if (EltIdx < 0)
8839         continue;
8840       if (StartIdx < 0)
8841         StartIdx = (EltIdx / Scale);
8842       if (EltIdx != (int)(StartIdx*Scale + j))
8843         return SDValue();
8844     }
8845     MaskVec.push_back(StartIdx);
8846   }
8847
8848   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8849   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8850   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8851 }
8852
8853 /// getVZextMovL - Return a zero-extending vector move low node.
8854 ///
8855 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8856                             SDValue SrcOp, SelectionDAG &DAG,
8857                             const X86Subtarget *Subtarget, SDLoc dl) {
8858   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8859     LoadSDNode *LD = nullptr;
8860     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8861       LD = dyn_cast<LoadSDNode>(SrcOp);
8862     if (!LD) {
8863       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8864       // instead.
8865       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8866       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8867           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8868           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8869           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8870         // PR2108
8871         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8872         return DAG.getNode(ISD::BITCAST, dl, VT,
8873                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8874                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8875                                                    OpVT,
8876                                                    SrcOp.getOperand(0)
8877                                                           .getOperand(0))));
8878       }
8879     }
8880   }
8881
8882   return DAG.getNode(ISD::BITCAST, dl, VT,
8883                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8884                                  DAG.getNode(ISD::BITCAST, dl,
8885                                              OpVT, SrcOp)));
8886 }
8887
8888 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8889 /// which could not be matched by any known target speficic shuffle
8890 static SDValue
8891 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8892
8893   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8894   if (NewOp.getNode())
8895     return NewOp;
8896
8897   MVT VT = SVOp->getSimpleValueType(0);
8898
8899   unsigned NumElems = VT.getVectorNumElements();
8900   unsigned NumLaneElems = NumElems / 2;
8901
8902   SDLoc dl(SVOp);
8903   MVT EltVT = VT.getVectorElementType();
8904   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8905   SDValue Output[2];
8906
8907   SmallVector<int, 16> Mask;
8908   for (unsigned l = 0; l < 2; ++l) {
8909     // Build a shuffle mask for the output, discovering on the fly which
8910     // input vectors to use as shuffle operands (recorded in InputUsed).
8911     // If building a suitable shuffle vector proves too hard, then bail
8912     // out with UseBuildVector set.
8913     bool UseBuildVector = false;
8914     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8915     unsigned LaneStart = l * NumLaneElems;
8916     for (unsigned i = 0; i != NumLaneElems; ++i) {
8917       // The mask element.  This indexes into the input.
8918       int Idx = SVOp->getMaskElt(i+LaneStart);
8919       if (Idx < 0) {
8920         // the mask element does not index into any input vector.
8921         Mask.push_back(-1);
8922         continue;
8923       }
8924
8925       // The input vector this mask element indexes into.
8926       int Input = Idx / NumLaneElems;
8927
8928       // Turn the index into an offset from the start of the input vector.
8929       Idx -= Input * NumLaneElems;
8930
8931       // Find or create a shuffle vector operand to hold this input.
8932       unsigned OpNo;
8933       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8934         if (InputUsed[OpNo] == Input)
8935           // This input vector is already an operand.
8936           break;
8937         if (InputUsed[OpNo] < 0) {
8938           // Create a new operand for this input vector.
8939           InputUsed[OpNo] = Input;
8940           break;
8941         }
8942       }
8943
8944       if (OpNo >= array_lengthof(InputUsed)) {
8945         // More than two input vectors used!  Give up on trying to create a
8946         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8947         UseBuildVector = true;
8948         break;
8949       }
8950
8951       // Add the mask index for the new shuffle vector.
8952       Mask.push_back(Idx + OpNo * NumLaneElems);
8953     }
8954
8955     if (UseBuildVector) {
8956       SmallVector<SDValue, 16> SVOps;
8957       for (unsigned i = 0; i != NumLaneElems; ++i) {
8958         // The mask element.  This indexes into the input.
8959         int Idx = SVOp->getMaskElt(i+LaneStart);
8960         if (Idx < 0) {
8961           SVOps.push_back(DAG.getUNDEF(EltVT));
8962           continue;
8963         }
8964
8965         // The input vector this mask element indexes into.
8966         int Input = Idx / NumElems;
8967
8968         // Turn the index into an offset from the start of the input vector.
8969         Idx -= Input * NumElems;
8970
8971         // Extract the vector element by hand.
8972         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8973                                     SVOp->getOperand(Input),
8974                                     DAG.getIntPtrConstant(Idx)));
8975       }
8976
8977       // Construct the output using a BUILD_VECTOR.
8978       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8979     } else if (InputUsed[0] < 0) {
8980       // No input vectors were used! The result is undefined.
8981       Output[l] = DAG.getUNDEF(NVT);
8982     } else {
8983       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8984                                         (InputUsed[0] % 2) * NumLaneElems,
8985                                         DAG, dl);
8986       // If only one input was used, use an undefined vector for the other.
8987       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8988         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8989                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8990       // At least one input vector was used. Create a new shuffle vector.
8991       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8992     }
8993
8994     Mask.clear();
8995   }
8996
8997   // Concatenate the result back
8998   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8999 }
9000
9001 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
9002 /// 4 elements, and match them with several different shuffle types.
9003 static SDValue
9004 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
9005   SDValue V1 = SVOp->getOperand(0);
9006   SDValue V2 = SVOp->getOperand(1);
9007   SDLoc dl(SVOp);
9008   MVT VT = SVOp->getSimpleValueType(0);
9009
9010   assert(VT.is128BitVector() && "Unsupported vector size");
9011
9012   std::pair<int, int> Locs[4];
9013   int Mask1[] = { -1, -1, -1, -1 };
9014   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
9015
9016   unsigned NumHi = 0;
9017   unsigned NumLo = 0;
9018   for (unsigned i = 0; i != 4; ++i) {
9019     int Idx = PermMask[i];
9020     if (Idx < 0) {
9021       Locs[i] = std::make_pair(-1, -1);
9022     } else {
9023       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
9024       if (Idx < 4) {
9025         Locs[i] = std::make_pair(0, NumLo);
9026         Mask1[NumLo] = Idx;
9027         NumLo++;
9028       } else {
9029         Locs[i] = std::make_pair(1, NumHi);
9030         if (2+NumHi < 4)
9031           Mask1[2+NumHi] = Idx;
9032         NumHi++;
9033       }
9034     }
9035   }
9036
9037   if (NumLo <= 2 && NumHi <= 2) {
9038     // If no more than two elements come from either vector. This can be
9039     // implemented with two shuffles. First shuffle gather the elements.
9040     // The second shuffle, which takes the first shuffle as both of its
9041     // vector operands, put the elements into the right order.
9042     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9043
9044     int Mask2[] = { -1, -1, -1, -1 };
9045
9046     for (unsigned i = 0; i != 4; ++i)
9047       if (Locs[i].first != -1) {
9048         unsigned Idx = (i < 2) ? 0 : 4;
9049         Idx += Locs[i].first * 2 + Locs[i].second;
9050         Mask2[i] = Idx;
9051       }
9052
9053     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
9054   }
9055
9056   if (NumLo == 3 || NumHi == 3) {
9057     // Otherwise, we must have three elements from one vector, call it X, and
9058     // one element from the other, call it Y.  First, use a shufps to build an
9059     // intermediate vector with the one element from Y and the element from X
9060     // that will be in the same half in the final destination (the indexes don't
9061     // matter). Then, use a shufps to build the final vector, taking the half
9062     // containing the element from Y from the intermediate, and the other half
9063     // from X.
9064     if (NumHi == 3) {
9065       // Normalize it so the 3 elements come from V1.
9066       CommuteVectorShuffleMask(PermMask, 4);
9067       std::swap(V1, V2);
9068     }
9069
9070     // Find the element from V2.
9071     unsigned HiIndex;
9072     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
9073       int Val = PermMask[HiIndex];
9074       if (Val < 0)
9075         continue;
9076       if (Val >= 4)
9077         break;
9078     }
9079
9080     Mask1[0] = PermMask[HiIndex];
9081     Mask1[1] = -1;
9082     Mask1[2] = PermMask[HiIndex^1];
9083     Mask1[3] = -1;
9084     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9085
9086     if (HiIndex >= 2) {
9087       Mask1[0] = PermMask[0];
9088       Mask1[1] = PermMask[1];
9089       Mask1[2] = HiIndex & 1 ? 6 : 4;
9090       Mask1[3] = HiIndex & 1 ? 4 : 6;
9091       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
9092     }
9093
9094     Mask1[0] = HiIndex & 1 ? 2 : 0;
9095     Mask1[1] = HiIndex & 1 ? 0 : 2;
9096     Mask1[2] = PermMask[2];
9097     Mask1[3] = PermMask[3];
9098     if (Mask1[2] >= 0)
9099       Mask1[2] += 4;
9100     if (Mask1[3] >= 0)
9101       Mask1[3] += 4;
9102     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
9103   }
9104
9105   // Break it into (shuffle shuffle_hi, shuffle_lo).
9106   int LoMask[] = { -1, -1, -1, -1 };
9107   int HiMask[] = { -1, -1, -1, -1 };
9108
9109   int *MaskPtr = LoMask;
9110   unsigned MaskIdx = 0;
9111   unsigned LoIdx = 0;
9112   unsigned HiIdx = 2;
9113   for (unsigned i = 0; i != 4; ++i) {
9114     if (i == 2) {
9115       MaskPtr = HiMask;
9116       MaskIdx = 1;
9117       LoIdx = 0;
9118       HiIdx = 2;
9119     }
9120     int Idx = PermMask[i];
9121     if (Idx < 0) {
9122       Locs[i] = std::make_pair(-1, -1);
9123     } else if (Idx < 4) {
9124       Locs[i] = std::make_pair(MaskIdx, LoIdx);
9125       MaskPtr[LoIdx] = Idx;
9126       LoIdx++;
9127     } else {
9128       Locs[i] = std::make_pair(MaskIdx, HiIdx);
9129       MaskPtr[HiIdx] = Idx;
9130       HiIdx++;
9131     }
9132   }
9133
9134   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
9135   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
9136   int MaskOps[] = { -1, -1, -1, -1 };
9137   for (unsigned i = 0; i != 4; ++i)
9138     if (Locs[i].first != -1)
9139       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
9140   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
9141 }
9142
9143 static bool MayFoldVectorLoad(SDValue V) {
9144   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
9145     V = V.getOperand(0);
9146
9147   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
9148     V = V.getOperand(0);
9149   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
9150       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
9151     // BUILD_VECTOR (load), undef
9152     V = V.getOperand(0);
9153
9154   return MayFoldLoad(V);
9155 }
9156
9157 static
9158 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
9159   MVT VT = Op.getSimpleValueType();
9160
9161   // Canonizalize to v2f64.
9162   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
9163   return DAG.getNode(ISD::BITCAST, dl, VT,
9164                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
9165                                           V1, DAG));
9166 }
9167
9168 static
9169 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
9170                         bool HasSSE2) {
9171   SDValue V1 = Op.getOperand(0);
9172   SDValue V2 = Op.getOperand(1);
9173   MVT VT = Op.getSimpleValueType();
9174
9175   assert(VT != MVT::v2i64 && "unsupported shuffle type");
9176
9177   if (HasSSE2 && VT == MVT::v2f64)
9178     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
9179
9180   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
9181   return DAG.getNode(ISD::BITCAST, dl, VT,
9182                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
9183                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
9184                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
9185 }
9186
9187 static
9188 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
9189   SDValue V1 = Op.getOperand(0);
9190   SDValue V2 = Op.getOperand(1);
9191   MVT VT = Op.getSimpleValueType();
9192
9193   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
9194          "unsupported shuffle type");
9195
9196   if (V2.getOpcode() == ISD::UNDEF)
9197     V2 = V1;
9198
9199   // v4i32 or v4f32
9200   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
9201 }
9202
9203 static
9204 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
9205   SDValue V1 = Op.getOperand(0);
9206   SDValue V2 = Op.getOperand(1);
9207   MVT VT = Op.getSimpleValueType();
9208   unsigned NumElems = VT.getVectorNumElements();
9209
9210   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
9211   // operand of these instructions is only memory, so check if there's a
9212   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
9213   // same masks.
9214   bool CanFoldLoad = false;
9215
9216   // Trivial case, when V2 comes from a load.
9217   if (MayFoldVectorLoad(V2))
9218     CanFoldLoad = true;
9219
9220   // When V1 is a load, it can be folded later into a store in isel, example:
9221   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
9222   //    turns into:
9223   //  (MOVLPSmr addr:$src1, VR128:$src2)
9224   // So, recognize this potential and also use MOVLPS or MOVLPD
9225   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
9226     CanFoldLoad = true;
9227
9228   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9229   if (CanFoldLoad) {
9230     if (HasSSE2 && NumElems == 2)
9231       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9232
9233     if (NumElems == 4)
9234       // If we don't care about the second element, proceed to use movss.
9235       if (SVOp->getMaskElt(1) != -1)
9236         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9237   }
9238
9239   // movl and movlp will both match v2i64, but v2i64 is never matched by
9240   // movl earlier because we make it strict to avoid messing with the movlp load
9241   // folding logic (see the code above getMOVLP call). Match it here then,
9242   // this is horrible, but will stay like this until we move all shuffle
9243   // matching to x86 specific nodes. Note that for the 1st condition all
9244   // types are matched with movsd.
9245   if (HasSSE2) {
9246     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9247     // as to remove this logic from here, as much as possible
9248     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9249       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9250     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9251   }
9252
9253   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9254
9255   // Invert the operand order and use SHUFPS to match it.
9256   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9257                               getShuffleSHUFImmediate(SVOp), DAG);
9258 }
9259
9260 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9261                                          SelectionDAG &DAG) {
9262   SDLoc dl(Load);
9263   MVT VT = Load->getSimpleValueType(0);
9264   MVT EVT = VT.getVectorElementType();
9265   SDValue Addr = Load->getOperand(1);
9266   SDValue NewAddr = DAG.getNode(
9267       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9268       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9269
9270   SDValue NewLoad =
9271       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9272                   DAG.getMachineFunction().getMachineMemOperand(
9273                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9274   return NewLoad;
9275 }
9276
9277 // It is only safe to call this function if isINSERTPSMask is true for
9278 // this shufflevector mask.
9279 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9280                            SelectionDAG &DAG) {
9281   // Generate an insertps instruction when inserting an f32 from memory onto a
9282   // v4f32 or when copying a member from one v4f32 to another.
9283   // We also use it for transferring i32 from one register to another,
9284   // since it simply copies the same bits.
9285   // If we're transferring an i32 from memory to a specific element in a
9286   // register, we output a generic DAG that will match the PINSRD
9287   // instruction.
9288   MVT VT = SVOp->getSimpleValueType(0);
9289   MVT EVT = VT.getVectorElementType();
9290   SDValue V1 = SVOp->getOperand(0);
9291   SDValue V2 = SVOp->getOperand(1);
9292   auto Mask = SVOp->getMask();
9293   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9294          "unsupported vector type for insertps/pinsrd");
9295
9296   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9297   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9298   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9299
9300   SDValue From;
9301   SDValue To;
9302   unsigned DestIndex;
9303   if (FromV1 == 1) {
9304     From = V1;
9305     To = V2;
9306     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9307                 Mask.begin();
9308
9309     // If we have 1 element from each vector, we have to check if we're
9310     // changing V1's element's place. If so, we're done. Otherwise, we
9311     // should assume we're changing V2's element's place and behave
9312     // accordingly.
9313     int FromV2 = std::count_if(Mask.begin(), Mask.end(), FromV2Predicate);
9314     assert(DestIndex <= INT32_MAX && "truncated destination index");
9315     if (FromV1 == FromV2 &&
9316         static_cast<int>(DestIndex) == Mask[DestIndex] % 4) {
9317       From = V2;
9318       To = V1;
9319       DestIndex =
9320           std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9321     }
9322   } else {
9323     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9324            "More than one element from V1 and from V2, or no elements from one "
9325            "of the vectors. This case should not have returned true from "
9326            "isINSERTPSMask");
9327     From = V2;
9328     To = V1;
9329     DestIndex =
9330         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9331   }
9332
9333   // Get an index into the source vector in the range [0,4) (the mask is
9334   // in the range [0,8) because it can address V1 and V2)
9335   unsigned SrcIndex = Mask[DestIndex] % 4;
9336   if (MayFoldLoad(From)) {
9337     // Trivial case, when From comes from a load and is only used by the
9338     // shuffle. Make it use insertps from the vector that we need from that
9339     // load.
9340     SDValue NewLoad =
9341         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9342     if (!NewLoad.getNode())
9343       return SDValue();
9344
9345     if (EVT == MVT::f32) {
9346       // Create this as a scalar to vector to match the instruction pattern.
9347       SDValue LoadScalarToVector =
9348           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9349       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9350       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9351                          InsertpsMask);
9352     } else { // EVT == MVT::i32
9353       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9354       // instruction, to match the PINSRD instruction, which loads an i32 to a
9355       // certain vector element.
9356       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9357                          DAG.getConstant(DestIndex, MVT::i32));
9358     }
9359   }
9360
9361   // Vector-element-to-vector
9362   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9363   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9364 }
9365
9366 // Reduce a vector shuffle to zext.
9367 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9368                                     SelectionDAG &DAG) {
9369   // PMOVZX is only available from SSE41.
9370   if (!Subtarget->hasSSE41())
9371     return SDValue();
9372
9373   MVT VT = Op.getSimpleValueType();
9374
9375   // Only AVX2 support 256-bit vector integer extending.
9376   if (!Subtarget->hasInt256() && VT.is256BitVector())
9377     return SDValue();
9378
9379   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9380   SDLoc DL(Op);
9381   SDValue V1 = Op.getOperand(0);
9382   SDValue V2 = Op.getOperand(1);
9383   unsigned NumElems = VT.getVectorNumElements();
9384
9385   // Extending is an unary operation and the element type of the source vector
9386   // won't be equal to or larger than i64.
9387   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9388       VT.getVectorElementType() == MVT::i64)
9389     return SDValue();
9390
9391   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9392   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9393   while ((1U << Shift) < NumElems) {
9394     if (SVOp->getMaskElt(1U << Shift) == 1)
9395       break;
9396     Shift += 1;
9397     // The maximal ratio is 8, i.e. from i8 to i64.
9398     if (Shift > 3)
9399       return SDValue();
9400   }
9401
9402   // Check the shuffle mask.
9403   unsigned Mask = (1U << Shift) - 1;
9404   for (unsigned i = 0; i != NumElems; ++i) {
9405     int EltIdx = SVOp->getMaskElt(i);
9406     if ((i & Mask) != 0 && EltIdx != -1)
9407       return SDValue();
9408     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9409       return SDValue();
9410   }
9411
9412   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9413   MVT NeVT = MVT::getIntegerVT(NBits);
9414   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9415
9416   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9417     return SDValue();
9418
9419   // Simplify the operand as it's prepared to be fed into shuffle.
9420   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9421   if (V1.getOpcode() == ISD::BITCAST &&
9422       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9423       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9424       V1.getOperand(0).getOperand(0)
9425         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9426     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9427     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9428     ConstantSDNode *CIdx =
9429       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9430     // If it's foldable, i.e. normal load with single use, we will let code
9431     // selection to fold it. Otherwise, we will short the conversion sequence.
9432     if (CIdx && CIdx->getZExtValue() == 0 &&
9433         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9434       MVT FullVT = V.getSimpleValueType();
9435       MVT V1VT = V1.getSimpleValueType();
9436       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9437         // The "ext_vec_elt" node is wider than the result node.
9438         // In this case we should extract subvector from V.
9439         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9440         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9441         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9442                                         FullVT.getVectorNumElements()/Ratio);
9443         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9444                         DAG.getIntPtrConstant(0));
9445       }
9446       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9447     }
9448   }
9449
9450   return DAG.getNode(ISD::BITCAST, DL, VT,
9451                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9452 }
9453
9454 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9455                                       SelectionDAG &DAG) {
9456   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9457   MVT VT = Op.getSimpleValueType();
9458   SDLoc dl(Op);
9459   SDValue V1 = Op.getOperand(0);
9460   SDValue V2 = Op.getOperand(1);
9461
9462   if (isZeroShuffle(SVOp))
9463     return getZeroVector(VT, Subtarget, DAG, dl);
9464
9465   // Handle splat operations
9466   if (SVOp->isSplat()) {
9467     // Use vbroadcast whenever the splat comes from a foldable load
9468     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9469     if (Broadcast.getNode())
9470       return Broadcast;
9471   }
9472
9473   // Check integer expanding shuffles.
9474   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9475   if (NewOp.getNode())
9476     return NewOp;
9477
9478   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9479   // do it!
9480   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9481       VT == MVT::v32i8) {
9482     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9483     if (NewOp.getNode())
9484       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9485   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9486     // FIXME: Figure out a cleaner way to do this.
9487     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9488       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9489       if (NewOp.getNode()) {
9490         MVT NewVT = NewOp.getSimpleValueType();
9491         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9492                                NewVT, true, false))
9493           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9494                               dl);
9495       }
9496     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9497       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9498       if (NewOp.getNode()) {
9499         MVT NewVT = NewOp.getSimpleValueType();
9500         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9501           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9502                               dl);
9503       }
9504     }
9505   }
9506   return SDValue();
9507 }
9508
9509 SDValue
9510 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9511   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9512   SDValue V1 = Op.getOperand(0);
9513   SDValue V2 = Op.getOperand(1);
9514   MVT VT = Op.getSimpleValueType();
9515   SDLoc dl(Op);
9516   unsigned NumElems = VT.getVectorNumElements();
9517   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9518   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9519   bool V1IsSplat = false;
9520   bool V2IsSplat = false;
9521   bool HasSSE2 = Subtarget->hasSSE2();
9522   bool HasFp256    = Subtarget->hasFp256();
9523   bool HasInt256   = Subtarget->hasInt256();
9524   MachineFunction &MF = DAG.getMachineFunction();
9525   bool OptForSize = MF.getFunction()->getAttributes().
9526     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9527
9528   // Check if we should use the experimental vector shuffle lowering. If so,
9529   // delegate completely to that code path.
9530   if (ExperimentalVectorShuffleLowering)
9531     return lowerVectorShuffle(Op, Subtarget, DAG);
9532
9533   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9534
9535   if (V1IsUndef && V2IsUndef)
9536     return DAG.getUNDEF(VT);
9537
9538   // When we create a shuffle node we put the UNDEF node to second operand,
9539   // but in some cases the first operand may be transformed to UNDEF.
9540   // In this case we should just commute the node.
9541   if (V1IsUndef)
9542     return DAG.getCommutedVectorShuffle(*SVOp);
9543
9544   // Vector shuffle lowering takes 3 steps:
9545   //
9546   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9547   //    narrowing and commutation of operands should be handled.
9548   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9549   //    shuffle nodes.
9550   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9551   //    so the shuffle can be broken into other shuffles and the legalizer can
9552   //    try the lowering again.
9553   //
9554   // The general idea is that no vector_shuffle operation should be left to
9555   // be matched during isel, all of them must be converted to a target specific
9556   // node here.
9557
9558   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9559   // narrowing and commutation of operands should be handled. The actual code
9560   // doesn't include all of those, work in progress...
9561   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9562   if (NewOp.getNode())
9563     return NewOp;
9564
9565   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9566
9567   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9568   // unpckh_undef). Only use pshufd if speed is more important than size.
9569   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9570     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9571   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9572     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9573
9574   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9575       V2IsUndef && MayFoldVectorLoad(V1))
9576     return getMOVDDup(Op, dl, V1, DAG);
9577
9578   if (isMOVHLPS_v_undef_Mask(M, VT))
9579     return getMOVHighToLow(Op, dl, DAG);
9580
9581   // Use to match splats
9582   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9583       (VT == MVT::v2f64 || VT == MVT::v2i64))
9584     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9585
9586   if (isPSHUFDMask(M, VT)) {
9587     // The actual implementation will match the mask in the if above and then
9588     // during isel it can match several different instructions, not only pshufd
9589     // as its name says, sad but true, emulate the behavior for now...
9590     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9591       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9592
9593     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9594
9595     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9596       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9597
9598     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9599       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9600                                   DAG);
9601
9602     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9603                                 TargetMask, DAG);
9604   }
9605
9606   if (isPALIGNRMask(M, VT, Subtarget))
9607     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9608                                 getShufflePALIGNRImmediate(SVOp),
9609                                 DAG);
9610
9611   // Check if this can be converted into a logical shift.
9612   bool isLeft = false;
9613   unsigned ShAmt = 0;
9614   SDValue ShVal;
9615   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9616   if (isShift && ShVal.hasOneUse()) {
9617     // If the shifted value has multiple uses, it may be cheaper to use
9618     // v_set0 + movlhps or movhlps, etc.
9619     MVT EltVT = VT.getVectorElementType();
9620     ShAmt *= EltVT.getSizeInBits();
9621     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9622   }
9623
9624   if (isMOVLMask(M, VT)) {
9625     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9626       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9627     if (!isMOVLPMask(M, VT)) {
9628       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9629         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9630
9631       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9632         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9633     }
9634   }
9635
9636   // FIXME: fold these into legal mask.
9637   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9638     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9639
9640   if (isMOVHLPSMask(M, VT))
9641     return getMOVHighToLow(Op, dl, DAG);
9642
9643   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9644     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9645
9646   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9647     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9648
9649   if (isMOVLPMask(M, VT))
9650     return getMOVLP(Op, dl, DAG, HasSSE2);
9651
9652   if (ShouldXformToMOVHLPS(M, VT) ||
9653       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9654     return DAG.getCommutedVectorShuffle(*SVOp);
9655
9656   if (isShift) {
9657     // No better options. Use a vshldq / vsrldq.
9658     MVT EltVT = VT.getVectorElementType();
9659     ShAmt *= EltVT.getSizeInBits();
9660     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9661   }
9662
9663   bool Commuted = false;
9664   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9665   // 1,1,1,1 -> v8i16 though.
9666   BitVector UndefElements;
9667   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V1.getNode()))
9668     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9669       V1IsSplat = true;
9670   if (auto *BVOp = dyn_cast<BuildVectorSDNode>(V2.getNode()))
9671     if (BVOp->getConstantSplatNode(&UndefElements) && UndefElements.none())
9672       V2IsSplat = true;
9673
9674   // Canonicalize the splat or undef, if present, to be on the RHS.
9675   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9676     CommuteVectorShuffleMask(M, NumElems);
9677     std::swap(V1, V2);
9678     std::swap(V1IsSplat, V2IsSplat);
9679     Commuted = true;
9680   }
9681
9682   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9683     // Shuffling low element of v1 into undef, just return v1.
9684     if (V2IsUndef)
9685       return V1;
9686     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9687     // the instruction selector will not match, so get a canonical MOVL with
9688     // swapped operands to undo the commute.
9689     return getMOVL(DAG, dl, VT, V2, V1);
9690   }
9691
9692   if (isUNPCKLMask(M, VT, HasInt256))
9693     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9694
9695   if (isUNPCKHMask(M, VT, HasInt256))
9696     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9697
9698   if (V2IsSplat) {
9699     // Normalize mask so all entries that point to V2 points to its first
9700     // element then try to match unpck{h|l} again. If match, return a
9701     // new vector_shuffle with the corrected mask.p
9702     SmallVector<int, 8> NewMask(M.begin(), M.end());
9703     NormalizeMask(NewMask, NumElems);
9704     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9705       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9706     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9707       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9708   }
9709
9710   if (Commuted) {
9711     // Commute is back and try unpck* again.
9712     // FIXME: this seems wrong.
9713     CommuteVectorShuffleMask(M, NumElems);
9714     std::swap(V1, V2);
9715     std::swap(V1IsSplat, V2IsSplat);
9716
9717     if (isUNPCKLMask(M, VT, HasInt256))
9718       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9719
9720     if (isUNPCKHMask(M, VT, HasInt256))
9721       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9722   }
9723
9724   // Normalize the node to match x86 shuffle ops if needed
9725   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9726     return DAG.getCommutedVectorShuffle(*SVOp);
9727
9728   // The checks below are all present in isShuffleMaskLegal, but they are
9729   // inlined here right now to enable us to directly emit target specific
9730   // nodes, and remove one by one until they don't return Op anymore.
9731
9732   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9733       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9734     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9735       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9736   }
9737
9738   if (isPSHUFHWMask(M, VT, HasInt256))
9739     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9740                                 getShufflePSHUFHWImmediate(SVOp),
9741                                 DAG);
9742
9743   if (isPSHUFLWMask(M, VT, HasInt256))
9744     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9745                                 getShufflePSHUFLWImmediate(SVOp),
9746                                 DAG);
9747
9748   unsigned MaskValue;
9749   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9750                   &MaskValue))
9751     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9752
9753   if (isSHUFPMask(M, VT))
9754     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9755                                 getShuffleSHUFImmediate(SVOp), DAG);
9756
9757   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9758     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9759   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9760     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9761
9762   //===--------------------------------------------------------------------===//
9763   // Generate target specific nodes for 128 or 256-bit shuffles only
9764   // supported in the AVX instruction set.
9765   //
9766
9767   // Handle VMOVDDUPY permutations
9768   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9769     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9770
9771   // Handle VPERMILPS/D* permutations
9772   if (isVPERMILPMask(M, VT)) {
9773     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9774       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9775                                   getShuffleSHUFImmediate(SVOp), DAG);
9776     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9777                                 getShuffleSHUFImmediate(SVOp), DAG);
9778   }
9779
9780   unsigned Idx;
9781   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9782     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9783                               Idx*(NumElems/2), DAG, dl);
9784
9785   // Handle VPERM2F128/VPERM2I128 permutations
9786   if (isVPERM2X128Mask(M, VT, HasFp256))
9787     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9788                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9789
9790   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9791     return getINSERTPS(SVOp, dl, DAG);
9792
9793   unsigned Imm8;
9794   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9795     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9796
9797   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9798       VT.is512BitVector()) {
9799     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9800     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9801     SmallVector<SDValue, 16> permclMask;
9802     for (unsigned i = 0; i != NumElems; ++i) {
9803       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9804     }
9805
9806     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9807     if (V2IsUndef)
9808       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9809       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9810                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9811     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9812                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9813   }
9814
9815   //===--------------------------------------------------------------------===//
9816   // Since no target specific shuffle was selected for this generic one,
9817   // lower it into other known shuffles. FIXME: this isn't true yet, but
9818   // this is the plan.
9819   //
9820
9821   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9822   if (VT == MVT::v8i16) {
9823     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9824     if (NewOp.getNode())
9825       return NewOp;
9826   }
9827
9828   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9829     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9830     if (NewOp.getNode())
9831       return NewOp;
9832   }
9833
9834   if (VT == MVT::v16i8) {
9835     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9836     if (NewOp.getNode())
9837       return NewOp;
9838   }
9839
9840   if (VT == MVT::v32i8) {
9841     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9842     if (NewOp.getNode())
9843       return NewOp;
9844   }
9845
9846   // Handle all 128-bit wide vectors with 4 elements, and match them with
9847   // several different shuffle types.
9848   if (NumElems == 4 && VT.is128BitVector())
9849     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9850
9851   // Handle general 256-bit shuffles
9852   if (VT.is256BitVector())
9853     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9854
9855   return SDValue();
9856 }
9857
9858 // This function assumes its argument is a BUILD_VECTOR of constants or
9859 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9860 // true.
9861 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9862                                     unsigned &MaskValue) {
9863   MaskValue = 0;
9864   unsigned NumElems = BuildVector->getNumOperands();
9865   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9866   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9867   unsigned NumElemsInLane = NumElems / NumLanes;
9868
9869   // Blend for v16i16 should be symetric for the both lanes.
9870   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9871     SDValue EltCond = BuildVector->getOperand(i);
9872     SDValue SndLaneEltCond =
9873         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9874
9875     int Lane1Cond = -1, Lane2Cond = -1;
9876     if (isa<ConstantSDNode>(EltCond))
9877       Lane1Cond = !isZero(EltCond);
9878     if (isa<ConstantSDNode>(SndLaneEltCond))
9879       Lane2Cond = !isZero(SndLaneEltCond);
9880
9881     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9882       // Lane1Cond != 0, means we want the first argument.
9883       // Lane1Cond == 0, means we want the second argument.
9884       // The encoding of this argument is 0 for the first argument, 1
9885       // for the second. Therefore, invert the condition.
9886       MaskValue |= !Lane1Cond << i;
9887     else if (Lane1Cond < 0)
9888       MaskValue |= !Lane2Cond << i;
9889     else
9890       return false;
9891   }
9892   return true;
9893 }
9894
9895 // Try to lower a vselect node into a simple blend instruction.
9896 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9897                                    SelectionDAG &DAG) {
9898   SDValue Cond = Op.getOperand(0);
9899   SDValue LHS = Op.getOperand(1);
9900   SDValue RHS = Op.getOperand(2);
9901   SDLoc dl(Op);
9902   MVT VT = Op.getSimpleValueType();
9903   MVT EltVT = VT.getVectorElementType();
9904   unsigned NumElems = VT.getVectorNumElements();
9905
9906   // There is no blend with immediate in AVX-512.
9907   if (VT.is512BitVector())
9908     return SDValue();
9909
9910   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9911     return SDValue();
9912   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9913     return SDValue();
9914
9915   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9916     return SDValue();
9917
9918   // Check the mask for BLEND and build the value.
9919   unsigned MaskValue = 0;
9920   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9921     return SDValue();
9922
9923   // Convert i32 vectors to floating point if it is not AVX2.
9924   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9925   MVT BlendVT = VT;
9926   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9927     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9928                                NumElems);
9929     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9930     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9931   }
9932
9933   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9934                             DAG.getConstant(MaskValue, MVT::i32));
9935   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9936 }
9937
9938 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9939   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9940   if (BlendOp.getNode())
9941     return BlendOp;
9942
9943   // Some types for vselect were previously set to Expand, not Legal or
9944   // Custom. Return an empty SDValue so we fall-through to Expand, after
9945   // the Custom lowering phase.
9946   MVT VT = Op.getSimpleValueType();
9947   switch (VT.SimpleTy) {
9948   default:
9949     break;
9950   case MVT::v8i16:
9951   case MVT::v16i16:
9952     return SDValue();
9953   }
9954
9955   // We couldn't create a "Blend with immediate" node.
9956   // This node should still be legal, but we'll have to emit a blendv*
9957   // instruction.
9958   return Op;
9959 }
9960
9961 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9962   MVT VT = Op.getSimpleValueType();
9963   SDLoc dl(Op);
9964
9965   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9966     return SDValue();
9967
9968   if (VT.getSizeInBits() == 8) {
9969     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9970                                   Op.getOperand(0), Op.getOperand(1));
9971     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9972                                   DAG.getValueType(VT));
9973     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9974   }
9975
9976   if (VT.getSizeInBits() == 16) {
9977     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9978     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9979     if (Idx == 0)
9980       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9981                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9982                                      DAG.getNode(ISD::BITCAST, dl,
9983                                                  MVT::v4i32,
9984                                                  Op.getOperand(0)),
9985                                      Op.getOperand(1)));
9986     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9987                                   Op.getOperand(0), Op.getOperand(1));
9988     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9989                                   DAG.getValueType(VT));
9990     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9991   }
9992
9993   if (VT == MVT::f32) {
9994     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9995     // the result back to FR32 register. It's only worth matching if the
9996     // result has a single use which is a store or a bitcast to i32.  And in
9997     // the case of a store, it's not worth it if the index is a constant 0,
9998     // because a MOVSSmr can be used instead, which is smaller and faster.
9999     if (!Op.hasOneUse())
10000       return SDValue();
10001     SDNode *User = *Op.getNode()->use_begin();
10002     if ((User->getOpcode() != ISD::STORE ||
10003          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10004           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10005         (User->getOpcode() != ISD::BITCAST ||
10006          User->getValueType(0) != MVT::i32))
10007       return SDValue();
10008     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10009                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
10010                                               Op.getOperand(0)),
10011                                               Op.getOperand(1));
10012     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
10013   }
10014
10015   if (VT == MVT::i32 || VT == MVT::i64) {
10016     // ExtractPS/pextrq works with constant index.
10017     if (isa<ConstantSDNode>(Op.getOperand(1)))
10018       return Op;
10019   }
10020   return SDValue();
10021 }
10022
10023 /// Extract one bit from mask vector, like v16i1 or v8i1.
10024 /// AVX-512 feature.
10025 SDValue
10026 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10027   SDValue Vec = Op.getOperand(0);
10028   SDLoc dl(Vec);
10029   MVT VecVT = Vec.getSimpleValueType();
10030   SDValue Idx = Op.getOperand(1);
10031   MVT EltVT = Op.getSimpleValueType();
10032
10033   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10034
10035   // variable index can't be handled in mask registers,
10036   // extend vector to VR512
10037   if (!isa<ConstantSDNode>(Idx)) {
10038     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10039     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10040     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10041                               ExtVT.getVectorElementType(), Ext, Idx);
10042     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10043   }
10044
10045   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10046   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10047   unsigned MaxSift = rc->getSize()*8 - 1;
10048   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10049                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10050   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10051                     DAG.getConstant(MaxSift, MVT::i8));
10052   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10053                        DAG.getIntPtrConstant(0));
10054 }
10055
10056 SDValue
10057 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10058                                            SelectionDAG &DAG) const {
10059   SDLoc dl(Op);
10060   SDValue Vec = Op.getOperand(0);
10061   MVT VecVT = Vec.getSimpleValueType();
10062   SDValue Idx = Op.getOperand(1);
10063
10064   if (Op.getSimpleValueType() == MVT::i1)
10065     return ExtractBitFromMaskVector(Op, DAG);
10066
10067   if (!isa<ConstantSDNode>(Idx)) {
10068     if (VecVT.is512BitVector() ||
10069         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10070          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10071
10072       MVT MaskEltVT =
10073         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10074       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10075                                     MaskEltVT.getSizeInBits());
10076
10077       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10078       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10079                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10080                                 Idx, DAG.getConstant(0, getPointerTy()));
10081       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10082       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10083                         Perm, DAG.getConstant(0, getPointerTy()));
10084     }
10085     return SDValue();
10086   }
10087
10088   // If this is a 256-bit vector result, first extract the 128-bit vector and
10089   // then extract the element from the 128-bit vector.
10090   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10091
10092     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10093     // Get the 128-bit vector.
10094     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10095     MVT EltVT = VecVT.getVectorElementType();
10096
10097     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10098
10099     //if (IdxVal >= NumElems/2)
10100     //  IdxVal -= NumElems/2;
10101     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10102     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10103                        DAG.getConstant(IdxVal, MVT::i32));
10104   }
10105
10106   assert(VecVT.is128BitVector() && "Unexpected vector length");
10107
10108   if (Subtarget->hasSSE41()) {
10109     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
10110     if (Res.getNode())
10111       return Res;
10112   }
10113
10114   MVT VT = Op.getSimpleValueType();
10115   // TODO: handle v16i8.
10116   if (VT.getSizeInBits() == 16) {
10117     SDValue Vec = Op.getOperand(0);
10118     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10119     if (Idx == 0)
10120       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10121                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10122                                      DAG.getNode(ISD::BITCAST, dl,
10123                                                  MVT::v4i32, Vec),
10124                                      Op.getOperand(1)));
10125     // Transform it so it match pextrw which produces a 32-bit result.
10126     MVT EltVT = MVT::i32;
10127     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10128                                   Op.getOperand(0), Op.getOperand(1));
10129     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10130                                   DAG.getValueType(VT));
10131     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10132   }
10133
10134   if (VT.getSizeInBits() == 32) {
10135     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10136     if (Idx == 0)
10137       return Op;
10138
10139     // SHUFPS the element to the lowest double word, then movss.
10140     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10141     MVT VVT = Op.getOperand(0).getSimpleValueType();
10142     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10143                                        DAG.getUNDEF(VVT), Mask);
10144     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10145                        DAG.getIntPtrConstant(0));
10146   }
10147
10148   if (VT.getSizeInBits() == 64) {
10149     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10150     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10151     //        to match extract_elt for f64.
10152     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10153     if (Idx == 0)
10154       return Op;
10155
10156     // UNPCKHPD the element to the lowest double word, then movsd.
10157     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10158     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10159     int Mask[2] = { 1, -1 };
10160     MVT VVT = Op.getOperand(0).getSimpleValueType();
10161     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10162                                        DAG.getUNDEF(VVT), Mask);
10163     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10164                        DAG.getIntPtrConstant(0));
10165   }
10166
10167   return SDValue();
10168 }
10169
10170 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10171   MVT VT = Op.getSimpleValueType();
10172   MVT EltVT = VT.getVectorElementType();
10173   SDLoc dl(Op);
10174
10175   SDValue N0 = Op.getOperand(0);
10176   SDValue N1 = Op.getOperand(1);
10177   SDValue N2 = Op.getOperand(2);
10178
10179   if (!VT.is128BitVector())
10180     return SDValue();
10181
10182   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
10183       isa<ConstantSDNode>(N2)) {
10184     unsigned Opc;
10185     if (VT == MVT::v8i16)
10186       Opc = X86ISD::PINSRW;
10187     else if (VT == MVT::v16i8)
10188       Opc = X86ISD::PINSRB;
10189     else
10190       Opc = X86ISD::PINSRB;
10191
10192     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10193     // argument.
10194     if (N1.getValueType() != MVT::i32)
10195       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10196     if (N2.getValueType() != MVT::i32)
10197       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10198     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10199   }
10200
10201   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
10202     // Bits [7:6] of the constant are the source select.  This will always be
10203     //  zero here.  The DAG Combiner may combine an extract_elt index into these
10204     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
10205     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
10206     // Bits [5:4] of the constant are the destination select.  This is the
10207     //  value of the incoming immediate.
10208     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
10209     //   combine either bitwise AND or insert of float 0.0 to set these bits.
10210     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
10211     // Create this as a scalar to vector..
10212     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10213     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10214   }
10215
10216   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
10217     // PINSR* works with constant index.
10218     return Op;
10219   }
10220   return SDValue();
10221 }
10222
10223 /// Insert one bit to mask vector, like v16i1 or v8i1.
10224 /// AVX-512 feature.
10225 SDValue 
10226 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10227   SDLoc dl(Op);
10228   SDValue Vec = Op.getOperand(0);
10229   SDValue Elt = Op.getOperand(1);
10230   SDValue Idx = Op.getOperand(2);
10231   MVT VecVT = Vec.getSimpleValueType();
10232
10233   if (!isa<ConstantSDNode>(Idx)) {
10234     // Non constant index. Extend source and destination,
10235     // insert element and then truncate the result.
10236     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10237     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10238     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
10239       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10240       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10241     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10242   }
10243
10244   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10245   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10246   if (Vec.getOpcode() == ISD::UNDEF)
10247     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10248                        DAG.getConstant(IdxVal, MVT::i8));
10249   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10250   unsigned MaxSift = rc->getSize()*8 - 1;
10251   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10252                     DAG.getConstant(MaxSift, MVT::i8));
10253   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10254                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10255   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10256 }
10257 SDValue
10258 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10259   MVT VT = Op.getSimpleValueType();
10260   MVT EltVT = VT.getVectorElementType();
10261   
10262   if (EltVT == MVT::i1)
10263     return InsertBitToMaskVector(Op, DAG);
10264
10265   SDLoc dl(Op);
10266   SDValue N0 = Op.getOperand(0);
10267   SDValue N1 = Op.getOperand(1);
10268   SDValue N2 = Op.getOperand(2);
10269
10270   // If this is a 256-bit vector result, first extract the 128-bit vector,
10271   // insert the element into the extracted half and then place it back.
10272   if (VT.is256BitVector() || VT.is512BitVector()) {
10273     if (!isa<ConstantSDNode>(N2))
10274       return SDValue();
10275
10276     // Get the desired 128-bit vector half.
10277     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10278     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10279
10280     // Insert the element into the desired half.
10281     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10282     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10283
10284     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10285                     DAG.getConstant(IdxIn128, MVT::i32));
10286
10287     // Insert the changed part back to the 256-bit vector
10288     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10289   }
10290
10291   if (Subtarget->hasSSE41())
10292     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10293
10294   if (EltVT == MVT::i8)
10295     return SDValue();
10296
10297   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10298     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10299     // as its second argument.
10300     if (N1.getValueType() != MVT::i32)
10301       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10302     if (N2.getValueType() != MVT::i32)
10303       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10304     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10305   }
10306   return SDValue();
10307 }
10308
10309 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10310   SDLoc dl(Op);
10311   MVT OpVT = Op.getSimpleValueType();
10312
10313   // If this is a 256-bit vector result, first insert into a 128-bit
10314   // vector and then insert into the 256-bit vector.
10315   if (!OpVT.is128BitVector()) {
10316     // Insert into a 128-bit vector.
10317     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10318     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10319                                  OpVT.getVectorNumElements() / SizeFactor);
10320
10321     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10322
10323     // Insert the 128-bit vector.
10324     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10325   }
10326
10327   if (OpVT == MVT::v1i64 &&
10328       Op.getOperand(0).getValueType() == MVT::i64)
10329     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10330
10331   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10332   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10333   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10334                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10335 }
10336
10337 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10338 // a simple subregister reference or explicit instructions to grab
10339 // upper bits of a vector.
10340 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10341                                       SelectionDAG &DAG) {
10342   SDLoc dl(Op);
10343   SDValue In =  Op.getOperand(0);
10344   SDValue Idx = Op.getOperand(1);
10345   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10346   MVT ResVT   = Op.getSimpleValueType();
10347   MVT InVT    = In.getSimpleValueType();
10348
10349   if (Subtarget->hasFp256()) {
10350     if (ResVT.is128BitVector() &&
10351         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10352         isa<ConstantSDNode>(Idx)) {
10353       return Extract128BitVector(In, IdxVal, DAG, dl);
10354     }
10355     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10356         isa<ConstantSDNode>(Idx)) {
10357       return Extract256BitVector(In, IdxVal, DAG, dl);
10358     }
10359   }
10360   return SDValue();
10361 }
10362
10363 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10364 // simple superregister reference or explicit instructions to insert
10365 // the upper bits of a vector.
10366 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10367                                      SelectionDAG &DAG) {
10368   if (Subtarget->hasFp256()) {
10369     SDLoc dl(Op.getNode());
10370     SDValue Vec = Op.getNode()->getOperand(0);
10371     SDValue SubVec = Op.getNode()->getOperand(1);
10372     SDValue Idx = Op.getNode()->getOperand(2);
10373
10374     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10375          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10376         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10377         isa<ConstantSDNode>(Idx)) {
10378       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10379       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10380     }
10381
10382     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10383         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10384         isa<ConstantSDNode>(Idx)) {
10385       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10386       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10387     }
10388   }
10389   return SDValue();
10390 }
10391
10392 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10393 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10394 // one of the above mentioned nodes. It has to be wrapped because otherwise
10395 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10396 // be used to form addressing mode. These wrapped nodes will be selected
10397 // into MOV32ri.
10398 SDValue
10399 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10400   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10401
10402   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10403   // global base reg.
10404   unsigned char OpFlag = 0;
10405   unsigned WrapperKind = X86ISD::Wrapper;
10406   CodeModel::Model M = DAG.getTarget().getCodeModel();
10407
10408   if (Subtarget->isPICStyleRIPRel() &&
10409       (M == CodeModel::Small || M == CodeModel::Kernel))
10410     WrapperKind = X86ISD::WrapperRIP;
10411   else if (Subtarget->isPICStyleGOT())
10412     OpFlag = X86II::MO_GOTOFF;
10413   else if (Subtarget->isPICStyleStubPIC())
10414     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10415
10416   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10417                                              CP->getAlignment(),
10418                                              CP->getOffset(), OpFlag);
10419   SDLoc DL(CP);
10420   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10421   // With PIC, the address is actually $g + Offset.
10422   if (OpFlag) {
10423     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10424                          DAG.getNode(X86ISD::GlobalBaseReg,
10425                                      SDLoc(), getPointerTy()),
10426                          Result);
10427   }
10428
10429   return Result;
10430 }
10431
10432 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10433   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10434
10435   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10436   // global base reg.
10437   unsigned char OpFlag = 0;
10438   unsigned WrapperKind = X86ISD::Wrapper;
10439   CodeModel::Model M = DAG.getTarget().getCodeModel();
10440
10441   if (Subtarget->isPICStyleRIPRel() &&
10442       (M == CodeModel::Small || M == CodeModel::Kernel))
10443     WrapperKind = X86ISD::WrapperRIP;
10444   else if (Subtarget->isPICStyleGOT())
10445     OpFlag = X86II::MO_GOTOFF;
10446   else if (Subtarget->isPICStyleStubPIC())
10447     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10448
10449   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10450                                           OpFlag);
10451   SDLoc DL(JT);
10452   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10453
10454   // With PIC, the address is actually $g + Offset.
10455   if (OpFlag)
10456     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10457                          DAG.getNode(X86ISD::GlobalBaseReg,
10458                                      SDLoc(), getPointerTy()),
10459                          Result);
10460
10461   return Result;
10462 }
10463
10464 SDValue
10465 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10466   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10467
10468   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10469   // global base reg.
10470   unsigned char OpFlag = 0;
10471   unsigned WrapperKind = X86ISD::Wrapper;
10472   CodeModel::Model M = DAG.getTarget().getCodeModel();
10473
10474   if (Subtarget->isPICStyleRIPRel() &&
10475       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10476     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10477       OpFlag = X86II::MO_GOTPCREL;
10478     WrapperKind = X86ISD::WrapperRIP;
10479   } else if (Subtarget->isPICStyleGOT()) {
10480     OpFlag = X86II::MO_GOT;
10481   } else if (Subtarget->isPICStyleStubPIC()) {
10482     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10483   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10484     OpFlag = X86II::MO_DARWIN_NONLAZY;
10485   }
10486
10487   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10488
10489   SDLoc DL(Op);
10490   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10491
10492   // With PIC, the address is actually $g + Offset.
10493   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10494       !Subtarget->is64Bit()) {
10495     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10496                          DAG.getNode(X86ISD::GlobalBaseReg,
10497                                      SDLoc(), getPointerTy()),
10498                          Result);
10499   }
10500
10501   // For symbols that require a load from a stub to get the address, emit the
10502   // load.
10503   if (isGlobalStubReference(OpFlag))
10504     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10505                          MachinePointerInfo::getGOT(), false, false, false, 0);
10506
10507   return Result;
10508 }
10509
10510 SDValue
10511 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10512   // Create the TargetBlockAddressAddress node.
10513   unsigned char OpFlags =
10514     Subtarget->ClassifyBlockAddressReference();
10515   CodeModel::Model M = DAG.getTarget().getCodeModel();
10516   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10517   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10518   SDLoc dl(Op);
10519   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10520                                              OpFlags);
10521
10522   if (Subtarget->isPICStyleRIPRel() &&
10523       (M == CodeModel::Small || M == CodeModel::Kernel))
10524     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10525   else
10526     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10527
10528   // With PIC, the address is actually $g + Offset.
10529   if (isGlobalRelativeToPICBase(OpFlags)) {
10530     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10531                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10532                          Result);
10533   }
10534
10535   return Result;
10536 }
10537
10538 SDValue
10539 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10540                                       int64_t Offset, SelectionDAG &DAG) const {
10541   // Create the TargetGlobalAddress node, folding in the constant
10542   // offset if it is legal.
10543   unsigned char OpFlags =
10544       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10545   CodeModel::Model M = DAG.getTarget().getCodeModel();
10546   SDValue Result;
10547   if (OpFlags == X86II::MO_NO_FLAG &&
10548       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10549     // A direct static reference to a global.
10550     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10551     Offset = 0;
10552   } else {
10553     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10554   }
10555
10556   if (Subtarget->isPICStyleRIPRel() &&
10557       (M == CodeModel::Small || M == CodeModel::Kernel))
10558     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10559   else
10560     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10561
10562   // With PIC, the address is actually $g + Offset.
10563   if (isGlobalRelativeToPICBase(OpFlags)) {
10564     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10565                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10566                          Result);
10567   }
10568
10569   // For globals that require a load from a stub to get the address, emit the
10570   // load.
10571   if (isGlobalStubReference(OpFlags))
10572     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10573                          MachinePointerInfo::getGOT(), false, false, false, 0);
10574
10575   // If there was a non-zero offset that we didn't fold, create an explicit
10576   // addition for it.
10577   if (Offset != 0)
10578     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10579                          DAG.getConstant(Offset, getPointerTy()));
10580
10581   return Result;
10582 }
10583
10584 SDValue
10585 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10586   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10587   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10588   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10589 }
10590
10591 static SDValue
10592 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10593            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10594            unsigned char OperandFlags, bool LocalDynamic = false) {
10595   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10596   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10597   SDLoc dl(GA);
10598   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10599                                            GA->getValueType(0),
10600                                            GA->getOffset(),
10601                                            OperandFlags);
10602
10603   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10604                                            : X86ISD::TLSADDR;
10605
10606   if (InFlag) {
10607     SDValue Ops[] = { Chain,  TGA, *InFlag };
10608     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10609   } else {
10610     SDValue Ops[]  = { Chain, TGA };
10611     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10612   }
10613
10614   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10615   MFI->setAdjustsStack(true);
10616
10617   SDValue Flag = Chain.getValue(1);
10618   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10619 }
10620
10621 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10622 static SDValue
10623 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10624                                 const EVT PtrVT) {
10625   SDValue InFlag;
10626   SDLoc dl(GA);  // ? function entry point might be better
10627   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10628                                    DAG.getNode(X86ISD::GlobalBaseReg,
10629                                                SDLoc(), PtrVT), InFlag);
10630   InFlag = Chain.getValue(1);
10631
10632   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10633 }
10634
10635 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10636 static SDValue
10637 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10638                                 const EVT PtrVT) {
10639   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10640                     X86::RAX, X86II::MO_TLSGD);
10641 }
10642
10643 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10644                                            SelectionDAG &DAG,
10645                                            const EVT PtrVT,
10646                                            bool is64Bit) {
10647   SDLoc dl(GA);
10648
10649   // Get the start address of the TLS block for this module.
10650   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10651       .getInfo<X86MachineFunctionInfo>();
10652   MFI->incNumLocalDynamicTLSAccesses();
10653
10654   SDValue Base;
10655   if (is64Bit) {
10656     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10657                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10658   } else {
10659     SDValue InFlag;
10660     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10661         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10662     InFlag = Chain.getValue(1);
10663     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10664                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10665   }
10666
10667   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10668   // of Base.
10669
10670   // Build x@dtpoff.
10671   unsigned char OperandFlags = X86II::MO_DTPOFF;
10672   unsigned WrapperKind = X86ISD::Wrapper;
10673   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10674                                            GA->getValueType(0),
10675                                            GA->getOffset(), OperandFlags);
10676   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10677
10678   // Add x@dtpoff with the base.
10679   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10680 }
10681
10682 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10683 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10684                                    const EVT PtrVT, TLSModel::Model model,
10685                                    bool is64Bit, bool isPIC) {
10686   SDLoc dl(GA);
10687
10688   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10689   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10690                                                          is64Bit ? 257 : 256));
10691
10692   SDValue ThreadPointer =
10693       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10694                   MachinePointerInfo(Ptr), false, false, false, 0);
10695
10696   unsigned char OperandFlags = 0;
10697   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10698   // initialexec.
10699   unsigned WrapperKind = X86ISD::Wrapper;
10700   if (model == TLSModel::LocalExec) {
10701     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10702   } else if (model == TLSModel::InitialExec) {
10703     if (is64Bit) {
10704       OperandFlags = X86II::MO_GOTTPOFF;
10705       WrapperKind = X86ISD::WrapperRIP;
10706     } else {
10707       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10708     }
10709   } else {
10710     llvm_unreachable("Unexpected model");
10711   }
10712
10713   // emit "addl x@ntpoff,%eax" (local exec)
10714   // or "addl x@indntpoff,%eax" (initial exec)
10715   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10716   SDValue TGA =
10717       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10718                                  GA->getOffset(), OperandFlags);
10719   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10720
10721   if (model == TLSModel::InitialExec) {
10722     if (isPIC && !is64Bit) {
10723       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10724                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10725                            Offset);
10726     }
10727
10728     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10729                          MachinePointerInfo::getGOT(), false, false, false, 0);
10730   }
10731
10732   // The address of the thread local variable is the add of the thread
10733   // pointer with the offset of the variable.
10734   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10735 }
10736
10737 SDValue
10738 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10739
10740   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10741   const GlobalValue *GV = GA->getGlobal();
10742
10743   if (Subtarget->isTargetELF()) {
10744     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10745
10746     switch (model) {
10747       case TLSModel::GeneralDynamic:
10748         if (Subtarget->is64Bit())
10749           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10750         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10751       case TLSModel::LocalDynamic:
10752         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10753                                            Subtarget->is64Bit());
10754       case TLSModel::InitialExec:
10755       case TLSModel::LocalExec:
10756         return LowerToTLSExecModel(
10757             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10758             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10759     }
10760     llvm_unreachable("Unknown TLS model.");
10761   }
10762
10763   if (Subtarget->isTargetDarwin()) {
10764     // Darwin only has one model of TLS.  Lower to that.
10765     unsigned char OpFlag = 0;
10766     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10767                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10768
10769     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10770     // global base reg.
10771     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10772                  !Subtarget->is64Bit();
10773     if (PIC32)
10774       OpFlag = X86II::MO_TLVP_PIC_BASE;
10775     else
10776       OpFlag = X86II::MO_TLVP;
10777     SDLoc DL(Op);
10778     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10779                                                 GA->getValueType(0),
10780                                                 GA->getOffset(), OpFlag);
10781     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10782
10783     // With PIC32, the address is actually $g + Offset.
10784     if (PIC32)
10785       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10786                            DAG.getNode(X86ISD::GlobalBaseReg,
10787                                        SDLoc(), getPointerTy()),
10788                            Offset);
10789
10790     // Lowering the machine isd will make sure everything is in the right
10791     // location.
10792     SDValue Chain = DAG.getEntryNode();
10793     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10794     SDValue Args[] = { Chain, Offset };
10795     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10796
10797     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10798     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10799     MFI->setAdjustsStack(true);
10800
10801     // And our return value (tls address) is in the standard call return value
10802     // location.
10803     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10804     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10805                               Chain.getValue(1));
10806   }
10807
10808   if (Subtarget->isTargetKnownWindowsMSVC() ||
10809       Subtarget->isTargetWindowsGNU()) {
10810     // Just use the implicit TLS architecture
10811     // Need to generate someting similar to:
10812     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10813     //                                  ; from TEB
10814     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10815     //   mov     rcx, qword [rdx+rcx*8]
10816     //   mov     eax, .tls$:tlsvar
10817     //   [rax+rcx] contains the address
10818     // Windows 64bit: gs:0x58
10819     // Windows 32bit: fs:__tls_array
10820
10821     SDLoc dl(GA);
10822     SDValue Chain = DAG.getEntryNode();
10823
10824     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10825     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10826     // use its literal value of 0x2C.
10827     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10828                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10829                                                              256)
10830                                         : Type::getInt32PtrTy(*DAG.getContext(),
10831                                                               257));
10832
10833     SDValue TlsArray =
10834         Subtarget->is64Bit()
10835             ? DAG.getIntPtrConstant(0x58)
10836             : (Subtarget->isTargetWindowsGNU()
10837                    ? DAG.getIntPtrConstant(0x2C)
10838                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10839
10840     SDValue ThreadPointer =
10841         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10842                     MachinePointerInfo(Ptr), false, false, false, 0);
10843
10844     // Load the _tls_index variable
10845     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10846     if (Subtarget->is64Bit())
10847       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10848                            IDX, MachinePointerInfo(), MVT::i32,
10849                            false, false, false, 0);
10850     else
10851       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10852                         false, false, false, 0);
10853
10854     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10855                                     getPointerTy());
10856     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10857
10858     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10859     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10860                       false, false, false, 0);
10861
10862     // Get the offset of start of .tls section
10863     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10864                                              GA->getValueType(0),
10865                                              GA->getOffset(), X86II::MO_SECREL);
10866     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10867
10868     // The address of the thread local variable is the add of the thread
10869     // pointer with the offset of the variable.
10870     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10871   }
10872
10873   llvm_unreachable("TLS not implemented for this target.");
10874 }
10875
10876 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10877 /// and take a 2 x i32 value to shift plus a shift amount.
10878 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10879   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10880   MVT VT = Op.getSimpleValueType();
10881   unsigned VTBits = VT.getSizeInBits();
10882   SDLoc dl(Op);
10883   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10884   SDValue ShOpLo = Op.getOperand(0);
10885   SDValue ShOpHi = Op.getOperand(1);
10886   SDValue ShAmt  = Op.getOperand(2);
10887   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10888   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10889   // during isel.
10890   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10891                                   DAG.getConstant(VTBits - 1, MVT::i8));
10892   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10893                                      DAG.getConstant(VTBits - 1, MVT::i8))
10894                        : DAG.getConstant(0, VT);
10895
10896   SDValue Tmp2, Tmp3;
10897   if (Op.getOpcode() == ISD::SHL_PARTS) {
10898     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10899     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10900   } else {
10901     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10902     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10903   }
10904
10905   // If the shift amount is larger or equal than the width of a part we can't
10906   // rely on the results of shld/shrd. Insert a test and select the appropriate
10907   // values for large shift amounts.
10908   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10909                                 DAG.getConstant(VTBits, MVT::i8));
10910   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10911                              AndNode, DAG.getConstant(0, MVT::i8));
10912
10913   SDValue Hi, Lo;
10914   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10915   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10916   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10917
10918   if (Op.getOpcode() == ISD::SHL_PARTS) {
10919     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10920     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10921   } else {
10922     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10923     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10924   }
10925
10926   SDValue Ops[2] = { Lo, Hi };
10927   return DAG.getMergeValues(Ops, dl);
10928 }
10929
10930 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10931                                            SelectionDAG &DAG) const {
10932   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10933
10934   if (SrcVT.isVector())
10935     return SDValue();
10936
10937   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10938          "Unknown SINT_TO_FP to lower!");
10939
10940   // These are really Legal; return the operand so the caller accepts it as
10941   // Legal.
10942   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10943     return Op;
10944   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10945       Subtarget->is64Bit()) {
10946     return Op;
10947   }
10948
10949   SDLoc dl(Op);
10950   unsigned Size = SrcVT.getSizeInBits()/8;
10951   MachineFunction &MF = DAG.getMachineFunction();
10952   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10953   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10954   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10955                                StackSlot,
10956                                MachinePointerInfo::getFixedStack(SSFI),
10957                                false, false, 0);
10958   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10959 }
10960
10961 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10962                                      SDValue StackSlot,
10963                                      SelectionDAG &DAG) const {
10964   // Build the FILD
10965   SDLoc DL(Op);
10966   SDVTList Tys;
10967   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10968   if (useSSE)
10969     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10970   else
10971     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10972
10973   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10974
10975   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10976   MachineMemOperand *MMO;
10977   if (FI) {
10978     int SSFI = FI->getIndex();
10979     MMO =
10980       DAG.getMachineFunction()
10981       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10982                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10983   } else {
10984     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10985     StackSlot = StackSlot.getOperand(1);
10986   }
10987   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10988   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10989                                            X86ISD::FILD, DL,
10990                                            Tys, Ops, SrcVT, MMO);
10991
10992   if (useSSE) {
10993     Chain = Result.getValue(1);
10994     SDValue InFlag = Result.getValue(2);
10995
10996     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10997     // shouldn't be necessary except that RFP cannot be live across
10998     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10999     MachineFunction &MF = DAG.getMachineFunction();
11000     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11001     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11002     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11003     Tys = DAG.getVTList(MVT::Other);
11004     SDValue Ops[] = {
11005       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11006     };
11007     MachineMemOperand *MMO =
11008       DAG.getMachineFunction()
11009       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11010                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11011
11012     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11013                                     Ops, Op.getValueType(), MMO);
11014     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11015                          MachinePointerInfo::getFixedStack(SSFI),
11016                          false, false, false, 0);
11017   }
11018
11019   return Result;
11020 }
11021
11022 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11023 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11024                                                SelectionDAG &DAG) const {
11025   // This algorithm is not obvious. Here it is what we're trying to output:
11026   /*
11027      movq       %rax,  %xmm0
11028      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11029      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11030      #ifdef __SSE3__
11031        haddpd   %xmm0, %xmm0
11032      #else
11033        pshufd   $0x4e, %xmm0, %xmm1
11034        addpd    %xmm1, %xmm0
11035      #endif
11036   */
11037
11038   SDLoc dl(Op);
11039   LLVMContext *Context = DAG.getContext();
11040
11041   // Build some magic constants.
11042   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11043   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11044   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11045
11046   SmallVector<Constant*,2> CV1;
11047   CV1.push_back(
11048     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11049                                       APInt(64, 0x4330000000000000ULL))));
11050   CV1.push_back(
11051     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11052                                       APInt(64, 0x4530000000000000ULL))));
11053   Constant *C1 = ConstantVector::get(CV1);
11054   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11055
11056   // Load the 64-bit value into an XMM register.
11057   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11058                             Op.getOperand(0));
11059   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11060                               MachinePointerInfo::getConstantPool(),
11061                               false, false, false, 16);
11062   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
11063                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
11064                               CLod0);
11065
11066   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11067                               MachinePointerInfo::getConstantPool(),
11068                               false, false, false, 16);
11069   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
11070   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11071   SDValue Result;
11072
11073   if (Subtarget->hasSSE3()) {
11074     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11075     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11076   } else {
11077     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
11078     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11079                                            S2F, 0x4E, DAG);
11080     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11081                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
11082                          Sub);
11083   }
11084
11085   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11086                      DAG.getIntPtrConstant(0));
11087 }
11088
11089 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11090 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11091                                                SelectionDAG &DAG) const {
11092   SDLoc dl(Op);
11093   // FP constant to bias correct the final result.
11094   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
11095                                    MVT::f64);
11096
11097   // Load the 32-bit value into an XMM register.
11098   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11099                              Op.getOperand(0));
11100
11101   // Zero out the upper parts of the register.
11102   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11103
11104   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11105                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
11106                      DAG.getIntPtrConstant(0));
11107
11108   // Or the load with the bias.
11109   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
11110                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11111                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11112                                                    MVT::v2f64, Load)),
11113                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
11114                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
11115                                                    MVT::v2f64, Bias)));
11116   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11117                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
11118                    DAG.getIntPtrConstant(0));
11119
11120   // Subtract the bias.
11121   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11122
11123   // Handle final rounding.
11124   EVT DestVT = Op.getValueType();
11125
11126   if (DestVT.bitsLT(MVT::f64))
11127     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11128                        DAG.getIntPtrConstant(0));
11129   if (DestVT.bitsGT(MVT::f64))
11130     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11131
11132   // Handle final rounding.
11133   return Sub;
11134 }
11135
11136 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11137                                                SelectionDAG &DAG) const {
11138   SDValue N0 = Op.getOperand(0);
11139   MVT SVT = N0.getSimpleValueType();
11140   SDLoc dl(Op);
11141
11142   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
11143           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
11144          "Custom UINT_TO_FP is not supported!");
11145
11146   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11147   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11148                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11149 }
11150
11151 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11152                                            SelectionDAG &DAG) const {
11153   SDValue N0 = Op.getOperand(0);
11154   SDLoc dl(Op);
11155
11156   if (Op.getValueType().isVector())
11157     return lowerUINT_TO_FP_vec(Op, DAG);
11158
11159   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11160   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11161   // the optimization here.
11162   if (DAG.SignBitIsZero(N0))
11163     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11164
11165   MVT SrcVT = N0.getSimpleValueType();
11166   MVT DstVT = Op.getSimpleValueType();
11167   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11168     return LowerUINT_TO_FP_i64(Op, DAG);
11169   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11170     return LowerUINT_TO_FP_i32(Op, DAG);
11171   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11172     return SDValue();
11173
11174   // Make a 64-bit buffer, and use it to build an FILD.
11175   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11176   if (SrcVT == MVT::i32) {
11177     SDValue WordOff = DAG.getConstant(4, getPointerTy());
11178     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11179                                      getPointerTy(), StackSlot, WordOff);
11180     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11181                                   StackSlot, MachinePointerInfo(),
11182                                   false, false, 0);
11183     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
11184                                   OffsetSlot, MachinePointerInfo(),
11185                                   false, false, 0);
11186     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11187     return Fild;
11188   }
11189
11190   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11191   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11192                                StackSlot, MachinePointerInfo(),
11193                                false, false, 0);
11194   // For i64 source, we need to add the appropriate power of 2 if the input
11195   // was negative.  This is the same as the optimization in
11196   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11197   // we must be careful to do the computation in x87 extended precision, not
11198   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11199   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11200   MachineMemOperand *MMO =
11201     DAG.getMachineFunction()
11202     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11203                           MachineMemOperand::MOLoad, 8, 8);
11204
11205   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11206   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11207   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11208                                          MVT::i64, MMO);
11209
11210   APInt FF(32, 0x5F800000ULL);
11211
11212   // Check whether the sign bit is set.
11213   SDValue SignSet = DAG.getSetCC(dl,
11214                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
11215                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
11216                                  ISD::SETLT);
11217
11218   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
11219   SDValue FudgePtr = DAG.getConstantPool(
11220                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
11221                                          getPointerTy());
11222
11223   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
11224   SDValue Zero = DAG.getIntPtrConstant(0);
11225   SDValue Four = DAG.getIntPtrConstant(4);
11226   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
11227                                Zero, Four);
11228   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
11229
11230   // Load the value out, extending it from f32 to f80.
11231   // FIXME: Avoid the extend by constructing the right constant pool?
11232   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
11233                                  FudgePtr, MachinePointerInfo::getConstantPool(),
11234                                  MVT::f32, false, false, false, 4);
11235   // Extend everything to 80 bits to force it to be done on x87.
11236   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
11237   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
11238 }
11239
11240 std::pair<SDValue,SDValue>
11241 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
11242                                     bool IsSigned, bool IsReplace) const {
11243   SDLoc DL(Op);
11244
11245   EVT DstTy = Op.getValueType();
11246
11247   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
11248     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
11249     DstTy = MVT::i64;
11250   }
11251
11252   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11253          DstTy.getSimpleVT() >= MVT::i16 &&
11254          "Unknown FP_TO_INT to lower!");
11255
11256   // These are really Legal.
11257   if (DstTy == MVT::i32 &&
11258       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11259     return std::make_pair(SDValue(), SDValue());
11260   if (Subtarget->is64Bit() &&
11261       DstTy == MVT::i64 &&
11262       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11263     return std::make_pair(SDValue(), SDValue());
11264
11265   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11266   // stack slot, or into the FTOL runtime function.
11267   MachineFunction &MF = DAG.getMachineFunction();
11268   unsigned MemSize = DstTy.getSizeInBits()/8;
11269   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11270   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11271
11272   unsigned Opc;
11273   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11274     Opc = X86ISD::WIN_FTOL;
11275   else
11276     switch (DstTy.getSimpleVT().SimpleTy) {
11277     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11278     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11279     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11280     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11281     }
11282
11283   SDValue Chain = DAG.getEntryNode();
11284   SDValue Value = Op.getOperand(0);
11285   EVT TheVT = Op.getOperand(0).getValueType();
11286   // FIXME This causes a redundant load/store if the SSE-class value is already
11287   // in memory, such as if it is on the callstack.
11288   if (isScalarFPTypeInSSEReg(TheVT)) {
11289     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11290     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11291                          MachinePointerInfo::getFixedStack(SSFI),
11292                          false, false, 0);
11293     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11294     SDValue Ops[] = {
11295       Chain, StackSlot, DAG.getValueType(TheVT)
11296     };
11297
11298     MachineMemOperand *MMO =
11299       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11300                               MachineMemOperand::MOLoad, MemSize, MemSize);
11301     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11302     Chain = Value.getValue(1);
11303     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11304     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11305   }
11306
11307   MachineMemOperand *MMO =
11308     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11309                             MachineMemOperand::MOStore, MemSize, MemSize);
11310
11311   if (Opc != X86ISD::WIN_FTOL) {
11312     // Build the FP_TO_INT*_IN_MEM
11313     SDValue Ops[] = { Chain, Value, StackSlot };
11314     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11315                                            Ops, DstTy, MMO);
11316     return std::make_pair(FIST, StackSlot);
11317   } else {
11318     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11319       DAG.getVTList(MVT::Other, MVT::Glue),
11320       Chain, Value);
11321     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11322       MVT::i32, ftol.getValue(1));
11323     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11324       MVT::i32, eax.getValue(2));
11325     SDValue Ops[] = { eax, edx };
11326     SDValue pair = IsReplace
11327       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11328       : DAG.getMergeValues(Ops, DL);
11329     return std::make_pair(pair, SDValue());
11330   }
11331 }
11332
11333 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11334                               const X86Subtarget *Subtarget) {
11335   MVT VT = Op->getSimpleValueType(0);
11336   SDValue In = Op->getOperand(0);
11337   MVT InVT = In.getSimpleValueType();
11338   SDLoc dl(Op);
11339
11340   // Optimize vectors in AVX mode:
11341   //
11342   //   v8i16 -> v8i32
11343   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11344   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11345   //   Concat upper and lower parts.
11346   //
11347   //   v4i32 -> v4i64
11348   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11349   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11350   //   Concat upper and lower parts.
11351   //
11352
11353   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11354       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11355       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11356     return SDValue();
11357
11358   if (Subtarget->hasInt256())
11359     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11360
11361   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11362   SDValue Undef = DAG.getUNDEF(InVT);
11363   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11364   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11365   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11366
11367   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11368                              VT.getVectorNumElements()/2);
11369
11370   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11371   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11372
11373   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11374 }
11375
11376 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11377                                         SelectionDAG &DAG) {
11378   MVT VT = Op->getSimpleValueType(0);
11379   SDValue In = Op->getOperand(0);
11380   MVT InVT = In.getSimpleValueType();
11381   SDLoc DL(Op);
11382   unsigned int NumElts = VT.getVectorNumElements();
11383   if (NumElts != 8 && NumElts != 16)
11384     return SDValue();
11385
11386   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11387     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11388
11389   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11390   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11391   // Now we have only mask extension
11392   assert(InVT.getVectorElementType() == MVT::i1);
11393   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11394   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11395   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11396   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11397   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11398                            MachinePointerInfo::getConstantPool(),
11399                            false, false, false, Alignment);
11400
11401   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11402   if (VT.is512BitVector())
11403     return Brcst;
11404   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11405 }
11406
11407 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11408                                SelectionDAG &DAG) {
11409   if (Subtarget->hasFp256()) {
11410     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11411     if (Res.getNode())
11412       return Res;
11413   }
11414
11415   return SDValue();
11416 }
11417
11418 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11419                                 SelectionDAG &DAG) {
11420   SDLoc DL(Op);
11421   MVT VT = Op.getSimpleValueType();
11422   SDValue In = Op.getOperand(0);
11423   MVT SVT = In.getSimpleValueType();
11424
11425   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11426     return LowerZERO_EXTEND_AVX512(Op, DAG);
11427
11428   if (Subtarget->hasFp256()) {
11429     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11430     if (Res.getNode())
11431       return Res;
11432   }
11433
11434   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11435          VT.getVectorNumElements() != SVT.getVectorNumElements());
11436   return SDValue();
11437 }
11438
11439 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11440   SDLoc DL(Op);
11441   MVT VT = Op.getSimpleValueType();
11442   SDValue In = Op.getOperand(0);
11443   MVT InVT = In.getSimpleValueType();
11444
11445   if (VT == MVT::i1) {
11446     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11447            "Invalid scalar TRUNCATE operation");
11448     if (InVT == MVT::i32)
11449       return SDValue();
11450     if (InVT.getSizeInBits() == 64)
11451       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11452     else if (InVT.getSizeInBits() < 32)
11453       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11454     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11455   }
11456   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11457          "Invalid TRUNCATE operation");
11458
11459   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11460     if (VT.getVectorElementType().getSizeInBits() >=8)
11461       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11462
11463     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11464     unsigned NumElts = InVT.getVectorNumElements();
11465     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11466     if (InVT.getSizeInBits() < 512) {
11467       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11468       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11469       InVT = ExtVT;
11470     }
11471     
11472     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11473     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11474     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11475     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11476     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11477                            MachinePointerInfo::getConstantPool(),
11478                            false, false, false, Alignment);
11479     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11480     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11481     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11482   }
11483
11484   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11485     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11486     if (Subtarget->hasInt256()) {
11487       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11488       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11489       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11490                                 ShufMask);
11491       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11492                          DAG.getIntPtrConstant(0));
11493     }
11494
11495     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11496                                DAG.getIntPtrConstant(0));
11497     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11498                                DAG.getIntPtrConstant(2));
11499     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11500     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11501     static const int ShufMask[] = {0, 2, 4, 6};
11502     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11503   }
11504
11505   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11506     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11507     if (Subtarget->hasInt256()) {
11508       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11509
11510       SmallVector<SDValue,32> pshufbMask;
11511       for (unsigned i = 0; i < 2; ++i) {
11512         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11513         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11514         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11515         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11516         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11517         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11518         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11519         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11520         for (unsigned j = 0; j < 8; ++j)
11521           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11522       }
11523       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11524       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11525       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11526
11527       static const int ShufMask[] = {0,  2,  -1,  -1};
11528       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11529                                 &ShufMask[0]);
11530       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11531                        DAG.getIntPtrConstant(0));
11532       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11533     }
11534
11535     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11536                                DAG.getIntPtrConstant(0));
11537
11538     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11539                                DAG.getIntPtrConstant(4));
11540
11541     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11542     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11543
11544     // The PSHUFB mask:
11545     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11546                                    -1, -1, -1, -1, -1, -1, -1, -1};
11547
11548     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11549     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11550     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11551
11552     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11553     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11554
11555     // The MOVLHPS Mask:
11556     static const int ShufMask2[] = {0, 1, 4, 5};
11557     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11558     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11559   }
11560
11561   // Handle truncation of V256 to V128 using shuffles.
11562   if (!VT.is128BitVector() || !InVT.is256BitVector())
11563     return SDValue();
11564
11565   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11566
11567   unsigned NumElems = VT.getVectorNumElements();
11568   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11569
11570   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11571   // Prepare truncation shuffle mask
11572   for (unsigned i = 0; i != NumElems; ++i)
11573     MaskVec[i] = i * 2;
11574   SDValue V = DAG.getVectorShuffle(NVT, DL,
11575                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11576                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11577   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11578                      DAG.getIntPtrConstant(0));
11579 }
11580
11581 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11582                                            SelectionDAG &DAG) const {
11583   assert(!Op.getSimpleValueType().isVector());
11584
11585   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11586     /*IsSigned=*/ true, /*IsReplace=*/ false);
11587   SDValue FIST = Vals.first, StackSlot = Vals.second;
11588   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11589   if (!FIST.getNode()) return Op;
11590
11591   if (StackSlot.getNode())
11592     // Load the result.
11593     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11594                        FIST, StackSlot, MachinePointerInfo(),
11595                        false, false, false, 0);
11596
11597   // The node is the result.
11598   return FIST;
11599 }
11600
11601 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11602                                            SelectionDAG &DAG) const {
11603   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11604     /*IsSigned=*/ false, /*IsReplace=*/ false);
11605   SDValue FIST = Vals.first, StackSlot = Vals.second;
11606   assert(FIST.getNode() && "Unexpected failure");
11607
11608   if (StackSlot.getNode())
11609     // Load the result.
11610     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11611                        FIST, StackSlot, MachinePointerInfo(),
11612                        false, false, false, 0);
11613
11614   // The node is the result.
11615   return FIST;
11616 }
11617
11618 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11619   SDLoc DL(Op);
11620   MVT VT = Op.getSimpleValueType();
11621   SDValue In = Op.getOperand(0);
11622   MVT SVT = In.getSimpleValueType();
11623
11624   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11625
11626   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11627                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11628                                  In, DAG.getUNDEF(SVT)));
11629 }
11630
11631 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11632   LLVMContext *Context = DAG.getContext();
11633   SDLoc dl(Op);
11634   MVT VT = Op.getSimpleValueType();
11635   MVT EltVT = VT;
11636   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11637   if (VT.isVector()) {
11638     EltVT = VT.getVectorElementType();
11639     NumElts = VT.getVectorNumElements();
11640   }
11641   Constant *C;
11642   if (EltVT == MVT::f64)
11643     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11644                                           APInt(64, ~(1ULL << 63))));
11645   else
11646     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11647                                           APInt(32, ~(1U << 31))));
11648   C = ConstantVector::getSplat(NumElts, C);
11649   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11650   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11651   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11652   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11653                              MachinePointerInfo::getConstantPool(),
11654                              false, false, false, Alignment);
11655   if (VT.isVector()) {
11656     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11657     return DAG.getNode(ISD::BITCAST, dl, VT,
11658                        DAG.getNode(ISD::AND, dl, ANDVT,
11659                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11660                                                Op.getOperand(0)),
11661                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11662   }
11663   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11664 }
11665
11666 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11667   LLVMContext *Context = DAG.getContext();
11668   SDLoc dl(Op);
11669   MVT VT = Op.getSimpleValueType();
11670   MVT EltVT = VT;
11671   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11672   if (VT.isVector()) {
11673     EltVT = VT.getVectorElementType();
11674     NumElts = VT.getVectorNumElements();
11675   }
11676   Constant *C;
11677   if (EltVT == MVT::f64)
11678     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11679                                           APInt(64, 1ULL << 63)));
11680   else
11681     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11682                                           APInt(32, 1U << 31)));
11683   C = ConstantVector::getSplat(NumElts, C);
11684   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11685   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11686   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11687   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11688                              MachinePointerInfo::getConstantPool(),
11689                              false, false, false, Alignment);
11690   if (VT.isVector()) {
11691     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11692     return DAG.getNode(ISD::BITCAST, dl, VT,
11693                        DAG.getNode(ISD::XOR, dl, XORVT,
11694                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11695                                                Op.getOperand(0)),
11696                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11697   }
11698
11699   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11700 }
11701
11702 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11703   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11704   LLVMContext *Context = DAG.getContext();
11705   SDValue Op0 = Op.getOperand(0);
11706   SDValue Op1 = Op.getOperand(1);
11707   SDLoc dl(Op);
11708   MVT VT = Op.getSimpleValueType();
11709   MVT SrcVT = Op1.getSimpleValueType();
11710
11711   // If second operand is smaller, extend it first.
11712   if (SrcVT.bitsLT(VT)) {
11713     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11714     SrcVT = VT;
11715   }
11716   // And if it is bigger, shrink it first.
11717   if (SrcVT.bitsGT(VT)) {
11718     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11719     SrcVT = VT;
11720   }
11721
11722   // At this point the operands and the result should have the same
11723   // type, and that won't be f80 since that is not custom lowered.
11724
11725   // First get the sign bit of second operand.
11726   SmallVector<Constant*,4> CV;
11727   if (SrcVT == MVT::f64) {
11728     const fltSemantics &Sem = APFloat::IEEEdouble;
11729     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11730     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11731   } else {
11732     const fltSemantics &Sem = APFloat::IEEEsingle;
11733     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11734     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11735     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11736     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11737   }
11738   Constant *C = ConstantVector::get(CV);
11739   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11740   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11741                               MachinePointerInfo::getConstantPool(),
11742                               false, false, false, 16);
11743   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11744
11745   // Shift sign bit right or left if the two operands have different types.
11746   if (SrcVT.bitsGT(VT)) {
11747     // Op0 is MVT::f32, Op1 is MVT::f64.
11748     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11749     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11750                           DAG.getConstant(32, MVT::i32));
11751     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11752     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11753                           DAG.getIntPtrConstant(0));
11754   }
11755
11756   // Clear first operand sign bit.
11757   CV.clear();
11758   if (VT == MVT::f64) {
11759     const fltSemantics &Sem = APFloat::IEEEdouble;
11760     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11761                                                    APInt(64, ~(1ULL << 63)))));
11762     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11763   } else {
11764     const fltSemantics &Sem = APFloat::IEEEsingle;
11765     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11766                                                    APInt(32, ~(1U << 31)))));
11767     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11768     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11769     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11770   }
11771   C = ConstantVector::get(CV);
11772   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11773   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11774                               MachinePointerInfo::getConstantPool(),
11775                               false, false, false, 16);
11776   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11777
11778   // Or the value with the sign bit.
11779   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11780 }
11781
11782 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11783   SDValue N0 = Op.getOperand(0);
11784   SDLoc dl(Op);
11785   MVT VT = Op.getSimpleValueType();
11786
11787   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11788   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11789                                   DAG.getConstant(1, VT));
11790   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11791 }
11792
11793 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11794 //
11795 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11796                                       SelectionDAG &DAG) {
11797   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11798
11799   if (!Subtarget->hasSSE41())
11800     return SDValue();
11801
11802   if (!Op->hasOneUse())
11803     return SDValue();
11804
11805   SDNode *N = Op.getNode();
11806   SDLoc DL(N);
11807
11808   SmallVector<SDValue, 8> Opnds;
11809   DenseMap<SDValue, unsigned> VecInMap;
11810   SmallVector<SDValue, 8> VecIns;
11811   EVT VT = MVT::Other;
11812
11813   // Recognize a special case where a vector is casted into wide integer to
11814   // test all 0s.
11815   Opnds.push_back(N->getOperand(0));
11816   Opnds.push_back(N->getOperand(1));
11817
11818   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11819     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11820     // BFS traverse all OR'd operands.
11821     if (I->getOpcode() == ISD::OR) {
11822       Opnds.push_back(I->getOperand(0));
11823       Opnds.push_back(I->getOperand(1));
11824       // Re-evaluate the number of nodes to be traversed.
11825       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11826       continue;
11827     }
11828
11829     // Quit if a non-EXTRACT_VECTOR_ELT
11830     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11831       return SDValue();
11832
11833     // Quit if without a constant index.
11834     SDValue Idx = I->getOperand(1);
11835     if (!isa<ConstantSDNode>(Idx))
11836       return SDValue();
11837
11838     SDValue ExtractedFromVec = I->getOperand(0);
11839     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11840     if (M == VecInMap.end()) {
11841       VT = ExtractedFromVec.getValueType();
11842       // Quit if not 128/256-bit vector.
11843       if (!VT.is128BitVector() && !VT.is256BitVector())
11844         return SDValue();
11845       // Quit if not the same type.
11846       if (VecInMap.begin() != VecInMap.end() &&
11847           VT != VecInMap.begin()->first.getValueType())
11848         return SDValue();
11849       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11850       VecIns.push_back(ExtractedFromVec);
11851     }
11852     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11853   }
11854
11855   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11856          "Not extracted from 128-/256-bit vector.");
11857
11858   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11859
11860   for (DenseMap<SDValue, unsigned>::const_iterator
11861         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11862     // Quit if not all elements are used.
11863     if (I->second != FullMask)
11864       return SDValue();
11865   }
11866
11867   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11868
11869   // Cast all vectors into TestVT for PTEST.
11870   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11871     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11872
11873   // If more than one full vectors are evaluated, OR them first before PTEST.
11874   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11875     // Each iteration will OR 2 nodes and append the result until there is only
11876     // 1 node left, i.e. the final OR'd value of all vectors.
11877     SDValue LHS = VecIns[Slot];
11878     SDValue RHS = VecIns[Slot + 1];
11879     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11880   }
11881
11882   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11883                      VecIns.back(), VecIns.back());
11884 }
11885
11886 /// \brief return true if \c Op has a use that doesn't just read flags.
11887 static bool hasNonFlagsUse(SDValue Op) {
11888   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11889        ++UI) {
11890     SDNode *User = *UI;
11891     unsigned UOpNo = UI.getOperandNo();
11892     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11893       // Look pass truncate.
11894       UOpNo = User->use_begin().getOperandNo();
11895       User = *User->use_begin();
11896     }
11897
11898     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11899         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11900       return true;
11901   }
11902   return false;
11903 }
11904
11905 /// Emit nodes that will be selected as "test Op0,Op0", or something
11906 /// equivalent.
11907 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11908                                     SelectionDAG &DAG) const {
11909   if (Op.getValueType() == MVT::i1)
11910     // KORTEST instruction should be selected
11911     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11912                        DAG.getConstant(0, Op.getValueType()));
11913
11914   // CF and OF aren't always set the way we want. Determine which
11915   // of these we need.
11916   bool NeedCF = false;
11917   bool NeedOF = false;
11918   switch (X86CC) {
11919   default: break;
11920   case X86::COND_A: case X86::COND_AE:
11921   case X86::COND_B: case X86::COND_BE:
11922     NeedCF = true;
11923     break;
11924   case X86::COND_G: case X86::COND_GE:
11925   case X86::COND_L: case X86::COND_LE:
11926   case X86::COND_O: case X86::COND_NO: {
11927     // Check if we really need to set the
11928     // Overflow flag. If NoSignedWrap is present
11929     // that is not actually needed.
11930     switch (Op->getOpcode()) {
11931     case ISD::ADD:
11932     case ISD::SUB:
11933     case ISD::MUL:
11934     case ISD::SHL: {
11935       const BinaryWithFlagsSDNode *BinNode =
11936           cast<BinaryWithFlagsSDNode>(Op.getNode());
11937       if (BinNode->hasNoSignedWrap())
11938         break;
11939     }
11940     default:
11941       NeedOF = true;
11942       break;
11943     }
11944     break;
11945   }
11946   }
11947   // See if we can use the EFLAGS value from the operand instead of
11948   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11949   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11950   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11951     // Emit a CMP with 0, which is the TEST pattern.
11952     //if (Op.getValueType() == MVT::i1)
11953     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11954     //                     DAG.getConstant(0, MVT::i1));
11955     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11956                        DAG.getConstant(0, Op.getValueType()));
11957   }
11958   unsigned Opcode = 0;
11959   unsigned NumOperands = 0;
11960
11961   // Truncate operations may prevent the merge of the SETCC instruction
11962   // and the arithmetic instruction before it. Attempt to truncate the operands
11963   // of the arithmetic instruction and use a reduced bit-width instruction.
11964   bool NeedTruncation = false;
11965   SDValue ArithOp = Op;
11966   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11967     SDValue Arith = Op->getOperand(0);
11968     // Both the trunc and the arithmetic op need to have one user each.
11969     if (Arith->hasOneUse())
11970       switch (Arith.getOpcode()) {
11971         default: break;
11972         case ISD::ADD:
11973         case ISD::SUB:
11974         case ISD::AND:
11975         case ISD::OR:
11976         case ISD::XOR: {
11977           NeedTruncation = true;
11978           ArithOp = Arith;
11979         }
11980       }
11981   }
11982
11983   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11984   // which may be the result of a CAST.  We use the variable 'Op', which is the
11985   // non-casted variable when we check for possible users.
11986   switch (ArithOp.getOpcode()) {
11987   case ISD::ADD:
11988     // Due to an isel shortcoming, be conservative if this add is likely to be
11989     // selected as part of a load-modify-store instruction. When the root node
11990     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11991     // uses of other nodes in the match, such as the ADD in this case. This
11992     // leads to the ADD being left around and reselected, with the result being
11993     // two adds in the output.  Alas, even if none our users are stores, that
11994     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11995     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11996     // climbing the DAG back to the root, and it doesn't seem to be worth the
11997     // effort.
11998     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11999          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12000       if (UI->getOpcode() != ISD::CopyToReg &&
12001           UI->getOpcode() != ISD::SETCC &&
12002           UI->getOpcode() != ISD::STORE)
12003         goto default_case;
12004
12005     if (ConstantSDNode *C =
12006         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12007       // An add of one will be selected as an INC.
12008       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12009         Opcode = X86ISD::INC;
12010         NumOperands = 1;
12011         break;
12012       }
12013
12014       // An add of negative one (subtract of one) will be selected as a DEC.
12015       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12016         Opcode = X86ISD::DEC;
12017         NumOperands = 1;
12018         break;
12019       }
12020     }
12021
12022     // Otherwise use a regular EFLAGS-setting add.
12023     Opcode = X86ISD::ADD;
12024     NumOperands = 2;
12025     break;
12026   case ISD::SHL:
12027   case ISD::SRL:
12028     // If we have a constant logical shift that's only used in a comparison
12029     // against zero turn it into an equivalent AND. This allows turning it into
12030     // a TEST instruction later.
12031     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12032         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12033       EVT VT = Op.getValueType();
12034       unsigned BitWidth = VT.getSizeInBits();
12035       unsigned ShAmt = Op->getConstantOperandVal(1);
12036       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12037         break;
12038       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12039                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12040                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12041       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12042         break;
12043       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12044                                 DAG.getConstant(Mask, VT));
12045       DAG.ReplaceAllUsesWith(Op, New);
12046       Op = New;
12047     }
12048     break;
12049
12050   case ISD::AND:
12051     // If the primary and result isn't used, don't bother using X86ISD::AND,
12052     // because a TEST instruction will be better.
12053     if (!hasNonFlagsUse(Op))
12054       break;
12055     // FALL THROUGH
12056   case ISD::SUB:
12057   case ISD::OR:
12058   case ISD::XOR:
12059     // Due to the ISEL shortcoming noted above, be conservative if this op is
12060     // likely to be selected as part of a load-modify-store instruction.
12061     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12062            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12063       if (UI->getOpcode() == ISD::STORE)
12064         goto default_case;
12065
12066     // Otherwise use a regular EFLAGS-setting instruction.
12067     switch (ArithOp.getOpcode()) {
12068     default: llvm_unreachable("unexpected operator!");
12069     case ISD::SUB: Opcode = X86ISD::SUB; break;
12070     case ISD::XOR: Opcode = X86ISD::XOR; break;
12071     case ISD::AND: Opcode = X86ISD::AND; break;
12072     case ISD::OR: {
12073       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12074         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12075         if (EFLAGS.getNode())
12076           return EFLAGS;
12077       }
12078       Opcode = X86ISD::OR;
12079       break;
12080     }
12081     }
12082
12083     NumOperands = 2;
12084     break;
12085   case X86ISD::ADD:
12086   case X86ISD::SUB:
12087   case X86ISD::INC:
12088   case X86ISD::DEC:
12089   case X86ISD::OR:
12090   case X86ISD::XOR:
12091   case X86ISD::AND:
12092     return SDValue(Op.getNode(), 1);
12093   default:
12094   default_case:
12095     break;
12096   }
12097
12098   // If we found that truncation is beneficial, perform the truncation and
12099   // update 'Op'.
12100   if (NeedTruncation) {
12101     EVT VT = Op.getValueType();
12102     SDValue WideVal = Op->getOperand(0);
12103     EVT WideVT = WideVal.getValueType();
12104     unsigned ConvertedOp = 0;
12105     // Use a target machine opcode to prevent further DAGCombine
12106     // optimizations that may separate the arithmetic operations
12107     // from the setcc node.
12108     switch (WideVal.getOpcode()) {
12109       default: break;
12110       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12111       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12112       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12113       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12114       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12115     }
12116
12117     if (ConvertedOp) {
12118       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12119       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12120         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12121         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12122         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12123       }
12124     }
12125   }
12126
12127   if (Opcode == 0)
12128     // Emit a CMP with 0, which is the TEST pattern.
12129     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12130                        DAG.getConstant(0, Op.getValueType()));
12131
12132   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12133   SmallVector<SDValue, 4> Ops;
12134   for (unsigned i = 0; i != NumOperands; ++i)
12135     Ops.push_back(Op.getOperand(i));
12136
12137   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12138   DAG.ReplaceAllUsesWith(Op, New);
12139   return SDValue(New.getNode(), 1);
12140 }
12141
12142 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12143 /// equivalent.
12144 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12145                                    SDLoc dl, SelectionDAG &DAG) const {
12146   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12147     if (C->getAPIntValue() == 0)
12148       return EmitTest(Op0, X86CC, dl, DAG);
12149
12150      if (Op0.getValueType() == MVT::i1)
12151        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12152   }
12153  
12154   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12155        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12156     // Do the comparison at i32 if it's smaller, besides the Atom case. 
12157     // This avoids subregister aliasing issues. Keep the smaller reference 
12158     // if we're optimizing for size, however, as that'll allow better folding 
12159     // of memory operations.
12160     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12161         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
12162              AttributeSet::FunctionIndex, Attribute::MinSize) &&
12163         !Subtarget->isAtom()) {
12164       unsigned ExtendOp =
12165           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12166       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12167       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12168     }
12169     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12170     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12171     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12172                               Op0, Op1);
12173     return SDValue(Sub.getNode(), 1);
12174   }
12175   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12176 }
12177
12178 /// Convert a comparison if required by the subtarget.
12179 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12180                                                  SelectionDAG &DAG) const {
12181   // If the subtarget does not support the FUCOMI instruction, floating-point
12182   // comparisons have to be converted.
12183   if (Subtarget->hasCMov() ||
12184       Cmp.getOpcode() != X86ISD::CMP ||
12185       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12186       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12187     return Cmp;
12188
12189   // The instruction selector will select an FUCOM instruction instead of
12190   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12191   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12192   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12193   SDLoc dl(Cmp);
12194   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12195   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12196   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12197                             DAG.getConstant(8, MVT::i8));
12198   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12199   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12200 }
12201
12202 static bool isAllOnes(SDValue V) {
12203   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
12204   return C && C->isAllOnesValue();
12205 }
12206
12207 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
12208 /// if it's possible.
12209 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
12210                                      SDLoc dl, SelectionDAG &DAG) const {
12211   SDValue Op0 = And.getOperand(0);
12212   SDValue Op1 = And.getOperand(1);
12213   if (Op0.getOpcode() == ISD::TRUNCATE)
12214     Op0 = Op0.getOperand(0);
12215   if (Op1.getOpcode() == ISD::TRUNCATE)
12216     Op1 = Op1.getOperand(0);
12217
12218   SDValue LHS, RHS;
12219   if (Op1.getOpcode() == ISD::SHL)
12220     std::swap(Op0, Op1);
12221   if (Op0.getOpcode() == ISD::SHL) {
12222     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
12223       if (And00C->getZExtValue() == 1) {
12224         // If we looked past a truncate, check that it's only truncating away
12225         // known zeros.
12226         unsigned BitWidth = Op0.getValueSizeInBits();
12227         unsigned AndBitWidth = And.getValueSizeInBits();
12228         if (BitWidth > AndBitWidth) {
12229           APInt Zeros, Ones;
12230           DAG.computeKnownBits(Op0, Zeros, Ones);
12231           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
12232             return SDValue();
12233         }
12234         LHS = Op1;
12235         RHS = Op0.getOperand(1);
12236       }
12237   } else if (Op1.getOpcode() == ISD::Constant) {
12238     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
12239     uint64_t AndRHSVal = AndRHS->getZExtValue();
12240     SDValue AndLHS = Op0;
12241
12242     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
12243       LHS = AndLHS.getOperand(0);
12244       RHS = AndLHS.getOperand(1);
12245     }
12246
12247     // Use BT if the immediate can't be encoded in a TEST instruction.
12248     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
12249       LHS = AndLHS;
12250       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
12251     }
12252   }
12253
12254   if (LHS.getNode()) {
12255     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12256     // instruction.  Since the shift amount is in-range-or-undefined, we know
12257     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12258     // the encoding for the i16 version is larger than the i32 version.
12259     // Also promote i16 to i32 for performance / code size reason.
12260     if (LHS.getValueType() == MVT::i8 ||
12261         LHS.getValueType() == MVT::i16)
12262       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12263
12264     // If the operand types disagree, extend the shift amount to match.  Since
12265     // BT ignores high bits (like shifts) we can use anyextend.
12266     if (LHS.getValueType() != RHS.getValueType())
12267       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12268
12269     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12270     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12271     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12272                        DAG.getConstant(Cond, MVT::i8), BT);
12273   }
12274
12275   return SDValue();
12276 }
12277
12278 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12279 /// mask CMPs.
12280 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12281                               SDValue &Op1) {
12282   unsigned SSECC;
12283   bool Swap = false;
12284
12285   // SSE Condition code mapping:
12286   //  0 - EQ
12287   //  1 - LT
12288   //  2 - LE
12289   //  3 - UNORD
12290   //  4 - NEQ
12291   //  5 - NLT
12292   //  6 - NLE
12293   //  7 - ORD
12294   switch (SetCCOpcode) {
12295   default: llvm_unreachable("Unexpected SETCC condition");
12296   case ISD::SETOEQ:
12297   case ISD::SETEQ:  SSECC = 0; break;
12298   case ISD::SETOGT:
12299   case ISD::SETGT:  Swap = true; // Fallthrough
12300   case ISD::SETLT:
12301   case ISD::SETOLT: SSECC = 1; break;
12302   case ISD::SETOGE:
12303   case ISD::SETGE:  Swap = true; // Fallthrough
12304   case ISD::SETLE:
12305   case ISD::SETOLE: SSECC = 2; break;
12306   case ISD::SETUO:  SSECC = 3; break;
12307   case ISD::SETUNE:
12308   case ISD::SETNE:  SSECC = 4; break;
12309   case ISD::SETULE: Swap = true; // Fallthrough
12310   case ISD::SETUGE: SSECC = 5; break;
12311   case ISD::SETULT: Swap = true; // Fallthrough
12312   case ISD::SETUGT: SSECC = 6; break;
12313   case ISD::SETO:   SSECC = 7; break;
12314   case ISD::SETUEQ:
12315   case ISD::SETONE: SSECC = 8; break;
12316   }
12317   if (Swap)
12318     std::swap(Op0, Op1);
12319
12320   return SSECC;
12321 }
12322
12323 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12324 // ones, and then concatenate the result back.
12325 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12326   MVT VT = Op.getSimpleValueType();
12327
12328   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12329          "Unsupported value type for operation");
12330
12331   unsigned NumElems = VT.getVectorNumElements();
12332   SDLoc dl(Op);
12333   SDValue CC = Op.getOperand(2);
12334
12335   // Extract the LHS vectors
12336   SDValue LHS = Op.getOperand(0);
12337   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12338   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12339
12340   // Extract the RHS vectors
12341   SDValue RHS = Op.getOperand(1);
12342   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12343   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12344
12345   // Issue the operation on the smaller types and concatenate the result back
12346   MVT EltVT = VT.getVectorElementType();
12347   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12348   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12349                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12350                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12351 }
12352
12353 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12354                                      const X86Subtarget *Subtarget) {
12355   SDValue Op0 = Op.getOperand(0);
12356   SDValue Op1 = Op.getOperand(1);
12357   SDValue CC = Op.getOperand(2);
12358   MVT VT = Op.getSimpleValueType();
12359   SDLoc dl(Op);
12360
12361   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12362          Op.getValueType().getScalarType() == MVT::i1 &&
12363          "Cannot set masked compare for this operation");
12364
12365   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12366   unsigned  Opc = 0;
12367   bool Unsigned = false;
12368   bool Swap = false;
12369   unsigned SSECC;
12370   switch (SetCCOpcode) {
12371   default: llvm_unreachable("Unexpected SETCC condition");
12372   case ISD::SETNE:  SSECC = 4; break;
12373   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12374   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12375   case ISD::SETLT:  Swap = true; //fall-through
12376   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12377   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12378   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12379   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12380   case ISD::SETULE: Unsigned = true; //fall-through
12381   case ISD::SETLE:  SSECC = 2; break;
12382   }
12383
12384   if (Swap)
12385     std::swap(Op0, Op1);
12386   if (Opc)
12387     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12388   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12389   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12390                      DAG.getConstant(SSECC, MVT::i8));
12391 }
12392
12393 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12394 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12395 /// return an empty value.
12396 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12397 {
12398   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12399   if (!BV)
12400     return SDValue();
12401
12402   MVT VT = Op1.getSimpleValueType();
12403   MVT EVT = VT.getVectorElementType();
12404   unsigned n = VT.getVectorNumElements();
12405   SmallVector<SDValue, 8> ULTOp1;
12406
12407   for (unsigned i = 0; i < n; ++i) {
12408     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12409     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12410       return SDValue();
12411
12412     // Avoid underflow.
12413     APInt Val = Elt->getAPIntValue();
12414     if (Val == 0)
12415       return SDValue();
12416
12417     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12418   }
12419
12420   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12421 }
12422
12423 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12424                            SelectionDAG &DAG) {
12425   SDValue Op0 = Op.getOperand(0);
12426   SDValue Op1 = Op.getOperand(1);
12427   SDValue CC = Op.getOperand(2);
12428   MVT VT = Op.getSimpleValueType();
12429   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12430   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12431   SDLoc dl(Op);
12432
12433   if (isFP) {
12434 #ifndef NDEBUG
12435     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12436     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12437 #endif
12438
12439     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12440     unsigned Opc = X86ISD::CMPP;
12441     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12442       assert(VT.getVectorNumElements() <= 16);
12443       Opc = X86ISD::CMPM;
12444     }
12445     // In the two special cases we can't handle, emit two comparisons.
12446     if (SSECC == 8) {
12447       unsigned CC0, CC1;
12448       unsigned CombineOpc;
12449       if (SetCCOpcode == ISD::SETUEQ) {
12450         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12451       } else {
12452         assert(SetCCOpcode == ISD::SETONE);
12453         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12454       }
12455
12456       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12457                                  DAG.getConstant(CC0, MVT::i8));
12458       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12459                                  DAG.getConstant(CC1, MVT::i8));
12460       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12461     }
12462     // Handle all other FP comparisons here.
12463     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12464                        DAG.getConstant(SSECC, MVT::i8));
12465   }
12466
12467   // Break 256-bit integer vector compare into smaller ones.
12468   if (VT.is256BitVector() && !Subtarget->hasInt256())
12469     return Lower256IntVSETCC(Op, DAG);
12470
12471   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12472   EVT OpVT = Op1.getValueType();
12473   if (Subtarget->hasAVX512()) {
12474     if (Op1.getValueType().is512BitVector() ||
12475         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12476       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12477
12478     // In AVX-512 architecture setcc returns mask with i1 elements,
12479     // But there is no compare instruction for i8 and i16 elements.
12480     // We are not talking about 512-bit operands in this case, these
12481     // types are illegal.
12482     if (MaskResult &&
12483         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12484          OpVT.getVectorElementType().getSizeInBits() >= 8))
12485       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12486                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12487   }
12488
12489   // We are handling one of the integer comparisons here.  Since SSE only has
12490   // GT and EQ comparisons for integer, swapping operands and multiple
12491   // operations may be required for some comparisons.
12492   unsigned Opc;
12493   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12494   bool Subus = false;
12495
12496   switch (SetCCOpcode) {
12497   default: llvm_unreachable("Unexpected SETCC condition");
12498   case ISD::SETNE:  Invert = true;
12499   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12500   case ISD::SETLT:  Swap = true;
12501   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12502   case ISD::SETGE:  Swap = true;
12503   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12504                     Invert = true; break;
12505   case ISD::SETULT: Swap = true;
12506   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12507                     FlipSigns = true; break;
12508   case ISD::SETUGE: Swap = true;
12509   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12510                     FlipSigns = true; Invert = true; break;
12511   }
12512
12513   // Special case: Use min/max operations for SETULE/SETUGE
12514   MVT VET = VT.getVectorElementType();
12515   bool hasMinMax =
12516        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12517     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12518
12519   if (hasMinMax) {
12520     switch (SetCCOpcode) {
12521     default: break;
12522     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12523     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12524     }
12525
12526     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12527   }
12528
12529   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12530   if (!MinMax && hasSubus) {
12531     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12532     // Op0 u<= Op1:
12533     //   t = psubus Op0, Op1
12534     //   pcmpeq t, <0..0>
12535     switch (SetCCOpcode) {
12536     default: break;
12537     case ISD::SETULT: {
12538       // If the comparison is against a constant we can turn this into a
12539       // setule.  With psubus, setule does not require a swap.  This is
12540       // beneficial because the constant in the register is no longer
12541       // destructed as the destination so it can be hoisted out of a loop.
12542       // Only do this pre-AVX since vpcmp* is no longer destructive.
12543       if (Subtarget->hasAVX())
12544         break;
12545       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12546       if (ULEOp1.getNode()) {
12547         Op1 = ULEOp1;
12548         Subus = true; Invert = false; Swap = false;
12549       }
12550       break;
12551     }
12552     // Psubus is better than flip-sign because it requires no inversion.
12553     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12554     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12555     }
12556
12557     if (Subus) {
12558       Opc = X86ISD::SUBUS;
12559       FlipSigns = false;
12560     }
12561   }
12562
12563   if (Swap)
12564     std::swap(Op0, Op1);
12565
12566   // Check that the operation in question is available (most are plain SSE2,
12567   // but PCMPGTQ and PCMPEQQ have different requirements).
12568   if (VT == MVT::v2i64) {
12569     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12570       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12571
12572       // First cast everything to the right type.
12573       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12574       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12575
12576       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12577       // bits of the inputs before performing those operations. The lower
12578       // compare is always unsigned.
12579       SDValue SB;
12580       if (FlipSigns) {
12581         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12582       } else {
12583         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12584         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12585         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12586                          Sign, Zero, Sign, Zero);
12587       }
12588       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12589       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12590
12591       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12592       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12593       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12594
12595       // Create masks for only the low parts/high parts of the 64 bit integers.
12596       static const int MaskHi[] = { 1, 1, 3, 3 };
12597       static const int MaskLo[] = { 0, 0, 2, 2 };
12598       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12599       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12600       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12601
12602       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12603       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12604
12605       if (Invert)
12606         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12607
12608       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12609     }
12610
12611     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12612       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12613       // pcmpeqd + pshufd + pand.
12614       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12615
12616       // First cast everything to the right type.
12617       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12618       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12619
12620       // Do the compare.
12621       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12622
12623       // Make sure the lower and upper halves are both all-ones.
12624       static const int Mask[] = { 1, 0, 3, 2 };
12625       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12626       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12627
12628       if (Invert)
12629         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12630
12631       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12632     }
12633   }
12634
12635   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12636   // bits of the inputs before performing those operations.
12637   if (FlipSigns) {
12638     EVT EltVT = VT.getVectorElementType();
12639     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12640     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12641     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12642   }
12643
12644   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12645
12646   // If the logical-not of the result is required, perform that now.
12647   if (Invert)
12648     Result = DAG.getNOT(dl, Result, VT);
12649
12650   if (MinMax)
12651     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12652
12653   if (Subus)
12654     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12655                          getZeroVector(VT, Subtarget, DAG, dl));
12656
12657   return Result;
12658 }
12659
12660 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12661
12662   MVT VT = Op.getSimpleValueType();
12663
12664   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12665
12666   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12667          && "SetCC type must be 8-bit or 1-bit integer");
12668   SDValue Op0 = Op.getOperand(0);
12669   SDValue Op1 = Op.getOperand(1);
12670   SDLoc dl(Op);
12671   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12672
12673   // Optimize to BT if possible.
12674   // Lower (X & (1 << N)) == 0 to BT(X, N).
12675   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12676   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12677   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12678       Op1.getOpcode() == ISD::Constant &&
12679       cast<ConstantSDNode>(Op1)->isNullValue() &&
12680       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12681     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12682     if (NewSetCC.getNode())
12683       return NewSetCC;
12684   }
12685
12686   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12687   // these.
12688   if (Op1.getOpcode() == ISD::Constant &&
12689       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12690        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12691       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12692
12693     // If the input is a setcc, then reuse the input setcc or use a new one with
12694     // the inverted condition.
12695     if (Op0.getOpcode() == X86ISD::SETCC) {
12696       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12697       bool Invert = (CC == ISD::SETNE) ^
12698         cast<ConstantSDNode>(Op1)->isNullValue();
12699       if (!Invert)
12700         return Op0;
12701
12702       CCode = X86::GetOppositeBranchCondition(CCode);
12703       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12704                                   DAG.getConstant(CCode, MVT::i8),
12705                                   Op0.getOperand(1));
12706       if (VT == MVT::i1)
12707         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12708       return SetCC;
12709     }
12710   }
12711   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12712       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12713       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12714
12715     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12716     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12717   }
12718
12719   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12720   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12721   if (X86CC == X86::COND_INVALID)
12722     return SDValue();
12723
12724   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12725   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12726   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12727                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12728   if (VT == MVT::i1)
12729     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12730   return SetCC;
12731 }
12732
12733 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12734 static bool isX86LogicalCmp(SDValue Op) {
12735   unsigned Opc = Op.getNode()->getOpcode();
12736   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12737       Opc == X86ISD::SAHF)
12738     return true;
12739   if (Op.getResNo() == 1 &&
12740       (Opc == X86ISD::ADD ||
12741        Opc == X86ISD::SUB ||
12742        Opc == X86ISD::ADC ||
12743        Opc == X86ISD::SBB ||
12744        Opc == X86ISD::SMUL ||
12745        Opc == X86ISD::UMUL ||
12746        Opc == X86ISD::INC ||
12747        Opc == X86ISD::DEC ||
12748        Opc == X86ISD::OR ||
12749        Opc == X86ISD::XOR ||
12750        Opc == X86ISD::AND))
12751     return true;
12752
12753   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12754     return true;
12755
12756   return false;
12757 }
12758
12759 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12760   if (V.getOpcode() != ISD::TRUNCATE)
12761     return false;
12762
12763   SDValue VOp0 = V.getOperand(0);
12764   unsigned InBits = VOp0.getValueSizeInBits();
12765   unsigned Bits = V.getValueSizeInBits();
12766   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12767 }
12768
12769 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12770   bool addTest = true;
12771   SDValue Cond  = Op.getOperand(0);
12772   SDValue Op1 = Op.getOperand(1);
12773   SDValue Op2 = Op.getOperand(2);
12774   SDLoc DL(Op);
12775   EVT VT = Op1.getValueType();
12776   SDValue CC;
12777
12778   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12779   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12780   // sequence later on.
12781   if (Cond.getOpcode() == ISD::SETCC &&
12782       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12783        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12784       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12785     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12786     int SSECC = translateX86FSETCC(
12787         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12788
12789     if (SSECC != 8) {
12790       if (Subtarget->hasAVX512()) {
12791         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12792                                   DAG.getConstant(SSECC, MVT::i8));
12793         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12794       }
12795       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12796                                 DAG.getConstant(SSECC, MVT::i8));
12797       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12798       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12799       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12800     }
12801   }
12802
12803   if (Cond.getOpcode() == ISD::SETCC) {
12804     SDValue NewCond = LowerSETCC(Cond, DAG);
12805     if (NewCond.getNode())
12806       Cond = NewCond;
12807   }
12808
12809   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12810   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12811   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12812   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12813   if (Cond.getOpcode() == X86ISD::SETCC &&
12814       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12815       isZero(Cond.getOperand(1).getOperand(1))) {
12816     SDValue Cmp = Cond.getOperand(1);
12817
12818     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12819
12820     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12821         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12822       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12823
12824       SDValue CmpOp0 = Cmp.getOperand(0);
12825       // Apply further optimizations for special cases
12826       // (select (x != 0), -1, 0) -> neg & sbb
12827       // (select (x == 0), 0, -1) -> neg & sbb
12828       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12829         if (YC->isNullValue() &&
12830             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12831           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12832           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12833                                     DAG.getConstant(0, CmpOp0.getValueType()),
12834                                     CmpOp0);
12835           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12836                                     DAG.getConstant(X86::COND_B, MVT::i8),
12837                                     SDValue(Neg.getNode(), 1));
12838           return Res;
12839         }
12840
12841       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12842                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12843       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12844
12845       SDValue Res =   // Res = 0 or -1.
12846         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12847                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12848
12849       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12850         Res = DAG.getNOT(DL, Res, Res.getValueType());
12851
12852       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12853       if (!N2C || !N2C->isNullValue())
12854         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12855       return Res;
12856     }
12857   }
12858
12859   // Look past (and (setcc_carry (cmp ...)), 1).
12860   if (Cond.getOpcode() == ISD::AND &&
12861       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12862     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12863     if (C && C->getAPIntValue() == 1)
12864       Cond = Cond.getOperand(0);
12865   }
12866
12867   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12868   // setting operand in place of the X86ISD::SETCC.
12869   unsigned CondOpcode = Cond.getOpcode();
12870   if (CondOpcode == X86ISD::SETCC ||
12871       CondOpcode == X86ISD::SETCC_CARRY) {
12872     CC = Cond.getOperand(0);
12873
12874     SDValue Cmp = Cond.getOperand(1);
12875     unsigned Opc = Cmp.getOpcode();
12876     MVT VT = Op.getSimpleValueType();
12877
12878     bool IllegalFPCMov = false;
12879     if (VT.isFloatingPoint() && !VT.isVector() &&
12880         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12881       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12882
12883     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12884         Opc == X86ISD::BT) { // FIXME
12885       Cond = Cmp;
12886       addTest = false;
12887     }
12888   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12889              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12890              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12891               Cond.getOperand(0).getValueType() != MVT::i8)) {
12892     SDValue LHS = Cond.getOperand(0);
12893     SDValue RHS = Cond.getOperand(1);
12894     unsigned X86Opcode;
12895     unsigned X86Cond;
12896     SDVTList VTs;
12897     switch (CondOpcode) {
12898     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12899     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12900     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12901     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12902     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12903     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12904     default: llvm_unreachable("unexpected overflowing operator");
12905     }
12906     if (CondOpcode == ISD::UMULO)
12907       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12908                           MVT::i32);
12909     else
12910       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12911
12912     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12913
12914     if (CondOpcode == ISD::UMULO)
12915       Cond = X86Op.getValue(2);
12916     else
12917       Cond = X86Op.getValue(1);
12918
12919     CC = DAG.getConstant(X86Cond, MVT::i8);
12920     addTest = false;
12921   }
12922
12923   if (addTest) {
12924     // Look pass the truncate if the high bits are known zero.
12925     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12926         Cond = Cond.getOperand(0);
12927
12928     // We know the result of AND is compared against zero. Try to match
12929     // it to BT.
12930     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12931       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12932       if (NewSetCC.getNode()) {
12933         CC = NewSetCC.getOperand(0);
12934         Cond = NewSetCC.getOperand(1);
12935         addTest = false;
12936       }
12937     }
12938   }
12939
12940   if (addTest) {
12941     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12942     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12943   }
12944
12945   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12946   // a <  b ?  0 : -1 -> RES = setcc_carry
12947   // a >= b ? -1 :  0 -> RES = setcc_carry
12948   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12949   if (Cond.getOpcode() == X86ISD::SUB) {
12950     Cond = ConvertCmpIfNecessary(Cond, DAG);
12951     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12952
12953     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12954         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12955       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12956                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12957       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12958         return DAG.getNOT(DL, Res, Res.getValueType());
12959       return Res;
12960     }
12961   }
12962
12963   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12964   // widen the cmov and push the truncate through. This avoids introducing a new
12965   // branch during isel and doesn't add any extensions.
12966   if (Op.getValueType() == MVT::i8 &&
12967       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12968     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12969     if (T1.getValueType() == T2.getValueType() &&
12970         // Blacklist CopyFromReg to avoid partial register stalls.
12971         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12972       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12973       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12974       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12975     }
12976   }
12977
12978   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12979   // condition is true.
12980   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12981   SDValue Ops[] = { Op2, Op1, CC, Cond };
12982   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12983 }
12984
12985 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12986   MVT VT = Op->getSimpleValueType(0);
12987   SDValue In = Op->getOperand(0);
12988   MVT InVT = In.getSimpleValueType();
12989   SDLoc dl(Op);
12990
12991   unsigned int NumElts = VT.getVectorNumElements();
12992   if (NumElts != 8 && NumElts != 16)
12993     return SDValue();
12994
12995   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12996     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12997
12998   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12999   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13000
13001   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
13002   Constant *C = ConstantInt::get(*DAG.getContext(),
13003     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
13004
13005   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
13006   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
13007   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
13008                           MachinePointerInfo::getConstantPool(),
13009                           false, false, false, Alignment);
13010   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
13011   if (VT.is512BitVector())
13012     return Brcst;
13013   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
13014 }
13015
13016 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
13017                                 SelectionDAG &DAG) {
13018   MVT VT = Op->getSimpleValueType(0);
13019   SDValue In = Op->getOperand(0);
13020   MVT InVT = In.getSimpleValueType();
13021   SDLoc dl(Op);
13022
13023   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
13024     return LowerSIGN_EXTEND_AVX512(Op, DAG);
13025
13026   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
13027       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
13028       (VT != MVT::v16i16 || InVT != MVT::v16i8))
13029     return SDValue();
13030
13031   if (Subtarget->hasInt256())
13032     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13033
13034   // Optimize vectors in AVX mode
13035   // Sign extend  v8i16 to v8i32 and
13036   //              v4i32 to v4i64
13037   //
13038   // Divide input vector into two parts
13039   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
13040   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
13041   // concat the vectors to original VT
13042
13043   unsigned NumElems = InVT.getVectorNumElements();
13044   SDValue Undef = DAG.getUNDEF(InVT);
13045
13046   SmallVector<int,8> ShufMask1(NumElems, -1);
13047   for (unsigned i = 0; i != NumElems/2; ++i)
13048     ShufMask1[i] = i;
13049
13050   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
13051
13052   SmallVector<int,8> ShufMask2(NumElems, -1);
13053   for (unsigned i = 0; i != NumElems/2; ++i)
13054     ShufMask2[i] = i + NumElems/2;
13055
13056   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
13057
13058   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
13059                                 VT.getVectorNumElements()/2);
13060
13061   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
13062   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
13063
13064   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
13065 }
13066
13067 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
13068 // may emit an illegal shuffle but the expansion is still better than scalar
13069 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
13070 // we'll emit a shuffle and a arithmetic shift.
13071 // TODO: It is possible to support ZExt by zeroing the undef values during
13072 // the shuffle phase or after the shuffle.
13073 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
13074                                  SelectionDAG &DAG) {
13075   MVT RegVT = Op.getSimpleValueType();
13076   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
13077   assert(RegVT.isInteger() &&
13078          "We only custom lower integer vector sext loads.");
13079
13080   // Nothing useful we can do without SSE2 shuffles.
13081   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
13082
13083   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
13084   SDLoc dl(Ld);
13085   EVT MemVT = Ld->getMemoryVT();
13086   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13087   unsigned RegSz = RegVT.getSizeInBits();
13088
13089   ISD::LoadExtType Ext = Ld->getExtensionType();
13090
13091   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
13092          && "Only anyext and sext are currently implemented.");
13093   assert(MemVT != RegVT && "Cannot extend to the same type");
13094   assert(MemVT.isVector() && "Must load a vector from memory");
13095
13096   unsigned NumElems = RegVT.getVectorNumElements();
13097   unsigned MemSz = MemVT.getSizeInBits();
13098   assert(RegSz > MemSz && "Register size must be greater than the mem size");
13099
13100   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
13101     // The only way in which we have a legal 256-bit vector result but not the
13102     // integer 256-bit operations needed to directly lower a sextload is if we
13103     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
13104     // a 128-bit vector and a normal sign_extend to 256-bits that should get
13105     // correctly legalized. We do this late to allow the canonical form of
13106     // sextload to persist throughout the rest of the DAG combiner -- it wants
13107     // to fold together any extensions it can, and so will fuse a sign_extend
13108     // of an sextload into an sextload targeting a wider value.
13109     SDValue Load;
13110     if (MemSz == 128) {
13111       // Just switch this to a normal load.
13112       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
13113                                        "it must be a legal 128-bit vector "
13114                                        "type!");
13115       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
13116                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
13117                   Ld->isInvariant(), Ld->getAlignment());
13118     } else {
13119       assert(MemSz < 128 &&
13120              "Can't extend a type wider than 128 bits to a 256 bit vector!");
13121       // Do an sext load to a 128-bit vector type. We want to use the same
13122       // number of elements, but elements half as wide. This will end up being
13123       // recursively lowered by this routine, but will succeed as we definitely
13124       // have all the necessary features if we're using AVX1.
13125       EVT HalfEltVT =
13126           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
13127       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
13128       Load =
13129           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
13130                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
13131                          Ld->isNonTemporal(), Ld->isInvariant(),
13132                          Ld->getAlignment());
13133     }
13134
13135     // Replace chain users with the new chain.
13136     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
13137     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
13138
13139     // Finally, do a normal sign-extend to the desired register.
13140     return DAG.getSExtOrTrunc(Load, dl, RegVT);
13141   }
13142
13143   // All sizes must be a power of two.
13144   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
13145          "Non-power-of-two elements are not custom lowered!");
13146
13147   // Attempt to load the original value using scalar loads.
13148   // Find the largest scalar type that divides the total loaded size.
13149   MVT SclrLoadTy = MVT::i8;
13150   for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
13151        tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
13152     MVT Tp = (MVT::SimpleValueType)tp;
13153     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
13154       SclrLoadTy = Tp;
13155     }
13156   }
13157
13158   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
13159   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
13160       (64 <= MemSz))
13161     SclrLoadTy = MVT::f64;
13162
13163   // Calculate the number of scalar loads that we need to perform
13164   // in order to load our vector from memory.
13165   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
13166
13167   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
13168          "Can only lower sext loads with a single scalar load!");
13169
13170   unsigned loadRegZize = RegSz;
13171   if (Ext == ISD::SEXTLOAD && RegSz == 256)
13172     loadRegZize /= 2;
13173
13174   // Represent our vector as a sequence of elements which are the
13175   // largest scalar that we can load.
13176   EVT LoadUnitVecVT = EVT::getVectorVT(
13177       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
13178
13179   // Represent the data using the same element type that is stored in
13180   // memory. In practice, we ''widen'' MemVT.
13181   EVT WideVecVT =
13182       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
13183                        loadRegZize / MemVT.getScalarType().getSizeInBits());
13184
13185   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
13186          "Invalid vector type");
13187
13188   // We can't shuffle using an illegal type.
13189   assert(TLI.isTypeLegal(WideVecVT) &&
13190          "We only lower types that form legal widened vector types");
13191
13192   SmallVector<SDValue, 8> Chains;
13193   SDValue Ptr = Ld->getBasePtr();
13194   SDValue Increment =
13195       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, TLI.getPointerTy());
13196   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
13197
13198   for (unsigned i = 0; i < NumLoads; ++i) {
13199     // Perform a single load.
13200     SDValue ScalarLoad =
13201         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
13202                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
13203                     Ld->getAlignment());
13204     Chains.push_back(ScalarLoad.getValue(1));
13205     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
13206     // another round of DAGCombining.
13207     if (i == 0)
13208       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
13209     else
13210       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
13211                         ScalarLoad, DAG.getIntPtrConstant(i));
13212
13213     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
13214   }
13215
13216   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
13217
13218   // Bitcast the loaded value to a vector of the original element type, in
13219   // the size of the target vector type.
13220   SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
13221   unsigned SizeRatio = RegSz / MemSz;
13222
13223   if (Ext == ISD::SEXTLOAD) {
13224     // If we have SSE4.1 we can directly emit a VSEXT node.
13225     if (Subtarget->hasSSE41()) {
13226       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
13227       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13228       return Sext;
13229     }
13230
13231     // Otherwise we'll shuffle the small elements in the high bits of the
13232     // larger type and perform an arithmetic shift. If the shift is not legal
13233     // it's better to scalarize.
13234     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
13235            "We can't implement an sext load without a arithmetic right shift!");
13236
13237     // Redistribute the loaded elements into the different locations.
13238     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13239     for (unsigned i = 0; i != NumElems; ++i)
13240       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
13241
13242     SDValue Shuff = DAG.getVectorShuffle(
13243         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13244
13245     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13246
13247     // Build the arithmetic shift.
13248     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
13249                    MemVT.getVectorElementType().getSizeInBits();
13250     Shuff =
13251         DAG.getNode(ISD::SRA, dl, RegVT, Shuff, DAG.getConstant(Amt, RegVT));
13252
13253     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13254     return Shuff;
13255   }
13256
13257   // Redistribute the loaded elements into the different locations.
13258   SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
13259   for (unsigned i = 0; i != NumElems; ++i)
13260     ShuffleVec[i * SizeRatio] = i;
13261
13262   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
13263                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
13264
13265   // Bitcast to the requested type.
13266   Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
13267   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
13268   return Shuff;
13269 }
13270
13271 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
13272 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
13273 // from the AND / OR.
13274 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
13275   Opc = Op.getOpcode();
13276   if (Opc != ISD::OR && Opc != ISD::AND)
13277     return false;
13278   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13279           Op.getOperand(0).hasOneUse() &&
13280           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
13281           Op.getOperand(1).hasOneUse());
13282 }
13283
13284 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
13285 // 1 and that the SETCC node has a single use.
13286 static bool isXor1OfSetCC(SDValue Op) {
13287   if (Op.getOpcode() != ISD::XOR)
13288     return false;
13289   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
13290   if (N1C && N1C->getAPIntValue() == 1) {
13291     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
13292       Op.getOperand(0).hasOneUse();
13293   }
13294   return false;
13295 }
13296
13297 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
13298   bool addTest = true;
13299   SDValue Chain = Op.getOperand(0);
13300   SDValue Cond  = Op.getOperand(1);
13301   SDValue Dest  = Op.getOperand(2);
13302   SDLoc dl(Op);
13303   SDValue CC;
13304   bool Inverted = false;
13305
13306   if (Cond.getOpcode() == ISD::SETCC) {
13307     // Check for setcc([su]{add,sub,mul}o == 0).
13308     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
13309         isa<ConstantSDNode>(Cond.getOperand(1)) &&
13310         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
13311         Cond.getOperand(0).getResNo() == 1 &&
13312         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
13313          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
13314          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
13315          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
13316          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
13317          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
13318       Inverted = true;
13319       Cond = Cond.getOperand(0);
13320     } else {
13321       SDValue NewCond = LowerSETCC(Cond, DAG);
13322       if (NewCond.getNode())
13323         Cond = NewCond;
13324     }
13325   }
13326 #if 0
13327   // FIXME: LowerXALUO doesn't handle these!!
13328   else if (Cond.getOpcode() == X86ISD::ADD  ||
13329            Cond.getOpcode() == X86ISD::SUB  ||
13330            Cond.getOpcode() == X86ISD::SMUL ||
13331            Cond.getOpcode() == X86ISD::UMUL)
13332     Cond = LowerXALUO(Cond, DAG);
13333 #endif
13334
13335   // Look pass (and (setcc_carry (cmp ...)), 1).
13336   if (Cond.getOpcode() == ISD::AND &&
13337       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13338     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13339     if (C && C->getAPIntValue() == 1)
13340       Cond = Cond.getOperand(0);
13341   }
13342
13343   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13344   // setting operand in place of the X86ISD::SETCC.
13345   unsigned CondOpcode = Cond.getOpcode();
13346   if (CondOpcode == X86ISD::SETCC ||
13347       CondOpcode == X86ISD::SETCC_CARRY) {
13348     CC = Cond.getOperand(0);
13349
13350     SDValue Cmp = Cond.getOperand(1);
13351     unsigned Opc = Cmp.getOpcode();
13352     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
13353     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
13354       Cond = Cmp;
13355       addTest = false;
13356     } else {
13357       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
13358       default: break;
13359       case X86::COND_O:
13360       case X86::COND_B:
13361         // These can only come from an arithmetic instruction with overflow,
13362         // e.g. SADDO, UADDO.
13363         Cond = Cond.getNode()->getOperand(1);
13364         addTest = false;
13365         break;
13366       }
13367     }
13368   }
13369   CondOpcode = Cond.getOpcode();
13370   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13371       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13372       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13373        Cond.getOperand(0).getValueType() != MVT::i8)) {
13374     SDValue LHS = Cond.getOperand(0);
13375     SDValue RHS = Cond.getOperand(1);
13376     unsigned X86Opcode;
13377     unsigned X86Cond;
13378     SDVTList VTs;
13379     // Keep this in sync with LowerXALUO, otherwise we might create redundant
13380     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
13381     // X86ISD::INC).
13382     switch (CondOpcode) {
13383     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13384     case ISD::SADDO:
13385       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13386         if (C->isOne()) {
13387           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
13388           break;
13389         }
13390       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13391     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13392     case ISD::SSUBO:
13393       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
13394         if (C->isOne()) {
13395           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
13396           break;
13397         }
13398       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13399     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13400     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13401     default: llvm_unreachable("unexpected overflowing operator");
13402     }
13403     if (Inverted)
13404       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
13405     if (CondOpcode == ISD::UMULO)
13406       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13407                           MVT::i32);
13408     else
13409       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13410
13411     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
13412
13413     if (CondOpcode == ISD::UMULO)
13414       Cond = X86Op.getValue(2);
13415     else
13416       Cond = X86Op.getValue(1);
13417
13418     CC = DAG.getConstant(X86Cond, MVT::i8);
13419     addTest = false;
13420   } else {
13421     unsigned CondOpc;
13422     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
13423       SDValue Cmp = Cond.getOperand(0).getOperand(1);
13424       if (CondOpc == ISD::OR) {
13425         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
13426         // two branches instead of an explicit OR instruction with a
13427         // separate test.
13428         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13429             isX86LogicalCmp(Cmp)) {
13430           CC = Cond.getOperand(0).getOperand(0);
13431           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13432                               Chain, Dest, CC, Cmp);
13433           CC = Cond.getOperand(1).getOperand(0);
13434           Cond = Cmp;
13435           addTest = false;
13436         }
13437       } else { // ISD::AND
13438         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
13439         // two branches instead of an explicit AND instruction with a
13440         // separate test. However, we only do this if this block doesn't
13441         // have a fall-through edge, because this requires an explicit
13442         // jmp when the condition is false.
13443         if (Cmp == Cond.getOperand(1).getOperand(1) &&
13444             isX86LogicalCmp(Cmp) &&
13445             Op.getNode()->hasOneUse()) {
13446           X86::CondCode CCode =
13447             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13448           CCode = X86::GetOppositeBranchCondition(CCode);
13449           CC = DAG.getConstant(CCode, MVT::i8);
13450           SDNode *User = *Op.getNode()->use_begin();
13451           // Look for an unconditional branch following this conditional branch.
13452           // We need this because we need to reverse the successors in order
13453           // to implement FCMP_OEQ.
13454           if (User->getOpcode() == ISD::BR) {
13455             SDValue FalseBB = User->getOperand(1);
13456             SDNode *NewBR =
13457               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13458             assert(NewBR == User);
13459             (void)NewBR;
13460             Dest = FalseBB;
13461
13462             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13463                                 Chain, Dest, CC, Cmp);
13464             X86::CondCode CCode =
13465               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13466             CCode = X86::GetOppositeBranchCondition(CCode);
13467             CC = DAG.getConstant(CCode, MVT::i8);
13468             Cond = Cmp;
13469             addTest = false;
13470           }
13471         }
13472       }
13473     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13474       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13475       // It should be transformed during dag combiner except when the condition
13476       // is set by a arithmetics with overflow node.
13477       X86::CondCode CCode =
13478         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13479       CCode = X86::GetOppositeBranchCondition(CCode);
13480       CC = DAG.getConstant(CCode, MVT::i8);
13481       Cond = Cond.getOperand(0).getOperand(1);
13482       addTest = false;
13483     } else if (Cond.getOpcode() == ISD::SETCC &&
13484                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13485       // For FCMP_OEQ, we can emit
13486       // two branches instead of an explicit AND instruction with a
13487       // separate test. However, we only do this if this block doesn't
13488       // have a fall-through edge, because this requires an explicit
13489       // jmp when the condition is false.
13490       if (Op.getNode()->hasOneUse()) {
13491         SDNode *User = *Op.getNode()->use_begin();
13492         // Look for an unconditional branch following this conditional branch.
13493         // We need this because we need to reverse the successors in order
13494         // to implement FCMP_OEQ.
13495         if (User->getOpcode() == ISD::BR) {
13496           SDValue FalseBB = User->getOperand(1);
13497           SDNode *NewBR =
13498             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13499           assert(NewBR == User);
13500           (void)NewBR;
13501           Dest = FalseBB;
13502
13503           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13504                                     Cond.getOperand(0), Cond.getOperand(1));
13505           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13506           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13507           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13508                               Chain, Dest, CC, Cmp);
13509           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13510           Cond = Cmp;
13511           addTest = false;
13512         }
13513       }
13514     } else if (Cond.getOpcode() == ISD::SETCC &&
13515                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13516       // For FCMP_UNE, we can emit
13517       // two branches instead of an explicit AND instruction with a
13518       // separate test. However, we only do this if this block doesn't
13519       // have a fall-through edge, because this requires an explicit
13520       // jmp when the condition is false.
13521       if (Op.getNode()->hasOneUse()) {
13522         SDNode *User = *Op.getNode()->use_begin();
13523         // Look for an unconditional branch following this conditional branch.
13524         // We need this because we need to reverse the successors in order
13525         // to implement FCMP_UNE.
13526         if (User->getOpcode() == ISD::BR) {
13527           SDValue FalseBB = User->getOperand(1);
13528           SDNode *NewBR =
13529             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13530           assert(NewBR == User);
13531           (void)NewBR;
13532
13533           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13534                                     Cond.getOperand(0), Cond.getOperand(1));
13535           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13536           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13537           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13538                               Chain, Dest, CC, Cmp);
13539           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13540           Cond = Cmp;
13541           addTest = false;
13542           Dest = FalseBB;
13543         }
13544       }
13545     }
13546   }
13547
13548   if (addTest) {
13549     // Look pass the truncate if the high bits are known zero.
13550     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13551         Cond = Cond.getOperand(0);
13552
13553     // We know the result of AND is compared against zero. Try to match
13554     // it to BT.
13555     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13556       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13557       if (NewSetCC.getNode()) {
13558         CC = NewSetCC.getOperand(0);
13559         Cond = NewSetCC.getOperand(1);
13560         addTest = false;
13561       }
13562     }
13563   }
13564
13565   if (addTest) {
13566     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13567     CC = DAG.getConstant(X86Cond, MVT::i8);
13568     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13569   }
13570   Cond = ConvertCmpIfNecessary(Cond, DAG);
13571   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13572                      Chain, Dest, CC, Cond);
13573 }
13574
13575 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13576 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13577 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13578 // that the guard pages used by the OS virtual memory manager are allocated in
13579 // correct sequence.
13580 SDValue
13581 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13582                                            SelectionDAG &DAG) const {
13583   MachineFunction &MF = DAG.getMachineFunction();
13584   bool SplitStack = MF.shouldSplitStack();
13585   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13586                SplitStack;
13587   SDLoc dl(Op);
13588
13589   if (!Lower) {
13590     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13591     SDNode* Node = Op.getNode();
13592
13593     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13594     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13595         " not tell us which reg is the stack pointer!");
13596     EVT VT = Node->getValueType(0);
13597     SDValue Tmp1 = SDValue(Node, 0);
13598     SDValue Tmp2 = SDValue(Node, 1);
13599     SDValue Tmp3 = Node->getOperand(2);
13600     SDValue Chain = Tmp1.getOperand(0);
13601
13602     // Chain the dynamic stack allocation so that it doesn't modify the stack
13603     // pointer when other instructions are using the stack.
13604     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13605         SDLoc(Node));
13606
13607     SDValue Size = Tmp2.getOperand(1);
13608     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13609     Chain = SP.getValue(1);
13610     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13611     const TargetFrameLowering &TFI =
13612         *DAG.getTarget().getSubtargetImpl()->getFrameLowering();
13613     unsigned StackAlign = TFI.getStackAlignment();
13614     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13615     if (Align > StackAlign)
13616       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13617           DAG.getConstant(-(uint64_t)Align, VT));
13618     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13619
13620     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13621         DAG.getIntPtrConstant(0, true), SDValue(),
13622         SDLoc(Node));
13623
13624     SDValue Ops[2] = { Tmp1, Tmp2 };
13625     return DAG.getMergeValues(Ops, dl);
13626   }
13627
13628   // Get the inputs.
13629   SDValue Chain = Op.getOperand(0);
13630   SDValue Size  = Op.getOperand(1);
13631   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13632   EVT VT = Op.getNode()->getValueType(0);
13633
13634   bool Is64Bit = Subtarget->is64Bit();
13635   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13636
13637   if (SplitStack) {
13638     MachineRegisterInfo &MRI = MF.getRegInfo();
13639
13640     if (Is64Bit) {
13641       // The 64 bit implementation of segmented stacks needs to clobber both r10
13642       // r11. This makes it impossible to use it along with nested parameters.
13643       const Function *F = MF.getFunction();
13644
13645       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13646            I != E; ++I)
13647         if (I->hasNestAttr())
13648           report_fatal_error("Cannot use segmented stacks with functions that "
13649                              "have nested arguments.");
13650     }
13651
13652     const TargetRegisterClass *AddrRegClass =
13653       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13654     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13655     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13656     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13657                                 DAG.getRegister(Vreg, SPTy));
13658     SDValue Ops1[2] = { Value, Chain };
13659     return DAG.getMergeValues(Ops1, dl);
13660   } else {
13661     SDValue Flag;
13662     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13663
13664     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13665     Flag = Chain.getValue(1);
13666     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13667
13668     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13669
13670     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
13671         DAG.getTarget().getSubtargetImpl()->getRegisterInfo());
13672     unsigned SPReg = RegInfo->getStackRegister();
13673     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13674     Chain = SP.getValue(1);
13675
13676     if (Align) {
13677       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13678                        DAG.getConstant(-(uint64_t)Align, VT));
13679       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13680     }
13681
13682     SDValue Ops1[2] = { SP, Chain };
13683     return DAG.getMergeValues(Ops1, dl);
13684   }
13685 }
13686
13687 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13688   MachineFunction &MF = DAG.getMachineFunction();
13689   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13690
13691   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13692   SDLoc DL(Op);
13693
13694   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13695     // vastart just stores the address of the VarArgsFrameIndex slot into the
13696     // memory location argument.
13697     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13698                                    getPointerTy());
13699     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13700                         MachinePointerInfo(SV), false, false, 0);
13701   }
13702
13703   // __va_list_tag:
13704   //   gp_offset         (0 - 6 * 8)
13705   //   fp_offset         (48 - 48 + 8 * 16)
13706   //   overflow_arg_area (point to parameters coming in memory).
13707   //   reg_save_area
13708   SmallVector<SDValue, 8> MemOps;
13709   SDValue FIN = Op.getOperand(1);
13710   // Store gp_offset
13711   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13712                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13713                                                MVT::i32),
13714                                FIN, MachinePointerInfo(SV), false, false, 0);
13715   MemOps.push_back(Store);
13716
13717   // Store fp_offset
13718   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13719                     FIN, DAG.getIntPtrConstant(4));
13720   Store = DAG.getStore(Op.getOperand(0), DL,
13721                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13722                                        MVT::i32),
13723                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13724   MemOps.push_back(Store);
13725
13726   // Store ptr to overflow_arg_area
13727   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13728                     FIN, DAG.getIntPtrConstant(4));
13729   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13730                                     getPointerTy());
13731   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13732                        MachinePointerInfo(SV, 8),
13733                        false, false, 0);
13734   MemOps.push_back(Store);
13735
13736   // Store ptr to reg_save_area.
13737   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13738                     FIN, DAG.getIntPtrConstant(8));
13739   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13740                                     getPointerTy());
13741   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13742                        MachinePointerInfo(SV, 16), false, false, 0);
13743   MemOps.push_back(Store);
13744   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13745 }
13746
13747 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13748   assert(Subtarget->is64Bit() &&
13749          "LowerVAARG only handles 64-bit va_arg!");
13750   assert((Subtarget->isTargetLinux() ||
13751           Subtarget->isTargetDarwin()) &&
13752           "Unhandled target in LowerVAARG");
13753   assert(Op.getNode()->getNumOperands() == 4);
13754   SDValue Chain = Op.getOperand(0);
13755   SDValue SrcPtr = Op.getOperand(1);
13756   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13757   unsigned Align = Op.getConstantOperandVal(3);
13758   SDLoc dl(Op);
13759
13760   EVT ArgVT = Op.getNode()->getValueType(0);
13761   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13762   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13763   uint8_t ArgMode;
13764
13765   // Decide which area this value should be read from.
13766   // TODO: Implement the AMD64 ABI in its entirety. This simple
13767   // selection mechanism works only for the basic types.
13768   if (ArgVT == MVT::f80) {
13769     llvm_unreachable("va_arg for f80 not yet implemented");
13770   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13771     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13772   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13773     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13774   } else {
13775     llvm_unreachable("Unhandled argument type in LowerVAARG");
13776   }
13777
13778   if (ArgMode == 2) {
13779     // Sanity Check: Make sure using fp_offset makes sense.
13780     assert(!DAG.getTarget().Options.UseSoftFloat &&
13781            !(DAG.getMachineFunction()
13782                 .getFunction()->getAttributes()
13783                 .hasAttribute(AttributeSet::FunctionIndex,
13784                               Attribute::NoImplicitFloat)) &&
13785            Subtarget->hasSSE1());
13786   }
13787
13788   // Insert VAARG_64 node into the DAG
13789   // VAARG_64 returns two values: Variable Argument Address, Chain
13790   SmallVector<SDValue, 11> InstOps;
13791   InstOps.push_back(Chain);
13792   InstOps.push_back(SrcPtr);
13793   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13794   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13795   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13796   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13797   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13798                                           VTs, InstOps, MVT::i64,
13799                                           MachinePointerInfo(SV),
13800                                           /*Align=*/0,
13801                                           /*Volatile=*/false,
13802                                           /*ReadMem=*/true,
13803                                           /*WriteMem=*/true);
13804   Chain = VAARG.getValue(1);
13805
13806   // Load the next argument and return it
13807   return DAG.getLoad(ArgVT, dl,
13808                      Chain,
13809                      VAARG,
13810                      MachinePointerInfo(),
13811                      false, false, false, 0);
13812 }
13813
13814 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13815                            SelectionDAG &DAG) {
13816   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13817   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13818   SDValue Chain = Op.getOperand(0);
13819   SDValue DstPtr = Op.getOperand(1);
13820   SDValue SrcPtr = Op.getOperand(2);
13821   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13822   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13823   SDLoc DL(Op);
13824
13825   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13826                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13827                        false,
13828                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13829 }
13830
13831 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13832 // amount is a constant. Takes immediate version of shift as input.
13833 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13834                                           SDValue SrcOp, uint64_t ShiftAmt,
13835                                           SelectionDAG &DAG) {
13836   MVT ElementType = VT.getVectorElementType();
13837
13838   // Fold this packed shift into its first operand if ShiftAmt is 0.
13839   if (ShiftAmt == 0)
13840     return SrcOp;
13841
13842   // Check for ShiftAmt >= element width
13843   if (ShiftAmt >= ElementType.getSizeInBits()) {
13844     if (Opc == X86ISD::VSRAI)
13845       ShiftAmt = ElementType.getSizeInBits() - 1;
13846     else
13847       return DAG.getConstant(0, VT);
13848   }
13849
13850   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13851          && "Unknown target vector shift-by-constant node");
13852
13853   // Fold this packed vector shift into a build vector if SrcOp is a
13854   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13855   if (VT == SrcOp.getSimpleValueType() &&
13856       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13857     SmallVector<SDValue, 8> Elts;
13858     unsigned NumElts = SrcOp->getNumOperands();
13859     ConstantSDNode *ND;
13860
13861     switch(Opc) {
13862     default: llvm_unreachable(nullptr);
13863     case X86ISD::VSHLI:
13864       for (unsigned i=0; i!=NumElts; ++i) {
13865         SDValue CurrentOp = SrcOp->getOperand(i);
13866         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13867           Elts.push_back(CurrentOp);
13868           continue;
13869         }
13870         ND = cast<ConstantSDNode>(CurrentOp);
13871         const APInt &C = ND->getAPIntValue();
13872         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13873       }
13874       break;
13875     case X86ISD::VSRLI:
13876       for (unsigned i=0; i!=NumElts; ++i) {
13877         SDValue CurrentOp = SrcOp->getOperand(i);
13878         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13879           Elts.push_back(CurrentOp);
13880           continue;
13881         }
13882         ND = cast<ConstantSDNode>(CurrentOp);
13883         const APInt &C = ND->getAPIntValue();
13884         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13885       }
13886       break;
13887     case X86ISD::VSRAI:
13888       for (unsigned i=0; i!=NumElts; ++i) {
13889         SDValue CurrentOp = SrcOp->getOperand(i);
13890         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13891           Elts.push_back(CurrentOp);
13892           continue;
13893         }
13894         ND = cast<ConstantSDNode>(CurrentOp);
13895         const APInt &C = ND->getAPIntValue();
13896         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13897       }
13898       break;
13899     }
13900
13901     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13902   }
13903
13904   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13905 }
13906
13907 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13908 // may or may not be a constant. Takes immediate version of shift as input.
13909 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13910                                    SDValue SrcOp, SDValue ShAmt,
13911                                    SelectionDAG &DAG) {
13912   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13913
13914   // Catch shift-by-constant.
13915   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13916     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13917                                       CShAmt->getZExtValue(), DAG);
13918
13919   // Change opcode to non-immediate version
13920   switch (Opc) {
13921     default: llvm_unreachable("Unknown target vector shift node");
13922     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13923     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13924     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13925   }
13926
13927   // Need to build a vector containing shift amount
13928   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13929   SDValue ShOps[4];
13930   ShOps[0] = ShAmt;
13931   ShOps[1] = DAG.getConstant(0, MVT::i32);
13932   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13933   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13934
13935   // The return type has to be a 128-bit type with the same element
13936   // type as the input type.
13937   MVT EltVT = VT.getVectorElementType();
13938   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13939
13940   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13941   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13942 }
13943
13944 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13945   SDLoc dl(Op);
13946   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13947   switch (IntNo) {
13948   default: return SDValue();    // Don't custom lower most intrinsics.
13949   // Comparison intrinsics.
13950   case Intrinsic::x86_sse_comieq_ss:
13951   case Intrinsic::x86_sse_comilt_ss:
13952   case Intrinsic::x86_sse_comile_ss:
13953   case Intrinsic::x86_sse_comigt_ss:
13954   case Intrinsic::x86_sse_comige_ss:
13955   case Intrinsic::x86_sse_comineq_ss:
13956   case Intrinsic::x86_sse_ucomieq_ss:
13957   case Intrinsic::x86_sse_ucomilt_ss:
13958   case Intrinsic::x86_sse_ucomile_ss:
13959   case Intrinsic::x86_sse_ucomigt_ss:
13960   case Intrinsic::x86_sse_ucomige_ss:
13961   case Intrinsic::x86_sse_ucomineq_ss:
13962   case Intrinsic::x86_sse2_comieq_sd:
13963   case Intrinsic::x86_sse2_comilt_sd:
13964   case Intrinsic::x86_sse2_comile_sd:
13965   case Intrinsic::x86_sse2_comigt_sd:
13966   case Intrinsic::x86_sse2_comige_sd:
13967   case Intrinsic::x86_sse2_comineq_sd:
13968   case Intrinsic::x86_sse2_ucomieq_sd:
13969   case Intrinsic::x86_sse2_ucomilt_sd:
13970   case Intrinsic::x86_sse2_ucomile_sd:
13971   case Intrinsic::x86_sse2_ucomigt_sd:
13972   case Intrinsic::x86_sse2_ucomige_sd:
13973   case Intrinsic::x86_sse2_ucomineq_sd: {
13974     unsigned Opc;
13975     ISD::CondCode CC;
13976     switch (IntNo) {
13977     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13978     case Intrinsic::x86_sse_comieq_ss:
13979     case Intrinsic::x86_sse2_comieq_sd:
13980       Opc = X86ISD::COMI;
13981       CC = ISD::SETEQ;
13982       break;
13983     case Intrinsic::x86_sse_comilt_ss:
13984     case Intrinsic::x86_sse2_comilt_sd:
13985       Opc = X86ISD::COMI;
13986       CC = ISD::SETLT;
13987       break;
13988     case Intrinsic::x86_sse_comile_ss:
13989     case Intrinsic::x86_sse2_comile_sd:
13990       Opc = X86ISD::COMI;
13991       CC = ISD::SETLE;
13992       break;
13993     case Intrinsic::x86_sse_comigt_ss:
13994     case Intrinsic::x86_sse2_comigt_sd:
13995       Opc = X86ISD::COMI;
13996       CC = ISD::SETGT;
13997       break;
13998     case Intrinsic::x86_sse_comige_ss:
13999     case Intrinsic::x86_sse2_comige_sd:
14000       Opc = X86ISD::COMI;
14001       CC = ISD::SETGE;
14002       break;
14003     case Intrinsic::x86_sse_comineq_ss:
14004     case Intrinsic::x86_sse2_comineq_sd:
14005       Opc = X86ISD::COMI;
14006       CC = ISD::SETNE;
14007       break;
14008     case Intrinsic::x86_sse_ucomieq_ss:
14009     case Intrinsic::x86_sse2_ucomieq_sd:
14010       Opc = X86ISD::UCOMI;
14011       CC = ISD::SETEQ;
14012       break;
14013     case Intrinsic::x86_sse_ucomilt_ss:
14014     case Intrinsic::x86_sse2_ucomilt_sd:
14015       Opc = X86ISD::UCOMI;
14016       CC = ISD::SETLT;
14017       break;
14018     case Intrinsic::x86_sse_ucomile_ss:
14019     case Intrinsic::x86_sse2_ucomile_sd:
14020       Opc = X86ISD::UCOMI;
14021       CC = ISD::SETLE;
14022       break;
14023     case Intrinsic::x86_sse_ucomigt_ss:
14024     case Intrinsic::x86_sse2_ucomigt_sd:
14025       Opc = X86ISD::UCOMI;
14026       CC = ISD::SETGT;
14027       break;
14028     case Intrinsic::x86_sse_ucomige_ss:
14029     case Intrinsic::x86_sse2_ucomige_sd:
14030       Opc = X86ISD::UCOMI;
14031       CC = ISD::SETGE;
14032       break;
14033     case Intrinsic::x86_sse_ucomineq_ss:
14034     case Intrinsic::x86_sse2_ucomineq_sd:
14035       Opc = X86ISD::UCOMI;
14036       CC = ISD::SETNE;
14037       break;
14038     }
14039
14040     SDValue LHS = Op.getOperand(1);
14041     SDValue RHS = Op.getOperand(2);
14042     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
14043     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
14044     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
14045     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14046                                 DAG.getConstant(X86CC, MVT::i8), Cond);
14047     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14048   }
14049
14050   // Arithmetic intrinsics.
14051   case Intrinsic::x86_sse2_pmulu_dq:
14052   case Intrinsic::x86_avx2_pmulu_dq:
14053     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
14054                        Op.getOperand(1), Op.getOperand(2));
14055
14056   case Intrinsic::x86_sse41_pmuldq:
14057   case Intrinsic::x86_avx2_pmul_dq:
14058     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
14059                        Op.getOperand(1), Op.getOperand(2));
14060
14061   case Intrinsic::x86_sse2_pmulhu_w:
14062   case Intrinsic::x86_avx2_pmulhu_w:
14063     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
14064                        Op.getOperand(1), Op.getOperand(2));
14065
14066   case Intrinsic::x86_sse2_pmulh_w:
14067   case Intrinsic::x86_avx2_pmulh_w:
14068     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
14069                        Op.getOperand(1), Op.getOperand(2));
14070
14071   // SSE2/AVX2 sub with unsigned saturation intrinsics
14072   case Intrinsic::x86_sse2_psubus_b:
14073   case Intrinsic::x86_sse2_psubus_w:
14074   case Intrinsic::x86_avx2_psubus_b:
14075   case Intrinsic::x86_avx2_psubus_w:
14076     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
14077                        Op.getOperand(1), Op.getOperand(2));
14078
14079   // SSE3/AVX horizontal add/sub intrinsics
14080   case Intrinsic::x86_sse3_hadd_ps:
14081   case Intrinsic::x86_sse3_hadd_pd:
14082   case Intrinsic::x86_avx_hadd_ps_256:
14083   case Intrinsic::x86_avx_hadd_pd_256:
14084   case Intrinsic::x86_sse3_hsub_ps:
14085   case Intrinsic::x86_sse3_hsub_pd:
14086   case Intrinsic::x86_avx_hsub_ps_256:
14087   case Intrinsic::x86_avx_hsub_pd_256:
14088   case Intrinsic::x86_ssse3_phadd_w_128:
14089   case Intrinsic::x86_ssse3_phadd_d_128:
14090   case Intrinsic::x86_avx2_phadd_w:
14091   case Intrinsic::x86_avx2_phadd_d:
14092   case Intrinsic::x86_ssse3_phsub_w_128:
14093   case Intrinsic::x86_ssse3_phsub_d_128:
14094   case Intrinsic::x86_avx2_phsub_w:
14095   case Intrinsic::x86_avx2_phsub_d: {
14096     unsigned Opcode;
14097     switch (IntNo) {
14098     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14099     case Intrinsic::x86_sse3_hadd_ps:
14100     case Intrinsic::x86_sse3_hadd_pd:
14101     case Intrinsic::x86_avx_hadd_ps_256:
14102     case Intrinsic::x86_avx_hadd_pd_256:
14103       Opcode = X86ISD::FHADD;
14104       break;
14105     case Intrinsic::x86_sse3_hsub_ps:
14106     case Intrinsic::x86_sse3_hsub_pd:
14107     case Intrinsic::x86_avx_hsub_ps_256:
14108     case Intrinsic::x86_avx_hsub_pd_256:
14109       Opcode = X86ISD::FHSUB;
14110       break;
14111     case Intrinsic::x86_ssse3_phadd_w_128:
14112     case Intrinsic::x86_ssse3_phadd_d_128:
14113     case Intrinsic::x86_avx2_phadd_w:
14114     case Intrinsic::x86_avx2_phadd_d:
14115       Opcode = X86ISD::HADD;
14116       break;
14117     case Intrinsic::x86_ssse3_phsub_w_128:
14118     case Intrinsic::x86_ssse3_phsub_d_128:
14119     case Intrinsic::x86_avx2_phsub_w:
14120     case Intrinsic::x86_avx2_phsub_d:
14121       Opcode = X86ISD::HSUB;
14122       break;
14123     }
14124     return DAG.getNode(Opcode, dl, Op.getValueType(),
14125                        Op.getOperand(1), Op.getOperand(2));
14126   }
14127
14128   // SSE2/SSE41/AVX2 integer max/min intrinsics.
14129   case Intrinsic::x86_sse2_pmaxu_b:
14130   case Intrinsic::x86_sse41_pmaxuw:
14131   case Intrinsic::x86_sse41_pmaxud:
14132   case Intrinsic::x86_avx2_pmaxu_b:
14133   case Intrinsic::x86_avx2_pmaxu_w:
14134   case Intrinsic::x86_avx2_pmaxu_d:
14135   case Intrinsic::x86_sse2_pminu_b:
14136   case Intrinsic::x86_sse41_pminuw:
14137   case Intrinsic::x86_sse41_pminud:
14138   case Intrinsic::x86_avx2_pminu_b:
14139   case Intrinsic::x86_avx2_pminu_w:
14140   case Intrinsic::x86_avx2_pminu_d:
14141   case Intrinsic::x86_sse41_pmaxsb:
14142   case Intrinsic::x86_sse2_pmaxs_w:
14143   case Intrinsic::x86_sse41_pmaxsd:
14144   case Intrinsic::x86_avx2_pmaxs_b:
14145   case Intrinsic::x86_avx2_pmaxs_w:
14146   case Intrinsic::x86_avx2_pmaxs_d:
14147   case Intrinsic::x86_sse41_pminsb:
14148   case Intrinsic::x86_sse2_pmins_w:
14149   case Intrinsic::x86_sse41_pminsd:
14150   case Intrinsic::x86_avx2_pmins_b:
14151   case Intrinsic::x86_avx2_pmins_w:
14152   case Intrinsic::x86_avx2_pmins_d: {
14153     unsigned Opcode;
14154     switch (IntNo) {
14155     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14156     case Intrinsic::x86_sse2_pmaxu_b:
14157     case Intrinsic::x86_sse41_pmaxuw:
14158     case Intrinsic::x86_sse41_pmaxud:
14159     case Intrinsic::x86_avx2_pmaxu_b:
14160     case Intrinsic::x86_avx2_pmaxu_w:
14161     case Intrinsic::x86_avx2_pmaxu_d:
14162       Opcode = X86ISD::UMAX;
14163       break;
14164     case Intrinsic::x86_sse2_pminu_b:
14165     case Intrinsic::x86_sse41_pminuw:
14166     case Intrinsic::x86_sse41_pminud:
14167     case Intrinsic::x86_avx2_pminu_b:
14168     case Intrinsic::x86_avx2_pminu_w:
14169     case Intrinsic::x86_avx2_pminu_d:
14170       Opcode = X86ISD::UMIN;
14171       break;
14172     case Intrinsic::x86_sse41_pmaxsb:
14173     case Intrinsic::x86_sse2_pmaxs_w:
14174     case Intrinsic::x86_sse41_pmaxsd:
14175     case Intrinsic::x86_avx2_pmaxs_b:
14176     case Intrinsic::x86_avx2_pmaxs_w:
14177     case Intrinsic::x86_avx2_pmaxs_d:
14178       Opcode = X86ISD::SMAX;
14179       break;
14180     case Intrinsic::x86_sse41_pminsb:
14181     case Intrinsic::x86_sse2_pmins_w:
14182     case Intrinsic::x86_sse41_pminsd:
14183     case Intrinsic::x86_avx2_pmins_b:
14184     case Intrinsic::x86_avx2_pmins_w:
14185     case Intrinsic::x86_avx2_pmins_d:
14186       Opcode = X86ISD::SMIN;
14187       break;
14188     }
14189     return DAG.getNode(Opcode, dl, Op.getValueType(),
14190                        Op.getOperand(1), Op.getOperand(2));
14191   }
14192
14193   // SSE/SSE2/AVX floating point max/min intrinsics.
14194   case Intrinsic::x86_sse_max_ps:
14195   case Intrinsic::x86_sse2_max_pd:
14196   case Intrinsic::x86_avx_max_ps_256:
14197   case Intrinsic::x86_avx_max_pd_256:
14198   case Intrinsic::x86_sse_min_ps:
14199   case Intrinsic::x86_sse2_min_pd:
14200   case Intrinsic::x86_avx_min_ps_256:
14201   case Intrinsic::x86_avx_min_pd_256: {
14202     unsigned Opcode;
14203     switch (IntNo) {
14204     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14205     case Intrinsic::x86_sse_max_ps:
14206     case Intrinsic::x86_sse2_max_pd:
14207     case Intrinsic::x86_avx_max_ps_256:
14208     case Intrinsic::x86_avx_max_pd_256:
14209       Opcode = X86ISD::FMAX;
14210       break;
14211     case Intrinsic::x86_sse_min_ps:
14212     case Intrinsic::x86_sse2_min_pd:
14213     case Intrinsic::x86_avx_min_ps_256:
14214     case Intrinsic::x86_avx_min_pd_256:
14215       Opcode = X86ISD::FMIN;
14216       break;
14217     }
14218     return DAG.getNode(Opcode, dl, Op.getValueType(),
14219                        Op.getOperand(1), Op.getOperand(2));
14220   }
14221
14222   // AVX2 variable shift intrinsics
14223   case Intrinsic::x86_avx2_psllv_d:
14224   case Intrinsic::x86_avx2_psllv_q:
14225   case Intrinsic::x86_avx2_psllv_d_256:
14226   case Intrinsic::x86_avx2_psllv_q_256:
14227   case Intrinsic::x86_avx2_psrlv_d:
14228   case Intrinsic::x86_avx2_psrlv_q:
14229   case Intrinsic::x86_avx2_psrlv_d_256:
14230   case Intrinsic::x86_avx2_psrlv_q_256:
14231   case Intrinsic::x86_avx2_psrav_d:
14232   case Intrinsic::x86_avx2_psrav_d_256: {
14233     unsigned Opcode;
14234     switch (IntNo) {
14235     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14236     case Intrinsic::x86_avx2_psllv_d:
14237     case Intrinsic::x86_avx2_psllv_q:
14238     case Intrinsic::x86_avx2_psllv_d_256:
14239     case Intrinsic::x86_avx2_psllv_q_256:
14240       Opcode = ISD::SHL;
14241       break;
14242     case Intrinsic::x86_avx2_psrlv_d:
14243     case Intrinsic::x86_avx2_psrlv_q:
14244     case Intrinsic::x86_avx2_psrlv_d_256:
14245     case Intrinsic::x86_avx2_psrlv_q_256:
14246       Opcode = ISD::SRL;
14247       break;
14248     case Intrinsic::x86_avx2_psrav_d:
14249     case Intrinsic::x86_avx2_psrav_d_256:
14250       Opcode = ISD::SRA;
14251       break;
14252     }
14253     return DAG.getNode(Opcode, dl, Op.getValueType(),
14254                        Op.getOperand(1), Op.getOperand(2));
14255   }
14256
14257   case Intrinsic::x86_sse2_packssdw_128:
14258   case Intrinsic::x86_sse2_packsswb_128:
14259   case Intrinsic::x86_avx2_packssdw:
14260   case Intrinsic::x86_avx2_packsswb:
14261     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
14262                        Op.getOperand(1), Op.getOperand(2));
14263
14264   case Intrinsic::x86_sse2_packuswb_128:
14265   case Intrinsic::x86_sse41_packusdw:
14266   case Intrinsic::x86_avx2_packuswb:
14267   case Intrinsic::x86_avx2_packusdw:
14268     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
14269                        Op.getOperand(1), Op.getOperand(2));
14270
14271   case Intrinsic::x86_ssse3_pshuf_b_128:
14272   case Intrinsic::x86_avx2_pshuf_b:
14273     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
14274                        Op.getOperand(1), Op.getOperand(2));
14275
14276   case Intrinsic::x86_sse2_pshuf_d:
14277     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
14278                        Op.getOperand(1), Op.getOperand(2));
14279
14280   case Intrinsic::x86_sse2_pshufl_w:
14281     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
14282                        Op.getOperand(1), Op.getOperand(2));
14283
14284   case Intrinsic::x86_sse2_pshufh_w:
14285     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
14286                        Op.getOperand(1), Op.getOperand(2));
14287
14288   case Intrinsic::x86_ssse3_psign_b_128:
14289   case Intrinsic::x86_ssse3_psign_w_128:
14290   case Intrinsic::x86_ssse3_psign_d_128:
14291   case Intrinsic::x86_avx2_psign_b:
14292   case Intrinsic::x86_avx2_psign_w:
14293   case Intrinsic::x86_avx2_psign_d:
14294     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
14295                        Op.getOperand(1), Op.getOperand(2));
14296
14297   case Intrinsic::x86_sse41_insertps:
14298     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
14299                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14300
14301   case Intrinsic::x86_avx_vperm2f128_ps_256:
14302   case Intrinsic::x86_avx_vperm2f128_pd_256:
14303   case Intrinsic::x86_avx_vperm2f128_si_256:
14304   case Intrinsic::x86_avx2_vperm2i128:
14305     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
14306                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
14307
14308   case Intrinsic::x86_avx2_permd:
14309   case Intrinsic::x86_avx2_permps:
14310     // Operands intentionally swapped. Mask is last operand to intrinsic,
14311     // but second operand for node/instruction.
14312     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
14313                        Op.getOperand(2), Op.getOperand(1));
14314
14315   case Intrinsic::x86_sse_sqrt_ps:
14316   case Intrinsic::x86_sse2_sqrt_pd:
14317   case Intrinsic::x86_avx_sqrt_ps_256:
14318   case Intrinsic::x86_avx_sqrt_pd_256:
14319     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
14320
14321   // ptest and testp intrinsics. The intrinsic these come from are designed to
14322   // return an integer value, not just an instruction so lower it to the ptest
14323   // or testp pattern and a setcc for the result.
14324   case Intrinsic::x86_sse41_ptestz:
14325   case Intrinsic::x86_sse41_ptestc:
14326   case Intrinsic::x86_sse41_ptestnzc:
14327   case Intrinsic::x86_avx_ptestz_256:
14328   case Intrinsic::x86_avx_ptestc_256:
14329   case Intrinsic::x86_avx_ptestnzc_256:
14330   case Intrinsic::x86_avx_vtestz_ps:
14331   case Intrinsic::x86_avx_vtestc_ps:
14332   case Intrinsic::x86_avx_vtestnzc_ps:
14333   case Intrinsic::x86_avx_vtestz_pd:
14334   case Intrinsic::x86_avx_vtestc_pd:
14335   case Intrinsic::x86_avx_vtestnzc_pd:
14336   case Intrinsic::x86_avx_vtestz_ps_256:
14337   case Intrinsic::x86_avx_vtestc_ps_256:
14338   case Intrinsic::x86_avx_vtestnzc_ps_256:
14339   case Intrinsic::x86_avx_vtestz_pd_256:
14340   case Intrinsic::x86_avx_vtestc_pd_256:
14341   case Intrinsic::x86_avx_vtestnzc_pd_256: {
14342     bool IsTestPacked = false;
14343     unsigned X86CC;
14344     switch (IntNo) {
14345     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
14346     case Intrinsic::x86_avx_vtestz_ps:
14347     case Intrinsic::x86_avx_vtestz_pd:
14348     case Intrinsic::x86_avx_vtestz_ps_256:
14349     case Intrinsic::x86_avx_vtestz_pd_256:
14350       IsTestPacked = true; // Fallthrough
14351     case Intrinsic::x86_sse41_ptestz:
14352     case Intrinsic::x86_avx_ptestz_256:
14353       // ZF = 1
14354       X86CC = X86::COND_E;
14355       break;
14356     case Intrinsic::x86_avx_vtestc_ps:
14357     case Intrinsic::x86_avx_vtestc_pd:
14358     case Intrinsic::x86_avx_vtestc_ps_256:
14359     case Intrinsic::x86_avx_vtestc_pd_256:
14360       IsTestPacked = true; // Fallthrough
14361     case Intrinsic::x86_sse41_ptestc:
14362     case Intrinsic::x86_avx_ptestc_256:
14363       // CF = 1
14364       X86CC = X86::COND_B;
14365       break;
14366     case Intrinsic::x86_avx_vtestnzc_ps:
14367     case Intrinsic::x86_avx_vtestnzc_pd:
14368     case Intrinsic::x86_avx_vtestnzc_ps_256:
14369     case Intrinsic::x86_avx_vtestnzc_pd_256:
14370       IsTestPacked = true; // Fallthrough
14371     case Intrinsic::x86_sse41_ptestnzc:
14372     case Intrinsic::x86_avx_ptestnzc_256:
14373       // ZF and CF = 0
14374       X86CC = X86::COND_A;
14375       break;
14376     }
14377
14378     SDValue LHS = Op.getOperand(1);
14379     SDValue RHS = Op.getOperand(2);
14380     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
14381     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
14382     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14383     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
14384     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14385   }
14386   case Intrinsic::x86_avx512_kortestz_w:
14387   case Intrinsic::x86_avx512_kortestc_w: {
14388     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
14389     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
14390     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
14391     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
14392     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
14393     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
14394     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14395   }
14396
14397   // SSE/AVX shift intrinsics
14398   case Intrinsic::x86_sse2_psll_w:
14399   case Intrinsic::x86_sse2_psll_d:
14400   case Intrinsic::x86_sse2_psll_q:
14401   case Intrinsic::x86_avx2_psll_w:
14402   case Intrinsic::x86_avx2_psll_d:
14403   case Intrinsic::x86_avx2_psll_q:
14404   case Intrinsic::x86_sse2_psrl_w:
14405   case Intrinsic::x86_sse2_psrl_d:
14406   case Intrinsic::x86_sse2_psrl_q:
14407   case Intrinsic::x86_avx2_psrl_w:
14408   case Intrinsic::x86_avx2_psrl_d:
14409   case Intrinsic::x86_avx2_psrl_q:
14410   case Intrinsic::x86_sse2_psra_w:
14411   case Intrinsic::x86_sse2_psra_d:
14412   case Intrinsic::x86_avx2_psra_w:
14413   case Intrinsic::x86_avx2_psra_d: {
14414     unsigned Opcode;
14415     switch (IntNo) {
14416     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14417     case Intrinsic::x86_sse2_psll_w:
14418     case Intrinsic::x86_sse2_psll_d:
14419     case Intrinsic::x86_sse2_psll_q:
14420     case Intrinsic::x86_avx2_psll_w:
14421     case Intrinsic::x86_avx2_psll_d:
14422     case Intrinsic::x86_avx2_psll_q:
14423       Opcode = X86ISD::VSHL;
14424       break;
14425     case Intrinsic::x86_sse2_psrl_w:
14426     case Intrinsic::x86_sse2_psrl_d:
14427     case Intrinsic::x86_sse2_psrl_q:
14428     case Intrinsic::x86_avx2_psrl_w:
14429     case Intrinsic::x86_avx2_psrl_d:
14430     case Intrinsic::x86_avx2_psrl_q:
14431       Opcode = X86ISD::VSRL;
14432       break;
14433     case Intrinsic::x86_sse2_psra_w:
14434     case Intrinsic::x86_sse2_psra_d:
14435     case Intrinsic::x86_avx2_psra_w:
14436     case Intrinsic::x86_avx2_psra_d:
14437       Opcode = X86ISD::VSRA;
14438       break;
14439     }
14440     return DAG.getNode(Opcode, dl, Op.getValueType(),
14441                        Op.getOperand(1), Op.getOperand(2));
14442   }
14443
14444   // SSE/AVX immediate shift intrinsics
14445   case Intrinsic::x86_sse2_pslli_w:
14446   case Intrinsic::x86_sse2_pslli_d:
14447   case Intrinsic::x86_sse2_pslli_q:
14448   case Intrinsic::x86_avx2_pslli_w:
14449   case Intrinsic::x86_avx2_pslli_d:
14450   case Intrinsic::x86_avx2_pslli_q:
14451   case Intrinsic::x86_sse2_psrli_w:
14452   case Intrinsic::x86_sse2_psrli_d:
14453   case Intrinsic::x86_sse2_psrli_q:
14454   case Intrinsic::x86_avx2_psrli_w:
14455   case Intrinsic::x86_avx2_psrli_d:
14456   case Intrinsic::x86_avx2_psrli_q:
14457   case Intrinsic::x86_sse2_psrai_w:
14458   case Intrinsic::x86_sse2_psrai_d:
14459   case Intrinsic::x86_avx2_psrai_w:
14460   case Intrinsic::x86_avx2_psrai_d: {
14461     unsigned Opcode;
14462     switch (IntNo) {
14463     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14464     case Intrinsic::x86_sse2_pslli_w:
14465     case Intrinsic::x86_sse2_pslli_d:
14466     case Intrinsic::x86_sse2_pslli_q:
14467     case Intrinsic::x86_avx2_pslli_w:
14468     case Intrinsic::x86_avx2_pslli_d:
14469     case Intrinsic::x86_avx2_pslli_q:
14470       Opcode = X86ISD::VSHLI;
14471       break;
14472     case Intrinsic::x86_sse2_psrli_w:
14473     case Intrinsic::x86_sse2_psrli_d:
14474     case Intrinsic::x86_sse2_psrli_q:
14475     case Intrinsic::x86_avx2_psrli_w:
14476     case Intrinsic::x86_avx2_psrli_d:
14477     case Intrinsic::x86_avx2_psrli_q:
14478       Opcode = X86ISD::VSRLI;
14479       break;
14480     case Intrinsic::x86_sse2_psrai_w:
14481     case Intrinsic::x86_sse2_psrai_d:
14482     case Intrinsic::x86_avx2_psrai_w:
14483     case Intrinsic::x86_avx2_psrai_d:
14484       Opcode = X86ISD::VSRAI;
14485       break;
14486     }
14487     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14488                                Op.getOperand(1), Op.getOperand(2), DAG);
14489   }
14490
14491   case Intrinsic::x86_sse42_pcmpistria128:
14492   case Intrinsic::x86_sse42_pcmpestria128:
14493   case Intrinsic::x86_sse42_pcmpistric128:
14494   case Intrinsic::x86_sse42_pcmpestric128:
14495   case Intrinsic::x86_sse42_pcmpistrio128:
14496   case Intrinsic::x86_sse42_pcmpestrio128:
14497   case Intrinsic::x86_sse42_pcmpistris128:
14498   case Intrinsic::x86_sse42_pcmpestris128:
14499   case Intrinsic::x86_sse42_pcmpistriz128:
14500   case Intrinsic::x86_sse42_pcmpestriz128: {
14501     unsigned Opcode;
14502     unsigned X86CC;
14503     switch (IntNo) {
14504     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14505     case Intrinsic::x86_sse42_pcmpistria128:
14506       Opcode = X86ISD::PCMPISTRI;
14507       X86CC = X86::COND_A;
14508       break;
14509     case Intrinsic::x86_sse42_pcmpestria128:
14510       Opcode = X86ISD::PCMPESTRI;
14511       X86CC = X86::COND_A;
14512       break;
14513     case Intrinsic::x86_sse42_pcmpistric128:
14514       Opcode = X86ISD::PCMPISTRI;
14515       X86CC = X86::COND_B;
14516       break;
14517     case Intrinsic::x86_sse42_pcmpestric128:
14518       Opcode = X86ISD::PCMPESTRI;
14519       X86CC = X86::COND_B;
14520       break;
14521     case Intrinsic::x86_sse42_pcmpistrio128:
14522       Opcode = X86ISD::PCMPISTRI;
14523       X86CC = X86::COND_O;
14524       break;
14525     case Intrinsic::x86_sse42_pcmpestrio128:
14526       Opcode = X86ISD::PCMPESTRI;
14527       X86CC = X86::COND_O;
14528       break;
14529     case Intrinsic::x86_sse42_pcmpistris128:
14530       Opcode = X86ISD::PCMPISTRI;
14531       X86CC = X86::COND_S;
14532       break;
14533     case Intrinsic::x86_sse42_pcmpestris128:
14534       Opcode = X86ISD::PCMPESTRI;
14535       X86CC = X86::COND_S;
14536       break;
14537     case Intrinsic::x86_sse42_pcmpistriz128:
14538       Opcode = X86ISD::PCMPISTRI;
14539       X86CC = X86::COND_E;
14540       break;
14541     case Intrinsic::x86_sse42_pcmpestriz128:
14542       Opcode = X86ISD::PCMPESTRI;
14543       X86CC = X86::COND_E;
14544       break;
14545     }
14546     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14547     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14548     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14549     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14550                                 DAG.getConstant(X86CC, MVT::i8),
14551                                 SDValue(PCMP.getNode(), 1));
14552     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14553   }
14554
14555   case Intrinsic::x86_sse42_pcmpistri128:
14556   case Intrinsic::x86_sse42_pcmpestri128: {
14557     unsigned Opcode;
14558     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14559       Opcode = X86ISD::PCMPISTRI;
14560     else
14561       Opcode = X86ISD::PCMPESTRI;
14562
14563     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14564     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14565     return DAG.getNode(Opcode, dl, VTs, NewOps);
14566   }
14567   case Intrinsic::x86_fma_vfmadd_ps:
14568   case Intrinsic::x86_fma_vfmadd_pd:
14569   case Intrinsic::x86_fma_vfmsub_ps:
14570   case Intrinsic::x86_fma_vfmsub_pd:
14571   case Intrinsic::x86_fma_vfnmadd_ps:
14572   case Intrinsic::x86_fma_vfnmadd_pd:
14573   case Intrinsic::x86_fma_vfnmsub_ps:
14574   case Intrinsic::x86_fma_vfnmsub_pd:
14575   case Intrinsic::x86_fma_vfmaddsub_ps:
14576   case Intrinsic::x86_fma_vfmaddsub_pd:
14577   case Intrinsic::x86_fma_vfmsubadd_ps:
14578   case Intrinsic::x86_fma_vfmsubadd_pd:
14579   case Intrinsic::x86_fma_vfmadd_ps_256:
14580   case Intrinsic::x86_fma_vfmadd_pd_256:
14581   case Intrinsic::x86_fma_vfmsub_ps_256:
14582   case Intrinsic::x86_fma_vfmsub_pd_256:
14583   case Intrinsic::x86_fma_vfnmadd_ps_256:
14584   case Intrinsic::x86_fma_vfnmadd_pd_256:
14585   case Intrinsic::x86_fma_vfnmsub_ps_256:
14586   case Intrinsic::x86_fma_vfnmsub_pd_256:
14587   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14588   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14589   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14590   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14591   case Intrinsic::x86_fma_vfmadd_ps_512:
14592   case Intrinsic::x86_fma_vfmadd_pd_512:
14593   case Intrinsic::x86_fma_vfmsub_ps_512:
14594   case Intrinsic::x86_fma_vfmsub_pd_512:
14595   case Intrinsic::x86_fma_vfnmadd_ps_512:
14596   case Intrinsic::x86_fma_vfnmadd_pd_512:
14597   case Intrinsic::x86_fma_vfnmsub_ps_512:
14598   case Intrinsic::x86_fma_vfnmsub_pd_512:
14599   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14600   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14601   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14602   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14603     unsigned Opc;
14604     switch (IntNo) {
14605     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14606     case Intrinsic::x86_fma_vfmadd_ps:
14607     case Intrinsic::x86_fma_vfmadd_pd:
14608     case Intrinsic::x86_fma_vfmadd_ps_256:
14609     case Intrinsic::x86_fma_vfmadd_pd_256:
14610     case Intrinsic::x86_fma_vfmadd_ps_512:
14611     case Intrinsic::x86_fma_vfmadd_pd_512:
14612       Opc = X86ISD::FMADD;
14613       break;
14614     case Intrinsic::x86_fma_vfmsub_ps:
14615     case Intrinsic::x86_fma_vfmsub_pd:
14616     case Intrinsic::x86_fma_vfmsub_ps_256:
14617     case Intrinsic::x86_fma_vfmsub_pd_256:
14618     case Intrinsic::x86_fma_vfmsub_ps_512:
14619     case Intrinsic::x86_fma_vfmsub_pd_512:
14620       Opc = X86ISD::FMSUB;
14621       break;
14622     case Intrinsic::x86_fma_vfnmadd_ps:
14623     case Intrinsic::x86_fma_vfnmadd_pd:
14624     case Intrinsic::x86_fma_vfnmadd_ps_256:
14625     case Intrinsic::x86_fma_vfnmadd_pd_256:
14626     case Intrinsic::x86_fma_vfnmadd_ps_512:
14627     case Intrinsic::x86_fma_vfnmadd_pd_512:
14628       Opc = X86ISD::FNMADD;
14629       break;
14630     case Intrinsic::x86_fma_vfnmsub_ps:
14631     case Intrinsic::x86_fma_vfnmsub_pd:
14632     case Intrinsic::x86_fma_vfnmsub_ps_256:
14633     case Intrinsic::x86_fma_vfnmsub_pd_256:
14634     case Intrinsic::x86_fma_vfnmsub_ps_512:
14635     case Intrinsic::x86_fma_vfnmsub_pd_512:
14636       Opc = X86ISD::FNMSUB;
14637       break;
14638     case Intrinsic::x86_fma_vfmaddsub_ps:
14639     case Intrinsic::x86_fma_vfmaddsub_pd:
14640     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14641     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14642     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14643     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14644       Opc = X86ISD::FMADDSUB;
14645       break;
14646     case Intrinsic::x86_fma_vfmsubadd_ps:
14647     case Intrinsic::x86_fma_vfmsubadd_pd:
14648     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14649     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14650     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14651     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14652       Opc = X86ISD::FMSUBADD;
14653       break;
14654     }
14655
14656     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14657                        Op.getOperand(2), Op.getOperand(3));
14658   }
14659   }
14660 }
14661
14662 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14663                               SDValue Src, SDValue Mask, SDValue Base,
14664                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14665                               const X86Subtarget * Subtarget) {
14666   SDLoc dl(Op);
14667   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14668   assert(C && "Invalid scale type");
14669   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14670   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14671                              Index.getSimpleValueType().getVectorNumElements());
14672   SDValue MaskInReg;
14673   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14674   if (MaskC)
14675     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14676   else
14677     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14678   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14679   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14680   SDValue Segment = DAG.getRegister(0, MVT::i32);
14681   if (Src.getOpcode() == ISD::UNDEF)
14682     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14683   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14684   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14685   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14686   return DAG.getMergeValues(RetOps, dl);
14687 }
14688
14689 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14690                                SDValue Src, SDValue Mask, SDValue Base,
14691                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14692   SDLoc dl(Op);
14693   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14694   assert(C && "Invalid scale type");
14695   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14696   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14697   SDValue Segment = DAG.getRegister(0, MVT::i32);
14698   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14699                              Index.getSimpleValueType().getVectorNumElements());
14700   SDValue MaskInReg;
14701   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14702   if (MaskC)
14703     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14704   else
14705     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14706   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14707   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14708   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14709   return SDValue(Res, 1);
14710 }
14711
14712 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14713                                SDValue Mask, SDValue Base, SDValue Index,
14714                                SDValue ScaleOp, SDValue Chain) {
14715   SDLoc dl(Op);
14716   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14717   assert(C && "Invalid scale type");
14718   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14719   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14720   SDValue Segment = DAG.getRegister(0, MVT::i32);
14721   EVT MaskVT =
14722     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14723   SDValue MaskInReg;
14724   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14725   if (MaskC)
14726     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14727   else
14728     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14729   //SDVTList VTs = DAG.getVTList(MVT::Other);
14730   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14731   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14732   return SDValue(Res, 0);
14733 }
14734
14735 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14736 // read performance monitor counters (x86_rdpmc).
14737 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14738                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14739                               SmallVectorImpl<SDValue> &Results) {
14740   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14741   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14742   SDValue LO, HI;
14743
14744   // The ECX register is used to select the index of the performance counter
14745   // to read.
14746   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14747                                    N->getOperand(2));
14748   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14749
14750   // Reads the content of a 64-bit performance counter and returns it in the
14751   // registers EDX:EAX.
14752   if (Subtarget->is64Bit()) {
14753     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14754     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14755                             LO.getValue(2));
14756   } else {
14757     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14758     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14759                             LO.getValue(2));
14760   }
14761   Chain = HI.getValue(1);
14762
14763   if (Subtarget->is64Bit()) {
14764     // The EAX register is loaded with the low-order 32 bits. The EDX register
14765     // is loaded with the supported high-order bits of the counter.
14766     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14767                               DAG.getConstant(32, MVT::i8));
14768     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14769     Results.push_back(Chain);
14770     return;
14771   }
14772
14773   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14774   SDValue Ops[] = { LO, HI };
14775   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14776   Results.push_back(Pair);
14777   Results.push_back(Chain);
14778 }
14779
14780 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14781 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14782 // also used to custom lower READCYCLECOUNTER nodes.
14783 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14784                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14785                               SmallVectorImpl<SDValue> &Results) {
14786   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14787   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14788   SDValue LO, HI;
14789
14790   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14791   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14792   // and the EAX register is loaded with the low-order 32 bits.
14793   if (Subtarget->is64Bit()) {
14794     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14795     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14796                             LO.getValue(2));
14797   } else {
14798     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14799     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14800                             LO.getValue(2));
14801   }
14802   SDValue Chain = HI.getValue(1);
14803
14804   if (Opcode == X86ISD::RDTSCP_DAG) {
14805     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14806
14807     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14808     // the ECX register. Add 'ecx' explicitly to the chain.
14809     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14810                                      HI.getValue(2));
14811     // Explicitly store the content of ECX at the location passed in input
14812     // to the 'rdtscp' intrinsic.
14813     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14814                          MachinePointerInfo(), false, false, 0);
14815   }
14816
14817   if (Subtarget->is64Bit()) {
14818     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14819     // the EAX register is loaded with the low-order 32 bits.
14820     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14821                               DAG.getConstant(32, MVT::i8));
14822     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14823     Results.push_back(Chain);
14824     return;
14825   }
14826
14827   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14828   SDValue Ops[] = { LO, HI };
14829   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14830   Results.push_back(Pair);
14831   Results.push_back(Chain);
14832 }
14833
14834 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14835                                      SelectionDAG &DAG) {
14836   SmallVector<SDValue, 2> Results;
14837   SDLoc DL(Op);
14838   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14839                           Results);
14840   return DAG.getMergeValues(Results, DL);
14841 }
14842
14843 enum IntrinsicType {
14844   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14845 };
14846
14847 struct IntrinsicData {
14848   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14849     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14850   IntrinsicType Type;
14851   unsigned      Opc0;
14852   unsigned      Opc1;
14853 };
14854
14855 std::map < unsigned, IntrinsicData> IntrMap;
14856 static void InitIntinsicsMap() {
14857   static bool Initialized = false;
14858   if (Initialized) 
14859     return;
14860   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14861                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14862   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14863                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14864   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14865                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14866   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14867                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14868   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14869                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14870   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14871                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14872   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14873                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14874   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14875                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14876   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14877                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14878
14879   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14880                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14881   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14882                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14883   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14884                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14885   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14886                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14887   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14888                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14889   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14890                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14891   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14892                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14893   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14894                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14895    
14896   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14897                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14898                                                         X86::VGATHERPF1QPSm)));
14899   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14900                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14901                                                         X86::VGATHERPF1QPDm)));
14902   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14903                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14904                                                         X86::VGATHERPF1DPDm)));
14905   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14906                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14907                                                         X86::VGATHERPF1DPSm)));
14908   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14909                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14910                                                         X86::VSCATTERPF1QPSm)));
14911   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14912                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14913                                                         X86::VSCATTERPF1QPDm)));
14914   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14915                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14916                                                         X86::VSCATTERPF1DPDm)));
14917   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14918                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14919                                                         X86::VSCATTERPF1DPSm)));
14920   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14921                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14922   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14923                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14924   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14925                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14926   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14927                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14928   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14929                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14930   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14931                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14932   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14933                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14934   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14935                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14936   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14937                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14938   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14939                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14940   Initialized = true;
14941 }
14942
14943 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14944                                       SelectionDAG &DAG) {
14945   InitIntinsicsMap();
14946   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14947   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14948   if (itr == IntrMap.end())
14949     return SDValue();
14950
14951   SDLoc dl(Op);
14952   IntrinsicData Intr = itr->second;
14953   switch(Intr.Type) {
14954   case RDSEED:
14955   case RDRAND: {
14956     // Emit the node with the right value type.
14957     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14958     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14959
14960     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14961     // Otherwise return the value from Rand, which is always 0, casted to i32.
14962     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14963                       DAG.getConstant(1, Op->getValueType(1)),
14964                       DAG.getConstant(X86::COND_B, MVT::i32),
14965                       SDValue(Result.getNode(), 1) };
14966     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14967                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14968                                   Ops);
14969
14970     // Return { result, isValid, chain }.
14971     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14972                        SDValue(Result.getNode(), 2));
14973   }
14974   case GATHER: {
14975   //gather(v1, mask, index, base, scale);
14976     SDValue Chain = Op.getOperand(0);
14977     SDValue Src   = Op.getOperand(2);
14978     SDValue Base  = Op.getOperand(3);
14979     SDValue Index = Op.getOperand(4);
14980     SDValue Mask  = Op.getOperand(5);
14981     SDValue Scale = Op.getOperand(6);
14982     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14983                           Subtarget);
14984   }
14985   case SCATTER: {
14986   //scatter(base, mask, index, v1, scale);
14987     SDValue Chain = Op.getOperand(0);
14988     SDValue Base  = Op.getOperand(2);
14989     SDValue Mask  = Op.getOperand(3);
14990     SDValue Index = Op.getOperand(4);
14991     SDValue Src   = Op.getOperand(5);
14992     SDValue Scale = Op.getOperand(6);
14993     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14994   }
14995   case PREFETCH: {
14996     SDValue Hint = Op.getOperand(6);
14997     unsigned HintVal;
14998     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14999         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
15000       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
15001     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
15002     SDValue Chain = Op.getOperand(0);
15003     SDValue Mask  = Op.getOperand(2);
15004     SDValue Index = Op.getOperand(3);
15005     SDValue Base  = Op.getOperand(4);
15006     SDValue Scale = Op.getOperand(5);
15007     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15008   }
15009   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15010   case RDTSC: {
15011     SmallVector<SDValue, 2> Results;
15012     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
15013     return DAG.getMergeValues(Results, dl);
15014   }
15015   // Read Performance Monitoring Counters.
15016   case RDPMC: {
15017     SmallVector<SDValue, 2> Results;
15018     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15019     return DAG.getMergeValues(Results, dl);
15020   }
15021   // XTEST intrinsics.
15022   case XTEST: {
15023     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15024     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
15025     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15026                                 DAG.getConstant(X86::COND_NE, MVT::i8),
15027                                 InTrans);
15028     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15029     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15030                        Ret, SDValue(InTrans.getNode(), 1));
15031   }
15032   }
15033   llvm_unreachable("Unknown Intrinsic Type");
15034 }
15035
15036 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15037                                            SelectionDAG &DAG) const {
15038   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15039   MFI->setReturnAddressIsTaken(true);
15040
15041   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15042     return SDValue();
15043
15044   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15045   SDLoc dl(Op);
15046   EVT PtrVT = getPointerTy();
15047
15048   if (Depth > 0) {
15049     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15050     const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15051         DAG.getTarget().getSubtargetImpl()->getRegisterInfo());
15052     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
15053     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15054                        DAG.getNode(ISD::ADD, dl, PtrVT,
15055                                    FrameAddr, Offset),
15056                        MachinePointerInfo(), false, false, false, 0);
15057   }
15058
15059   // Just load the return address.
15060   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15061   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15062                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15063 }
15064
15065 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15066   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15067   MFI->setFrameAddressIsTaken(true);
15068
15069   EVT VT = Op.getValueType();
15070   SDLoc dl(Op);  // FIXME probably not meaningful
15071   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15072   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15073       DAG.getTarget().getSubtargetImpl()->getRegisterInfo());
15074   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15075   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
15076           (FrameReg == X86::EBP && VT == MVT::i32)) &&
15077          "Invalid Frame Register!");
15078   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
15079   while (Depth--)
15080     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
15081                             MachinePointerInfo(),
15082                             false, false, false, 0);
15083   return FrameAddr;
15084 }
15085
15086 // FIXME? Maybe this could be a TableGen attribute on some registers and
15087 // this table could be generated automatically from RegInfo.
15088 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
15089                                               EVT VT) const {
15090   unsigned Reg = StringSwitch<unsigned>(RegName)
15091                        .Case("esp", X86::ESP)
15092                        .Case("rsp", X86::RSP)
15093                        .Default(0);
15094   if (Reg)
15095     return Reg;
15096   report_fatal_error("Invalid register name global variable");
15097 }
15098
15099 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
15100                                                      SelectionDAG &DAG) const {
15101   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15102       DAG.getTarget().getSubtargetImpl()->getRegisterInfo());
15103   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
15104 }
15105
15106 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
15107   SDValue Chain     = Op.getOperand(0);
15108   SDValue Offset    = Op.getOperand(1);
15109   SDValue Handler   = Op.getOperand(2);
15110   SDLoc dl      (Op);
15111
15112   EVT PtrVT = getPointerTy();
15113   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
15114       DAG.getTarget().getSubtargetImpl()->getRegisterInfo());
15115   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
15116   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
15117           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
15118          "Invalid Frame Register!");
15119   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
15120   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
15121
15122   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
15123                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
15124   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
15125   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
15126                        false, false, 0);
15127   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
15128
15129   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
15130                      DAG.getRegister(StoreAddrReg, PtrVT));
15131 }
15132
15133 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
15134                                                SelectionDAG &DAG) const {
15135   SDLoc DL(Op);
15136   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
15137                      DAG.getVTList(MVT::i32, MVT::Other),
15138                      Op.getOperand(0), Op.getOperand(1));
15139 }
15140
15141 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
15142                                                 SelectionDAG &DAG) const {
15143   SDLoc DL(Op);
15144   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
15145                      Op.getOperand(0), Op.getOperand(1));
15146 }
15147
15148 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
15149   return Op.getOperand(0);
15150 }
15151
15152 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
15153                                                 SelectionDAG &DAG) const {
15154   SDValue Root = Op.getOperand(0);
15155   SDValue Trmp = Op.getOperand(1); // trampoline
15156   SDValue FPtr = Op.getOperand(2); // nested function
15157   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
15158   SDLoc dl (Op);
15159
15160   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15161   const TargetRegisterInfo *TRI =
15162       DAG.getTarget().getSubtargetImpl()->getRegisterInfo();
15163
15164   if (Subtarget->is64Bit()) {
15165     SDValue OutChains[6];
15166
15167     // Large code-model.
15168     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
15169     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
15170
15171     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
15172     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
15173
15174     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
15175
15176     // Load the pointer to the nested function into R11.
15177     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
15178     SDValue Addr = Trmp;
15179     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15180                                 Addr, MachinePointerInfo(TrmpAddr),
15181                                 false, false, 0);
15182
15183     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15184                        DAG.getConstant(2, MVT::i64));
15185     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
15186                                 MachinePointerInfo(TrmpAddr, 2),
15187                                 false, false, 2);
15188
15189     // Load the 'nest' parameter value into R10.
15190     // R10 is specified in X86CallingConv.td
15191     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
15192     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15193                        DAG.getConstant(10, MVT::i64));
15194     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15195                                 Addr, MachinePointerInfo(TrmpAddr, 10),
15196                                 false, false, 0);
15197
15198     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15199                        DAG.getConstant(12, MVT::i64));
15200     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
15201                                 MachinePointerInfo(TrmpAddr, 12),
15202                                 false, false, 2);
15203
15204     // Jump to the nested function.
15205     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
15206     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15207                        DAG.getConstant(20, MVT::i64));
15208     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
15209                                 Addr, MachinePointerInfo(TrmpAddr, 20),
15210                                 false, false, 0);
15211
15212     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
15213     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
15214                        DAG.getConstant(22, MVT::i64));
15215     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
15216                                 MachinePointerInfo(TrmpAddr, 22),
15217                                 false, false, 0);
15218
15219     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15220   } else {
15221     const Function *Func =
15222       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
15223     CallingConv::ID CC = Func->getCallingConv();
15224     unsigned NestReg;
15225
15226     switch (CC) {
15227     default:
15228       llvm_unreachable("Unsupported calling convention");
15229     case CallingConv::C:
15230     case CallingConv::X86_StdCall: {
15231       // Pass 'nest' parameter in ECX.
15232       // Must be kept in sync with X86CallingConv.td
15233       NestReg = X86::ECX;
15234
15235       // Check that ECX wasn't needed by an 'inreg' parameter.
15236       FunctionType *FTy = Func->getFunctionType();
15237       const AttributeSet &Attrs = Func->getAttributes();
15238
15239       if (!Attrs.isEmpty() && !Func->isVarArg()) {
15240         unsigned InRegCount = 0;
15241         unsigned Idx = 1;
15242
15243         for (FunctionType::param_iterator I = FTy->param_begin(),
15244              E = FTy->param_end(); I != E; ++I, ++Idx)
15245           if (Attrs.hasAttribute(Idx, Attribute::InReg))
15246             // FIXME: should only count parameters that are lowered to integers.
15247             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
15248
15249         if (InRegCount > 2) {
15250           report_fatal_error("Nest register in use - reduce number of inreg"
15251                              " parameters!");
15252         }
15253       }
15254       break;
15255     }
15256     case CallingConv::X86_FastCall:
15257     case CallingConv::X86_ThisCall:
15258     case CallingConv::Fast:
15259       // Pass 'nest' parameter in EAX.
15260       // Must be kept in sync with X86CallingConv.td
15261       NestReg = X86::EAX;
15262       break;
15263     }
15264
15265     SDValue OutChains[4];
15266     SDValue Addr, Disp;
15267
15268     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15269                        DAG.getConstant(10, MVT::i32));
15270     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
15271
15272     // This is storing the opcode for MOV32ri.
15273     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
15274     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
15275     OutChains[0] = DAG.getStore(Root, dl,
15276                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
15277                                 Trmp, MachinePointerInfo(TrmpAddr),
15278                                 false, false, 0);
15279
15280     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15281                        DAG.getConstant(1, MVT::i32));
15282     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
15283                                 MachinePointerInfo(TrmpAddr, 1),
15284                                 false, false, 1);
15285
15286     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
15287     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15288                        DAG.getConstant(5, MVT::i32));
15289     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
15290                                 MachinePointerInfo(TrmpAddr, 5),
15291                                 false, false, 1);
15292
15293     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
15294                        DAG.getConstant(6, MVT::i32));
15295     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
15296                                 MachinePointerInfo(TrmpAddr, 6),
15297                                 false, false, 1);
15298
15299     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
15300   }
15301 }
15302
15303 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
15304                                             SelectionDAG &DAG) const {
15305   /*
15306    The rounding mode is in bits 11:10 of FPSR, and has the following
15307    settings:
15308      00 Round to nearest
15309      01 Round to -inf
15310      10 Round to +inf
15311      11 Round to 0
15312
15313   FLT_ROUNDS, on the other hand, expects the following:
15314     -1 Undefined
15315      0 Round to 0
15316      1 Round to nearest
15317      2 Round to +inf
15318      3 Round to -inf
15319
15320   To perform the conversion, we do:
15321     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
15322   */
15323
15324   MachineFunction &MF = DAG.getMachineFunction();
15325   const TargetMachine &TM = MF.getTarget();
15326   const TargetFrameLowering &TFI = *TM.getSubtargetImpl()->getFrameLowering();
15327   unsigned StackAlignment = TFI.getStackAlignment();
15328   MVT VT = Op.getSimpleValueType();
15329   SDLoc DL(Op);
15330
15331   // Save FP Control Word to stack slot
15332   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
15333   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
15334
15335   MachineMemOperand *MMO =
15336    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
15337                            MachineMemOperand::MOStore, 2, 2);
15338
15339   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
15340   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
15341                                           DAG.getVTList(MVT::Other),
15342                                           Ops, MVT::i16, MMO);
15343
15344   // Load FP Control Word from stack slot
15345   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
15346                             MachinePointerInfo(), false, false, false, 0);
15347
15348   // Transform as necessary
15349   SDValue CWD1 =
15350     DAG.getNode(ISD::SRL, DL, MVT::i16,
15351                 DAG.getNode(ISD::AND, DL, MVT::i16,
15352                             CWD, DAG.getConstant(0x800, MVT::i16)),
15353                 DAG.getConstant(11, MVT::i8));
15354   SDValue CWD2 =
15355     DAG.getNode(ISD::SRL, DL, MVT::i16,
15356                 DAG.getNode(ISD::AND, DL, MVT::i16,
15357                             CWD, DAG.getConstant(0x400, MVT::i16)),
15358                 DAG.getConstant(9, MVT::i8));
15359
15360   SDValue RetVal =
15361     DAG.getNode(ISD::AND, DL, MVT::i16,
15362                 DAG.getNode(ISD::ADD, DL, MVT::i16,
15363                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
15364                             DAG.getConstant(1, MVT::i16)),
15365                 DAG.getConstant(3, MVT::i16));
15366
15367   return DAG.getNode((VT.getSizeInBits() < 16 ?
15368                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
15369 }
15370
15371 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
15372   MVT VT = Op.getSimpleValueType();
15373   EVT OpVT = VT;
15374   unsigned NumBits = VT.getSizeInBits();
15375   SDLoc dl(Op);
15376
15377   Op = Op.getOperand(0);
15378   if (VT == MVT::i8) {
15379     // Zero extend to i32 since there is not an i8 bsr.
15380     OpVT = MVT::i32;
15381     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15382   }
15383
15384   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
15385   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15386   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15387
15388   // If src is zero (i.e. bsr sets ZF), returns NumBits.
15389   SDValue Ops[] = {
15390     Op,
15391     DAG.getConstant(NumBits+NumBits-1, OpVT),
15392     DAG.getConstant(X86::COND_E, MVT::i8),
15393     Op.getValue(1)
15394   };
15395   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
15396
15397   // Finally xor with NumBits-1.
15398   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15399
15400   if (VT == MVT::i8)
15401     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15402   return Op;
15403 }
15404
15405 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
15406   MVT VT = Op.getSimpleValueType();
15407   EVT OpVT = VT;
15408   unsigned NumBits = VT.getSizeInBits();
15409   SDLoc dl(Op);
15410
15411   Op = Op.getOperand(0);
15412   if (VT == MVT::i8) {
15413     // Zero extend to i32 since there is not an i8 bsr.
15414     OpVT = MVT::i32;
15415     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
15416   }
15417
15418   // Issue a bsr (scan bits in reverse).
15419   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
15420   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
15421
15422   // And xor with NumBits-1.
15423   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
15424
15425   if (VT == MVT::i8)
15426     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
15427   return Op;
15428 }
15429
15430 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
15431   MVT VT = Op.getSimpleValueType();
15432   unsigned NumBits = VT.getSizeInBits();
15433   SDLoc dl(Op);
15434   Op = Op.getOperand(0);
15435
15436   // Issue a bsf (scan bits forward) which also sets EFLAGS.
15437   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
15438   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
15439
15440   // If src is zero (i.e. bsf sets ZF), returns NumBits.
15441   SDValue Ops[] = {
15442     Op,
15443     DAG.getConstant(NumBits, VT),
15444     DAG.getConstant(X86::COND_E, MVT::i8),
15445     Op.getValue(1)
15446   };
15447   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
15448 }
15449
15450 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
15451 // ones, and then concatenate the result back.
15452 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
15453   MVT VT = Op.getSimpleValueType();
15454
15455   assert(VT.is256BitVector() && VT.isInteger() &&
15456          "Unsupported value type for operation");
15457
15458   unsigned NumElems = VT.getVectorNumElements();
15459   SDLoc dl(Op);
15460
15461   // Extract the LHS vectors
15462   SDValue LHS = Op.getOperand(0);
15463   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15464   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15465
15466   // Extract the RHS vectors
15467   SDValue RHS = Op.getOperand(1);
15468   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15469   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15470
15471   MVT EltVT = VT.getVectorElementType();
15472   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15473
15474   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15475                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15476                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15477 }
15478
15479 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15480   assert(Op.getSimpleValueType().is256BitVector() &&
15481          Op.getSimpleValueType().isInteger() &&
15482          "Only handle AVX 256-bit vector integer operation");
15483   return Lower256IntArith(Op, DAG);
15484 }
15485
15486 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15487   assert(Op.getSimpleValueType().is256BitVector() &&
15488          Op.getSimpleValueType().isInteger() &&
15489          "Only handle AVX 256-bit vector integer operation");
15490   return Lower256IntArith(Op, DAG);
15491 }
15492
15493 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15494                         SelectionDAG &DAG) {
15495   SDLoc dl(Op);
15496   MVT VT = Op.getSimpleValueType();
15497
15498   // Decompose 256-bit ops into smaller 128-bit ops.
15499   if (VT.is256BitVector() && !Subtarget->hasInt256())
15500     return Lower256IntArith(Op, DAG);
15501
15502   SDValue A = Op.getOperand(0);
15503   SDValue B = Op.getOperand(1);
15504
15505   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15506   if (VT == MVT::v4i32) {
15507     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15508            "Should not custom lower when pmuldq is available!");
15509
15510     // Extract the odd parts.
15511     static const int UnpackMask[] = { 1, -1, 3, -1 };
15512     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15513     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15514
15515     // Multiply the even parts.
15516     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15517     // Now multiply odd parts.
15518     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15519
15520     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15521     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15522
15523     // Merge the two vectors back together with a shuffle. This expands into 2
15524     // shuffles.
15525     static const int ShufMask[] = { 0, 4, 2, 6 };
15526     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15527   }
15528
15529   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15530          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15531
15532   //  Ahi = psrlqi(a, 32);
15533   //  Bhi = psrlqi(b, 32);
15534   //
15535   //  AloBlo = pmuludq(a, b);
15536   //  AloBhi = pmuludq(a, Bhi);
15537   //  AhiBlo = pmuludq(Ahi, b);
15538
15539   //  AloBhi = psllqi(AloBhi, 32);
15540   //  AhiBlo = psllqi(AhiBlo, 32);
15541   //  return AloBlo + AloBhi + AhiBlo;
15542
15543   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15544   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15545
15546   // Bit cast to 32-bit vectors for MULUDQ
15547   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15548                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15549   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15550   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15551   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15552   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15553
15554   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15555   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15556   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15557
15558   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15559   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15560
15561   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15562   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15563 }
15564
15565 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15566   assert(Subtarget->isTargetWin64() && "Unexpected target");
15567   EVT VT = Op.getValueType();
15568   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15569          "Unexpected return type for lowering");
15570
15571   RTLIB::Libcall LC;
15572   bool isSigned;
15573   switch (Op->getOpcode()) {
15574   default: llvm_unreachable("Unexpected request for libcall!");
15575   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15576   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15577   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15578   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15579   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15580   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15581   }
15582
15583   SDLoc dl(Op);
15584   SDValue InChain = DAG.getEntryNode();
15585
15586   TargetLowering::ArgListTy Args;
15587   TargetLowering::ArgListEntry Entry;
15588   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15589     EVT ArgVT = Op->getOperand(i).getValueType();
15590     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15591            "Unexpected argument type for lowering");
15592     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15593     Entry.Node = StackPtr;
15594     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15595                            false, false, 16);
15596     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15597     Entry.Ty = PointerType::get(ArgTy,0);
15598     Entry.isSExt = false;
15599     Entry.isZExt = false;
15600     Args.push_back(Entry);
15601   }
15602
15603   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15604                                          getPointerTy());
15605
15606   TargetLowering::CallLoweringInfo CLI(DAG);
15607   CLI.setDebugLoc(dl).setChain(InChain)
15608     .setCallee(getLibcallCallingConv(LC),
15609                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15610                Callee, std::move(Args), 0)
15611     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15612
15613   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15614   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15615 }
15616
15617 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15618                              SelectionDAG &DAG) {
15619   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15620   EVT VT = Op0.getValueType();
15621   SDLoc dl(Op);
15622
15623   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15624          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15625
15626   // PMULxD operations multiply each even value (starting at 0) of LHS with
15627   // the related value of RHS and produce a widen result.
15628   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15629   // => <2 x i64> <ae|cg>
15630   //
15631   // In other word, to have all the results, we need to perform two PMULxD:
15632   // 1. one with the even values.
15633   // 2. one with the odd values.
15634   // To achieve #2, with need to place the odd values at an even position.
15635   //
15636   // Place the odd value at an even position (basically, shift all values 1
15637   // step to the left):
15638   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
15639   // <a|b|c|d> => <b|undef|d|undef>
15640   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15641   // <e|f|g|h> => <f|undef|h|undef>
15642   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15643
15644   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15645   // ints.
15646   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15647   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15648   unsigned Opcode =
15649       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15650   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
15651   // => <2 x i64> <ae|cg>
15652   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15653                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15654   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
15655   // => <2 x i64> <bf|dh>
15656   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15657                              DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
15658
15659   // Shuffle it back into the right order.
15660   SDValue Highs, Lows;
15661   if (VT == MVT::v8i32) {
15662     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
15663     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15664     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
15665     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15666   } else {
15667     const int HighMask[] = {1, 5, 3, 7};
15668     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15669     const int LowMask[] = {1, 4, 2, 6};
15670     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15671   }
15672
15673   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15674   // unsigned multiply.
15675   if (IsSigned && !Subtarget->hasSSE41()) {
15676     SDValue ShAmt =
15677         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15678     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15679                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15680     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15681                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15682
15683     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15684     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15685   }
15686
15687   // The first result of MUL_LOHI is actually the low value, followed by the
15688   // high value.
15689   SDValue Ops[] = {Lows, Highs};
15690   return DAG.getMergeValues(Ops, dl);
15691 }
15692
15693 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15694                                          const X86Subtarget *Subtarget) {
15695   MVT VT = Op.getSimpleValueType();
15696   SDLoc dl(Op);
15697   SDValue R = Op.getOperand(0);
15698   SDValue Amt = Op.getOperand(1);
15699
15700   // Optimize shl/srl/sra with constant shift amount.
15701   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
15702     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
15703       uint64_t ShiftAmt = ShiftConst->getZExtValue();
15704
15705       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15706           (Subtarget->hasInt256() &&
15707            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15708           (Subtarget->hasAVX512() &&
15709            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15710         if (Op.getOpcode() == ISD::SHL)
15711           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15712                                             DAG);
15713         if (Op.getOpcode() == ISD::SRL)
15714           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15715                                             DAG);
15716         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15717           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15718                                             DAG);
15719       }
15720
15721       if (VT == MVT::v16i8) {
15722         if (Op.getOpcode() == ISD::SHL) {
15723           // Make a large shift.
15724           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15725                                                    MVT::v8i16, R, ShiftAmt,
15726                                                    DAG);
15727           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15728           // Zero out the rightmost bits.
15729           SmallVector<SDValue, 16> V(16,
15730                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15731                                                      MVT::i8));
15732           return DAG.getNode(ISD::AND, dl, VT, SHL,
15733                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15734         }
15735         if (Op.getOpcode() == ISD::SRL) {
15736           // Make a large shift.
15737           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15738                                                    MVT::v8i16, R, ShiftAmt,
15739                                                    DAG);
15740           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15741           // Zero out the leftmost bits.
15742           SmallVector<SDValue, 16> V(16,
15743                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15744                                                      MVT::i8));
15745           return DAG.getNode(ISD::AND, dl, VT, SRL,
15746                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15747         }
15748         if (Op.getOpcode() == ISD::SRA) {
15749           if (ShiftAmt == 7) {
15750             // R s>> 7  ===  R s< 0
15751             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15752             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15753           }
15754
15755           // R s>> a === ((R u>> a) ^ m) - m
15756           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15757           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15758                                                          MVT::i8));
15759           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15760           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15761           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15762           return Res;
15763         }
15764         llvm_unreachable("Unknown shift opcode.");
15765       }
15766
15767       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15768         if (Op.getOpcode() == ISD::SHL) {
15769           // Make a large shift.
15770           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15771                                                    MVT::v16i16, R, ShiftAmt,
15772                                                    DAG);
15773           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15774           // Zero out the rightmost bits.
15775           SmallVector<SDValue, 32> V(32,
15776                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15777                                                      MVT::i8));
15778           return DAG.getNode(ISD::AND, dl, VT, SHL,
15779                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15780         }
15781         if (Op.getOpcode() == ISD::SRL) {
15782           // Make a large shift.
15783           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15784                                                    MVT::v16i16, R, ShiftAmt,
15785                                                    DAG);
15786           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15787           // Zero out the leftmost bits.
15788           SmallVector<SDValue, 32> V(32,
15789                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15790                                                      MVT::i8));
15791           return DAG.getNode(ISD::AND, dl, VT, SRL,
15792                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15793         }
15794         if (Op.getOpcode() == ISD::SRA) {
15795           if (ShiftAmt == 7) {
15796             // R s>> 7  ===  R s< 0
15797             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15798             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15799           }
15800
15801           // R s>> a === ((R u>> a) ^ m) - m
15802           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15803           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15804                                                          MVT::i8));
15805           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15806           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15807           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15808           return Res;
15809         }
15810         llvm_unreachable("Unknown shift opcode.");
15811       }
15812     }
15813   }
15814
15815   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15816   if (!Subtarget->is64Bit() &&
15817       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15818       Amt.getOpcode() == ISD::BITCAST &&
15819       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15820     Amt = Amt.getOperand(0);
15821     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15822                      VT.getVectorNumElements();
15823     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15824     uint64_t ShiftAmt = 0;
15825     for (unsigned i = 0; i != Ratio; ++i) {
15826       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15827       if (!C)
15828         return SDValue();
15829       // 6 == Log2(64)
15830       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15831     }
15832     // Check remaining shift amounts.
15833     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15834       uint64_t ShAmt = 0;
15835       for (unsigned j = 0; j != Ratio; ++j) {
15836         ConstantSDNode *C =
15837           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15838         if (!C)
15839           return SDValue();
15840         // 6 == Log2(64)
15841         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15842       }
15843       if (ShAmt != ShiftAmt)
15844         return SDValue();
15845     }
15846     switch (Op.getOpcode()) {
15847     default:
15848       llvm_unreachable("Unknown shift opcode!");
15849     case ISD::SHL:
15850       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15851                                         DAG);
15852     case ISD::SRL:
15853       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15854                                         DAG);
15855     case ISD::SRA:
15856       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15857                                         DAG);
15858     }
15859   }
15860
15861   return SDValue();
15862 }
15863
15864 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15865                                         const X86Subtarget* Subtarget) {
15866   MVT VT = Op.getSimpleValueType();
15867   SDLoc dl(Op);
15868   SDValue R = Op.getOperand(0);
15869   SDValue Amt = Op.getOperand(1);
15870
15871   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15872       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15873       (Subtarget->hasInt256() &&
15874        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15875         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15876        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15877     SDValue BaseShAmt;
15878     EVT EltVT = VT.getVectorElementType();
15879
15880     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15881       unsigned NumElts = VT.getVectorNumElements();
15882       unsigned i, j;
15883       for (i = 0; i != NumElts; ++i) {
15884         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15885           continue;
15886         break;
15887       }
15888       for (j = i; j != NumElts; ++j) {
15889         SDValue Arg = Amt.getOperand(j);
15890         if (Arg.getOpcode() == ISD::UNDEF) continue;
15891         if (Arg != Amt.getOperand(i))
15892           break;
15893       }
15894       if (i != NumElts && j == NumElts)
15895         BaseShAmt = Amt.getOperand(i);
15896     } else {
15897       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15898         Amt = Amt.getOperand(0);
15899       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15900                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15901         SDValue InVec = Amt.getOperand(0);
15902         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15903           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15904           unsigned i = 0;
15905           for (; i != NumElts; ++i) {
15906             SDValue Arg = InVec.getOperand(i);
15907             if (Arg.getOpcode() == ISD::UNDEF) continue;
15908             BaseShAmt = Arg;
15909             break;
15910           }
15911         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15912            if (ConstantSDNode *C =
15913                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15914              unsigned SplatIdx =
15915                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15916              if (C->getZExtValue() == SplatIdx)
15917                BaseShAmt = InVec.getOperand(1);
15918            }
15919         }
15920         if (!BaseShAmt.getNode())
15921           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15922                                   DAG.getIntPtrConstant(0));
15923       }
15924     }
15925
15926     if (BaseShAmt.getNode()) {
15927       if (EltVT.bitsGT(MVT::i32))
15928         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15929       else if (EltVT.bitsLT(MVT::i32))
15930         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15931
15932       switch (Op.getOpcode()) {
15933       default:
15934         llvm_unreachable("Unknown shift opcode!");
15935       case ISD::SHL:
15936         switch (VT.SimpleTy) {
15937         default: return SDValue();
15938         case MVT::v2i64:
15939         case MVT::v4i32:
15940         case MVT::v8i16:
15941         case MVT::v4i64:
15942         case MVT::v8i32:
15943         case MVT::v16i16:
15944         case MVT::v16i32:
15945         case MVT::v8i64:
15946           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15947         }
15948       case ISD::SRA:
15949         switch (VT.SimpleTy) {
15950         default: return SDValue();
15951         case MVT::v4i32:
15952         case MVT::v8i16:
15953         case MVT::v8i32:
15954         case MVT::v16i16:
15955         case MVT::v16i32:
15956         case MVT::v8i64:
15957           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15958         }
15959       case ISD::SRL:
15960         switch (VT.SimpleTy) {
15961         default: return SDValue();
15962         case MVT::v2i64:
15963         case MVT::v4i32:
15964         case MVT::v8i16:
15965         case MVT::v4i64:
15966         case MVT::v8i32:
15967         case MVT::v16i16:
15968         case MVT::v16i32:
15969         case MVT::v8i64:
15970           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15971         }
15972       }
15973     }
15974   }
15975
15976   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15977   if (!Subtarget->is64Bit() &&
15978       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15979       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15980       Amt.getOpcode() == ISD::BITCAST &&
15981       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15982     Amt = Amt.getOperand(0);
15983     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15984                      VT.getVectorNumElements();
15985     std::vector<SDValue> Vals(Ratio);
15986     for (unsigned i = 0; i != Ratio; ++i)
15987       Vals[i] = Amt.getOperand(i);
15988     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15989       for (unsigned j = 0; j != Ratio; ++j)
15990         if (Vals[j] != Amt.getOperand(i + j))
15991           return SDValue();
15992     }
15993     switch (Op.getOpcode()) {
15994     default:
15995       llvm_unreachable("Unknown shift opcode!");
15996     case ISD::SHL:
15997       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15998     case ISD::SRL:
15999       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
16000     case ISD::SRA:
16001       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
16002     }
16003   }
16004
16005   return SDValue();
16006 }
16007
16008 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16009                           SelectionDAG &DAG) {
16010   MVT VT = Op.getSimpleValueType();
16011   SDLoc dl(Op);
16012   SDValue R = Op.getOperand(0);
16013   SDValue Amt = Op.getOperand(1);
16014   SDValue V;
16015
16016   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16017   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16018
16019   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
16020   if (V.getNode())
16021     return V;
16022
16023   V = LowerScalarVariableShift(Op, DAG, Subtarget);
16024   if (V.getNode())
16025       return V;
16026
16027   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
16028     return Op;
16029   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
16030   if (Subtarget->hasInt256()) {
16031     if (Op.getOpcode() == ISD::SRL &&
16032         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16033          VT == MVT::v4i64 || VT == MVT::v8i32))
16034       return Op;
16035     if (Op.getOpcode() == ISD::SHL &&
16036         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
16037          VT == MVT::v4i64 || VT == MVT::v8i32))
16038       return Op;
16039     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
16040       return Op;
16041   }
16042
16043   // If possible, lower this packed shift into a vector multiply instead of
16044   // expanding it into a sequence of scalar shifts.
16045   // Do this only if the vector shift count is a constant build_vector.
16046   if (Op.getOpcode() == ISD::SHL && 
16047       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16048        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16049       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16050     SmallVector<SDValue, 8> Elts;
16051     EVT SVT = VT.getScalarType();
16052     unsigned SVTBits = SVT.getSizeInBits();
16053     const APInt &One = APInt(SVTBits, 1);
16054     unsigned NumElems = VT.getVectorNumElements();
16055
16056     for (unsigned i=0; i !=NumElems; ++i) {
16057       SDValue Op = Amt->getOperand(i);
16058       if (Op->getOpcode() == ISD::UNDEF) {
16059         Elts.push_back(Op);
16060         continue;
16061       }
16062
16063       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
16064       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
16065       uint64_t ShAmt = C.getZExtValue();
16066       if (ShAmt >= SVTBits) {
16067         Elts.push_back(DAG.getUNDEF(SVT));
16068         continue;
16069       }
16070       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
16071     }
16072     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
16073     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
16074   }
16075
16076   // Lower SHL with variable shift amount.
16077   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
16078     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
16079
16080     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
16081     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
16082     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
16083     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
16084   }
16085
16086   // If possible, lower this shift as a sequence of two shifts by
16087   // constant plus a MOVSS/MOVSD instead of scalarizing it.
16088   // Example:
16089   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
16090   //
16091   // Could be rewritten as:
16092   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
16093   //
16094   // The advantage is that the two shifts from the example would be
16095   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
16096   // the vector shift into four scalar shifts plus four pairs of vector
16097   // insert/extract.
16098   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
16099       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16100     unsigned TargetOpcode = X86ISD::MOVSS;
16101     bool CanBeSimplified;
16102     // The splat value for the first packed shift (the 'X' from the example).
16103     SDValue Amt1 = Amt->getOperand(0);
16104     // The splat value for the second packed shift (the 'Y' from the example).
16105     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
16106                                         Amt->getOperand(2);
16107
16108     // See if it is possible to replace this node with a sequence of
16109     // two shifts followed by a MOVSS/MOVSD
16110     if (VT == MVT::v4i32) {
16111       // Check if it is legal to use a MOVSS.
16112       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
16113                         Amt2 == Amt->getOperand(3);
16114       if (!CanBeSimplified) {
16115         // Otherwise, check if we can still simplify this node using a MOVSD.
16116         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
16117                           Amt->getOperand(2) == Amt->getOperand(3);
16118         TargetOpcode = X86ISD::MOVSD;
16119         Amt2 = Amt->getOperand(2);
16120       }
16121     } else {
16122       // Do similar checks for the case where the machine value type
16123       // is MVT::v8i16.
16124       CanBeSimplified = Amt1 == Amt->getOperand(1);
16125       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
16126         CanBeSimplified = Amt2 == Amt->getOperand(i);
16127
16128       if (!CanBeSimplified) {
16129         TargetOpcode = X86ISD::MOVSD;
16130         CanBeSimplified = true;
16131         Amt2 = Amt->getOperand(4);
16132         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
16133           CanBeSimplified = Amt1 == Amt->getOperand(i);
16134         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
16135           CanBeSimplified = Amt2 == Amt->getOperand(j);
16136       }
16137     }
16138     
16139     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
16140         isa<ConstantSDNode>(Amt2)) {
16141       // Replace this node with two shifts followed by a MOVSS/MOVSD.
16142       EVT CastVT = MVT::v4i32;
16143       SDValue Splat1 = 
16144         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
16145       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
16146       SDValue Splat2 = 
16147         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
16148       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
16149       if (TargetOpcode == X86ISD::MOVSD)
16150         CastVT = MVT::v2i64;
16151       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
16152       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
16153       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
16154                                             BitCast1, DAG);
16155       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
16156     }
16157   }
16158
16159   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
16160     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
16161
16162     // a = a << 5;
16163     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
16164     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
16165
16166     // Turn 'a' into a mask suitable for VSELECT
16167     SDValue VSelM = DAG.getConstant(0x80, VT);
16168     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16169     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16170
16171     SDValue CM1 = DAG.getConstant(0x0f, VT);
16172     SDValue CM2 = DAG.getConstant(0x3f, VT);
16173
16174     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
16175     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
16176     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
16177     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16178     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16179
16180     // a += a
16181     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16182     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16183     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16184
16185     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
16186     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
16187     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
16188     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
16189     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
16190
16191     // a += a
16192     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
16193     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
16194     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
16195
16196     // return VSELECT(r, r+r, a);
16197     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
16198                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
16199     return R;
16200   }
16201
16202   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
16203   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
16204   // solution better.
16205   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
16206     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
16207     unsigned ExtOpc =
16208         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
16209     R = DAG.getNode(ExtOpc, dl, NewVT, R);
16210     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
16211     return DAG.getNode(ISD::TRUNCATE, dl, VT,
16212                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
16213     }
16214
16215   // Decompose 256-bit shifts into smaller 128-bit shifts.
16216   if (VT.is256BitVector()) {
16217     unsigned NumElems = VT.getVectorNumElements();
16218     MVT EltVT = VT.getVectorElementType();
16219     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16220
16221     // Extract the two vectors
16222     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
16223     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
16224
16225     // Recreate the shift amount vectors
16226     SDValue Amt1, Amt2;
16227     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
16228       // Constant shift amount
16229       SmallVector<SDValue, 4> Amt1Csts;
16230       SmallVector<SDValue, 4> Amt2Csts;
16231       for (unsigned i = 0; i != NumElems/2; ++i)
16232         Amt1Csts.push_back(Amt->getOperand(i));
16233       for (unsigned i = NumElems/2; i != NumElems; ++i)
16234         Amt2Csts.push_back(Amt->getOperand(i));
16235
16236       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
16237       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
16238     } else {
16239       // Variable shift amount
16240       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
16241       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
16242     }
16243
16244     // Issue new vector shifts for the smaller types
16245     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
16246     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
16247
16248     // Concatenate the result back
16249     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
16250   }
16251
16252   return SDValue();
16253 }
16254
16255 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
16256   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
16257   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
16258   // looks for this combo and may remove the "setcc" instruction if the "setcc"
16259   // has only one use.
16260   SDNode *N = Op.getNode();
16261   SDValue LHS = N->getOperand(0);
16262   SDValue RHS = N->getOperand(1);
16263   unsigned BaseOp = 0;
16264   unsigned Cond = 0;
16265   SDLoc DL(Op);
16266   switch (Op.getOpcode()) {
16267   default: llvm_unreachable("Unknown ovf instruction!");
16268   case ISD::SADDO:
16269     // A subtract of one will be selected as a INC. Note that INC doesn't
16270     // set CF, so we can't do this for UADDO.
16271     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16272       if (C->isOne()) {
16273         BaseOp = X86ISD::INC;
16274         Cond = X86::COND_O;
16275         break;
16276       }
16277     BaseOp = X86ISD::ADD;
16278     Cond = X86::COND_O;
16279     break;
16280   case ISD::UADDO:
16281     BaseOp = X86ISD::ADD;
16282     Cond = X86::COND_B;
16283     break;
16284   case ISD::SSUBO:
16285     // A subtract of one will be selected as a DEC. Note that DEC doesn't
16286     // set CF, so we can't do this for USUBO.
16287     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
16288       if (C->isOne()) {
16289         BaseOp = X86ISD::DEC;
16290         Cond = X86::COND_O;
16291         break;
16292       }
16293     BaseOp = X86ISD::SUB;
16294     Cond = X86::COND_O;
16295     break;
16296   case ISD::USUBO:
16297     BaseOp = X86ISD::SUB;
16298     Cond = X86::COND_B;
16299     break;
16300   case ISD::SMULO:
16301     BaseOp = X86ISD::SMUL;
16302     Cond = X86::COND_O;
16303     break;
16304   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
16305     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
16306                                  MVT::i32);
16307     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
16308
16309     SDValue SetCC =
16310       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
16311                   DAG.getConstant(X86::COND_O, MVT::i32),
16312                   SDValue(Sum.getNode(), 2));
16313
16314     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16315   }
16316   }
16317
16318   // Also sets EFLAGS.
16319   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
16320   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
16321
16322   SDValue SetCC =
16323     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
16324                 DAG.getConstant(Cond, MVT::i32),
16325                 SDValue(Sum.getNode(), 1));
16326
16327   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
16328 }
16329
16330 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
16331                                                   SelectionDAG &DAG) const {
16332   SDLoc dl(Op);
16333   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
16334   MVT VT = Op.getSimpleValueType();
16335
16336   if (!Subtarget->hasSSE2() || !VT.isVector())
16337     return SDValue();
16338
16339   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
16340                       ExtraVT.getScalarType().getSizeInBits();
16341
16342   switch (VT.SimpleTy) {
16343     default: return SDValue();
16344     case MVT::v8i32:
16345     case MVT::v16i16:
16346       if (!Subtarget->hasFp256())
16347         return SDValue();
16348       if (!Subtarget->hasInt256()) {
16349         // needs to be split
16350         unsigned NumElems = VT.getVectorNumElements();
16351
16352         // Extract the LHS vectors
16353         SDValue LHS = Op.getOperand(0);
16354         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16355         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16356
16357         MVT EltVT = VT.getVectorElementType();
16358         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16359
16360         EVT ExtraEltVT = ExtraVT.getVectorElementType();
16361         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
16362         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
16363                                    ExtraNumElems/2);
16364         SDValue Extra = DAG.getValueType(ExtraVT);
16365
16366         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
16367         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
16368
16369         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
16370       }
16371       // fall through
16372     case MVT::v4i32:
16373     case MVT::v8i16: {
16374       SDValue Op0 = Op.getOperand(0);
16375       SDValue Op00 = Op0.getOperand(0);
16376       SDValue Tmp1;
16377       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
16378       if (Op0.getOpcode() == ISD::BITCAST &&
16379           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
16380         // (sext (vzext x)) -> (vsext x)
16381         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
16382         if (Tmp1.getNode()) {
16383           EVT ExtraEltVT = ExtraVT.getVectorElementType();
16384           // This folding is only valid when the in-reg type is a vector of i8,
16385           // i16, or i32.
16386           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
16387               ExtraEltVT == MVT::i32) {
16388             SDValue Tmp1Op0 = Tmp1.getOperand(0);
16389             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
16390                    "This optimization is invalid without a VZEXT.");
16391             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
16392           }
16393           Op0 = Tmp1;
16394         }
16395       }
16396
16397       // If the above didn't work, then just use Shift-Left + Shift-Right.
16398       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
16399                                         DAG);
16400       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
16401                                         DAG);
16402     }
16403   }
16404 }
16405
16406 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
16407                                  SelectionDAG &DAG) {
16408   SDLoc dl(Op);
16409   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
16410     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
16411   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
16412     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
16413
16414   // The only fence that needs an instruction is a sequentially-consistent
16415   // cross-thread fence.
16416   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
16417     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
16418     // no-sse2). There isn't any reason to disable it if the target processor
16419     // supports it.
16420     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
16421       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
16422
16423     SDValue Chain = Op.getOperand(0);
16424     SDValue Zero = DAG.getConstant(0, MVT::i32);
16425     SDValue Ops[] = {
16426       DAG.getRegister(X86::ESP, MVT::i32), // Base
16427       DAG.getTargetConstant(1, MVT::i8),   // Scale
16428       DAG.getRegister(0, MVT::i32),        // Index
16429       DAG.getTargetConstant(0, MVT::i32),  // Disp
16430       DAG.getRegister(0, MVT::i32),        // Segment.
16431       Zero,
16432       Chain
16433     };
16434     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
16435     return SDValue(Res, 0);
16436   }
16437
16438   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
16439   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
16440 }
16441
16442 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
16443                              SelectionDAG &DAG) {
16444   MVT T = Op.getSimpleValueType();
16445   SDLoc DL(Op);
16446   unsigned Reg = 0;
16447   unsigned size = 0;
16448   switch(T.SimpleTy) {
16449   default: llvm_unreachable("Invalid value type!");
16450   case MVT::i8:  Reg = X86::AL;  size = 1; break;
16451   case MVT::i16: Reg = X86::AX;  size = 2; break;
16452   case MVT::i32: Reg = X86::EAX; size = 4; break;
16453   case MVT::i64:
16454     assert(Subtarget->is64Bit() && "Node not type legal!");
16455     Reg = X86::RAX; size = 8;
16456     break;
16457   }
16458   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
16459                                   Op.getOperand(2), SDValue());
16460   SDValue Ops[] = { cpIn.getValue(0),
16461                     Op.getOperand(1),
16462                     Op.getOperand(3),
16463                     DAG.getTargetConstant(size, MVT::i8),
16464                     cpIn.getValue(1) };
16465   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16466   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
16467   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
16468                                            Ops, T, MMO);
16469
16470   SDValue cpOut =
16471     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
16472   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
16473                                       MVT::i32, cpOut.getValue(2));
16474   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
16475                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16476
16477   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
16478   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
16479   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
16480   return SDValue();
16481 }
16482
16483 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
16484                             SelectionDAG &DAG) {
16485   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16486   MVT DstVT = Op.getSimpleValueType();
16487
16488   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16489     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16490     if (DstVT != MVT::f64)
16491       // This conversion needs to be expanded.
16492       return SDValue();
16493
16494     SDValue InVec = Op->getOperand(0);
16495     SDLoc dl(Op);
16496     unsigned NumElts = SrcVT.getVectorNumElements();
16497     EVT SVT = SrcVT.getVectorElementType();
16498
16499     // Widen the vector in input in the case of MVT::v2i32.
16500     // Example: from MVT::v2i32 to MVT::v4i32.
16501     SmallVector<SDValue, 16> Elts;
16502     for (unsigned i = 0, e = NumElts; i != e; ++i)
16503       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16504                                  DAG.getIntPtrConstant(i)));
16505
16506     // Explicitly mark the extra elements as Undef.
16507     SDValue Undef = DAG.getUNDEF(SVT);
16508     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16509       Elts.push_back(Undef);
16510
16511     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16512     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16513     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16514     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16515                        DAG.getIntPtrConstant(0));
16516   }
16517
16518   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16519          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16520   assert((DstVT == MVT::i64 ||
16521           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16522          "Unexpected custom BITCAST");
16523   // i64 <=> MMX conversions are Legal.
16524   if (SrcVT==MVT::i64 && DstVT.isVector())
16525     return Op;
16526   if (DstVT==MVT::i64 && SrcVT.isVector())
16527     return Op;
16528   // MMX <=> MMX conversions are Legal.
16529   if (SrcVT.isVector() && DstVT.isVector())
16530     return Op;
16531   // All other conversions need to be expanded.
16532   return SDValue();
16533 }
16534
16535 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16536   SDNode *Node = Op.getNode();
16537   SDLoc dl(Node);
16538   EVT T = Node->getValueType(0);
16539   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16540                               DAG.getConstant(0, T), Node->getOperand(2));
16541   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16542                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16543                        Node->getOperand(0),
16544                        Node->getOperand(1), negOp,
16545                        cast<AtomicSDNode>(Node)->getMemOperand(),
16546                        cast<AtomicSDNode>(Node)->getOrdering(),
16547                        cast<AtomicSDNode>(Node)->getSynchScope());
16548 }
16549
16550 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16551   SDNode *Node = Op.getNode();
16552   SDLoc dl(Node);
16553   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16554
16555   // Convert seq_cst store -> xchg
16556   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16557   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16558   //        (The only way to get a 16-byte store is cmpxchg16b)
16559   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16560   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16561       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16562     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16563                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16564                                  Node->getOperand(0),
16565                                  Node->getOperand(1), Node->getOperand(2),
16566                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16567                                  cast<AtomicSDNode>(Node)->getOrdering(),
16568                                  cast<AtomicSDNode>(Node)->getSynchScope());
16569     return Swap.getValue(1);
16570   }
16571   // Other atomic stores have a simple pattern.
16572   return Op;
16573 }
16574
16575 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16576   EVT VT = Op.getNode()->getSimpleValueType(0);
16577
16578   // Let legalize expand this if it isn't a legal type yet.
16579   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16580     return SDValue();
16581
16582   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16583
16584   unsigned Opc;
16585   bool ExtraOp = false;
16586   switch (Op.getOpcode()) {
16587   default: llvm_unreachable("Invalid code");
16588   case ISD::ADDC: Opc = X86ISD::ADD; break;
16589   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16590   case ISD::SUBC: Opc = X86ISD::SUB; break;
16591   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16592   }
16593
16594   if (!ExtraOp)
16595     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16596                        Op.getOperand(1));
16597   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16598                      Op.getOperand(1), Op.getOperand(2));
16599 }
16600
16601 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16602                             SelectionDAG &DAG) {
16603   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16604
16605   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16606   // which returns the values as { float, float } (in XMM0) or
16607   // { double, double } (which is returned in XMM0, XMM1).
16608   SDLoc dl(Op);
16609   SDValue Arg = Op.getOperand(0);
16610   EVT ArgVT = Arg.getValueType();
16611   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16612
16613   TargetLowering::ArgListTy Args;
16614   TargetLowering::ArgListEntry Entry;
16615
16616   Entry.Node = Arg;
16617   Entry.Ty = ArgTy;
16618   Entry.isSExt = false;
16619   Entry.isZExt = false;
16620   Args.push_back(Entry);
16621
16622   bool isF64 = ArgVT == MVT::f64;
16623   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16624   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16625   // the results are returned via SRet in memory.
16626   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16627   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16628   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16629
16630   Type *RetTy = isF64
16631     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16632     : (Type*)VectorType::get(ArgTy, 4);
16633
16634   TargetLowering::CallLoweringInfo CLI(DAG);
16635   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16636     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16637
16638   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16639
16640   if (isF64)
16641     // Returned in xmm0 and xmm1.
16642     return CallResult.first;
16643
16644   // Returned in bits 0:31 and 32:64 xmm0.
16645   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16646                                CallResult.first, DAG.getIntPtrConstant(0));
16647   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16648                                CallResult.first, DAG.getIntPtrConstant(1));
16649   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16650   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16651 }
16652
16653 /// LowerOperation - Provide custom lowering hooks for some operations.
16654 ///
16655 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16656   switch (Op.getOpcode()) {
16657   default: llvm_unreachable("Should not custom lower this!");
16658   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16659   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16660   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16661     return LowerCMP_SWAP(Op, Subtarget, DAG);
16662   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16663   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16664   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16665   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16666   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16667   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16668   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16669   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16670   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16671   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16672   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16673   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16674   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16675   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16676   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16677   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16678   case ISD::SHL_PARTS:
16679   case ISD::SRA_PARTS:
16680   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16681   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16682   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16683   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16684   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16685   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16686   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16687   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16688   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16689   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16690   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
16691   case ISD::FABS:               return LowerFABS(Op, DAG);
16692   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16693   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16694   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16695   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16696   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16697   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16698   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16699   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16700   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16701   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16702   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16703   case ISD::INTRINSIC_VOID:
16704   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16705   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16706   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16707   case ISD::FRAME_TO_ARGS_OFFSET:
16708                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16709   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16710   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16711   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16712   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16713   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16714   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16715   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16716   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16717   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16718   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16719   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16720   case ISD::UMUL_LOHI:
16721   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16722   case ISD::SRA:
16723   case ISD::SRL:
16724   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16725   case ISD::SADDO:
16726   case ISD::UADDO:
16727   case ISD::SSUBO:
16728   case ISD::USUBO:
16729   case ISD::SMULO:
16730   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16731   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16732   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16733   case ISD::ADDC:
16734   case ISD::ADDE:
16735   case ISD::SUBC:
16736   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16737   case ISD::ADD:                return LowerADD(Op, DAG);
16738   case ISD::SUB:                return LowerSUB(Op, DAG);
16739   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16740   }
16741 }
16742
16743 static void ReplaceATOMIC_LOAD(SDNode *Node,
16744                                SmallVectorImpl<SDValue> &Results,
16745                                SelectionDAG &DAG) {
16746   SDLoc dl(Node);
16747   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16748
16749   // Convert wide load -> cmpxchg8b/cmpxchg16b
16750   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16751   //        (The only way to get a 16-byte load is cmpxchg16b)
16752   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16753   SDValue Zero = DAG.getConstant(0, VT);
16754   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16755   SDValue Swap =
16756       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16757                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16758                            cast<AtomicSDNode>(Node)->getMemOperand(),
16759                            cast<AtomicSDNode>(Node)->getOrdering(),
16760                            cast<AtomicSDNode>(Node)->getOrdering(),
16761                            cast<AtomicSDNode>(Node)->getSynchScope());
16762   Results.push_back(Swap.getValue(0));
16763   Results.push_back(Swap.getValue(2));
16764 }
16765
16766 /// ReplaceNodeResults - Replace a node with an illegal result type
16767 /// with a new node built out of custom code.
16768 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16769                                            SmallVectorImpl<SDValue>&Results,
16770                                            SelectionDAG &DAG) const {
16771   SDLoc dl(N);
16772   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16773   switch (N->getOpcode()) {
16774   default:
16775     llvm_unreachable("Do not know how to custom type legalize this operation!");
16776   case ISD::SIGN_EXTEND_INREG:
16777   case ISD::ADDC:
16778   case ISD::ADDE:
16779   case ISD::SUBC:
16780   case ISD::SUBE:
16781     // We don't want to expand or promote these.
16782     return;
16783   case ISD::SDIV:
16784   case ISD::UDIV:
16785   case ISD::SREM:
16786   case ISD::UREM:
16787   case ISD::SDIVREM:
16788   case ISD::UDIVREM: {
16789     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16790     Results.push_back(V);
16791     return;
16792   }
16793   case ISD::FP_TO_SINT:
16794   case ISD::FP_TO_UINT: {
16795     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16796
16797     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16798       return;
16799
16800     std::pair<SDValue,SDValue> Vals =
16801         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16802     SDValue FIST = Vals.first, StackSlot = Vals.second;
16803     if (FIST.getNode()) {
16804       EVT VT = N->getValueType(0);
16805       // Return a load from the stack slot.
16806       if (StackSlot.getNode())
16807         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16808                                       MachinePointerInfo(),
16809                                       false, false, false, 0));
16810       else
16811         Results.push_back(FIST);
16812     }
16813     return;
16814   }
16815   case ISD::UINT_TO_FP: {
16816     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16817     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16818         N->getValueType(0) != MVT::v2f32)
16819       return;
16820     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16821                                  N->getOperand(0));
16822     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16823                                      MVT::f64);
16824     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16825     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16826                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16827     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16828     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16829     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16830     return;
16831   }
16832   case ISD::FP_ROUND: {
16833     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16834         return;
16835     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16836     Results.push_back(V);
16837     return;
16838   }
16839   case ISD::INTRINSIC_W_CHAIN: {
16840     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16841     switch (IntNo) {
16842     default : llvm_unreachable("Do not know how to custom type "
16843                                "legalize this intrinsic operation!");
16844     case Intrinsic::x86_rdtsc:
16845       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16846                                      Results);
16847     case Intrinsic::x86_rdtscp:
16848       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16849                                      Results);
16850     case Intrinsic::x86_rdpmc:
16851       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16852     }
16853   }
16854   case ISD::READCYCLECOUNTER: {
16855     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16856                                    Results);
16857   }
16858   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16859     EVT T = N->getValueType(0);
16860     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16861     bool Regs64bit = T == MVT::i128;
16862     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16863     SDValue cpInL, cpInH;
16864     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16865                         DAG.getConstant(0, HalfT));
16866     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16867                         DAG.getConstant(1, HalfT));
16868     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16869                              Regs64bit ? X86::RAX : X86::EAX,
16870                              cpInL, SDValue());
16871     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16872                              Regs64bit ? X86::RDX : X86::EDX,
16873                              cpInH, cpInL.getValue(1));
16874     SDValue swapInL, swapInH;
16875     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16876                           DAG.getConstant(0, HalfT));
16877     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16878                           DAG.getConstant(1, HalfT));
16879     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16880                                Regs64bit ? X86::RBX : X86::EBX,
16881                                swapInL, cpInH.getValue(1));
16882     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16883                                Regs64bit ? X86::RCX : X86::ECX,
16884                                swapInH, swapInL.getValue(1));
16885     SDValue Ops[] = { swapInH.getValue(0),
16886                       N->getOperand(1),
16887                       swapInH.getValue(1) };
16888     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16889     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16890     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16891                                   X86ISD::LCMPXCHG8_DAG;
16892     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16893     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16894                                         Regs64bit ? X86::RAX : X86::EAX,
16895                                         HalfT, Result.getValue(1));
16896     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16897                                         Regs64bit ? X86::RDX : X86::EDX,
16898                                         HalfT, cpOutL.getValue(2));
16899     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16900
16901     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16902                                         MVT::i32, cpOutH.getValue(2));
16903     SDValue Success =
16904         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16905                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16906     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16907
16908     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16909     Results.push_back(Success);
16910     Results.push_back(EFLAGS.getValue(1));
16911     return;
16912   }
16913   case ISD::ATOMIC_SWAP:
16914   case ISD::ATOMIC_LOAD_ADD:
16915   case ISD::ATOMIC_LOAD_SUB:
16916   case ISD::ATOMIC_LOAD_AND:
16917   case ISD::ATOMIC_LOAD_OR:
16918   case ISD::ATOMIC_LOAD_XOR:
16919   case ISD::ATOMIC_LOAD_NAND:
16920   case ISD::ATOMIC_LOAD_MIN:
16921   case ISD::ATOMIC_LOAD_MAX:
16922   case ISD::ATOMIC_LOAD_UMIN:
16923   case ISD::ATOMIC_LOAD_UMAX:
16924     // Delegate to generic TypeLegalization. Situations we can really handle
16925     // should have already been dealt with by X86AtomicExpand.cpp.
16926     break;
16927   case ISD::ATOMIC_LOAD: {
16928     ReplaceATOMIC_LOAD(N, Results, DAG);
16929     return;
16930   }
16931   case ISD::BITCAST: {
16932     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16933     EVT DstVT = N->getValueType(0);
16934     EVT SrcVT = N->getOperand(0)->getValueType(0);
16935
16936     if (SrcVT != MVT::f64 ||
16937         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16938       return;
16939
16940     unsigned NumElts = DstVT.getVectorNumElements();
16941     EVT SVT = DstVT.getVectorElementType();
16942     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16943     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16944                                    MVT::v2f64, N->getOperand(0));
16945     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16946
16947     if (ExperimentalVectorWideningLegalization) {
16948       // If we are legalizing vectors by widening, we already have the desired
16949       // legal vector type, just return it.
16950       Results.push_back(ToVecInt);
16951       return;
16952     }
16953
16954     SmallVector<SDValue, 8> Elts;
16955     for (unsigned i = 0, e = NumElts; i != e; ++i)
16956       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16957                                    ToVecInt, DAG.getIntPtrConstant(i)));
16958
16959     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16960   }
16961   }
16962 }
16963
16964 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16965   switch (Opcode) {
16966   default: return nullptr;
16967   case X86ISD::BSF:                return "X86ISD::BSF";
16968   case X86ISD::BSR:                return "X86ISD::BSR";
16969   case X86ISD::SHLD:               return "X86ISD::SHLD";
16970   case X86ISD::SHRD:               return "X86ISD::SHRD";
16971   case X86ISD::FAND:               return "X86ISD::FAND";
16972   case X86ISD::FANDN:              return "X86ISD::FANDN";
16973   case X86ISD::FOR:                return "X86ISD::FOR";
16974   case X86ISD::FXOR:               return "X86ISD::FXOR";
16975   case X86ISD::FSRL:               return "X86ISD::FSRL";
16976   case X86ISD::FILD:               return "X86ISD::FILD";
16977   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16978   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16979   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16980   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16981   case X86ISD::FLD:                return "X86ISD::FLD";
16982   case X86ISD::FST:                return "X86ISD::FST";
16983   case X86ISD::CALL:               return "X86ISD::CALL";
16984   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16985   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16986   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16987   case X86ISD::BT:                 return "X86ISD::BT";
16988   case X86ISD::CMP:                return "X86ISD::CMP";
16989   case X86ISD::COMI:               return "X86ISD::COMI";
16990   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16991   case X86ISD::CMPM:               return "X86ISD::CMPM";
16992   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16993   case X86ISD::SETCC:              return "X86ISD::SETCC";
16994   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16995   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16996   case X86ISD::CMOV:               return "X86ISD::CMOV";
16997   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16998   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16999   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
17000   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
17001   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
17002   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
17003   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
17004   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
17005   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
17006   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
17007   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
17008   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
17009   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
17010   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
17011   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
17012   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
17013   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
17014   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
17015   case X86ISD::HADD:               return "X86ISD::HADD";
17016   case X86ISD::HSUB:               return "X86ISD::HSUB";
17017   case X86ISD::FHADD:              return "X86ISD::FHADD";
17018   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
17019   case X86ISD::UMAX:               return "X86ISD::UMAX";
17020   case X86ISD::UMIN:               return "X86ISD::UMIN";
17021   case X86ISD::SMAX:               return "X86ISD::SMAX";
17022   case X86ISD::SMIN:               return "X86ISD::SMIN";
17023   case X86ISD::FMAX:               return "X86ISD::FMAX";
17024   case X86ISD::FMIN:               return "X86ISD::FMIN";
17025   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
17026   case X86ISD::FMINC:              return "X86ISD::FMINC";
17027   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
17028   case X86ISD::FRCP:               return "X86ISD::FRCP";
17029   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
17030   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
17031   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
17032   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
17033   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
17034   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
17035   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
17036   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
17037   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
17038   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
17039   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
17040   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
17041   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
17042   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
17043   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
17044   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
17045   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
17046   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
17047   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
17048   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
17049   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
17050   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
17051   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
17052   case X86ISD::VSHL:               return "X86ISD::VSHL";
17053   case X86ISD::VSRL:               return "X86ISD::VSRL";
17054   case X86ISD::VSRA:               return "X86ISD::VSRA";
17055   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
17056   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
17057   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
17058   case X86ISD::CMPP:               return "X86ISD::CMPP";
17059   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
17060   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
17061   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
17062   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
17063   case X86ISD::ADD:                return "X86ISD::ADD";
17064   case X86ISD::SUB:                return "X86ISD::SUB";
17065   case X86ISD::ADC:                return "X86ISD::ADC";
17066   case X86ISD::SBB:                return "X86ISD::SBB";
17067   case X86ISD::SMUL:               return "X86ISD::SMUL";
17068   case X86ISD::UMUL:               return "X86ISD::UMUL";
17069   case X86ISD::INC:                return "X86ISD::INC";
17070   case X86ISD::DEC:                return "X86ISD::DEC";
17071   case X86ISD::OR:                 return "X86ISD::OR";
17072   case X86ISD::XOR:                return "X86ISD::XOR";
17073   case X86ISD::AND:                return "X86ISD::AND";
17074   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
17075   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
17076   case X86ISD::PTEST:              return "X86ISD::PTEST";
17077   case X86ISD::TESTP:              return "X86ISD::TESTP";
17078   case X86ISD::TESTM:              return "X86ISD::TESTM";
17079   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
17080   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
17081   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
17082   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
17083   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
17084   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
17085   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
17086   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
17087   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
17088   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
17089   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
17090   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
17091   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
17092   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
17093   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
17094   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
17095   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
17096   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
17097   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
17098   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
17099   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
17100   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
17101   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
17102   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
17103   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
17104   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
17105   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
17106   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
17107   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
17108   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
17109   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
17110   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
17111   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
17112   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
17113   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
17114   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
17115   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
17116   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
17117   case X86ISD::SAHF:               return "X86ISD::SAHF";
17118   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
17119   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
17120   case X86ISD::FMADD:              return "X86ISD::FMADD";
17121   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
17122   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
17123   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
17124   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
17125   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
17126   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
17127   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
17128   case X86ISD::XTEST:              return "X86ISD::XTEST";
17129   }
17130 }
17131
17132 // isLegalAddressingMode - Return true if the addressing mode represented
17133 // by AM is legal for this target, for a load/store of the specified type.
17134 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
17135                                               Type *Ty) const {
17136   // X86 supports extremely general addressing modes.
17137   CodeModel::Model M = getTargetMachine().getCodeModel();
17138   Reloc::Model R = getTargetMachine().getRelocationModel();
17139
17140   // X86 allows a sign-extended 32-bit immediate field as a displacement.
17141   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
17142     return false;
17143
17144   if (AM.BaseGV) {
17145     unsigned GVFlags =
17146       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
17147
17148     // If a reference to this global requires an extra load, we can't fold it.
17149     if (isGlobalStubReference(GVFlags))
17150       return false;
17151
17152     // If BaseGV requires a register for the PIC base, we cannot also have a
17153     // BaseReg specified.
17154     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
17155       return false;
17156
17157     // If lower 4G is not available, then we must use rip-relative addressing.
17158     if ((M != CodeModel::Small || R != Reloc::Static) &&
17159         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
17160       return false;
17161   }
17162
17163   switch (AM.Scale) {
17164   case 0:
17165   case 1:
17166   case 2:
17167   case 4:
17168   case 8:
17169     // These scales always work.
17170     break;
17171   case 3:
17172   case 5:
17173   case 9:
17174     // These scales are formed with basereg+scalereg.  Only accept if there is
17175     // no basereg yet.
17176     if (AM.HasBaseReg)
17177       return false;
17178     break;
17179   default:  // Other stuff never works.
17180     return false;
17181   }
17182
17183   return true;
17184 }
17185
17186 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
17187   unsigned Bits = Ty->getScalarSizeInBits();
17188
17189   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
17190   // particularly cheaper than those without.
17191   if (Bits == 8)
17192     return false;
17193
17194   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
17195   // variable shifts just as cheap as scalar ones.
17196   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
17197     return false;
17198
17199   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
17200   // fully general vector.
17201   return true;
17202 }
17203
17204 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
17205   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17206     return false;
17207   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
17208   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
17209   return NumBits1 > NumBits2;
17210 }
17211
17212 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
17213   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
17214     return false;
17215
17216   if (!isTypeLegal(EVT::getEVT(Ty1)))
17217     return false;
17218
17219   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
17220
17221   // Assuming the caller doesn't have a zeroext or signext return parameter,
17222   // truncation all the way down to i1 is valid.
17223   return true;
17224 }
17225
17226 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
17227   return isInt<32>(Imm);
17228 }
17229
17230 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
17231   // Can also use sub to handle negated immediates.
17232   return isInt<32>(Imm);
17233 }
17234
17235 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
17236   if (!VT1.isInteger() || !VT2.isInteger())
17237     return false;
17238   unsigned NumBits1 = VT1.getSizeInBits();
17239   unsigned NumBits2 = VT2.getSizeInBits();
17240   return NumBits1 > NumBits2;
17241 }
17242
17243 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
17244   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17245   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
17246 }
17247
17248 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
17249   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
17250   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
17251 }
17252
17253 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
17254   EVT VT1 = Val.getValueType();
17255   if (isZExtFree(VT1, VT2))
17256     return true;
17257
17258   if (Val.getOpcode() != ISD::LOAD)
17259     return false;
17260
17261   if (!VT1.isSimple() || !VT1.isInteger() ||
17262       !VT2.isSimple() || !VT2.isInteger())
17263     return false;
17264
17265   switch (VT1.getSimpleVT().SimpleTy) {
17266   default: break;
17267   case MVT::i8:
17268   case MVT::i16:
17269   case MVT::i32:
17270     // X86 has 8, 16, and 32-bit zero-extending loads.
17271     return true;
17272   }
17273
17274   return false;
17275 }
17276
17277 bool
17278 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
17279   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
17280     return false;
17281
17282   VT = VT.getScalarType();
17283
17284   if (!VT.isSimple())
17285     return false;
17286
17287   switch (VT.getSimpleVT().SimpleTy) {
17288   case MVT::f32:
17289   case MVT::f64:
17290     return true;
17291   default:
17292     break;
17293   }
17294
17295   return false;
17296 }
17297
17298 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
17299   // i16 instructions are longer (0x66 prefix) and potentially slower.
17300   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
17301 }
17302
17303 /// isShuffleMaskLegal - Targets can use this to indicate that they only
17304 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
17305 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
17306 /// are assumed to be legal.
17307 bool
17308 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
17309                                       EVT VT) const {
17310   if (!VT.isSimple())
17311     return false;
17312
17313   MVT SVT = VT.getSimpleVT();
17314
17315   // Very little shuffling can be done for 64-bit vectors right now.
17316   if (VT.getSizeInBits() == 64)
17317     return false;
17318
17319   // If this is a single-input shuffle with no 128 bit lane crossings we can
17320   // lower it into pshufb.
17321   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
17322       (SVT.is256BitVector() && Subtarget->hasInt256())) {
17323     bool isLegal = true;
17324     for (unsigned I = 0, E = M.size(); I != E; ++I) {
17325       if (M[I] >= (int)SVT.getVectorNumElements() ||
17326           ShuffleCrosses128bitLane(SVT, I, M[I])) {
17327         isLegal = false;
17328         break;
17329       }
17330     }
17331     if (isLegal)
17332       return true;
17333   }
17334
17335   // FIXME: blends, shifts.
17336   return (SVT.getVectorNumElements() == 2 ||
17337           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
17338           isMOVLMask(M, SVT) ||
17339           isMOVHLPSMask(M, SVT) ||
17340           isSHUFPMask(M, SVT) ||
17341           isPSHUFDMask(M, SVT) ||
17342           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
17343           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
17344           isPALIGNRMask(M, SVT, Subtarget) ||
17345           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
17346           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
17347           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17348           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
17349           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
17350 }
17351
17352 bool
17353 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
17354                                           EVT VT) const {
17355   if (!VT.isSimple())
17356     return false;
17357
17358   MVT SVT = VT.getSimpleVT();
17359   unsigned NumElts = SVT.getVectorNumElements();
17360   // FIXME: This collection of masks seems suspect.
17361   if (NumElts == 2)
17362     return true;
17363   if (NumElts == 4 && SVT.is128BitVector()) {
17364     return (isMOVLMask(Mask, SVT)  ||
17365             isCommutedMOVLMask(Mask, SVT, true) ||
17366             isSHUFPMask(Mask, SVT) ||
17367             isSHUFPMask(Mask, SVT, /* Commuted */ true));
17368   }
17369   return false;
17370 }
17371
17372 //===----------------------------------------------------------------------===//
17373 //                           X86 Scheduler Hooks
17374 //===----------------------------------------------------------------------===//
17375
17376 /// Utility function to emit xbegin specifying the start of an RTM region.
17377 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
17378                                      const TargetInstrInfo *TII) {
17379   DebugLoc DL = MI->getDebugLoc();
17380
17381   const BasicBlock *BB = MBB->getBasicBlock();
17382   MachineFunction::iterator I = MBB;
17383   ++I;
17384
17385   // For the v = xbegin(), we generate
17386   //
17387   // thisMBB:
17388   //  xbegin sinkMBB
17389   //
17390   // mainMBB:
17391   //  eax = -1
17392   //
17393   // sinkMBB:
17394   //  v = eax
17395
17396   MachineBasicBlock *thisMBB = MBB;
17397   MachineFunction *MF = MBB->getParent();
17398   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17399   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17400   MF->insert(I, mainMBB);
17401   MF->insert(I, sinkMBB);
17402
17403   // Transfer the remainder of BB and its successor edges to sinkMBB.
17404   sinkMBB->splice(sinkMBB->begin(), MBB,
17405                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17406   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17407
17408   // thisMBB:
17409   //  xbegin sinkMBB
17410   //  # fallthrough to mainMBB
17411   //  # abortion to sinkMBB
17412   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
17413   thisMBB->addSuccessor(mainMBB);
17414   thisMBB->addSuccessor(sinkMBB);
17415
17416   // mainMBB:
17417   //  EAX = -1
17418   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
17419   mainMBB->addSuccessor(sinkMBB);
17420
17421   // sinkMBB:
17422   // EAX is live into the sinkMBB
17423   sinkMBB->addLiveIn(X86::EAX);
17424   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17425           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17426     .addReg(X86::EAX);
17427
17428   MI->eraseFromParent();
17429   return sinkMBB;
17430 }
17431
17432 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
17433 // or XMM0_V32I8 in AVX all of this code can be replaced with that
17434 // in the .td file.
17435 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
17436                                        const TargetInstrInfo *TII) {
17437   unsigned Opc;
17438   switch (MI->getOpcode()) {
17439   default: llvm_unreachable("illegal opcode!");
17440   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
17441   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
17442   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
17443   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
17444   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
17445   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
17446   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
17447   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
17448   }
17449
17450   DebugLoc dl = MI->getDebugLoc();
17451   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17452
17453   unsigned NumArgs = MI->getNumOperands();
17454   for (unsigned i = 1; i < NumArgs; ++i) {
17455     MachineOperand &Op = MI->getOperand(i);
17456     if (!(Op.isReg() && Op.isImplicit()))
17457       MIB.addOperand(Op);
17458   }
17459   if (MI->hasOneMemOperand())
17460     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17461
17462   BuildMI(*BB, MI, dl,
17463     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17464     .addReg(X86::XMM0);
17465
17466   MI->eraseFromParent();
17467   return BB;
17468 }
17469
17470 // FIXME: Custom handling because TableGen doesn't support multiple implicit
17471 // defs in an instruction pattern
17472 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
17473                                        const TargetInstrInfo *TII) {
17474   unsigned Opc;
17475   switch (MI->getOpcode()) {
17476   default: llvm_unreachable("illegal opcode!");
17477   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
17478   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
17479   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
17480   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
17481   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
17482   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
17483   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
17484   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
17485   }
17486
17487   DebugLoc dl = MI->getDebugLoc();
17488   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17489
17490   unsigned NumArgs = MI->getNumOperands(); // remove the results
17491   for (unsigned i = 1; i < NumArgs; ++i) {
17492     MachineOperand &Op = MI->getOperand(i);
17493     if (!(Op.isReg() && Op.isImplicit()))
17494       MIB.addOperand(Op);
17495   }
17496   if (MI->hasOneMemOperand())
17497     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17498
17499   BuildMI(*BB, MI, dl,
17500     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17501     .addReg(X86::ECX);
17502
17503   MI->eraseFromParent();
17504   return BB;
17505 }
17506
17507 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17508                                        const TargetInstrInfo *TII,
17509                                        const X86Subtarget* Subtarget) {
17510   DebugLoc dl = MI->getDebugLoc();
17511
17512   // Address into RAX/EAX, other two args into ECX, EDX.
17513   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17514   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17515   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17516   for (int i = 0; i < X86::AddrNumOperands; ++i)
17517     MIB.addOperand(MI->getOperand(i));
17518
17519   unsigned ValOps = X86::AddrNumOperands;
17520   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17521     .addReg(MI->getOperand(ValOps).getReg());
17522   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17523     .addReg(MI->getOperand(ValOps+1).getReg());
17524
17525   // The instruction doesn't actually take any operands though.
17526   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17527
17528   MI->eraseFromParent(); // The pseudo is gone now.
17529   return BB;
17530 }
17531
17532 MachineBasicBlock *
17533 X86TargetLowering::EmitVAARG64WithCustomInserter(
17534                    MachineInstr *MI,
17535                    MachineBasicBlock *MBB) const {
17536   // Emit va_arg instruction on X86-64.
17537
17538   // Operands to this pseudo-instruction:
17539   // 0  ) Output        : destination address (reg)
17540   // 1-5) Input         : va_list address (addr, i64mem)
17541   // 6  ) ArgSize       : Size (in bytes) of vararg type
17542   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17543   // 8  ) Align         : Alignment of type
17544   // 9  ) EFLAGS (implicit-def)
17545
17546   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17547   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17548
17549   unsigned DestReg = MI->getOperand(0).getReg();
17550   MachineOperand &Base = MI->getOperand(1);
17551   MachineOperand &Scale = MI->getOperand(2);
17552   MachineOperand &Index = MI->getOperand(3);
17553   MachineOperand &Disp = MI->getOperand(4);
17554   MachineOperand &Segment = MI->getOperand(5);
17555   unsigned ArgSize = MI->getOperand(6).getImm();
17556   unsigned ArgMode = MI->getOperand(7).getImm();
17557   unsigned Align = MI->getOperand(8).getImm();
17558
17559   // Memory Reference
17560   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17561   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17562   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17563
17564   // Machine Information
17565   const TargetInstrInfo *TII =
17566       MBB->getParent()->getTarget().getSubtargetImpl()->getInstrInfo();
17567   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17568   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17569   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17570   DebugLoc DL = MI->getDebugLoc();
17571
17572   // struct va_list {
17573   //   i32   gp_offset
17574   //   i32   fp_offset
17575   //   i64   overflow_area (address)
17576   //   i64   reg_save_area (address)
17577   // }
17578   // sizeof(va_list) = 24
17579   // alignment(va_list) = 8
17580
17581   unsigned TotalNumIntRegs = 6;
17582   unsigned TotalNumXMMRegs = 8;
17583   bool UseGPOffset = (ArgMode == 1);
17584   bool UseFPOffset = (ArgMode == 2);
17585   unsigned MaxOffset = TotalNumIntRegs * 8 +
17586                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17587
17588   /* Align ArgSize to a multiple of 8 */
17589   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17590   bool NeedsAlign = (Align > 8);
17591
17592   MachineBasicBlock *thisMBB = MBB;
17593   MachineBasicBlock *overflowMBB;
17594   MachineBasicBlock *offsetMBB;
17595   MachineBasicBlock *endMBB;
17596
17597   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17598   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17599   unsigned OffsetReg = 0;
17600
17601   if (!UseGPOffset && !UseFPOffset) {
17602     // If we only pull from the overflow region, we don't create a branch.
17603     // We don't need to alter control flow.
17604     OffsetDestReg = 0; // unused
17605     OverflowDestReg = DestReg;
17606
17607     offsetMBB = nullptr;
17608     overflowMBB = thisMBB;
17609     endMBB = thisMBB;
17610   } else {
17611     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17612     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17613     // If not, pull from overflow_area. (branch to overflowMBB)
17614     //
17615     //       thisMBB
17616     //         |     .
17617     //         |        .
17618     //     offsetMBB   overflowMBB
17619     //         |        .
17620     //         |     .
17621     //        endMBB
17622
17623     // Registers for the PHI in endMBB
17624     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17625     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17626
17627     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17628     MachineFunction *MF = MBB->getParent();
17629     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17630     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17631     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17632
17633     MachineFunction::iterator MBBIter = MBB;
17634     ++MBBIter;
17635
17636     // Insert the new basic blocks
17637     MF->insert(MBBIter, offsetMBB);
17638     MF->insert(MBBIter, overflowMBB);
17639     MF->insert(MBBIter, endMBB);
17640
17641     // Transfer the remainder of MBB and its successor edges to endMBB.
17642     endMBB->splice(endMBB->begin(), thisMBB,
17643                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17644     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17645
17646     // Make offsetMBB and overflowMBB successors of thisMBB
17647     thisMBB->addSuccessor(offsetMBB);
17648     thisMBB->addSuccessor(overflowMBB);
17649
17650     // endMBB is a successor of both offsetMBB and overflowMBB
17651     offsetMBB->addSuccessor(endMBB);
17652     overflowMBB->addSuccessor(endMBB);
17653
17654     // Load the offset value into a register
17655     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17656     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17657       .addOperand(Base)
17658       .addOperand(Scale)
17659       .addOperand(Index)
17660       .addDisp(Disp, UseFPOffset ? 4 : 0)
17661       .addOperand(Segment)
17662       .setMemRefs(MMOBegin, MMOEnd);
17663
17664     // Check if there is enough room left to pull this argument.
17665     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17666       .addReg(OffsetReg)
17667       .addImm(MaxOffset + 8 - ArgSizeA8);
17668
17669     // Branch to "overflowMBB" if offset >= max
17670     // Fall through to "offsetMBB" otherwise
17671     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17672       .addMBB(overflowMBB);
17673   }
17674
17675   // In offsetMBB, emit code to use the reg_save_area.
17676   if (offsetMBB) {
17677     assert(OffsetReg != 0);
17678
17679     // Read the reg_save_area address.
17680     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17681     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17682       .addOperand(Base)
17683       .addOperand(Scale)
17684       .addOperand(Index)
17685       .addDisp(Disp, 16)
17686       .addOperand(Segment)
17687       .setMemRefs(MMOBegin, MMOEnd);
17688
17689     // Zero-extend the offset
17690     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17691       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17692         .addImm(0)
17693         .addReg(OffsetReg)
17694         .addImm(X86::sub_32bit);
17695
17696     // Add the offset to the reg_save_area to get the final address.
17697     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17698       .addReg(OffsetReg64)
17699       .addReg(RegSaveReg);
17700
17701     // Compute the offset for the next argument
17702     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17703     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17704       .addReg(OffsetReg)
17705       .addImm(UseFPOffset ? 16 : 8);
17706
17707     // Store it back into the va_list.
17708     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17709       .addOperand(Base)
17710       .addOperand(Scale)
17711       .addOperand(Index)
17712       .addDisp(Disp, UseFPOffset ? 4 : 0)
17713       .addOperand(Segment)
17714       .addReg(NextOffsetReg)
17715       .setMemRefs(MMOBegin, MMOEnd);
17716
17717     // Jump to endMBB
17718     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17719       .addMBB(endMBB);
17720   }
17721
17722   //
17723   // Emit code to use overflow area
17724   //
17725
17726   // Load the overflow_area address into a register.
17727   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17728   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17729     .addOperand(Base)
17730     .addOperand(Scale)
17731     .addOperand(Index)
17732     .addDisp(Disp, 8)
17733     .addOperand(Segment)
17734     .setMemRefs(MMOBegin, MMOEnd);
17735
17736   // If we need to align it, do so. Otherwise, just copy the address
17737   // to OverflowDestReg.
17738   if (NeedsAlign) {
17739     // Align the overflow address
17740     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17741     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17742
17743     // aligned_addr = (addr + (align-1)) & ~(align-1)
17744     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17745       .addReg(OverflowAddrReg)
17746       .addImm(Align-1);
17747
17748     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17749       .addReg(TmpReg)
17750       .addImm(~(uint64_t)(Align-1));
17751   } else {
17752     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17753       .addReg(OverflowAddrReg);
17754   }
17755
17756   // Compute the next overflow address after this argument.
17757   // (the overflow address should be kept 8-byte aligned)
17758   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17759   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17760     .addReg(OverflowDestReg)
17761     .addImm(ArgSizeA8);
17762
17763   // Store the new overflow address.
17764   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17765     .addOperand(Base)
17766     .addOperand(Scale)
17767     .addOperand(Index)
17768     .addDisp(Disp, 8)
17769     .addOperand(Segment)
17770     .addReg(NextAddrReg)
17771     .setMemRefs(MMOBegin, MMOEnd);
17772
17773   // If we branched, emit the PHI to the front of endMBB.
17774   if (offsetMBB) {
17775     BuildMI(*endMBB, endMBB->begin(), DL,
17776             TII->get(X86::PHI), DestReg)
17777       .addReg(OffsetDestReg).addMBB(offsetMBB)
17778       .addReg(OverflowDestReg).addMBB(overflowMBB);
17779   }
17780
17781   // Erase the pseudo instruction
17782   MI->eraseFromParent();
17783
17784   return endMBB;
17785 }
17786
17787 MachineBasicBlock *
17788 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17789                                                  MachineInstr *MI,
17790                                                  MachineBasicBlock *MBB) const {
17791   // Emit code to save XMM registers to the stack. The ABI says that the
17792   // number of registers to save is given in %al, so it's theoretically
17793   // possible to do an indirect jump trick to avoid saving all of them,
17794   // however this code takes a simpler approach and just executes all
17795   // of the stores if %al is non-zero. It's less code, and it's probably
17796   // easier on the hardware branch predictor, and stores aren't all that
17797   // expensive anyway.
17798
17799   // Create the new basic blocks. One block contains all the XMM stores,
17800   // and one block is the final destination regardless of whether any
17801   // stores were performed.
17802   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17803   MachineFunction *F = MBB->getParent();
17804   MachineFunction::iterator MBBIter = MBB;
17805   ++MBBIter;
17806   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17807   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17808   F->insert(MBBIter, XMMSaveMBB);
17809   F->insert(MBBIter, EndMBB);
17810
17811   // Transfer the remainder of MBB and its successor edges to EndMBB.
17812   EndMBB->splice(EndMBB->begin(), MBB,
17813                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17814   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17815
17816   // The original block will now fall through to the XMM save block.
17817   MBB->addSuccessor(XMMSaveMBB);
17818   // The XMMSaveMBB will fall through to the end block.
17819   XMMSaveMBB->addSuccessor(EndMBB);
17820
17821   // Now add the instructions.
17822   const TargetInstrInfo *TII =
17823       MBB->getParent()->getTarget().getSubtargetImpl()->getInstrInfo();
17824   DebugLoc DL = MI->getDebugLoc();
17825
17826   unsigned CountReg = MI->getOperand(0).getReg();
17827   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17828   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17829
17830   if (!Subtarget->isTargetWin64()) {
17831     // If %al is 0, branch around the XMM save block.
17832     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17833     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17834     MBB->addSuccessor(EndMBB);
17835   }
17836
17837   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17838   // that was just emitted, but clearly shouldn't be "saved".
17839   assert((MI->getNumOperands() <= 3 ||
17840           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17841           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17842          && "Expected last argument to be EFLAGS");
17843   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17844   // In the XMM save block, save all the XMM argument registers.
17845   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17846     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17847     MachineMemOperand *MMO =
17848       F->getMachineMemOperand(
17849           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17850         MachineMemOperand::MOStore,
17851         /*Size=*/16, /*Align=*/16);
17852     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17853       .addFrameIndex(RegSaveFrameIndex)
17854       .addImm(/*Scale=*/1)
17855       .addReg(/*IndexReg=*/0)
17856       .addImm(/*Disp=*/Offset)
17857       .addReg(/*Segment=*/0)
17858       .addReg(MI->getOperand(i).getReg())
17859       .addMemOperand(MMO);
17860   }
17861
17862   MI->eraseFromParent();   // The pseudo instruction is gone now.
17863
17864   return EndMBB;
17865 }
17866
17867 // The EFLAGS operand of SelectItr might be missing a kill marker
17868 // because there were multiple uses of EFLAGS, and ISel didn't know
17869 // which to mark. Figure out whether SelectItr should have had a
17870 // kill marker, and set it if it should. Returns the correct kill
17871 // marker value.
17872 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17873                                      MachineBasicBlock* BB,
17874                                      const TargetRegisterInfo* TRI) {
17875   // Scan forward through BB for a use/def of EFLAGS.
17876   MachineBasicBlock::iterator miI(std::next(SelectItr));
17877   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17878     const MachineInstr& mi = *miI;
17879     if (mi.readsRegister(X86::EFLAGS))
17880       return false;
17881     if (mi.definesRegister(X86::EFLAGS))
17882       break; // Should have kill-flag - update below.
17883   }
17884
17885   // If we hit the end of the block, check whether EFLAGS is live into a
17886   // successor.
17887   if (miI == BB->end()) {
17888     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17889                                           sEnd = BB->succ_end();
17890          sItr != sEnd; ++sItr) {
17891       MachineBasicBlock* succ = *sItr;
17892       if (succ->isLiveIn(X86::EFLAGS))
17893         return false;
17894     }
17895   }
17896
17897   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17898   // out. SelectMI should have a kill flag on EFLAGS.
17899   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17900   return true;
17901 }
17902
17903 MachineBasicBlock *
17904 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17905                                      MachineBasicBlock *BB) const {
17906   const TargetInstrInfo *TII =
17907       BB->getParent()->getTarget().getSubtargetImpl()->getInstrInfo();
17908   DebugLoc DL = MI->getDebugLoc();
17909
17910   // To "insert" a SELECT_CC instruction, we actually have to insert the
17911   // diamond control-flow pattern.  The incoming instruction knows the
17912   // destination vreg to set, the condition code register to branch on, the
17913   // true/false values to select between, and a branch opcode to use.
17914   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17915   MachineFunction::iterator It = BB;
17916   ++It;
17917
17918   //  thisMBB:
17919   //  ...
17920   //   TrueVal = ...
17921   //   cmpTY ccX, r1, r2
17922   //   bCC copy1MBB
17923   //   fallthrough --> copy0MBB
17924   MachineBasicBlock *thisMBB = BB;
17925   MachineFunction *F = BB->getParent();
17926   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17927   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17928   F->insert(It, copy0MBB);
17929   F->insert(It, sinkMBB);
17930
17931   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17932   // live into the sink and copy blocks.
17933   const TargetRegisterInfo *TRI =
17934       BB->getParent()->getTarget().getSubtargetImpl()->getRegisterInfo();
17935   if (!MI->killsRegister(X86::EFLAGS) &&
17936       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17937     copy0MBB->addLiveIn(X86::EFLAGS);
17938     sinkMBB->addLiveIn(X86::EFLAGS);
17939   }
17940
17941   // Transfer the remainder of BB and its successor edges to sinkMBB.
17942   sinkMBB->splice(sinkMBB->begin(), BB,
17943                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17944   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17945
17946   // Add the true and fallthrough blocks as its successors.
17947   BB->addSuccessor(copy0MBB);
17948   BB->addSuccessor(sinkMBB);
17949
17950   // Create the conditional branch instruction.
17951   unsigned Opc =
17952     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17953   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17954
17955   //  copy0MBB:
17956   //   %FalseValue = ...
17957   //   # fallthrough to sinkMBB
17958   copy0MBB->addSuccessor(sinkMBB);
17959
17960   //  sinkMBB:
17961   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17962   //  ...
17963   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17964           TII->get(X86::PHI), MI->getOperand(0).getReg())
17965     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17966     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17967
17968   MI->eraseFromParent();   // The pseudo instruction is gone now.
17969   return sinkMBB;
17970 }
17971
17972 MachineBasicBlock *
17973 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17974                                         bool Is64Bit) const {
17975   MachineFunction *MF = BB->getParent();
17976   const TargetInstrInfo *TII =
17977       MF->getTarget().getSubtargetImpl()->getInstrInfo();
17978   DebugLoc DL = MI->getDebugLoc();
17979   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17980
17981   assert(MF->shouldSplitStack());
17982
17983   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17984   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17985
17986   // BB:
17987   //  ... [Till the alloca]
17988   // If stacklet is not large enough, jump to mallocMBB
17989   //
17990   // bumpMBB:
17991   //  Allocate by subtracting from RSP
17992   //  Jump to continueMBB
17993   //
17994   // mallocMBB:
17995   //  Allocate by call to runtime
17996   //
17997   // continueMBB:
17998   //  ...
17999   //  [rest of original BB]
18000   //
18001
18002   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18003   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18004   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
18005
18006   MachineRegisterInfo &MRI = MF->getRegInfo();
18007   const TargetRegisterClass *AddrRegClass =
18008     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
18009
18010   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18011     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
18012     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
18013     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
18014     sizeVReg = MI->getOperand(1).getReg(),
18015     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
18016
18017   MachineFunction::iterator MBBIter = BB;
18018   ++MBBIter;
18019
18020   MF->insert(MBBIter, bumpMBB);
18021   MF->insert(MBBIter, mallocMBB);
18022   MF->insert(MBBIter, continueMBB);
18023
18024   continueMBB->splice(continueMBB->begin(), BB,
18025                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
18026   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
18027
18028   // Add code to the main basic block to check if the stack limit has been hit,
18029   // and if so, jump to mallocMBB otherwise to bumpMBB.
18030   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
18031   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
18032     .addReg(tmpSPVReg).addReg(sizeVReg);
18033   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
18034     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
18035     .addReg(SPLimitVReg);
18036   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
18037
18038   // bumpMBB simply decreases the stack pointer, since we know the current
18039   // stacklet has enough space.
18040   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
18041     .addReg(SPLimitVReg);
18042   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
18043     .addReg(SPLimitVReg);
18044   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18045
18046   // Calls into a routine in libgcc to allocate more space from the heap.
18047   const uint32_t *RegMask = MF->getTarget()
18048                                 .getSubtargetImpl()
18049                                 ->getRegisterInfo()
18050                                 ->getCallPreservedMask(CallingConv::C);
18051   if (Is64Bit) {
18052     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
18053       .addReg(sizeVReg);
18054     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
18055       .addExternalSymbol("__morestack_allocate_stack_space")
18056       .addRegMask(RegMask)
18057       .addReg(X86::RDI, RegState::Implicit)
18058       .addReg(X86::RAX, RegState::ImplicitDefine);
18059   } else {
18060     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
18061       .addImm(12);
18062     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
18063     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
18064       .addExternalSymbol("__morestack_allocate_stack_space")
18065       .addRegMask(RegMask)
18066       .addReg(X86::EAX, RegState::ImplicitDefine);
18067   }
18068
18069   if (!Is64Bit)
18070     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
18071       .addImm(16);
18072
18073   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
18074     .addReg(Is64Bit ? X86::RAX : X86::EAX);
18075   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
18076
18077   // Set up the CFG correctly.
18078   BB->addSuccessor(bumpMBB);
18079   BB->addSuccessor(mallocMBB);
18080   mallocMBB->addSuccessor(continueMBB);
18081   bumpMBB->addSuccessor(continueMBB);
18082
18083   // Take care of the PHI nodes.
18084   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
18085           MI->getOperand(0).getReg())
18086     .addReg(mallocPtrVReg).addMBB(mallocMBB)
18087     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
18088
18089   // Delete the original pseudo instruction.
18090   MI->eraseFromParent();
18091
18092   // And we're done.
18093   return continueMBB;
18094 }
18095
18096 MachineBasicBlock *
18097 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
18098                                         MachineBasicBlock *BB) const {
18099   const TargetInstrInfo *TII =
18100       BB->getParent()->getTarget().getSubtargetImpl()->getInstrInfo();
18101   DebugLoc DL = MI->getDebugLoc();
18102
18103   assert(!Subtarget->isTargetMacho());
18104
18105   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
18106   // non-trivial part is impdef of ESP.
18107
18108   if (Subtarget->isTargetWin64()) {
18109     if (Subtarget->isTargetCygMing()) {
18110       // ___chkstk(Mingw64):
18111       // Clobbers R10, R11, RAX and EFLAGS.
18112       // Updates RSP.
18113       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18114         .addExternalSymbol("___chkstk")
18115         .addReg(X86::RAX, RegState::Implicit)
18116         .addReg(X86::RSP, RegState::Implicit)
18117         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
18118         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
18119         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18120     } else {
18121       // __chkstk(MSVCRT): does not update stack pointer.
18122       // Clobbers R10, R11 and EFLAGS.
18123       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
18124         .addExternalSymbol("__chkstk")
18125         .addReg(X86::RAX, RegState::Implicit)
18126         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18127       // RAX has the offset to be subtracted from RSP.
18128       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
18129         .addReg(X86::RSP)
18130         .addReg(X86::RAX);
18131     }
18132   } else {
18133     const char *StackProbeSymbol =
18134       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
18135
18136     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
18137       .addExternalSymbol(StackProbeSymbol)
18138       .addReg(X86::EAX, RegState::Implicit)
18139       .addReg(X86::ESP, RegState::Implicit)
18140       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
18141       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
18142       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
18143   }
18144
18145   MI->eraseFromParent();   // The pseudo instruction is gone now.
18146   return BB;
18147 }
18148
18149 MachineBasicBlock *
18150 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
18151                                       MachineBasicBlock *BB) const {
18152   // This is pretty easy.  We're taking the value that we received from
18153   // our load from the relocation, sticking it in either RDI (x86-64)
18154   // or EAX and doing an indirect call.  The return value will then
18155   // be in the normal return register.
18156   MachineFunction *F = BB->getParent();
18157   const X86InstrInfo *TII = static_cast<const X86InstrInfo *>(
18158       F->getTarget().getSubtargetImpl()->getInstrInfo());
18159   DebugLoc DL = MI->getDebugLoc();
18160
18161   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
18162   assert(MI->getOperand(3).isGlobal() && "This should be a global");
18163
18164   // Get a register mask for the lowered call.
18165   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
18166   // proper register mask.
18167   const uint32_t *RegMask = F->getTarget()
18168                                 .getSubtargetImpl()
18169                                 ->getRegisterInfo()
18170                                 ->getCallPreservedMask(CallingConv::C);
18171   if (Subtarget->is64Bit()) {
18172     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18173                                       TII->get(X86::MOV64rm), X86::RDI)
18174     .addReg(X86::RIP)
18175     .addImm(0).addReg(0)
18176     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18177                       MI->getOperand(3).getTargetFlags())
18178     .addReg(0);
18179     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
18180     addDirectMem(MIB, X86::RDI);
18181     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
18182   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
18183     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18184                                       TII->get(X86::MOV32rm), X86::EAX)
18185     .addReg(0)
18186     .addImm(0).addReg(0)
18187     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18188                       MI->getOperand(3).getTargetFlags())
18189     .addReg(0);
18190     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18191     addDirectMem(MIB, X86::EAX);
18192     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18193   } else {
18194     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
18195                                       TII->get(X86::MOV32rm), X86::EAX)
18196     .addReg(TII->getGlobalBaseReg(F))
18197     .addImm(0).addReg(0)
18198     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
18199                       MI->getOperand(3).getTargetFlags())
18200     .addReg(0);
18201     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
18202     addDirectMem(MIB, X86::EAX);
18203     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
18204   }
18205
18206   MI->eraseFromParent(); // The pseudo instruction is gone now.
18207   return BB;
18208 }
18209
18210 MachineBasicBlock *
18211 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
18212                                     MachineBasicBlock *MBB) const {
18213   DebugLoc DL = MI->getDebugLoc();
18214   MachineFunction *MF = MBB->getParent();
18215   const TargetInstrInfo *TII =
18216       MF->getTarget().getSubtargetImpl()->getInstrInfo();
18217   MachineRegisterInfo &MRI = MF->getRegInfo();
18218
18219   const BasicBlock *BB = MBB->getBasicBlock();
18220   MachineFunction::iterator I = MBB;
18221   ++I;
18222
18223   // Memory Reference
18224   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18225   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18226
18227   unsigned DstReg;
18228   unsigned MemOpndSlot = 0;
18229
18230   unsigned CurOp = 0;
18231
18232   DstReg = MI->getOperand(CurOp++).getReg();
18233   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
18234   assert(RC->hasType(MVT::i32) && "Invalid destination!");
18235   unsigned mainDstReg = MRI.createVirtualRegister(RC);
18236   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
18237
18238   MemOpndSlot = CurOp;
18239
18240   MVT PVT = getPointerTy();
18241   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18242          "Invalid Pointer Size!");
18243
18244   // For v = setjmp(buf), we generate
18245   //
18246   // thisMBB:
18247   //  buf[LabelOffset] = restoreMBB
18248   //  SjLjSetup restoreMBB
18249   //
18250   // mainMBB:
18251   //  v_main = 0
18252   //
18253   // sinkMBB:
18254   //  v = phi(main, restore)
18255   //
18256   // restoreMBB:
18257   //  v_restore = 1
18258
18259   MachineBasicBlock *thisMBB = MBB;
18260   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18261   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18262   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
18263   MF->insert(I, mainMBB);
18264   MF->insert(I, sinkMBB);
18265   MF->push_back(restoreMBB);
18266
18267   MachineInstrBuilder MIB;
18268
18269   // Transfer the remainder of BB and its successor edges to sinkMBB.
18270   sinkMBB->splice(sinkMBB->begin(), MBB,
18271                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18272   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18273
18274   // thisMBB:
18275   unsigned PtrStoreOpc = 0;
18276   unsigned LabelReg = 0;
18277   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18278   Reloc::Model RM = MF->getTarget().getRelocationModel();
18279   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
18280                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
18281
18282   // Prepare IP either in reg or imm.
18283   if (!UseImmLabel) {
18284     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
18285     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
18286     LabelReg = MRI.createVirtualRegister(PtrRC);
18287     if (Subtarget->is64Bit()) {
18288       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
18289               .addReg(X86::RIP)
18290               .addImm(0)
18291               .addReg(0)
18292               .addMBB(restoreMBB)
18293               .addReg(0);
18294     } else {
18295       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
18296       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
18297               .addReg(XII->getGlobalBaseReg(MF))
18298               .addImm(0)
18299               .addReg(0)
18300               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
18301               .addReg(0);
18302     }
18303   } else
18304     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
18305   // Store IP
18306   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
18307   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18308     if (i == X86::AddrDisp)
18309       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
18310     else
18311       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
18312   }
18313   if (!UseImmLabel)
18314     MIB.addReg(LabelReg);
18315   else
18316     MIB.addMBB(restoreMBB);
18317   MIB.setMemRefs(MMOBegin, MMOEnd);
18318   // Setup
18319   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
18320           .addMBB(restoreMBB);
18321
18322   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18323       MF->getTarget().getSubtargetImpl()->getRegisterInfo());
18324   MIB.addRegMask(RegInfo->getNoPreservedMask());
18325   thisMBB->addSuccessor(mainMBB);
18326   thisMBB->addSuccessor(restoreMBB);
18327
18328   // mainMBB:
18329   //  EAX = 0
18330   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
18331   mainMBB->addSuccessor(sinkMBB);
18332
18333   // sinkMBB:
18334   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18335           TII->get(X86::PHI), DstReg)
18336     .addReg(mainDstReg).addMBB(mainMBB)
18337     .addReg(restoreDstReg).addMBB(restoreMBB);
18338
18339   // restoreMBB:
18340   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
18341   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
18342   restoreMBB->addSuccessor(sinkMBB);
18343
18344   MI->eraseFromParent();
18345   return sinkMBB;
18346 }
18347
18348 MachineBasicBlock *
18349 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
18350                                      MachineBasicBlock *MBB) const {
18351   DebugLoc DL = MI->getDebugLoc();
18352   MachineFunction *MF = MBB->getParent();
18353   const TargetInstrInfo *TII =
18354       MF->getTarget().getSubtargetImpl()->getInstrInfo();
18355   MachineRegisterInfo &MRI = MF->getRegInfo();
18356
18357   // Memory Reference
18358   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
18359   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
18360
18361   MVT PVT = getPointerTy();
18362   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
18363          "Invalid Pointer Size!");
18364
18365   const TargetRegisterClass *RC =
18366     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
18367   unsigned Tmp = MRI.createVirtualRegister(RC);
18368   // Since FP is only updated here but NOT referenced, it's treated as GPR.
18369   const X86RegisterInfo *RegInfo = static_cast<const X86RegisterInfo *>(
18370       MF->getTarget().getSubtargetImpl()->getRegisterInfo());
18371   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
18372   unsigned SP = RegInfo->getStackRegister();
18373
18374   MachineInstrBuilder MIB;
18375
18376   const int64_t LabelOffset = 1 * PVT.getStoreSize();
18377   const int64_t SPOffset = 2 * PVT.getStoreSize();
18378
18379   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
18380   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
18381
18382   // Reload FP
18383   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
18384   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
18385     MIB.addOperand(MI->getOperand(i));
18386   MIB.setMemRefs(MMOBegin, MMOEnd);
18387   // Reload IP
18388   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
18389   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18390     if (i == X86::AddrDisp)
18391       MIB.addDisp(MI->getOperand(i), LabelOffset);
18392     else
18393       MIB.addOperand(MI->getOperand(i));
18394   }
18395   MIB.setMemRefs(MMOBegin, MMOEnd);
18396   // Reload SP
18397   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
18398   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
18399     if (i == X86::AddrDisp)
18400       MIB.addDisp(MI->getOperand(i), SPOffset);
18401     else
18402       MIB.addOperand(MI->getOperand(i));
18403   }
18404   MIB.setMemRefs(MMOBegin, MMOEnd);
18405   // Jump
18406   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
18407
18408   MI->eraseFromParent();
18409   return MBB;
18410 }
18411
18412 // Replace 213-type (isel default) FMA3 instructions with 231-type for
18413 // accumulator loops. Writing back to the accumulator allows the coalescer
18414 // to remove extra copies in the loop.   
18415 MachineBasicBlock *
18416 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
18417                                  MachineBasicBlock *MBB) const {
18418   MachineOperand &AddendOp = MI->getOperand(3);
18419
18420   // Bail out early if the addend isn't a register - we can't switch these.
18421   if (!AddendOp.isReg())
18422     return MBB;
18423
18424   MachineFunction &MF = *MBB->getParent();
18425   MachineRegisterInfo &MRI = MF.getRegInfo();
18426
18427   // Check whether the addend is defined by a PHI:
18428   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
18429   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
18430   if (!AddendDef.isPHI())
18431     return MBB;
18432
18433   // Look for the following pattern:
18434   // loop:
18435   //   %addend = phi [%entry, 0], [%loop, %result]
18436   //   ...
18437   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
18438
18439   // Replace with:
18440   //   loop:
18441   //   %addend = phi [%entry, 0], [%loop, %result]
18442   //   ...
18443   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
18444
18445   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
18446     assert(AddendDef.getOperand(i).isReg());
18447     MachineOperand PHISrcOp = AddendDef.getOperand(i);
18448     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
18449     if (&PHISrcInst == MI) {
18450       // Found a matching instruction.
18451       unsigned NewFMAOpc = 0;
18452       switch (MI->getOpcode()) {
18453         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
18454         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
18455         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
18456         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
18457         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
18458         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
18459         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
18460         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
18461         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
18462         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
18463         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
18464         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
18465         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
18466         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
18467         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
18468         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
18469         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
18470         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
18471         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
18472         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
18473         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
18474         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
18475         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
18476         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
18477         default: llvm_unreachable("Unrecognized FMA variant.");
18478       }
18479
18480       const TargetInstrInfo &TII =
18481           *MF.getTarget().getSubtargetImpl()->getInstrInfo();
18482       MachineInstrBuilder MIB =
18483         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
18484         .addOperand(MI->getOperand(0))
18485         .addOperand(MI->getOperand(3))
18486         .addOperand(MI->getOperand(2))
18487         .addOperand(MI->getOperand(1));
18488       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
18489       MI->eraseFromParent();
18490     }
18491   }
18492
18493   return MBB;
18494 }
18495
18496 MachineBasicBlock *
18497 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
18498                                                MachineBasicBlock *BB) const {
18499   switch (MI->getOpcode()) {
18500   default: llvm_unreachable("Unexpected instr type to insert");
18501   case X86::TAILJMPd64:
18502   case X86::TAILJMPr64:
18503   case X86::TAILJMPm64:
18504     llvm_unreachable("TAILJMP64 would not be touched here.");
18505   case X86::TCRETURNdi64:
18506   case X86::TCRETURNri64:
18507   case X86::TCRETURNmi64:
18508     return BB;
18509   case X86::WIN_ALLOCA:
18510     return EmitLoweredWinAlloca(MI, BB);
18511   case X86::SEG_ALLOCA_32:
18512     return EmitLoweredSegAlloca(MI, BB, false);
18513   case X86::SEG_ALLOCA_64:
18514     return EmitLoweredSegAlloca(MI, BB, true);
18515   case X86::TLSCall_32:
18516   case X86::TLSCall_64:
18517     return EmitLoweredTLSCall(MI, BB);
18518   case X86::CMOV_GR8:
18519   case X86::CMOV_FR32:
18520   case X86::CMOV_FR64:
18521   case X86::CMOV_V4F32:
18522   case X86::CMOV_V2F64:
18523   case X86::CMOV_V2I64:
18524   case X86::CMOV_V8F32:
18525   case X86::CMOV_V4F64:
18526   case X86::CMOV_V4I64:
18527   case X86::CMOV_V16F32:
18528   case X86::CMOV_V8F64:
18529   case X86::CMOV_V8I64:
18530   case X86::CMOV_GR16:
18531   case X86::CMOV_GR32:
18532   case X86::CMOV_RFP32:
18533   case X86::CMOV_RFP64:
18534   case X86::CMOV_RFP80:
18535     return EmitLoweredSelect(MI, BB);
18536
18537   case X86::FP32_TO_INT16_IN_MEM:
18538   case X86::FP32_TO_INT32_IN_MEM:
18539   case X86::FP32_TO_INT64_IN_MEM:
18540   case X86::FP64_TO_INT16_IN_MEM:
18541   case X86::FP64_TO_INT32_IN_MEM:
18542   case X86::FP64_TO_INT64_IN_MEM:
18543   case X86::FP80_TO_INT16_IN_MEM:
18544   case X86::FP80_TO_INT32_IN_MEM:
18545   case X86::FP80_TO_INT64_IN_MEM: {
18546     MachineFunction *F = BB->getParent();
18547     const TargetInstrInfo *TII =
18548         F->getTarget().getSubtargetImpl()->getInstrInfo();
18549     DebugLoc DL = MI->getDebugLoc();
18550
18551     // Change the floating point control register to use "round towards zero"
18552     // mode when truncating to an integer value.
18553     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18554     addFrameReference(BuildMI(*BB, MI, DL,
18555                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18556
18557     // Load the old value of the high byte of the control word...
18558     unsigned OldCW =
18559       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18560     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18561                       CWFrameIdx);
18562
18563     // Set the high part to be round to zero...
18564     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18565       .addImm(0xC7F);
18566
18567     // Reload the modified control word now...
18568     addFrameReference(BuildMI(*BB, MI, DL,
18569                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18570
18571     // Restore the memory image of control word to original value
18572     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18573       .addReg(OldCW);
18574
18575     // Get the X86 opcode to use.
18576     unsigned Opc;
18577     switch (MI->getOpcode()) {
18578     default: llvm_unreachable("illegal opcode!");
18579     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18580     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18581     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18582     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18583     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18584     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18585     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18586     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18587     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18588     }
18589
18590     X86AddressMode AM;
18591     MachineOperand &Op = MI->getOperand(0);
18592     if (Op.isReg()) {
18593       AM.BaseType = X86AddressMode::RegBase;
18594       AM.Base.Reg = Op.getReg();
18595     } else {
18596       AM.BaseType = X86AddressMode::FrameIndexBase;
18597       AM.Base.FrameIndex = Op.getIndex();
18598     }
18599     Op = MI->getOperand(1);
18600     if (Op.isImm())
18601       AM.Scale = Op.getImm();
18602     Op = MI->getOperand(2);
18603     if (Op.isImm())
18604       AM.IndexReg = Op.getImm();
18605     Op = MI->getOperand(3);
18606     if (Op.isGlobal()) {
18607       AM.GV = Op.getGlobal();
18608     } else {
18609       AM.Disp = Op.getImm();
18610     }
18611     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18612                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18613
18614     // Reload the original control word now.
18615     addFrameReference(BuildMI(*BB, MI, DL,
18616                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18617
18618     MI->eraseFromParent();   // The pseudo instruction is gone now.
18619     return BB;
18620   }
18621     // String/text processing lowering.
18622   case X86::PCMPISTRM128REG:
18623   case X86::VPCMPISTRM128REG:
18624   case X86::PCMPISTRM128MEM:
18625   case X86::VPCMPISTRM128MEM:
18626   case X86::PCMPESTRM128REG:
18627   case X86::VPCMPESTRM128REG:
18628   case X86::PCMPESTRM128MEM:
18629   case X86::VPCMPESTRM128MEM:
18630     assert(Subtarget->hasSSE42() &&
18631            "Target must have SSE4.2 or AVX features enabled");
18632     return EmitPCMPSTRM(
18633         MI, BB,
18634         BB->getParent()->getTarget().getSubtargetImpl()->getInstrInfo());
18635
18636   // String/text processing lowering.
18637   case X86::PCMPISTRIREG:
18638   case X86::VPCMPISTRIREG:
18639   case X86::PCMPISTRIMEM:
18640   case X86::VPCMPISTRIMEM:
18641   case X86::PCMPESTRIREG:
18642   case X86::VPCMPESTRIREG:
18643   case X86::PCMPESTRIMEM:
18644   case X86::VPCMPESTRIMEM:
18645     assert(Subtarget->hasSSE42() &&
18646            "Target must have SSE4.2 or AVX features enabled");
18647     return EmitPCMPSTRI(
18648         MI, BB,
18649         BB->getParent()->getTarget().getSubtargetImpl()->getInstrInfo());
18650
18651   // Thread synchronization.
18652   case X86::MONITOR:
18653     return EmitMonitor(
18654         MI, BB, BB->getParent()->getTarget().getSubtargetImpl()->getInstrInfo(),
18655         Subtarget);
18656
18657   // xbegin
18658   case X86::XBEGIN:
18659     return EmitXBegin(
18660         MI, BB,
18661         BB->getParent()->getTarget().getSubtargetImpl()->getInstrInfo());
18662
18663   case X86::VASTART_SAVE_XMM_REGS:
18664     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18665
18666   case X86::VAARG_64:
18667     return EmitVAARG64WithCustomInserter(MI, BB);
18668
18669   case X86::EH_SjLj_SetJmp32:
18670   case X86::EH_SjLj_SetJmp64:
18671     return emitEHSjLjSetJmp(MI, BB);
18672
18673   case X86::EH_SjLj_LongJmp32:
18674   case X86::EH_SjLj_LongJmp64:
18675     return emitEHSjLjLongJmp(MI, BB);
18676
18677   case TargetOpcode::STACKMAP:
18678   case TargetOpcode::PATCHPOINT:
18679     return emitPatchPoint(MI, BB);
18680
18681   case X86::VFMADDPDr213r:
18682   case X86::VFMADDPSr213r:
18683   case X86::VFMADDSDr213r:
18684   case X86::VFMADDSSr213r:
18685   case X86::VFMSUBPDr213r:
18686   case X86::VFMSUBPSr213r:
18687   case X86::VFMSUBSDr213r:
18688   case X86::VFMSUBSSr213r:
18689   case X86::VFNMADDPDr213r:
18690   case X86::VFNMADDPSr213r:
18691   case X86::VFNMADDSDr213r:
18692   case X86::VFNMADDSSr213r:
18693   case X86::VFNMSUBPDr213r:
18694   case X86::VFNMSUBPSr213r:
18695   case X86::VFNMSUBSDr213r:
18696   case X86::VFNMSUBSSr213r:
18697   case X86::VFMADDPDr213rY:
18698   case X86::VFMADDPSr213rY:
18699   case X86::VFMSUBPDr213rY:
18700   case X86::VFMSUBPSr213rY:
18701   case X86::VFNMADDPDr213rY:
18702   case X86::VFNMADDPSr213rY:
18703   case X86::VFNMSUBPDr213rY:
18704   case X86::VFNMSUBPSr213rY:
18705     return emitFMA3Instr(MI, BB);
18706   }
18707 }
18708
18709 //===----------------------------------------------------------------------===//
18710 //                           X86 Optimization Hooks
18711 //===----------------------------------------------------------------------===//
18712
18713 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18714                                                       APInt &KnownZero,
18715                                                       APInt &KnownOne,
18716                                                       const SelectionDAG &DAG,
18717                                                       unsigned Depth) const {
18718   unsigned BitWidth = KnownZero.getBitWidth();
18719   unsigned Opc = Op.getOpcode();
18720   assert((Opc >= ISD::BUILTIN_OP_END ||
18721           Opc == ISD::INTRINSIC_WO_CHAIN ||
18722           Opc == ISD::INTRINSIC_W_CHAIN ||
18723           Opc == ISD::INTRINSIC_VOID) &&
18724          "Should use MaskedValueIsZero if you don't know whether Op"
18725          " is a target node!");
18726
18727   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18728   switch (Opc) {
18729   default: break;
18730   case X86ISD::ADD:
18731   case X86ISD::SUB:
18732   case X86ISD::ADC:
18733   case X86ISD::SBB:
18734   case X86ISD::SMUL:
18735   case X86ISD::UMUL:
18736   case X86ISD::INC:
18737   case X86ISD::DEC:
18738   case X86ISD::OR:
18739   case X86ISD::XOR:
18740   case X86ISD::AND:
18741     // These nodes' second result is a boolean.
18742     if (Op.getResNo() == 0)
18743       break;
18744     // Fallthrough
18745   case X86ISD::SETCC:
18746     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18747     break;
18748   case ISD::INTRINSIC_WO_CHAIN: {
18749     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18750     unsigned NumLoBits = 0;
18751     switch (IntId) {
18752     default: break;
18753     case Intrinsic::x86_sse_movmsk_ps:
18754     case Intrinsic::x86_avx_movmsk_ps_256:
18755     case Intrinsic::x86_sse2_movmsk_pd:
18756     case Intrinsic::x86_avx_movmsk_pd_256:
18757     case Intrinsic::x86_mmx_pmovmskb:
18758     case Intrinsic::x86_sse2_pmovmskb_128:
18759     case Intrinsic::x86_avx2_pmovmskb: {
18760       // High bits of movmskp{s|d}, pmovmskb are known zero.
18761       switch (IntId) {
18762         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18763         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18764         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18765         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18766         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18767         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18768         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18769         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18770       }
18771       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18772       break;
18773     }
18774     }
18775     break;
18776   }
18777   }
18778 }
18779
18780 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18781   SDValue Op,
18782   const SelectionDAG &,
18783   unsigned Depth) const {
18784   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18785   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18786     return Op.getValueType().getScalarType().getSizeInBits();
18787
18788   // Fallback case.
18789   return 1;
18790 }
18791
18792 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18793 /// node is a GlobalAddress + offset.
18794 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18795                                        const GlobalValue* &GA,
18796                                        int64_t &Offset) const {
18797   if (N->getOpcode() == X86ISD::Wrapper) {
18798     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18799       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18800       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18801       return true;
18802     }
18803   }
18804   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18805 }
18806
18807 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18808 /// same as extracting the high 128-bit part of 256-bit vector and then
18809 /// inserting the result into the low part of a new 256-bit vector
18810 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18811   EVT VT = SVOp->getValueType(0);
18812   unsigned NumElems = VT.getVectorNumElements();
18813
18814   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18815   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18816     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18817         SVOp->getMaskElt(j) >= 0)
18818       return false;
18819
18820   return true;
18821 }
18822
18823 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18824 /// same as extracting the low 128-bit part of 256-bit vector and then
18825 /// inserting the result into the high part of a new 256-bit vector
18826 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18827   EVT VT = SVOp->getValueType(0);
18828   unsigned NumElems = VT.getVectorNumElements();
18829
18830   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18831   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18832     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18833         SVOp->getMaskElt(j) >= 0)
18834       return false;
18835
18836   return true;
18837 }
18838
18839 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18840 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18841                                         TargetLowering::DAGCombinerInfo &DCI,
18842                                         const X86Subtarget* Subtarget) {
18843   SDLoc dl(N);
18844   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18845   SDValue V1 = SVOp->getOperand(0);
18846   SDValue V2 = SVOp->getOperand(1);
18847   EVT VT = SVOp->getValueType(0);
18848   unsigned NumElems = VT.getVectorNumElements();
18849
18850   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18851       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18852     //
18853     //                   0,0,0,...
18854     //                      |
18855     //    V      UNDEF    BUILD_VECTOR    UNDEF
18856     //     \      /           \           /
18857     //  CONCAT_VECTOR         CONCAT_VECTOR
18858     //         \                  /
18859     //          \                /
18860     //          RESULT: V + zero extended
18861     //
18862     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18863         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18864         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18865       return SDValue();
18866
18867     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18868       return SDValue();
18869
18870     // To match the shuffle mask, the first half of the mask should
18871     // be exactly the first vector, and all the rest a splat with the
18872     // first element of the second one.
18873     for (unsigned i = 0; i != NumElems/2; ++i)
18874       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18875           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18876         return SDValue();
18877
18878     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18879     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18880       if (Ld->hasNUsesOfValue(1, 0)) {
18881         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18882         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18883         SDValue ResNode =
18884           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18885                                   Ld->getMemoryVT(),
18886                                   Ld->getPointerInfo(),
18887                                   Ld->getAlignment(),
18888                                   false/*isVolatile*/, true/*ReadMem*/,
18889                                   false/*WriteMem*/);
18890
18891         // Make sure the newly-created LOAD is in the same position as Ld in
18892         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18893         // and update uses of Ld's output chain to use the TokenFactor.
18894         if (Ld->hasAnyUseOfValue(1)) {
18895           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18896                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18897           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18898           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18899                                  SDValue(ResNode.getNode(), 1));
18900         }
18901
18902         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18903       }
18904     }
18905
18906     // Emit a zeroed vector and insert the desired subvector on its
18907     // first half.
18908     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18909     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18910     return DCI.CombineTo(N, InsV);
18911   }
18912
18913   //===--------------------------------------------------------------------===//
18914   // Combine some shuffles into subvector extracts and inserts:
18915   //
18916
18917   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18918   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18919     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18920     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18921     return DCI.CombineTo(N, InsV);
18922   }
18923
18924   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18925   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18926     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18927     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18928     return DCI.CombineTo(N, InsV);
18929   }
18930
18931   return SDValue();
18932 }
18933
18934 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
18935 /// possible.
18936 ///
18937 /// This is the leaf of the recursive combinine below. When we have found some
18938 /// chain of single-use x86 shuffle instructions and accumulated the combined
18939 /// shuffle mask represented by them, this will try to pattern match that mask
18940 /// into either a single instruction if there is a special purpose instruction
18941 /// for this operation, or into a PSHUFB instruction which is a fully general
18942 /// instruction but should only be used to replace chains over a certain depth.
18943 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
18944                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
18945                                    TargetLowering::DAGCombinerInfo &DCI,
18946                                    const X86Subtarget *Subtarget) {
18947   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
18948
18949   // Find the operand that enters the chain. Note that multiple uses are OK
18950   // here, we're not going to remove the operand we find.
18951   SDValue Input = Op.getOperand(0);
18952   while (Input.getOpcode() == ISD::BITCAST)
18953     Input = Input.getOperand(0);
18954
18955   MVT VT = Input.getSimpleValueType();
18956   MVT RootVT = Root.getSimpleValueType();
18957   SDLoc DL(Root);
18958
18959   // Just remove no-op shuffle masks.
18960   if (Mask.size() == 1) {
18961     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Input),
18962                   /*AddTo*/ true);
18963     return true;
18964   }
18965
18966   // Use the float domain if the operand type is a floating point type.
18967   bool FloatDomain = VT.isFloatingPoint();
18968
18969   // If we don't have access to VEX encodings, the generic PSHUF instructions
18970   // are preferable to some of the specialized forms despite requiring one more
18971   // byte to encode because they can implicitly copy.
18972   //
18973   // IF we *do* have VEX encodings, than we can use shorter, more specific
18974   // shuffle instructions freely as they can copy due to the extra register
18975   // operand.
18976   if (Subtarget->hasAVX()) {
18977     // We have both floating point and integer variants of shuffles that dup
18978     // either the low or high half of the vector.
18979     if (Mask.equals(0, 0) || Mask.equals(1, 1)) {
18980       bool Lo = Mask.equals(0, 0);
18981       unsigned Shuffle = FloatDomain ? (Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS)
18982                                      : (Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH);
18983       if (Depth == 1 && Root->getOpcode() == Shuffle)
18984         return false; // Nothing to do!
18985       MVT ShuffleVT = FloatDomain ? MVT::v4f32 : MVT::v2i64;
18986       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
18987       DCI.AddToWorklist(Op.getNode());
18988       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
18989       DCI.AddToWorklist(Op.getNode());
18990       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
18991                     /*AddTo*/ true);
18992       return true;
18993     }
18994
18995     // FIXME: We should match UNPCKLPS and UNPCKHPS here.
18996
18997     // For the integer domain we have specialized instructions for duplicating
18998     // any element size from the low or high half.
18999     if (!FloatDomain &&
19000         (Mask.equals(0, 0, 1, 1) || Mask.equals(2, 2, 3, 3) ||
19001          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3) ||
19002          Mask.equals(4, 4, 5, 5, 6, 6, 7, 7) ||
19003          Mask.equals(0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7) ||
19004          Mask.equals(8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15,
19005                      15))) {
19006       bool Lo = Mask[0] == 0;
19007       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
19008       if (Depth == 1 && Root->getOpcode() == Shuffle)
19009         return false; // Nothing to do!
19010       MVT ShuffleVT;
19011       switch (Mask.size()) {
19012       case 4: ShuffleVT = MVT::v4i32; break;
19013       case 8: ShuffleVT = MVT::v8i16; break;
19014       case 16: ShuffleVT = MVT::v16i8; break;
19015       };
19016       Op = DAG.getNode(ISD::BITCAST, DL, ShuffleVT, Input);
19017       DCI.AddToWorklist(Op.getNode());
19018       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
19019       DCI.AddToWorklist(Op.getNode());
19020       DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19021                     /*AddTo*/ true);
19022       return true;
19023     }
19024   }
19025
19026   // Don't try to re-form single instruction chains under any circumstances now
19027   // that we've done encoding canonicalization for them.
19028   if (Depth < 2)
19029     return false;
19030
19031   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
19032   // can replace them with a single PSHUFB instruction profitably. Intel's
19033   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
19034   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
19035   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
19036     SmallVector<SDValue, 16> PSHUFBMask;
19037     assert(Mask.size() <= 16 && "Can't shuffle elements smaller than bytes!");
19038     int Ratio = 16 / Mask.size();
19039     for (unsigned i = 0; i < 16; ++i) {
19040       int M = Ratio * Mask[i / Ratio] + i % Ratio;
19041       PSHUFBMask.push_back(DAG.getConstant(M, MVT::i8));
19042     }
19043     Op = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Input);
19044     DCI.AddToWorklist(Op.getNode());
19045     SDValue PSHUFBMaskOp =
19046         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, PSHUFBMask);
19047     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
19048     Op = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, Op, PSHUFBMaskOp);
19049     DCI.AddToWorklist(Op.getNode());
19050     DCI.CombineTo(Root.getNode(), DAG.getNode(ISD::BITCAST, DL, RootVT, Op),
19051                   /*AddTo*/ true);
19052     return true;
19053   }
19054
19055   // Failed to find any combines.
19056   return false;
19057 }
19058
19059 /// \brief Fully generic combining of x86 shuffle instructions.
19060 ///
19061 /// This should be the last combine run over the x86 shuffle instructions. Once
19062 /// they have been fully optimized, this will recursively consdier all chains
19063 /// of single-use shuffle instructions, build a generic model of the cumulative
19064 /// shuffle operation, and check for simpler instructions which implement this
19065 /// operation. We use this primarily for two purposes:
19066 ///
19067 /// 1) Collapse generic shuffles to specialized single instructions when
19068 ///    equivalent. In most cases, this is just an encoding size win, but
19069 ///    sometimes we will collapse multiple generic shuffles into a single
19070 ///    special-purpose shuffle.
19071 /// 2) Look for sequences of shuffle instructions with 3 or more total
19072 ///    instructions, and replace them with the slightly more expensive SSSE3
19073 ///    PSHUFB instruction if available. We do this as the last combining step
19074 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
19075 ///    a suitable short sequence of other instructions. The PHUFB will either
19076 ///    use a register or have to read from memory and so is slightly (but only
19077 ///    slightly) more expensive than the other shuffle instructions.
19078 ///
19079 /// Because this is inherently a quadratic operation (for each shuffle in
19080 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
19081 /// This should never be an issue in practice as the shuffle lowering doesn't
19082 /// produce sequences of more than 8 instructions.
19083 ///
19084 /// FIXME: We will currently miss some cases where the redundant shuffling
19085 /// would simplify under the threshold for PSHUFB formation because of
19086 /// combine-ordering. To fix this, we should do the redundant instruction
19087 /// combining in this recursive walk.
19088 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
19089                                           ArrayRef<int> IncomingMask, int Depth,
19090                                           bool HasPSHUFB, SelectionDAG &DAG,
19091                                           TargetLowering::DAGCombinerInfo &DCI,
19092                                           const X86Subtarget *Subtarget) {
19093   // Bound the depth of our recursive combine because this is ultimately
19094   // quadratic in nature.
19095   if (Depth > 8)
19096     return false;
19097
19098   // Directly rip through bitcasts to find the underlying operand.
19099   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
19100     Op = Op.getOperand(0);
19101
19102   MVT VT = Op.getSimpleValueType();
19103   if (!VT.isVector())
19104     return false; // Bail if we hit a non-vector.
19105   // FIXME: This routine should be taught about 256-bit shuffles, or a 256-bit
19106   // version should be added.
19107   if (VT.getSizeInBits() != 128)
19108     return false;
19109
19110   assert(Root.getSimpleValueType().isVector() &&
19111          "Shuffles operate on vector types!");
19112   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
19113          "Can only combine shuffles of the same vector register size.");
19114
19115   if (!isTargetShuffle(Op.getOpcode()))
19116     return false;
19117   SmallVector<int, 16> OpMask;
19118   bool IsUnary;
19119   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
19120   // We only can combine unary shuffles which we can decode the mask for.
19121   if (!HaveMask || !IsUnary)
19122     return false;
19123
19124   assert(VT.getVectorNumElements() == OpMask.size() &&
19125          "Different mask size from vector size!");
19126
19127   SmallVector<int, 16> Mask;
19128   Mask.reserve(std::max(OpMask.size(), IncomingMask.size()));
19129
19130   // Merge this shuffle operation's mask into our accumulated mask. This is
19131   // a bit tricky as the shuffle may have a different size from the root.
19132   if (OpMask.size() == IncomingMask.size()) {
19133     for (int M : IncomingMask)
19134       Mask.push_back(OpMask[M]);
19135   } else if (OpMask.size() < IncomingMask.size()) {
19136     assert(IncomingMask.size() % OpMask.size() == 0 &&
19137            "The smaller number of elements must divide the larger.");
19138     int Ratio = IncomingMask.size() / OpMask.size();
19139     for (int M : IncomingMask)
19140       Mask.push_back(Ratio * OpMask[M / Ratio] + M % Ratio);
19141   } else {
19142     assert(OpMask.size() > IncomingMask.size() && "All other cases handled!");
19143     assert(OpMask.size() % IncomingMask.size() == 0 &&
19144            "The smaller number of elements must divide the larger.");
19145     int Ratio = OpMask.size() / IncomingMask.size();
19146     for (int i = 0, e = OpMask.size(); i < e; ++i)
19147       Mask.push_back(OpMask[Ratio * IncomingMask[i / Ratio] + i % Ratio]);
19148   }
19149
19150   // See if we can recurse into the operand to combine more things.
19151   switch (Op.getOpcode()) {
19152     case X86ISD::PSHUFB:
19153       HasPSHUFB = true;
19154     case X86ISD::PSHUFD:
19155     case X86ISD::PSHUFHW:
19156     case X86ISD::PSHUFLW:
19157       if (Op.getOperand(0).hasOneUse() &&
19158           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19159                                         HasPSHUFB, DAG, DCI, Subtarget))
19160         return true;
19161       break;
19162
19163     case X86ISD::UNPCKL:
19164     case X86ISD::UNPCKH:
19165       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
19166       // We can't check for single use, we have to check that this shuffle is the only user.
19167       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
19168           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
19169                                         HasPSHUFB, DAG, DCI, Subtarget))
19170           return true;
19171       break;
19172   }
19173
19174   // Minor canonicalization of the accumulated shuffle mask to make it easier
19175   // to match below. All this does is detect masks with squential pairs of
19176   // elements, and shrink them to the half-width mask. It does this in a loop
19177   // so it will reduce the size of the mask to the minimal width mask which
19178   // performs an equivalent shuffle.
19179   while (Mask.size() > 1) {
19180     SmallVector<int, 16> NewMask;
19181     for (int i = 0, e = Mask.size()/2; i < e; ++i) {
19182       if (Mask[2*i] % 2 != 0 || Mask[2*i] != Mask[2*i + 1] + 1) {
19183         NewMask.clear();
19184         break;
19185       }
19186       NewMask.push_back(Mask[2*i] / 2);
19187     }
19188     if (NewMask.empty())
19189       break;
19190     Mask.swap(NewMask);
19191   }
19192
19193   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
19194                                 Subtarget);
19195 }
19196
19197 /// \brief Get the PSHUF-style mask from PSHUF node.
19198 ///
19199 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
19200 /// PSHUF-style masks that can be reused with such instructions.
19201 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
19202   SmallVector<int, 4> Mask;
19203   bool IsUnary;
19204   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
19205   (void)HaveMask;
19206   assert(HaveMask);
19207
19208   switch (N.getOpcode()) {
19209   case X86ISD::PSHUFD:
19210     return Mask;
19211   case X86ISD::PSHUFLW:
19212     Mask.resize(4);
19213     return Mask;
19214   case X86ISD::PSHUFHW:
19215     Mask.erase(Mask.begin(), Mask.begin() + 4);
19216     for (int &M : Mask)
19217       M -= 4;
19218     return Mask;
19219   default:
19220     llvm_unreachable("No valid shuffle instruction found!");
19221   }
19222 }
19223
19224 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
19225 ///
19226 /// We walk up the chain and look for a combinable shuffle, skipping over
19227 /// shuffles that we could hoist this shuffle's transformation past without
19228 /// altering anything.
19229 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
19230                                          SelectionDAG &DAG,
19231                                          TargetLowering::DAGCombinerInfo &DCI) {
19232   assert(N.getOpcode() == X86ISD::PSHUFD &&
19233          "Called with something other than an x86 128-bit half shuffle!");
19234   SDLoc DL(N);
19235
19236   // Walk up a single-use chain looking for a combinable shuffle.
19237   SDValue V = N.getOperand(0);
19238   for (; V.hasOneUse(); V = V.getOperand(0)) {
19239     switch (V.getOpcode()) {
19240     default:
19241       return false; // Nothing combined!
19242
19243     case ISD::BITCAST:
19244       // Skip bitcasts as we always know the type for the target specific
19245       // instructions.
19246       continue;
19247
19248     case X86ISD::PSHUFD:
19249       // Found another dword shuffle.
19250       break;
19251
19252     case X86ISD::PSHUFLW:
19253       // Check that the low words (being shuffled) are the identity in the
19254       // dword shuffle, and the high words are self-contained.
19255       if (Mask[0] != 0 || Mask[1] != 1 ||
19256           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
19257         return false;
19258
19259       continue;
19260
19261     case X86ISD::PSHUFHW:
19262       // Check that the high words (being shuffled) are the identity in the
19263       // dword shuffle, and the low words are self-contained.
19264       if (Mask[2] != 2 || Mask[3] != 3 ||
19265           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
19266         return false;
19267
19268       continue;
19269
19270     case X86ISD::UNPCKL:
19271     case X86ISD::UNPCKH:
19272       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
19273       // shuffle into a preceding word shuffle.
19274       if (V.getValueType() != MVT::v16i8 && V.getValueType() != MVT::v8i16)
19275         return false;
19276
19277       // Search for a half-shuffle which we can combine with.
19278       unsigned CombineOp =
19279           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19280       if (V.getOperand(0) != V.getOperand(1) ||
19281           !V->isOnlyUserOf(V.getOperand(0).getNode()))
19282         return false;
19283       V = V.getOperand(0);
19284       do {
19285         switch (V.getOpcode()) {
19286         default:
19287           return false; // Nothing to combine.
19288
19289         case X86ISD::PSHUFLW:
19290         case X86ISD::PSHUFHW:
19291           if (V.getOpcode() == CombineOp)
19292             break;
19293
19294           // Fallthrough!
19295         case ISD::BITCAST:
19296           V = V.getOperand(0);
19297           continue;
19298         }
19299         break;
19300       } while (V.hasOneUse());
19301       break;
19302     }
19303     // Break out of the loop if we break out of the switch.
19304     break;
19305   }
19306
19307   if (!V.hasOneUse())
19308     // We fell out of the loop without finding a viable combining instruction.
19309     return false;
19310
19311   // Record the old value to use in RAUW-ing.
19312   SDValue Old = V;
19313
19314   // Merge this node's mask and our incoming mask.
19315   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19316   for (int &M : Mask)
19317     M = VMask[M];
19318   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
19319                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19320
19321   // It is possible that one of the combinable shuffles was completely absorbed
19322   // by the other, just replace it and revisit all users in that case.
19323   if (Old.getNode() == V.getNode()) {
19324     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
19325     return true;
19326   }
19327
19328   // Replace N with its operand as we're going to combine that shuffle away.
19329   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19330
19331   // Replace the combinable shuffle with the combined one, updating all users
19332   // so that we re-evaluate the chain here.
19333   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19334   return true;
19335 }
19336
19337 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
19338 ///
19339 /// We walk up the chain, skipping shuffles of the other half and looking
19340 /// through shuffles which switch halves trying to find a shuffle of the same
19341 /// pair of dwords.
19342 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
19343                                         SelectionDAG &DAG,
19344                                         TargetLowering::DAGCombinerInfo &DCI) {
19345   assert(
19346       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
19347       "Called with something other than an x86 128-bit half shuffle!");
19348   SDLoc DL(N);
19349   unsigned CombineOpcode = N.getOpcode();
19350
19351   // Walk up a single-use chain looking for a combinable shuffle.
19352   SDValue V = N.getOperand(0);
19353   for (; V.hasOneUse(); V = V.getOperand(0)) {
19354     switch (V.getOpcode()) {
19355     default:
19356       return false; // Nothing combined!
19357
19358     case ISD::BITCAST:
19359       // Skip bitcasts as we always know the type for the target specific
19360       // instructions.
19361       continue;
19362
19363     case X86ISD::PSHUFLW:
19364     case X86ISD::PSHUFHW:
19365       if (V.getOpcode() == CombineOpcode)
19366         break;
19367
19368       // Other-half shuffles are no-ops.
19369       continue;
19370
19371     case X86ISD::PSHUFD: {
19372       // We can only handle pshufd if the half we are combining either stays in
19373       // its half, or switches to the other half. Bail if one of these isn't
19374       // true.
19375       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19376       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
19377       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
19378             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
19379         return false;
19380
19381       // Map the mask through the pshufd and keep walking up the chain.
19382       for (int i = 0; i < 4; ++i)
19383         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
19384
19385       // Switch halves if the pshufd does.
19386       CombineOpcode =
19387           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
19388       continue;
19389     }
19390     }
19391     // Break out of the loop if we break out of the switch.
19392     break;
19393   }
19394
19395   if (!V.hasOneUse())
19396     // We fell out of the loop without finding a viable combining instruction.
19397     return false;
19398
19399   // Record the old value to use in RAUW-ing.
19400   SDValue Old = V;
19401
19402   // Merge this node's mask and our incoming mask (adjusted to account for all
19403   // the pshufd instructions encountered).
19404   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19405   for (int &M : Mask)
19406     M = VMask[M];
19407   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
19408                   getV4X86ShuffleImm8ForMask(Mask, DAG));
19409
19410   // Replace N with its operand as we're going to combine that shuffle away.
19411   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
19412
19413   // Replace the combinable shuffle with the combined one, updating all users
19414   // so that we re-evaluate the chain here.
19415   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
19416   return true;
19417 }
19418
19419 /// \brief Try to combine x86 target specific shuffles.
19420 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
19421                                            TargetLowering::DAGCombinerInfo &DCI,
19422                                            const X86Subtarget *Subtarget) {
19423   SDLoc DL(N);
19424   MVT VT = N.getSimpleValueType();
19425   SmallVector<int, 4> Mask;
19426
19427   switch (N.getOpcode()) {
19428   case X86ISD::PSHUFD:
19429   case X86ISD::PSHUFLW:
19430   case X86ISD::PSHUFHW:
19431     Mask = getPSHUFShuffleMask(N);
19432     assert(Mask.size() == 4);
19433     break;
19434   default:
19435     return SDValue();
19436   }
19437
19438   // Nuke no-op shuffles that show up after combining.
19439   if (isNoopShuffleMask(Mask))
19440     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
19441
19442   // Look for simplifications involving one or two shuffle instructions.
19443   SDValue V = N.getOperand(0);
19444   switch (N.getOpcode()) {
19445   default:
19446     break;
19447   case X86ISD::PSHUFLW:
19448   case X86ISD::PSHUFHW:
19449     assert(VT == MVT::v8i16);
19450     (void)VT;
19451
19452     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
19453       return SDValue(); // We combined away this shuffle, so we're done.
19454
19455     // See if this reduces to a PSHUFD which is no more expensive and can
19456     // combine with more operations.
19457     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
19458         areAdjacentMasksSequential(Mask)) {
19459       int DMask[] = {-1, -1, -1, -1};
19460       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
19461       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
19462       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
19463       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
19464       DCI.AddToWorklist(V.getNode());
19465       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
19466                       getV4X86ShuffleImm8ForMask(DMask, DAG));
19467       DCI.AddToWorklist(V.getNode());
19468       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
19469     }
19470
19471     // Look for shuffle patterns which can be implemented as a single unpack.
19472     // FIXME: This doesn't handle the location of the PSHUFD generically, and
19473     // only works when we have a PSHUFD followed by two half-shuffles.
19474     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
19475         (V.getOpcode() == X86ISD::PSHUFLW ||
19476          V.getOpcode() == X86ISD::PSHUFHW) &&
19477         V.getOpcode() != N.getOpcode() &&
19478         V.hasOneUse()) {
19479       SDValue D = V.getOperand(0);
19480       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
19481         D = D.getOperand(0);
19482       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
19483         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
19484         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
19485         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19486         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
19487         int WordMask[8];
19488         for (int i = 0; i < 4; ++i) {
19489           WordMask[i + NOffset] = Mask[i] + NOffset;
19490           WordMask[i + VOffset] = VMask[i] + VOffset;
19491         }
19492         // Map the word mask through the DWord mask.
19493         int MappedMask[8];
19494         for (int i = 0; i < 8; ++i)
19495           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
19496         const int UnpackLoMask[] = {0, 0, 1, 1, 2, 2, 3, 3};
19497         const int UnpackHiMask[] = {4, 4, 5, 5, 6, 6, 7, 7};
19498         if (std::equal(std::begin(MappedMask), std::end(MappedMask),
19499                        std::begin(UnpackLoMask)) ||
19500             std::equal(std::begin(MappedMask), std::end(MappedMask),
19501                        std::begin(UnpackHiMask))) {
19502           // We can replace all three shuffles with an unpack.
19503           V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, D.getOperand(0));
19504           DCI.AddToWorklist(V.getNode());
19505           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
19506                                                 : X86ISD::UNPCKH,
19507                              DL, MVT::v8i16, V, V);
19508         }
19509       }
19510     }
19511
19512     break;
19513
19514   case X86ISD::PSHUFD:
19515     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
19516       return SDValue(); // We combined away this shuffle.
19517
19518     break;
19519   }
19520
19521   return SDValue();
19522 }
19523
19524 /// PerformShuffleCombine - Performs several different shuffle combines.
19525 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
19526                                      TargetLowering::DAGCombinerInfo &DCI,
19527                                      const X86Subtarget *Subtarget) {
19528   SDLoc dl(N);
19529   SDValue N0 = N->getOperand(0);
19530   SDValue N1 = N->getOperand(1);
19531   EVT VT = N->getValueType(0);
19532
19533   // Don't create instructions with illegal types after legalize types has run.
19534   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19535   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
19536     return SDValue();
19537
19538   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
19539   if (Subtarget->hasFp256() && VT.is256BitVector() &&
19540       N->getOpcode() == ISD::VECTOR_SHUFFLE)
19541     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
19542
19543   // During Type Legalization, when promoting illegal vector types,
19544   // the backend might introduce new shuffle dag nodes and bitcasts.
19545   //
19546   // This code performs the following transformation:
19547   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
19548   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
19549   //
19550   // We do this only if both the bitcast and the BINOP dag nodes have
19551   // one use. Also, perform this transformation only if the new binary
19552   // operation is legal. This is to avoid introducing dag nodes that
19553   // potentially need to be further expanded (or custom lowered) into a
19554   // less optimal sequence of dag nodes.
19555   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
19556       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
19557       N0.getOpcode() == ISD::BITCAST) {
19558     SDValue BC0 = N0.getOperand(0);
19559     EVT SVT = BC0.getValueType();
19560     unsigned Opcode = BC0.getOpcode();
19561     unsigned NumElts = VT.getVectorNumElements();
19562     
19563     if (BC0.hasOneUse() && SVT.isVector() &&
19564         SVT.getVectorNumElements() * 2 == NumElts &&
19565         TLI.isOperationLegal(Opcode, VT)) {
19566       bool CanFold = false;
19567       switch (Opcode) {
19568       default : break;
19569       case ISD::ADD :
19570       case ISD::FADD :
19571       case ISD::SUB :
19572       case ISD::FSUB :
19573       case ISD::MUL :
19574       case ISD::FMUL :
19575         CanFold = true;
19576       }
19577
19578       unsigned SVTNumElts = SVT.getVectorNumElements();
19579       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
19580       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
19581         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
19582       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
19583         CanFold = SVOp->getMaskElt(i) < 0;
19584
19585       if (CanFold) {
19586         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
19587         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
19588         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
19589         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
19590       }
19591     }
19592   }
19593
19594   // Only handle 128 wide vector from here on.
19595   if (!VT.is128BitVector())
19596     return SDValue();
19597
19598   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
19599   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
19600   // consecutive, non-overlapping, and in the right order.
19601   SmallVector<SDValue, 16> Elts;
19602   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
19603     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
19604
19605   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
19606   if (LD.getNode())
19607     return LD;
19608
19609   if (isTargetShuffle(N->getOpcode())) {
19610     SDValue Shuffle =
19611         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
19612     if (Shuffle.getNode())
19613       return Shuffle;
19614
19615     // Try recursively combining arbitrary sequences of x86 shuffle
19616     // instructions into higher-order shuffles. We do this after combining
19617     // specific PSHUF instruction sequences into their minimal form so that we
19618     // can evaluate how many specialized shuffle instructions are involved in
19619     // a particular chain.
19620     SmallVector<int, 1> NonceMask; // Just a placeholder.
19621     NonceMask.push_back(0);
19622     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
19623                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
19624                                       DCI, Subtarget))
19625       return SDValue(); // This routine will use CombineTo to replace N.
19626   }
19627
19628   return SDValue();
19629 }
19630
19631 /// PerformTruncateCombine - Converts truncate operation to
19632 /// a sequence of vector shuffle operations.
19633 /// It is possible when we truncate 256-bit vector to 128-bit vector
19634 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
19635                                       TargetLowering::DAGCombinerInfo &DCI,
19636                                       const X86Subtarget *Subtarget)  {
19637   return SDValue();
19638 }
19639
19640 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
19641 /// specific shuffle of a load can be folded into a single element load.
19642 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
19643 /// shuffles have been customed lowered so we need to handle those here.
19644 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
19645                                          TargetLowering::DAGCombinerInfo &DCI) {
19646   if (DCI.isBeforeLegalizeOps())
19647     return SDValue();
19648
19649   SDValue InVec = N->getOperand(0);
19650   SDValue EltNo = N->getOperand(1);
19651
19652   if (!isa<ConstantSDNode>(EltNo))
19653     return SDValue();
19654
19655   EVT VT = InVec.getValueType();
19656
19657   bool HasShuffleIntoBitcast = false;
19658   if (InVec.getOpcode() == ISD::BITCAST) {
19659     // Don't duplicate a load with other uses.
19660     if (!InVec.hasOneUse())
19661       return SDValue();
19662     EVT BCVT = InVec.getOperand(0).getValueType();
19663     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
19664       return SDValue();
19665     InVec = InVec.getOperand(0);
19666     HasShuffleIntoBitcast = true;
19667   }
19668
19669   if (!isTargetShuffle(InVec.getOpcode()))
19670     return SDValue();
19671
19672   // Don't duplicate a load with other uses.
19673   if (!InVec.hasOneUse())
19674     return SDValue();
19675
19676   SmallVector<int, 16> ShuffleMask;
19677   bool UnaryShuffle;
19678   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
19679                             UnaryShuffle))
19680     return SDValue();
19681
19682   // Select the input vector, guarding against out of range extract vector.
19683   unsigned NumElems = VT.getVectorNumElements();
19684   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
19685   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
19686   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
19687                                          : InVec.getOperand(1);
19688
19689   // If inputs to shuffle are the same for both ops, then allow 2 uses
19690   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
19691
19692   if (LdNode.getOpcode() == ISD::BITCAST) {
19693     // Don't duplicate a load with other uses.
19694     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
19695       return SDValue();
19696
19697     AllowedUses = 1; // only allow 1 load use if we have a bitcast
19698     LdNode = LdNode.getOperand(0);
19699   }
19700
19701   if (!ISD::isNormalLoad(LdNode.getNode()))
19702     return SDValue();
19703
19704   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
19705
19706   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
19707     return SDValue();
19708
19709   if (HasShuffleIntoBitcast) {
19710     // If there's a bitcast before the shuffle, check if the load type and
19711     // alignment is valid.
19712     unsigned Align = LN0->getAlignment();
19713     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19714     unsigned NewAlign = TLI.getDataLayout()->
19715       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
19716
19717     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
19718       return SDValue();
19719   }
19720
19721   // All checks match so transform back to vector_shuffle so that DAG combiner
19722   // can finish the job
19723   SDLoc dl(N);
19724
19725   // Create shuffle node taking into account the case that its a unary shuffle
19726   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
19727   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
19728                                  InVec.getOperand(0), Shuffle,
19729                                  &ShuffleMask[0]);
19730   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
19731   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
19732                      EltNo);
19733 }
19734
19735 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
19736 /// generation and convert it from being a bunch of shuffles and extracts
19737 /// to a simple store and scalar loads to extract the elements.
19738 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
19739                                          TargetLowering::DAGCombinerInfo &DCI) {
19740   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
19741   if (NewOp.getNode())
19742     return NewOp;
19743
19744   SDValue InputVector = N->getOperand(0);
19745
19746   // Detect whether we are trying to convert from mmx to i32 and the bitcast
19747   // from mmx to v2i32 has a single usage.
19748   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
19749       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
19750       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
19751     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
19752                        N->getValueType(0),
19753                        InputVector.getNode()->getOperand(0));
19754
19755   // Only operate on vectors of 4 elements, where the alternative shuffling
19756   // gets to be more expensive.
19757   if (InputVector.getValueType() != MVT::v4i32)
19758     return SDValue();
19759
19760   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
19761   // single use which is a sign-extend or zero-extend, and all elements are
19762   // used.
19763   SmallVector<SDNode *, 4> Uses;
19764   unsigned ExtractedElements = 0;
19765   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
19766        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
19767     if (UI.getUse().getResNo() != InputVector.getResNo())
19768       return SDValue();
19769
19770     SDNode *Extract = *UI;
19771     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
19772       return SDValue();
19773
19774     if (Extract->getValueType(0) != MVT::i32)
19775       return SDValue();
19776     if (!Extract->hasOneUse())
19777       return SDValue();
19778     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
19779         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
19780       return SDValue();
19781     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
19782       return SDValue();
19783
19784     // Record which element was extracted.
19785     ExtractedElements |=
19786       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
19787
19788     Uses.push_back(Extract);
19789   }
19790
19791   // If not all the elements were used, this may not be worthwhile.
19792   if (ExtractedElements != 15)
19793     return SDValue();
19794
19795   // Ok, we've now decided to do the transformation.
19796   SDLoc dl(InputVector);
19797
19798   // Store the value to a temporary stack slot.
19799   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
19800   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
19801                             MachinePointerInfo(), false, false, 0);
19802
19803   // Replace each use (extract) with a load of the appropriate element.
19804   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
19805        UE = Uses.end(); UI != UE; ++UI) {
19806     SDNode *Extract = *UI;
19807
19808     // cOMpute the element's address.
19809     SDValue Idx = Extract->getOperand(1);
19810     unsigned EltSize =
19811         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
19812     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
19813     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19814     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19815
19816     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19817                                      StackPtr, OffsetVal);
19818
19819     // Load the scalar.
19820     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19821                                      ScalarAddr, MachinePointerInfo(),
19822                                      false, false, false, 0);
19823
19824     // Replace the exact with the load.
19825     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19826   }
19827
19828   // The replacement was made in place; don't return anything.
19829   return SDValue();
19830 }
19831
19832 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19833 static std::pair<unsigned, bool>
19834 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19835                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19836   if (!VT.isVector())
19837     return std::make_pair(0, false);
19838
19839   bool NeedSplit = false;
19840   switch (VT.getSimpleVT().SimpleTy) {
19841   default: return std::make_pair(0, false);
19842   case MVT::v32i8:
19843   case MVT::v16i16:
19844   case MVT::v8i32:
19845     if (!Subtarget->hasAVX2())
19846       NeedSplit = true;
19847     if (!Subtarget->hasAVX())
19848       return std::make_pair(0, false);
19849     break;
19850   case MVT::v16i8:
19851   case MVT::v8i16:
19852   case MVT::v4i32:
19853     if (!Subtarget->hasSSE2())
19854       return std::make_pair(0, false);
19855   }
19856
19857   // SSE2 has only a small subset of the operations.
19858   bool hasUnsigned = Subtarget->hasSSE41() ||
19859                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19860   bool hasSigned = Subtarget->hasSSE41() ||
19861                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19862
19863   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19864
19865   unsigned Opc = 0;
19866   // Check for x CC y ? x : y.
19867   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19868       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19869     switch (CC) {
19870     default: break;
19871     case ISD::SETULT:
19872     case ISD::SETULE:
19873       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19874     case ISD::SETUGT:
19875     case ISD::SETUGE:
19876       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19877     case ISD::SETLT:
19878     case ISD::SETLE:
19879       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19880     case ISD::SETGT:
19881     case ISD::SETGE:
19882       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19883     }
19884   // Check for x CC y ? y : x -- a min/max with reversed arms.
19885   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19886              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19887     switch (CC) {
19888     default: break;
19889     case ISD::SETULT:
19890     case ISD::SETULE:
19891       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19892     case ISD::SETUGT:
19893     case ISD::SETUGE:
19894       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19895     case ISD::SETLT:
19896     case ISD::SETLE:
19897       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19898     case ISD::SETGT:
19899     case ISD::SETGE:
19900       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19901     }
19902   }
19903
19904   return std::make_pair(Opc, NeedSplit);
19905 }
19906
19907 static SDValue
19908 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19909                                       const X86Subtarget *Subtarget) {
19910   SDLoc dl(N);
19911   SDValue Cond = N->getOperand(0);
19912   SDValue LHS = N->getOperand(1);
19913   SDValue RHS = N->getOperand(2);
19914
19915   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19916     SDValue CondSrc = Cond->getOperand(0);
19917     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19918       Cond = CondSrc->getOperand(0);
19919   }
19920
19921   MVT VT = N->getSimpleValueType(0);
19922   MVT EltVT = VT.getVectorElementType();
19923   unsigned NumElems = VT.getVectorNumElements();
19924   // There is no blend with immediate in AVX-512.
19925   if (VT.is512BitVector())
19926     return SDValue();
19927
19928   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19929     return SDValue();
19930   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19931     return SDValue();
19932
19933   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19934     return SDValue();
19935
19936   unsigned MaskValue = 0;
19937   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19938     return SDValue();
19939
19940   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19941   for (unsigned i = 0; i < NumElems; ++i) {
19942     // Be sure we emit undef where we can.
19943     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19944       ShuffleMask[i] = -1;
19945     else
19946       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19947   }
19948
19949   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19950 }
19951
19952 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19953 /// nodes.
19954 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19955                                     TargetLowering::DAGCombinerInfo &DCI,
19956                                     const X86Subtarget *Subtarget) {
19957   SDLoc DL(N);
19958   SDValue Cond = N->getOperand(0);
19959   // Get the LHS/RHS of the select.
19960   SDValue LHS = N->getOperand(1);
19961   SDValue RHS = N->getOperand(2);
19962   EVT VT = LHS.getValueType();
19963   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19964
19965   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19966   // instructions match the semantics of the common C idiom x<y?x:y but not
19967   // x<=y?x:y, because of how they handle negative zero (which can be
19968   // ignored in unsafe-math mode).
19969   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19970       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19971       (Subtarget->hasSSE2() ||
19972        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19973     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19974
19975     unsigned Opcode = 0;
19976     // Check for x CC y ? x : y.
19977     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19978         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19979       switch (CC) {
19980       default: break;
19981       case ISD::SETULT:
19982         // Converting this to a min would handle NaNs incorrectly, and swapping
19983         // the operands would cause it to handle comparisons between positive
19984         // and negative zero incorrectly.
19985         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19986           if (!DAG.getTarget().Options.UnsafeFPMath &&
19987               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19988             break;
19989           std::swap(LHS, RHS);
19990         }
19991         Opcode = X86ISD::FMIN;
19992         break;
19993       case ISD::SETOLE:
19994         // Converting this to a min would handle comparisons between positive
19995         // and negative zero incorrectly.
19996         if (!DAG.getTarget().Options.UnsafeFPMath &&
19997             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19998           break;
19999         Opcode = X86ISD::FMIN;
20000         break;
20001       case ISD::SETULE:
20002         // Converting this to a min would handle both negative zeros and NaNs
20003         // incorrectly, but we can swap the operands to fix both.
20004         std::swap(LHS, RHS);
20005       case ISD::SETOLT:
20006       case ISD::SETLT:
20007       case ISD::SETLE:
20008         Opcode = X86ISD::FMIN;
20009         break;
20010
20011       case ISD::SETOGE:
20012         // Converting this to a max would handle comparisons between positive
20013         // and negative zero incorrectly.
20014         if (!DAG.getTarget().Options.UnsafeFPMath &&
20015             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
20016           break;
20017         Opcode = X86ISD::FMAX;
20018         break;
20019       case ISD::SETUGT:
20020         // Converting this to a max would handle NaNs incorrectly, and swapping
20021         // the operands would cause it to handle comparisons between positive
20022         // and negative zero incorrectly.
20023         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
20024           if (!DAG.getTarget().Options.UnsafeFPMath &&
20025               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
20026             break;
20027           std::swap(LHS, RHS);
20028         }
20029         Opcode = X86ISD::FMAX;
20030         break;
20031       case ISD::SETUGE:
20032         // Converting this to a max would handle both negative zeros and NaNs
20033         // incorrectly, but we can swap the operands to fix both.
20034         std::swap(LHS, RHS);
20035       case ISD::SETOGT:
20036       case ISD::SETGT:
20037       case ISD::SETGE:
20038         Opcode = X86ISD::FMAX;
20039         break;
20040       }
20041     // Check for x CC y ? y : x -- a min/max with reversed arms.
20042     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
20043                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
20044       switch (CC) {
20045       default: break;
20046       case ISD::SETOGE:
20047         // Converting this to a min would handle comparisons between positive
20048         // and negative zero incorrectly, and swapping the operands would
20049         // cause it to handle NaNs incorrectly.
20050         if (!DAG.getTarget().Options.UnsafeFPMath &&
20051             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
20052           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20053             break;
20054           std::swap(LHS, RHS);
20055         }
20056         Opcode = X86ISD::FMIN;
20057         break;
20058       case ISD::SETUGT:
20059         // Converting this to a min would handle NaNs incorrectly.
20060         if (!DAG.getTarget().Options.UnsafeFPMath &&
20061             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
20062           break;
20063         Opcode = X86ISD::FMIN;
20064         break;
20065       case ISD::SETUGE:
20066         // Converting this to a min would handle both negative zeros and NaNs
20067         // incorrectly, but we can swap the operands to fix both.
20068         std::swap(LHS, RHS);
20069       case ISD::SETOGT:
20070       case ISD::SETGT:
20071       case ISD::SETGE:
20072         Opcode = X86ISD::FMIN;
20073         break;
20074
20075       case ISD::SETULT:
20076         // Converting this to a max would handle NaNs incorrectly.
20077         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20078           break;
20079         Opcode = X86ISD::FMAX;
20080         break;
20081       case ISD::SETOLE:
20082         // Converting this to a max would handle comparisons between positive
20083         // and negative zero incorrectly, and swapping the operands would
20084         // cause it to handle NaNs incorrectly.
20085         if (!DAG.getTarget().Options.UnsafeFPMath &&
20086             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
20087           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
20088             break;
20089           std::swap(LHS, RHS);
20090         }
20091         Opcode = X86ISD::FMAX;
20092         break;
20093       case ISD::SETULE:
20094         // Converting this to a max would handle both negative zeros and NaNs
20095         // incorrectly, but we can swap the operands to fix both.
20096         std::swap(LHS, RHS);
20097       case ISD::SETOLT:
20098       case ISD::SETLT:
20099       case ISD::SETLE:
20100         Opcode = X86ISD::FMAX;
20101         break;
20102       }
20103     }
20104
20105     if (Opcode)
20106       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
20107   }
20108
20109   EVT CondVT = Cond.getValueType();
20110   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
20111       CondVT.getVectorElementType() == MVT::i1) {
20112     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
20113     // lowering on AVX-512. In this case we convert it to
20114     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
20115     // The same situation for all 128 and 256-bit vectors of i8 and i16
20116     EVT OpVT = LHS.getValueType();
20117     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
20118         (OpVT.getVectorElementType() == MVT::i8 ||
20119          OpVT.getVectorElementType() == MVT::i16)) {
20120       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
20121       DCI.AddToWorklist(Cond.getNode());
20122       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
20123     }
20124   }
20125   // If this is a select between two integer constants, try to do some
20126   // optimizations.
20127   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
20128     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
20129       // Don't do this for crazy integer types.
20130       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
20131         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
20132         // so that TrueC (the true value) is larger than FalseC.
20133         bool NeedsCondInvert = false;
20134
20135         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
20136             // Efficiently invertible.
20137             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
20138              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
20139               isa<ConstantSDNode>(Cond.getOperand(1))))) {
20140           NeedsCondInvert = true;
20141           std::swap(TrueC, FalseC);
20142         }
20143
20144         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
20145         if (FalseC->getAPIntValue() == 0 &&
20146             TrueC->getAPIntValue().isPowerOf2()) {
20147           if (NeedsCondInvert) // Invert the condition if needed.
20148             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20149                                DAG.getConstant(1, Cond.getValueType()));
20150
20151           // Zero extend the condition if needed.
20152           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
20153
20154           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20155           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
20156                              DAG.getConstant(ShAmt, MVT::i8));
20157         }
20158
20159         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
20160         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20161           if (NeedsCondInvert) // Invert the condition if needed.
20162             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20163                                DAG.getConstant(1, Cond.getValueType()));
20164
20165           // Zero extend the condition if needed.
20166           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20167                              FalseC->getValueType(0), Cond);
20168           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20169                              SDValue(FalseC, 0));
20170         }
20171
20172         // Optimize cases that will turn into an LEA instruction.  This requires
20173         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20174         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20175           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20176           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20177
20178           bool isFastMultiplier = false;
20179           if (Diff < 10) {
20180             switch ((unsigned char)Diff) {
20181               default: break;
20182               case 1:  // result = add base, cond
20183               case 2:  // result = lea base(    , cond*2)
20184               case 3:  // result = lea base(cond, cond*2)
20185               case 4:  // result = lea base(    , cond*4)
20186               case 5:  // result = lea base(cond, cond*4)
20187               case 8:  // result = lea base(    , cond*8)
20188               case 9:  // result = lea base(cond, cond*8)
20189                 isFastMultiplier = true;
20190                 break;
20191             }
20192           }
20193
20194           if (isFastMultiplier) {
20195             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20196             if (NeedsCondInvert) // Invert the condition if needed.
20197               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
20198                                  DAG.getConstant(1, Cond.getValueType()));
20199
20200             // Zero extend the condition if needed.
20201             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20202                                Cond);
20203             // Scale the condition by the difference.
20204             if (Diff != 1)
20205               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20206                                  DAG.getConstant(Diff, Cond.getValueType()));
20207
20208             // Add the base if non-zero.
20209             if (FalseC->getAPIntValue() != 0)
20210               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20211                                  SDValue(FalseC, 0));
20212             return Cond;
20213           }
20214         }
20215       }
20216   }
20217
20218   // Canonicalize max and min:
20219   // (x > y) ? x : y -> (x >= y) ? x : y
20220   // (x < y) ? x : y -> (x <= y) ? x : y
20221   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
20222   // the need for an extra compare
20223   // against zero. e.g.
20224   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
20225   // subl   %esi, %edi
20226   // testl  %edi, %edi
20227   // movl   $0, %eax
20228   // cmovgl %edi, %eax
20229   // =>
20230   // xorl   %eax, %eax
20231   // subl   %esi, $edi
20232   // cmovsl %eax, %edi
20233   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
20234       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
20235       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
20236     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20237     switch (CC) {
20238     default: break;
20239     case ISD::SETLT:
20240     case ISD::SETGT: {
20241       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
20242       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
20243                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
20244       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
20245     }
20246     }
20247   }
20248
20249   // Early exit check
20250   if (!TLI.isTypeLegal(VT))
20251     return SDValue();
20252
20253   // Match VSELECTs into subs with unsigned saturation.
20254   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20255       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
20256       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
20257        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
20258     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
20259
20260     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
20261     // left side invert the predicate to simplify logic below.
20262     SDValue Other;
20263     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
20264       Other = RHS;
20265       CC = ISD::getSetCCInverse(CC, true);
20266     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
20267       Other = LHS;
20268     }
20269
20270     if (Other.getNode() && Other->getNumOperands() == 2 &&
20271         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
20272       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
20273       SDValue CondRHS = Cond->getOperand(1);
20274
20275       // Look for a general sub with unsigned saturation first.
20276       // x >= y ? x-y : 0 --> subus x, y
20277       // x >  y ? x-y : 0 --> subus x, y
20278       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
20279           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
20280         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
20281
20282       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
20283         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
20284           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
20285             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
20286               // If the RHS is a constant we have to reverse the const
20287               // canonicalization.
20288               // x > C-1 ? x+-C : 0 --> subus x, C
20289               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
20290                   CondRHSConst->getAPIntValue() ==
20291                       (-OpRHSConst->getAPIntValue() - 1))
20292                 return DAG.getNode(
20293                     X86ISD::SUBUS, DL, VT, OpLHS,
20294                     DAG.getConstant(-OpRHSConst->getAPIntValue(), VT));
20295
20296           // Another special case: If C was a sign bit, the sub has been
20297           // canonicalized into a xor.
20298           // FIXME: Would it be better to use computeKnownBits to determine
20299           //        whether it's safe to decanonicalize the xor?
20300           // x s< 0 ? x^C : 0 --> subus x, C
20301           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
20302               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
20303               OpRHSConst->getAPIntValue().isSignBit())
20304             // Note that we have to rebuild the RHS constant here to ensure we
20305             // don't rely on particular values of undef lanes.
20306             return DAG.getNode(
20307                 X86ISD::SUBUS, DL, VT, OpLHS,
20308                 DAG.getConstant(OpRHSConst->getAPIntValue(), VT));
20309         }
20310     }
20311   }
20312
20313   // Try to match a min/max vector operation.
20314   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
20315     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
20316     unsigned Opc = ret.first;
20317     bool NeedSplit = ret.second;
20318
20319     if (Opc && NeedSplit) {
20320       unsigned NumElems = VT.getVectorNumElements();
20321       // Extract the LHS vectors
20322       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
20323       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
20324
20325       // Extract the RHS vectors
20326       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
20327       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
20328
20329       // Create min/max for each subvector
20330       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
20331       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
20332
20333       // Merge the result
20334       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
20335     } else if (Opc)
20336       return DAG.getNode(Opc, DL, VT, LHS, RHS);
20337   }
20338
20339   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
20340   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
20341       // Check if SETCC has already been promoted
20342       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
20343       // Check that condition value type matches vselect operand type
20344       CondVT == VT) { 
20345
20346     assert(Cond.getValueType().isVector() &&
20347            "vector select expects a vector selector!");
20348
20349     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
20350     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
20351
20352     if (!TValIsAllOnes && !FValIsAllZeros) {
20353       // Try invert the condition if true value is not all 1s and false value
20354       // is not all 0s.
20355       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
20356       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
20357
20358       if (TValIsAllZeros || FValIsAllOnes) {
20359         SDValue CC = Cond.getOperand(2);
20360         ISD::CondCode NewCC =
20361           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
20362                                Cond.getOperand(0).getValueType().isInteger());
20363         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
20364         std::swap(LHS, RHS);
20365         TValIsAllOnes = FValIsAllOnes;
20366         FValIsAllZeros = TValIsAllZeros;
20367       }
20368     }
20369
20370     if (TValIsAllOnes || FValIsAllZeros) {
20371       SDValue Ret;
20372
20373       if (TValIsAllOnes && FValIsAllZeros)
20374         Ret = Cond;
20375       else if (TValIsAllOnes)
20376         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
20377                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
20378       else if (FValIsAllZeros)
20379         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
20380                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
20381
20382       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
20383     }
20384   }
20385
20386   // Try to fold this VSELECT into a MOVSS/MOVSD
20387   if (N->getOpcode() == ISD::VSELECT &&
20388       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
20389     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
20390         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
20391       bool CanFold = false;
20392       unsigned NumElems = Cond.getNumOperands();
20393       SDValue A = LHS;
20394       SDValue B = RHS;
20395       
20396       if (isZero(Cond.getOperand(0))) {
20397         CanFold = true;
20398
20399         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
20400         // fold (vselect <0,-1> -> (movsd A, B)
20401         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20402           CanFold = isAllOnes(Cond.getOperand(i));
20403       } else if (isAllOnes(Cond.getOperand(0))) {
20404         CanFold = true;
20405         std::swap(A, B);
20406
20407         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
20408         // fold (vselect <-1,0> -> (movsd B, A)
20409         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
20410           CanFold = isZero(Cond.getOperand(i));
20411       }
20412
20413       if (CanFold) {
20414         if (VT == MVT::v4i32 || VT == MVT::v4f32)
20415           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
20416         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
20417       }
20418
20419       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
20420         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
20421         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
20422         //                             (v2i64 (bitcast B)))))
20423         //
20424         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
20425         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
20426         //                             (v2f64 (bitcast B)))))
20427         //
20428         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
20429         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
20430         //                             (v2i64 (bitcast A)))))
20431         //
20432         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
20433         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
20434         //                             (v2f64 (bitcast A)))))
20435
20436         CanFold = (isZero(Cond.getOperand(0)) &&
20437                    isZero(Cond.getOperand(1)) &&
20438                    isAllOnes(Cond.getOperand(2)) &&
20439                    isAllOnes(Cond.getOperand(3)));
20440
20441         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
20442             isAllOnes(Cond.getOperand(1)) &&
20443             isZero(Cond.getOperand(2)) &&
20444             isZero(Cond.getOperand(3))) {
20445           CanFold = true;
20446           std::swap(LHS, RHS);
20447         }
20448
20449         if (CanFold) {
20450           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
20451           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
20452           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
20453           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
20454                                                 NewB, DAG);
20455           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
20456         }
20457       }
20458     }
20459   }
20460
20461   // If we know that this node is legal then we know that it is going to be
20462   // matched by one of the SSE/AVX BLEND instructions. These instructions only
20463   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
20464   // to simplify previous instructions.
20465   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
20466       !DCI.isBeforeLegalize() &&
20467       // We explicitly check against v8i16 and v16i16 because, although
20468       // they're marked as Custom, they might only be legal when Cond is a
20469       // build_vector of constants. This will be taken care in a later
20470       // condition.
20471       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
20472        VT != MVT::v8i16)) {
20473     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
20474
20475     // Don't optimize vector selects that map to mask-registers.
20476     if (BitWidth == 1)
20477       return SDValue();
20478
20479     // Check all uses of that condition operand to check whether it will be
20480     // consumed by non-BLEND instructions, which may depend on all bits are set
20481     // properly.
20482     for (SDNode::use_iterator I = Cond->use_begin(),
20483                               E = Cond->use_end(); I != E; ++I)
20484       if (I->getOpcode() != ISD::VSELECT)
20485         // TODO: Add other opcodes eventually lowered into BLEND.
20486         return SDValue();
20487
20488     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
20489     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
20490
20491     APInt KnownZero, KnownOne;
20492     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
20493                                           DCI.isBeforeLegalizeOps());
20494     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
20495         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
20496       DCI.CommitTargetLoweringOpt(TLO);
20497   }
20498
20499   // We should generate an X86ISD::BLENDI from a vselect if its argument
20500   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
20501   // constants. This specific pattern gets generated when we split a
20502   // selector for a 512 bit vector in a machine without AVX512 (but with
20503   // 256-bit vectors), during legalization:
20504   //
20505   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
20506   //
20507   // Iff we find this pattern and the build_vectors are built from
20508   // constants, we translate the vselect into a shuffle_vector that we
20509   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
20510   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
20511     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
20512     if (Shuffle.getNode())
20513       return Shuffle;
20514   }
20515
20516   return SDValue();
20517 }
20518
20519 // Check whether a boolean test is testing a boolean value generated by
20520 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
20521 // code.
20522 //
20523 // Simplify the following patterns:
20524 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
20525 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
20526 // to (Op EFLAGS Cond)
20527 //
20528 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
20529 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
20530 // to (Op EFLAGS !Cond)
20531 //
20532 // where Op could be BRCOND or CMOV.
20533 //
20534 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
20535   // Quit if not CMP and SUB with its value result used.
20536   if (Cmp.getOpcode() != X86ISD::CMP &&
20537       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
20538       return SDValue();
20539
20540   // Quit if not used as a boolean value.
20541   if (CC != X86::COND_E && CC != X86::COND_NE)
20542     return SDValue();
20543
20544   // Check CMP operands. One of them should be 0 or 1 and the other should be
20545   // an SetCC or extended from it.
20546   SDValue Op1 = Cmp.getOperand(0);
20547   SDValue Op2 = Cmp.getOperand(1);
20548
20549   SDValue SetCC;
20550   const ConstantSDNode* C = nullptr;
20551   bool needOppositeCond = (CC == X86::COND_E);
20552   bool checkAgainstTrue = false; // Is it a comparison against 1?
20553
20554   if ((C = dyn_cast<ConstantSDNode>(Op1)))
20555     SetCC = Op2;
20556   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
20557     SetCC = Op1;
20558   else // Quit if all operands are not constants.
20559     return SDValue();
20560
20561   if (C->getZExtValue() == 1) {
20562     needOppositeCond = !needOppositeCond;
20563     checkAgainstTrue = true;
20564   } else if (C->getZExtValue() != 0)
20565     // Quit if the constant is neither 0 or 1.
20566     return SDValue();
20567
20568   bool truncatedToBoolWithAnd = false;
20569   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
20570   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
20571          SetCC.getOpcode() == ISD::TRUNCATE ||
20572          SetCC.getOpcode() == ISD::AND) {
20573     if (SetCC.getOpcode() == ISD::AND) {
20574       int OpIdx = -1;
20575       ConstantSDNode *CS;
20576       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
20577           CS->getZExtValue() == 1)
20578         OpIdx = 1;
20579       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
20580           CS->getZExtValue() == 1)
20581         OpIdx = 0;
20582       if (OpIdx == -1)
20583         break;
20584       SetCC = SetCC.getOperand(OpIdx);
20585       truncatedToBoolWithAnd = true;
20586     } else
20587       SetCC = SetCC.getOperand(0);
20588   }
20589
20590   switch (SetCC.getOpcode()) {
20591   case X86ISD::SETCC_CARRY:
20592     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
20593     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
20594     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
20595     // truncated to i1 using 'and'.
20596     if (checkAgainstTrue && !truncatedToBoolWithAnd)
20597       break;
20598     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
20599            "Invalid use of SETCC_CARRY!");
20600     // FALL THROUGH
20601   case X86ISD::SETCC:
20602     // Set the condition code or opposite one if necessary.
20603     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
20604     if (needOppositeCond)
20605       CC = X86::GetOppositeBranchCondition(CC);
20606     return SetCC.getOperand(1);
20607   case X86ISD::CMOV: {
20608     // Check whether false/true value has canonical one, i.e. 0 or 1.
20609     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
20610     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
20611     // Quit if true value is not a constant.
20612     if (!TVal)
20613       return SDValue();
20614     // Quit if false value is not a constant.
20615     if (!FVal) {
20616       SDValue Op = SetCC.getOperand(0);
20617       // Skip 'zext' or 'trunc' node.
20618       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
20619           Op.getOpcode() == ISD::TRUNCATE)
20620         Op = Op.getOperand(0);
20621       // A special case for rdrand/rdseed, where 0 is set if false cond is
20622       // found.
20623       if ((Op.getOpcode() != X86ISD::RDRAND &&
20624            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
20625         return SDValue();
20626     }
20627     // Quit if false value is not the constant 0 or 1.
20628     bool FValIsFalse = true;
20629     if (FVal && FVal->getZExtValue() != 0) {
20630       if (FVal->getZExtValue() != 1)
20631         return SDValue();
20632       // If FVal is 1, opposite cond is needed.
20633       needOppositeCond = !needOppositeCond;
20634       FValIsFalse = false;
20635     }
20636     // Quit if TVal is not the constant opposite of FVal.
20637     if (FValIsFalse && TVal->getZExtValue() != 1)
20638       return SDValue();
20639     if (!FValIsFalse && TVal->getZExtValue() != 0)
20640       return SDValue();
20641     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
20642     if (needOppositeCond)
20643       CC = X86::GetOppositeBranchCondition(CC);
20644     return SetCC.getOperand(3);
20645   }
20646   }
20647
20648   return SDValue();
20649 }
20650
20651 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
20652 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
20653                                   TargetLowering::DAGCombinerInfo &DCI,
20654                                   const X86Subtarget *Subtarget) {
20655   SDLoc DL(N);
20656
20657   // If the flag operand isn't dead, don't touch this CMOV.
20658   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
20659     return SDValue();
20660
20661   SDValue FalseOp = N->getOperand(0);
20662   SDValue TrueOp = N->getOperand(1);
20663   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
20664   SDValue Cond = N->getOperand(3);
20665
20666   if (CC == X86::COND_E || CC == X86::COND_NE) {
20667     switch (Cond.getOpcode()) {
20668     default: break;
20669     case X86ISD::BSR:
20670     case X86ISD::BSF:
20671       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
20672       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
20673         return (CC == X86::COND_E) ? FalseOp : TrueOp;
20674     }
20675   }
20676
20677   SDValue Flags;
20678
20679   Flags = checkBoolTestSetCCCombine(Cond, CC);
20680   if (Flags.getNode() &&
20681       // Extra check as FCMOV only supports a subset of X86 cond.
20682       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
20683     SDValue Ops[] = { FalseOp, TrueOp,
20684                       DAG.getConstant(CC, MVT::i8), Flags };
20685     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
20686   }
20687
20688   // If this is a select between two integer constants, try to do some
20689   // optimizations.  Note that the operands are ordered the opposite of SELECT
20690   // operands.
20691   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
20692     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
20693       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
20694       // larger than FalseC (the false value).
20695       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
20696         CC = X86::GetOppositeBranchCondition(CC);
20697         std::swap(TrueC, FalseC);
20698         std::swap(TrueOp, FalseOp);
20699       }
20700
20701       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
20702       // This is efficient for any integer data type (including i8/i16) and
20703       // shift amount.
20704       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
20705         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20706                            DAG.getConstant(CC, MVT::i8), Cond);
20707
20708         // Zero extend the condition if needed.
20709         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
20710
20711         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
20712         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
20713                            DAG.getConstant(ShAmt, MVT::i8));
20714         if (N->getNumValues() == 2)  // Dead flag value?
20715           return DCI.CombineTo(N, Cond, SDValue());
20716         return Cond;
20717       }
20718
20719       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
20720       // for any integer data type, including i8/i16.
20721       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
20722         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20723                            DAG.getConstant(CC, MVT::i8), Cond);
20724
20725         // Zero extend the condition if needed.
20726         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
20727                            FalseC->getValueType(0), Cond);
20728         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20729                            SDValue(FalseC, 0));
20730
20731         if (N->getNumValues() == 2)  // Dead flag value?
20732           return DCI.CombineTo(N, Cond, SDValue());
20733         return Cond;
20734       }
20735
20736       // Optimize cases that will turn into an LEA instruction.  This requires
20737       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
20738       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
20739         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
20740         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
20741
20742         bool isFastMultiplier = false;
20743         if (Diff < 10) {
20744           switch ((unsigned char)Diff) {
20745           default: break;
20746           case 1:  // result = add base, cond
20747           case 2:  // result = lea base(    , cond*2)
20748           case 3:  // result = lea base(cond, cond*2)
20749           case 4:  // result = lea base(    , cond*4)
20750           case 5:  // result = lea base(cond, cond*4)
20751           case 8:  // result = lea base(    , cond*8)
20752           case 9:  // result = lea base(cond, cond*8)
20753             isFastMultiplier = true;
20754             break;
20755           }
20756         }
20757
20758         if (isFastMultiplier) {
20759           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
20760           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
20761                              DAG.getConstant(CC, MVT::i8), Cond);
20762           // Zero extend the condition if needed.
20763           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
20764                              Cond);
20765           // Scale the condition by the difference.
20766           if (Diff != 1)
20767             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
20768                                DAG.getConstant(Diff, Cond.getValueType()));
20769
20770           // Add the base if non-zero.
20771           if (FalseC->getAPIntValue() != 0)
20772             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
20773                                SDValue(FalseC, 0));
20774           if (N->getNumValues() == 2)  // Dead flag value?
20775             return DCI.CombineTo(N, Cond, SDValue());
20776           return Cond;
20777         }
20778       }
20779     }
20780   }
20781
20782   // Handle these cases:
20783   //   (select (x != c), e, c) -> select (x != c), e, x),
20784   //   (select (x == c), c, e) -> select (x == c), x, e)
20785   // where the c is an integer constant, and the "select" is the combination
20786   // of CMOV and CMP.
20787   //
20788   // The rationale for this change is that the conditional-move from a constant
20789   // needs two instructions, however, conditional-move from a register needs
20790   // only one instruction.
20791   //
20792   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
20793   //  some instruction-combining opportunities. This opt needs to be
20794   //  postponed as late as possible.
20795   //
20796   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
20797     // the DCI.xxxx conditions are provided to postpone the optimization as
20798     // late as possible.
20799
20800     ConstantSDNode *CmpAgainst = nullptr;
20801     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
20802         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
20803         !isa<ConstantSDNode>(Cond.getOperand(0))) {
20804
20805       if (CC == X86::COND_NE &&
20806           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
20807         CC = X86::GetOppositeBranchCondition(CC);
20808         std::swap(TrueOp, FalseOp);
20809       }
20810
20811       if (CC == X86::COND_E &&
20812           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
20813         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
20814                           DAG.getConstant(CC, MVT::i8), Cond };
20815         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
20816       }
20817     }
20818   }
20819
20820   return SDValue();
20821 }
20822
20823 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20824                                                 const X86Subtarget *Subtarget) {
20825   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20826   switch (IntNo) {
20827   default: return SDValue();
20828   // SSE/AVX/AVX2 blend intrinsics.
20829   case Intrinsic::x86_avx2_pblendvb:
20830   case Intrinsic::x86_avx2_pblendw:
20831   case Intrinsic::x86_avx2_pblendd_128:
20832   case Intrinsic::x86_avx2_pblendd_256:
20833     // Don't try to simplify this intrinsic if we don't have AVX2.
20834     if (!Subtarget->hasAVX2())
20835       return SDValue();
20836     // FALL-THROUGH
20837   case Intrinsic::x86_avx_blend_pd_256:
20838   case Intrinsic::x86_avx_blend_ps_256:
20839   case Intrinsic::x86_avx_blendv_pd_256:
20840   case Intrinsic::x86_avx_blendv_ps_256:
20841     // Don't try to simplify this intrinsic if we don't have AVX.
20842     if (!Subtarget->hasAVX())
20843       return SDValue();
20844     // FALL-THROUGH
20845   case Intrinsic::x86_sse41_pblendw:
20846   case Intrinsic::x86_sse41_blendpd:
20847   case Intrinsic::x86_sse41_blendps:
20848   case Intrinsic::x86_sse41_blendvps:
20849   case Intrinsic::x86_sse41_blendvpd:
20850   case Intrinsic::x86_sse41_pblendvb: {
20851     SDValue Op0 = N->getOperand(1);
20852     SDValue Op1 = N->getOperand(2);
20853     SDValue Mask = N->getOperand(3);
20854
20855     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20856     if (!Subtarget->hasSSE41())
20857       return SDValue();
20858
20859     // fold (blend A, A, Mask) -> A
20860     if (Op0 == Op1)
20861       return Op0;
20862     // fold (blend A, B, allZeros) -> A
20863     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20864       return Op0;
20865     // fold (blend A, B, allOnes) -> B
20866     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20867       return Op1;
20868     
20869     // Simplify the case where the mask is a constant i32 value.
20870     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20871       if (C->isNullValue())
20872         return Op0;
20873       if (C->isAllOnesValue())
20874         return Op1;
20875     }
20876
20877     return SDValue();
20878   }
20879
20880   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20881   case Intrinsic::x86_sse2_psrai_w:
20882   case Intrinsic::x86_sse2_psrai_d:
20883   case Intrinsic::x86_avx2_psrai_w:
20884   case Intrinsic::x86_avx2_psrai_d:
20885   case Intrinsic::x86_sse2_psra_w:
20886   case Intrinsic::x86_sse2_psra_d:
20887   case Intrinsic::x86_avx2_psra_w:
20888   case Intrinsic::x86_avx2_psra_d: {
20889     SDValue Op0 = N->getOperand(1);
20890     SDValue Op1 = N->getOperand(2);
20891     EVT VT = Op0.getValueType();
20892     assert(VT.isVector() && "Expected a vector type!");
20893
20894     if (isa<BuildVectorSDNode>(Op1))
20895       Op1 = Op1.getOperand(0);
20896
20897     if (!isa<ConstantSDNode>(Op1))
20898       return SDValue();
20899
20900     EVT SVT = VT.getVectorElementType();
20901     unsigned SVTBits = SVT.getSizeInBits();
20902
20903     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20904     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20905     uint64_t ShAmt = C.getZExtValue();
20906
20907     // Don't try to convert this shift into a ISD::SRA if the shift
20908     // count is bigger than or equal to the element size.
20909     if (ShAmt >= SVTBits)
20910       return SDValue();
20911
20912     // Trivial case: if the shift count is zero, then fold this
20913     // into the first operand.
20914     if (ShAmt == 0)
20915       return Op0;
20916
20917     // Replace this packed shift intrinsic with a target independent
20918     // shift dag node.
20919     SDValue Splat = DAG.getConstant(C, VT);
20920     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20921   }
20922   }
20923 }
20924
20925 /// PerformMulCombine - Optimize a single multiply with constant into two
20926 /// in order to implement it with two cheaper instructions, e.g.
20927 /// LEA + SHL, LEA + LEA.
20928 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20929                                  TargetLowering::DAGCombinerInfo &DCI) {
20930   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20931     return SDValue();
20932
20933   EVT VT = N->getValueType(0);
20934   if (VT != MVT::i64)
20935     return SDValue();
20936
20937   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20938   if (!C)
20939     return SDValue();
20940   uint64_t MulAmt = C->getZExtValue();
20941   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20942     return SDValue();
20943
20944   uint64_t MulAmt1 = 0;
20945   uint64_t MulAmt2 = 0;
20946   if ((MulAmt % 9) == 0) {
20947     MulAmt1 = 9;
20948     MulAmt2 = MulAmt / 9;
20949   } else if ((MulAmt % 5) == 0) {
20950     MulAmt1 = 5;
20951     MulAmt2 = MulAmt / 5;
20952   } else if ((MulAmt % 3) == 0) {
20953     MulAmt1 = 3;
20954     MulAmt2 = MulAmt / 3;
20955   }
20956   if (MulAmt2 &&
20957       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20958     SDLoc DL(N);
20959
20960     if (isPowerOf2_64(MulAmt2) &&
20961         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20962       // If second multiplifer is pow2, issue it first. We want the multiply by
20963       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20964       // is an add.
20965       std::swap(MulAmt1, MulAmt2);
20966
20967     SDValue NewMul;
20968     if (isPowerOf2_64(MulAmt1))
20969       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20970                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20971     else
20972       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20973                            DAG.getConstant(MulAmt1, VT));
20974
20975     if (isPowerOf2_64(MulAmt2))
20976       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20977                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20978     else
20979       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20980                            DAG.getConstant(MulAmt2, VT));
20981
20982     // Do not add new nodes to DAG combiner worklist.
20983     DCI.CombineTo(N, NewMul, false);
20984   }
20985   return SDValue();
20986 }
20987
20988 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20989   SDValue N0 = N->getOperand(0);
20990   SDValue N1 = N->getOperand(1);
20991   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20992   EVT VT = N0.getValueType();
20993
20994   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20995   // since the result of setcc_c is all zero's or all ones.
20996   if (VT.isInteger() && !VT.isVector() &&
20997       N1C && N0.getOpcode() == ISD::AND &&
20998       N0.getOperand(1).getOpcode() == ISD::Constant) {
20999     SDValue N00 = N0.getOperand(0);
21000     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
21001         ((N00.getOpcode() == ISD::ANY_EXTEND ||
21002           N00.getOpcode() == ISD::ZERO_EXTEND) &&
21003          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
21004       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
21005       APInt ShAmt = N1C->getAPIntValue();
21006       Mask = Mask.shl(ShAmt);
21007       if (Mask != 0)
21008         return DAG.getNode(ISD::AND, SDLoc(N), VT,
21009                            N00, DAG.getConstant(Mask, VT));
21010     }
21011   }
21012
21013   // Hardware support for vector shifts is sparse which makes us scalarize the
21014   // vector operations in many cases. Also, on sandybridge ADD is faster than
21015   // shl.
21016   // (shl V, 1) -> add V,V
21017   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
21018     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
21019       assert(N0.getValueType().isVector() && "Invalid vector shift type");
21020       // We shift all of the values by one. In many cases we do not have
21021       // hardware support for this operation. This is better expressed as an ADD
21022       // of two values.
21023       if (N1SplatC->getZExtValue() == 1)
21024         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
21025     }
21026
21027   return SDValue();
21028 }
21029
21030 /// \brief Returns a vector of 0s if the node in input is a vector logical
21031 /// shift by a constant amount which is known to be bigger than or equal
21032 /// to the vector element size in bits.
21033 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
21034                                       const X86Subtarget *Subtarget) {
21035   EVT VT = N->getValueType(0);
21036
21037   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
21038       (!Subtarget->hasInt256() ||
21039        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
21040     return SDValue();
21041
21042   SDValue Amt = N->getOperand(1);
21043   SDLoc DL(N);
21044   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
21045     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
21046       APInt ShiftAmt = AmtSplat->getAPIntValue();
21047       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
21048
21049       // SSE2/AVX2 logical shifts always return a vector of 0s
21050       // if the shift amount is bigger than or equal to
21051       // the element size. The constant shift amount will be
21052       // encoded as a 8-bit immediate.
21053       if (ShiftAmt.trunc(8).uge(MaxAmount))
21054         return getZeroVector(VT, Subtarget, DAG, DL);
21055     }
21056
21057   return SDValue();
21058 }
21059
21060 /// PerformShiftCombine - Combine shifts.
21061 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
21062                                    TargetLowering::DAGCombinerInfo &DCI,
21063                                    const X86Subtarget *Subtarget) {
21064   if (N->getOpcode() == ISD::SHL) {
21065     SDValue V = PerformSHLCombine(N, DAG);
21066     if (V.getNode()) return V;
21067   }
21068
21069   if (N->getOpcode() != ISD::SRA) {
21070     // Try to fold this logical shift into a zero vector.
21071     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
21072     if (V.getNode()) return V;
21073   }
21074
21075   return SDValue();
21076 }
21077
21078 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
21079 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
21080 // and friends.  Likewise for OR -> CMPNEQSS.
21081 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
21082                             TargetLowering::DAGCombinerInfo &DCI,
21083                             const X86Subtarget *Subtarget) {
21084   unsigned opcode;
21085
21086   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
21087   // we're requiring SSE2 for both.
21088   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
21089     SDValue N0 = N->getOperand(0);
21090     SDValue N1 = N->getOperand(1);
21091     SDValue CMP0 = N0->getOperand(1);
21092     SDValue CMP1 = N1->getOperand(1);
21093     SDLoc DL(N);
21094
21095     // The SETCCs should both refer to the same CMP.
21096     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
21097       return SDValue();
21098
21099     SDValue CMP00 = CMP0->getOperand(0);
21100     SDValue CMP01 = CMP0->getOperand(1);
21101     EVT     VT    = CMP00.getValueType();
21102
21103     if (VT == MVT::f32 || VT == MVT::f64) {
21104       bool ExpectingFlags = false;
21105       // Check for any users that want flags:
21106       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
21107            !ExpectingFlags && UI != UE; ++UI)
21108         switch (UI->getOpcode()) {
21109         default:
21110         case ISD::BR_CC:
21111         case ISD::BRCOND:
21112         case ISD::SELECT:
21113           ExpectingFlags = true;
21114           break;
21115         case ISD::CopyToReg:
21116         case ISD::SIGN_EXTEND:
21117         case ISD::ZERO_EXTEND:
21118         case ISD::ANY_EXTEND:
21119           break;
21120         }
21121
21122       if (!ExpectingFlags) {
21123         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
21124         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
21125
21126         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
21127           X86::CondCode tmp = cc0;
21128           cc0 = cc1;
21129           cc1 = tmp;
21130         }
21131
21132         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
21133             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
21134           // FIXME: need symbolic constants for these magic numbers.
21135           // See X86ATTInstPrinter.cpp:printSSECC().
21136           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
21137           if (Subtarget->hasAVX512()) {
21138             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
21139                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
21140             if (N->getValueType(0) != MVT::i1)
21141               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
21142                                  FSetCC);
21143             return FSetCC;
21144           }
21145           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
21146                                               CMP00.getValueType(), CMP00, CMP01,
21147                                               DAG.getConstant(x86cc, MVT::i8));
21148
21149           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
21150           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
21151
21152           if (is64BitFP && !Subtarget->is64Bit()) {
21153             // On a 32-bit target, we cannot bitcast the 64-bit float to a
21154             // 64-bit integer, since that's not a legal type. Since
21155             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
21156             // bits, but can do this little dance to extract the lowest 32 bits
21157             // and work with those going forward.
21158             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
21159                                            OnesOrZeroesF);
21160             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
21161                                            Vector64);
21162             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
21163                                         Vector32, DAG.getIntPtrConstant(0));
21164             IntVT = MVT::i32;
21165           }
21166
21167           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
21168           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
21169                                       DAG.getConstant(1, IntVT));
21170           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
21171           return OneBitOfTruth;
21172         }
21173       }
21174     }
21175   }
21176   return SDValue();
21177 }
21178
21179 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
21180 /// so it can be folded inside ANDNP.
21181 static bool CanFoldXORWithAllOnes(const SDNode *N) {
21182   EVT VT = N->getValueType(0);
21183
21184   // Match direct AllOnes for 128 and 256-bit vectors
21185   if (ISD::isBuildVectorAllOnes(N))
21186     return true;
21187
21188   // Look through a bit convert.
21189   if (N->getOpcode() == ISD::BITCAST)
21190     N = N->getOperand(0).getNode();
21191
21192   // Sometimes the operand may come from a insert_subvector building a 256-bit
21193   // allones vector
21194   if (VT.is256BitVector() &&
21195       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
21196     SDValue V1 = N->getOperand(0);
21197     SDValue V2 = N->getOperand(1);
21198
21199     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
21200         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
21201         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
21202         ISD::isBuildVectorAllOnes(V2.getNode()))
21203       return true;
21204   }
21205
21206   return false;
21207 }
21208
21209 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
21210 // register. In most cases we actually compare or select YMM-sized registers
21211 // and mixing the two types creates horrible code. This method optimizes
21212 // some of the transition sequences.
21213 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
21214                                  TargetLowering::DAGCombinerInfo &DCI,
21215                                  const X86Subtarget *Subtarget) {
21216   EVT VT = N->getValueType(0);
21217   if (!VT.is256BitVector())
21218     return SDValue();
21219
21220   assert((N->getOpcode() == ISD::ANY_EXTEND ||
21221           N->getOpcode() == ISD::ZERO_EXTEND ||
21222           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
21223
21224   SDValue Narrow = N->getOperand(0);
21225   EVT NarrowVT = Narrow->getValueType(0);
21226   if (!NarrowVT.is128BitVector())
21227     return SDValue();
21228
21229   if (Narrow->getOpcode() != ISD::XOR &&
21230       Narrow->getOpcode() != ISD::AND &&
21231       Narrow->getOpcode() != ISD::OR)
21232     return SDValue();
21233
21234   SDValue N0  = Narrow->getOperand(0);
21235   SDValue N1  = Narrow->getOperand(1);
21236   SDLoc DL(Narrow);
21237
21238   // The Left side has to be a trunc.
21239   if (N0.getOpcode() != ISD::TRUNCATE)
21240     return SDValue();
21241
21242   // The type of the truncated inputs.
21243   EVT WideVT = N0->getOperand(0)->getValueType(0);
21244   if (WideVT != VT)
21245     return SDValue();
21246
21247   // The right side has to be a 'trunc' or a constant vector.
21248   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
21249   ConstantSDNode *RHSConstSplat = nullptr;
21250   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
21251     RHSConstSplat = RHSBV->getConstantSplatNode();
21252   if (!RHSTrunc && !RHSConstSplat)
21253     return SDValue();
21254
21255   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21256
21257   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
21258     return SDValue();
21259
21260   // Set N0 and N1 to hold the inputs to the new wide operation.
21261   N0 = N0->getOperand(0);
21262   if (RHSConstSplat) {
21263     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
21264                      SDValue(RHSConstSplat, 0));
21265     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
21266     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
21267   } else if (RHSTrunc) {
21268     N1 = N1->getOperand(0);
21269   }
21270
21271   // Generate the wide operation.
21272   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
21273   unsigned Opcode = N->getOpcode();
21274   switch (Opcode) {
21275   case ISD::ANY_EXTEND:
21276     return Op;
21277   case ISD::ZERO_EXTEND: {
21278     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
21279     APInt Mask = APInt::getAllOnesValue(InBits);
21280     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
21281     return DAG.getNode(ISD::AND, DL, VT,
21282                        Op, DAG.getConstant(Mask, VT));
21283   }
21284   case ISD::SIGN_EXTEND:
21285     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
21286                        Op, DAG.getValueType(NarrowVT));
21287   default:
21288     llvm_unreachable("Unexpected opcode");
21289   }
21290 }
21291
21292 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
21293                                  TargetLowering::DAGCombinerInfo &DCI,
21294                                  const X86Subtarget *Subtarget) {
21295   EVT VT = N->getValueType(0);
21296   if (DCI.isBeforeLegalizeOps())
21297     return SDValue();
21298
21299   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21300   if (R.getNode())
21301     return R;
21302
21303   // Create BEXTR instructions
21304   // BEXTR is ((X >> imm) & (2**size-1))
21305   if (VT == MVT::i32 || VT == MVT::i64) {
21306     SDValue N0 = N->getOperand(0);
21307     SDValue N1 = N->getOperand(1);
21308     SDLoc DL(N);
21309
21310     // Check for BEXTR.
21311     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
21312         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
21313       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
21314       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21315       if (MaskNode && ShiftNode) {
21316         uint64_t Mask = MaskNode->getZExtValue();
21317         uint64_t Shift = ShiftNode->getZExtValue();
21318         if (isMask_64(Mask)) {
21319           uint64_t MaskSize = CountPopulation_64(Mask);
21320           if (Shift + MaskSize <= VT.getSizeInBits())
21321             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
21322                                DAG.getConstant(Shift | (MaskSize << 8), VT));
21323         }
21324       }
21325     } // BEXTR
21326
21327     return SDValue();
21328   }
21329
21330   // Want to form ANDNP nodes:
21331   // 1) In the hopes of then easily combining them with OR and AND nodes
21332   //    to form PBLEND/PSIGN.
21333   // 2) To match ANDN packed intrinsics
21334   if (VT != MVT::v2i64 && VT != MVT::v4i64)
21335     return SDValue();
21336
21337   SDValue N0 = N->getOperand(0);
21338   SDValue N1 = N->getOperand(1);
21339   SDLoc DL(N);
21340
21341   // Check LHS for vnot
21342   if (N0.getOpcode() == ISD::XOR &&
21343       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
21344       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
21345     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
21346
21347   // Check RHS for vnot
21348   if (N1.getOpcode() == ISD::XOR &&
21349       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
21350       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
21351     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
21352
21353   return SDValue();
21354 }
21355
21356 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
21357                                 TargetLowering::DAGCombinerInfo &DCI,
21358                                 const X86Subtarget *Subtarget) {
21359   if (DCI.isBeforeLegalizeOps())
21360     return SDValue();
21361
21362   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
21363   if (R.getNode())
21364     return R;
21365
21366   SDValue N0 = N->getOperand(0);
21367   SDValue N1 = N->getOperand(1);
21368   EVT VT = N->getValueType(0);
21369
21370   // look for psign/blend
21371   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
21372     if (!Subtarget->hasSSSE3() ||
21373         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
21374       return SDValue();
21375
21376     // Canonicalize pandn to RHS
21377     if (N0.getOpcode() == X86ISD::ANDNP)
21378       std::swap(N0, N1);
21379     // or (and (m, y), (pandn m, x))
21380     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
21381       SDValue Mask = N1.getOperand(0);
21382       SDValue X    = N1.getOperand(1);
21383       SDValue Y;
21384       if (N0.getOperand(0) == Mask)
21385         Y = N0.getOperand(1);
21386       if (N0.getOperand(1) == Mask)
21387         Y = N0.getOperand(0);
21388
21389       // Check to see if the mask appeared in both the AND and ANDNP and
21390       if (!Y.getNode())
21391         return SDValue();
21392
21393       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
21394       // Look through mask bitcast.
21395       if (Mask.getOpcode() == ISD::BITCAST)
21396         Mask = Mask.getOperand(0);
21397       if (X.getOpcode() == ISD::BITCAST)
21398         X = X.getOperand(0);
21399       if (Y.getOpcode() == ISD::BITCAST)
21400         Y = Y.getOperand(0);
21401
21402       EVT MaskVT = Mask.getValueType();
21403
21404       // Validate that the Mask operand is a vector sra node.
21405       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
21406       // there is no psrai.b
21407       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
21408       unsigned SraAmt = ~0;
21409       if (Mask.getOpcode() == ISD::SRA) {
21410         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
21411           if (auto *AmtConst = AmtBV->getConstantSplatNode())
21412             SraAmt = AmtConst->getZExtValue();
21413       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
21414         SDValue SraC = Mask.getOperand(1);
21415         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
21416       }
21417       if ((SraAmt + 1) != EltBits)
21418         return SDValue();
21419
21420       SDLoc DL(N);
21421
21422       // Now we know we at least have a plendvb with the mask val.  See if
21423       // we can form a psignb/w/d.
21424       // psign = x.type == y.type == mask.type && y = sub(0, x);
21425       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
21426           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
21427           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
21428         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
21429                "Unsupported VT for PSIGN");
21430         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
21431         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21432       }
21433       // PBLENDVB only available on SSE 4.1
21434       if (!Subtarget->hasSSE41())
21435         return SDValue();
21436
21437       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
21438
21439       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
21440       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
21441       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
21442       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
21443       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
21444     }
21445   }
21446
21447   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
21448     return SDValue();
21449
21450   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
21451   MachineFunction &MF = DAG.getMachineFunction();
21452   bool OptForSize = MF.getFunction()->getAttributes().
21453     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
21454
21455   // SHLD/SHRD instructions have lower register pressure, but on some
21456   // platforms they have higher latency than the equivalent
21457   // series of shifts/or that would otherwise be generated.
21458   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
21459   // have higher latencies and we are not optimizing for size.
21460   if (!OptForSize && Subtarget->isSHLDSlow())
21461     return SDValue();
21462
21463   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
21464     std::swap(N0, N1);
21465   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
21466     return SDValue();
21467   if (!N0.hasOneUse() || !N1.hasOneUse())
21468     return SDValue();
21469
21470   SDValue ShAmt0 = N0.getOperand(1);
21471   if (ShAmt0.getValueType() != MVT::i8)
21472     return SDValue();
21473   SDValue ShAmt1 = N1.getOperand(1);
21474   if (ShAmt1.getValueType() != MVT::i8)
21475     return SDValue();
21476   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
21477     ShAmt0 = ShAmt0.getOperand(0);
21478   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
21479     ShAmt1 = ShAmt1.getOperand(0);
21480
21481   SDLoc DL(N);
21482   unsigned Opc = X86ISD::SHLD;
21483   SDValue Op0 = N0.getOperand(0);
21484   SDValue Op1 = N1.getOperand(0);
21485   if (ShAmt0.getOpcode() == ISD::SUB) {
21486     Opc = X86ISD::SHRD;
21487     std::swap(Op0, Op1);
21488     std::swap(ShAmt0, ShAmt1);
21489   }
21490
21491   unsigned Bits = VT.getSizeInBits();
21492   if (ShAmt1.getOpcode() == ISD::SUB) {
21493     SDValue Sum = ShAmt1.getOperand(0);
21494     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
21495       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
21496       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
21497         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
21498       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
21499         return DAG.getNode(Opc, DL, VT,
21500                            Op0, Op1,
21501                            DAG.getNode(ISD::TRUNCATE, DL,
21502                                        MVT::i8, ShAmt0));
21503     }
21504   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
21505     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
21506     if (ShAmt0C &&
21507         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
21508       return DAG.getNode(Opc, DL, VT,
21509                          N0.getOperand(0), N1.getOperand(0),
21510                          DAG.getNode(ISD::TRUNCATE, DL,
21511                                        MVT::i8, ShAmt0));
21512   }
21513
21514   return SDValue();
21515 }
21516
21517 // Generate NEG and CMOV for integer abs.
21518 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
21519   EVT VT = N->getValueType(0);
21520
21521   // Since X86 does not have CMOV for 8-bit integer, we don't convert
21522   // 8-bit integer abs to NEG and CMOV.
21523   if (VT.isInteger() && VT.getSizeInBits() == 8)
21524     return SDValue();
21525
21526   SDValue N0 = N->getOperand(0);
21527   SDValue N1 = N->getOperand(1);
21528   SDLoc DL(N);
21529
21530   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
21531   // and change it to SUB and CMOV.
21532   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
21533       N0.getOpcode() == ISD::ADD &&
21534       N0.getOperand(1) == N1 &&
21535       N1.getOpcode() == ISD::SRA &&
21536       N1.getOperand(0) == N0.getOperand(0))
21537     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
21538       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
21539         // Generate SUB & CMOV.
21540         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
21541                                   DAG.getConstant(0, VT), N0.getOperand(0));
21542
21543         SDValue Ops[] = { N0.getOperand(0), Neg,
21544                           DAG.getConstant(X86::COND_GE, MVT::i8),
21545                           SDValue(Neg.getNode(), 1) };
21546         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
21547       }
21548   return SDValue();
21549 }
21550
21551 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
21552 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
21553                                  TargetLowering::DAGCombinerInfo &DCI,
21554                                  const X86Subtarget *Subtarget) {
21555   if (DCI.isBeforeLegalizeOps())
21556     return SDValue();
21557
21558   if (Subtarget->hasCMov()) {
21559     SDValue RV = performIntegerAbsCombine(N, DAG);
21560     if (RV.getNode())
21561       return RV;
21562   }
21563
21564   return SDValue();
21565 }
21566
21567 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
21568 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
21569                                   TargetLowering::DAGCombinerInfo &DCI,
21570                                   const X86Subtarget *Subtarget) {
21571   LoadSDNode *Ld = cast<LoadSDNode>(N);
21572   EVT RegVT = Ld->getValueType(0);
21573   EVT MemVT = Ld->getMemoryVT();
21574   SDLoc dl(Ld);
21575   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21576
21577   // On Sandybridge unaligned 256bit loads are inefficient.
21578   ISD::LoadExtType Ext = Ld->getExtensionType();
21579   unsigned Alignment = Ld->getAlignment();
21580   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
21581   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
21582       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
21583     unsigned NumElems = RegVT.getVectorNumElements();
21584     if (NumElems < 2)
21585       return SDValue();
21586
21587     SDValue Ptr = Ld->getBasePtr();
21588     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
21589
21590     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
21591                                   NumElems/2);
21592     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21593                                 Ld->getPointerInfo(), Ld->isVolatile(),
21594                                 Ld->isNonTemporal(), Ld->isInvariant(),
21595                                 Alignment);
21596     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21597     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
21598                                 Ld->getPointerInfo(), Ld->isVolatile(),
21599                                 Ld->isNonTemporal(), Ld->isInvariant(),
21600                                 std::min(16U, Alignment));
21601     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21602                              Load1.getValue(1),
21603                              Load2.getValue(1));
21604
21605     SDValue NewVec = DAG.getUNDEF(RegVT);
21606     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
21607     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
21608     return DCI.CombineTo(N, NewVec, TF, true);
21609   }
21610
21611   return SDValue();
21612 }
21613
21614 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
21615 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
21616                                    const X86Subtarget *Subtarget) {
21617   StoreSDNode *St = cast<StoreSDNode>(N);
21618   EVT VT = St->getValue().getValueType();
21619   EVT StVT = St->getMemoryVT();
21620   SDLoc dl(St);
21621   SDValue StoredVal = St->getOperand(1);
21622   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21623
21624   // If we are saving a concatenation of two XMM registers, perform two stores.
21625   // On Sandy Bridge, 256-bit memory operations are executed by two
21626   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
21627   // memory  operation.
21628   unsigned Alignment = St->getAlignment();
21629   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
21630   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
21631       StVT == VT && !IsAligned) {
21632     unsigned NumElems = VT.getVectorNumElements();
21633     if (NumElems < 2)
21634       return SDValue();
21635
21636     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
21637     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
21638
21639     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
21640     SDValue Ptr0 = St->getBasePtr();
21641     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
21642
21643     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
21644                                 St->getPointerInfo(), St->isVolatile(),
21645                                 St->isNonTemporal(), Alignment);
21646     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
21647                                 St->getPointerInfo(), St->isVolatile(),
21648                                 St->isNonTemporal(),
21649                                 std::min(16U, Alignment));
21650     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
21651   }
21652
21653   // Optimize trunc store (of multiple scalars) to shuffle and store.
21654   // First, pack all of the elements in one place. Next, store to memory
21655   // in fewer chunks.
21656   if (St->isTruncatingStore() && VT.isVector()) {
21657     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21658     unsigned NumElems = VT.getVectorNumElements();
21659     assert(StVT != VT && "Cannot truncate to the same type");
21660     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
21661     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
21662
21663     // From, To sizes and ElemCount must be pow of two
21664     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
21665     // We are going to use the original vector elt for storing.
21666     // Accumulated smaller vector elements must be a multiple of the store size.
21667     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21668
21669     unsigned SizeRatio  = FromSz / ToSz;
21670
21671     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21672
21673     // Create a type on which we perform the shuffle
21674     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21675             StVT.getScalarType(), NumElems*SizeRatio);
21676
21677     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21678
21679     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21680     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21681     for (unsigned i = 0; i != NumElems; ++i)
21682       ShuffleVec[i] = i * SizeRatio;
21683
21684     // Can't shuffle using an illegal type.
21685     if (!TLI.isTypeLegal(WideVecVT))
21686       return SDValue();
21687
21688     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21689                                          DAG.getUNDEF(WideVecVT),
21690                                          &ShuffleVec[0]);
21691     // At this point all of the data is stored at the bottom of the
21692     // register. We now need to save it to mem.
21693
21694     // Find the largest store unit
21695     MVT StoreType = MVT::i8;
21696     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21697          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21698       MVT Tp = (MVT::SimpleValueType)tp;
21699       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21700         StoreType = Tp;
21701     }
21702
21703     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21704     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21705         (64 <= NumElems * ToSz))
21706       StoreType = MVT::f64;
21707
21708     // Bitcast the original vector into a vector of store-size units
21709     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21710             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21711     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21712     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21713     SmallVector<SDValue, 8> Chains;
21714     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21715                                         TLI.getPointerTy());
21716     SDValue Ptr = St->getBasePtr();
21717
21718     // Perform one or more big stores into memory.
21719     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21720       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21721                                    StoreType, ShuffWide,
21722                                    DAG.getIntPtrConstant(i));
21723       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21724                                 St->getPointerInfo(), St->isVolatile(),
21725                                 St->isNonTemporal(), St->getAlignment());
21726       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21727       Chains.push_back(Ch);
21728     }
21729
21730     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21731   }
21732
21733   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21734   // the FP state in cases where an emms may be missing.
21735   // A preferable solution to the general problem is to figure out the right
21736   // places to insert EMMS.  This qualifies as a quick hack.
21737
21738   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21739   if (VT.getSizeInBits() != 64)
21740     return SDValue();
21741
21742   const Function *F = DAG.getMachineFunction().getFunction();
21743   bool NoImplicitFloatOps = F->getAttributes().
21744     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21745   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21746                      && Subtarget->hasSSE2();
21747   if ((VT.isVector() ||
21748        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21749       isa<LoadSDNode>(St->getValue()) &&
21750       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21751       St->getChain().hasOneUse() && !St->isVolatile()) {
21752     SDNode* LdVal = St->getValue().getNode();
21753     LoadSDNode *Ld = nullptr;
21754     int TokenFactorIndex = -1;
21755     SmallVector<SDValue, 8> Ops;
21756     SDNode* ChainVal = St->getChain().getNode();
21757     // Must be a store of a load.  We currently handle two cases:  the load
21758     // is a direct child, and it's under an intervening TokenFactor.  It is
21759     // possible to dig deeper under nested TokenFactors.
21760     if (ChainVal == LdVal)
21761       Ld = cast<LoadSDNode>(St->getChain());
21762     else if (St->getValue().hasOneUse() &&
21763              ChainVal->getOpcode() == ISD::TokenFactor) {
21764       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21765         if (ChainVal->getOperand(i).getNode() == LdVal) {
21766           TokenFactorIndex = i;
21767           Ld = cast<LoadSDNode>(St->getValue());
21768         } else
21769           Ops.push_back(ChainVal->getOperand(i));
21770       }
21771     }
21772
21773     if (!Ld || !ISD::isNormalLoad(Ld))
21774       return SDValue();
21775
21776     // If this is not the MMX case, i.e. we are just turning i64 load/store
21777     // into f64 load/store, avoid the transformation if there are multiple
21778     // uses of the loaded value.
21779     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21780       return SDValue();
21781
21782     SDLoc LdDL(Ld);
21783     SDLoc StDL(N);
21784     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21785     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21786     // pair instead.
21787     if (Subtarget->is64Bit() || F64IsLegal) {
21788       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21789       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21790                                   Ld->getPointerInfo(), Ld->isVolatile(),
21791                                   Ld->isNonTemporal(), Ld->isInvariant(),
21792                                   Ld->getAlignment());
21793       SDValue NewChain = NewLd.getValue(1);
21794       if (TokenFactorIndex != -1) {
21795         Ops.push_back(NewChain);
21796         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21797       }
21798       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21799                           St->getPointerInfo(),
21800                           St->isVolatile(), St->isNonTemporal(),
21801                           St->getAlignment());
21802     }
21803
21804     // Otherwise, lower to two pairs of 32-bit loads / stores.
21805     SDValue LoAddr = Ld->getBasePtr();
21806     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21807                                  DAG.getConstant(4, MVT::i32));
21808
21809     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21810                                Ld->getPointerInfo(),
21811                                Ld->isVolatile(), Ld->isNonTemporal(),
21812                                Ld->isInvariant(), Ld->getAlignment());
21813     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21814                                Ld->getPointerInfo().getWithOffset(4),
21815                                Ld->isVolatile(), Ld->isNonTemporal(),
21816                                Ld->isInvariant(),
21817                                MinAlign(Ld->getAlignment(), 4));
21818
21819     SDValue NewChain = LoLd.getValue(1);
21820     if (TokenFactorIndex != -1) {
21821       Ops.push_back(LoLd);
21822       Ops.push_back(HiLd);
21823       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21824     }
21825
21826     LoAddr = St->getBasePtr();
21827     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21828                          DAG.getConstant(4, MVT::i32));
21829
21830     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21831                                 St->getPointerInfo(),
21832                                 St->isVolatile(), St->isNonTemporal(),
21833                                 St->getAlignment());
21834     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21835                                 St->getPointerInfo().getWithOffset(4),
21836                                 St->isVolatile(),
21837                                 St->isNonTemporal(),
21838                                 MinAlign(St->getAlignment(), 4));
21839     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21840   }
21841   return SDValue();
21842 }
21843
21844 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21845 /// and return the operands for the horizontal operation in LHS and RHS.  A
21846 /// horizontal operation performs the binary operation on successive elements
21847 /// of its first operand, then on successive elements of its second operand,
21848 /// returning the resulting values in a vector.  For example, if
21849 ///   A = < float a0, float a1, float a2, float a3 >
21850 /// and
21851 ///   B = < float b0, float b1, float b2, float b3 >
21852 /// then the result of doing a horizontal operation on A and B is
21853 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21854 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21855 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21856 /// set to A, RHS to B, and the routine returns 'true'.
21857 /// Note that the binary operation should have the property that if one of the
21858 /// operands is UNDEF then the result is UNDEF.
21859 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21860   // Look for the following pattern: if
21861   //   A = < float a0, float a1, float a2, float a3 >
21862   //   B = < float b0, float b1, float b2, float b3 >
21863   // and
21864   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21865   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21866   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21867   // which is A horizontal-op B.
21868
21869   // At least one of the operands should be a vector shuffle.
21870   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21871       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21872     return false;
21873
21874   MVT VT = LHS.getSimpleValueType();
21875
21876   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21877          "Unsupported vector type for horizontal add/sub");
21878
21879   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21880   // operate independently on 128-bit lanes.
21881   unsigned NumElts = VT.getVectorNumElements();
21882   unsigned NumLanes = VT.getSizeInBits()/128;
21883   unsigned NumLaneElts = NumElts / NumLanes;
21884   assert((NumLaneElts % 2 == 0) &&
21885          "Vector type should have an even number of elements in each lane");
21886   unsigned HalfLaneElts = NumLaneElts/2;
21887
21888   // View LHS in the form
21889   //   LHS = VECTOR_SHUFFLE A, B, LMask
21890   // If LHS is not a shuffle then pretend it is the shuffle
21891   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21892   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21893   // type VT.
21894   SDValue A, B;
21895   SmallVector<int, 16> LMask(NumElts);
21896   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21897     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21898       A = LHS.getOperand(0);
21899     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21900       B = LHS.getOperand(1);
21901     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21902     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21903   } else {
21904     if (LHS.getOpcode() != ISD::UNDEF)
21905       A = LHS;
21906     for (unsigned i = 0; i != NumElts; ++i)
21907       LMask[i] = i;
21908   }
21909
21910   // Likewise, view RHS in the form
21911   //   RHS = VECTOR_SHUFFLE C, D, RMask
21912   SDValue C, D;
21913   SmallVector<int, 16> RMask(NumElts);
21914   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21915     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21916       C = RHS.getOperand(0);
21917     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21918       D = RHS.getOperand(1);
21919     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21920     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21921   } else {
21922     if (RHS.getOpcode() != ISD::UNDEF)
21923       C = RHS;
21924     for (unsigned i = 0; i != NumElts; ++i)
21925       RMask[i] = i;
21926   }
21927
21928   // Check that the shuffles are both shuffling the same vectors.
21929   if (!(A == C && B == D) && !(A == D && B == C))
21930     return false;
21931
21932   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21933   if (!A.getNode() && !B.getNode())
21934     return false;
21935
21936   // If A and B occur in reverse order in RHS, then "swap" them (which means
21937   // rewriting the mask).
21938   if (A != C)
21939     CommuteVectorShuffleMask(RMask, NumElts);
21940
21941   // At this point LHS and RHS are equivalent to
21942   //   LHS = VECTOR_SHUFFLE A, B, LMask
21943   //   RHS = VECTOR_SHUFFLE A, B, RMask
21944   // Check that the masks correspond to performing a horizontal operation.
21945   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21946     for (unsigned i = 0; i != NumLaneElts; ++i) {
21947       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21948
21949       // Ignore any UNDEF components.
21950       if (LIdx < 0 || RIdx < 0 ||
21951           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21952           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21953         continue;
21954
21955       // Check that successive elements are being operated on.  If not, this is
21956       // not a horizontal operation.
21957       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21958       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21959       if (!(LIdx == Index && RIdx == Index + 1) &&
21960           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21961         return false;
21962     }
21963   }
21964
21965   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21966   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21967   return true;
21968 }
21969
21970 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21971 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21972                                   const X86Subtarget *Subtarget) {
21973   EVT VT = N->getValueType(0);
21974   SDValue LHS = N->getOperand(0);
21975   SDValue RHS = N->getOperand(1);
21976
21977   // Try to synthesize horizontal adds from adds of shuffles.
21978   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21979        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21980       isHorizontalBinOp(LHS, RHS, true))
21981     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21982   return SDValue();
21983 }
21984
21985 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21986 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21987                                   const X86Subtarget *Subtarget) {
21988   EVT VT = N->getValueType(0);
21989   SDValue LHS = N->getOperand(0);
21990   SDValue RHS = N->getOperand(1);
21991
21992   // Try to synthesize horizontal subs from subs of shuffles.
21993   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21994        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21995       isHorizontalBinOp(LHS, RHS, false))
21996     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21997   return SDValue();
21998 }
21999
22000 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
22001 /// X86ISD::FXOR nodes.
22002 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
22003   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
22004   // F[X]OR(0.0, x) -> x
22005   // F[X]OR(x, 0.0) -> x
22006   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22007     if (C->getValueAPF().isPosZero())
22008       return N->getOperand(1);
22009   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22010     if (C->getValueAPF().isPosZero())
22011       return N->getOperand(0);
22012   return SDValue();
22013 }
22014
22015 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
22016 /// X86ISD::FMAX nodes.
22017 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
22018   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
22019
22020   // Only perform optimizations if UnsafeMath is used.
22021   if (!DAG.getTarget().Options.UnsafeFPMath)
22022     return SDValue();
22023
22024   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
22025   // into FMINC and FMAXC, which are Commutative operations.
22026   unsigned NewOp = 0;
22027   switch (N->getOpcode()) {
22028     default: llvm_unreachable("unknown opcode");
22029     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
22030     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
22031   }
22032
22033   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
22034                      N->getOperand(0), N->getOperand(1));
22035 }
22036
22037 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
22038 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
22039   // FAND(0.0, x) -> 0.0
22040   // FAND(x, 0.0) -> 0.0
22041   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22042     if (C->getValueAPF().isPosZero())
22043       return N->getOperand(0);
22044   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22045     if (C->getValueAPF().isPosZero())
22046       return N->getOperand(1);
22047   return SDValue();
22048 }
22049
22050 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
22051 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
22052   // FANDN(x, 0.0) -> 0.0
22053   // FANDN(0.0, x) -> x
22054   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
22055     if (C->getValueAPF().isPosZero())
22056       return N->getOperand(1);
22057   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
22058     if (C->getValueAPF().isPosZero())
22059       return N->getOperand(1);
22060   return SDValue();
22061 }
22062
22063 static SDValue PerformBTCombine(SDNode *N,
22064                                 SelectionDAG &DAG,
22065                                 TargetLowering::DAGCombinerInfo &DCI) {
22066   // BT ignores high bits in the bit index operand.
22067   SDValue Op1 = N->getOperand(1);
22068   if (Op1.hasOneUse()) {
22069     unsigned BitWidth = Op1.getValueSizeInBits();
22070     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
22071     APInt KnownZero, KnownOne;
22072     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
22073                                           !DCI.isBeforeLegalizeOps());
22074     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22075     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
22076         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
22077       DCI.CommitTargetLoweringOpt(TLO);
22078   }
22079   return SDValue();
22080 }
22081
22082 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
22083   SDValue Op = N->getOperand(0);
22084   if (Op.getOpcode() == ISD::BITCAST)
22085     Op = Op.getOperand(0);
22086   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
22087   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
22088       VT.getVectorElementType().getSizeInBits() ==
22089       OpVT.getVectorElementType().getSizeInBits()) {
22090     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
22091   }
22092   return SDValue();
22093 }
22094
22095 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
22096                                                const X86Subtarget *Subtarget) {
22097   EVT VT = N->getValueType(0);
22098   if (!VT.isVector())
22099     return SDValue();
22100
22101   SDValue N0 = N->getOperand(0);
22102   SDValue N1 = N->getOperand(1);
22103   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
22104   SDLoc dl(N);
22105
22106   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
22107   // both SSE and AVX2 since there is no sign-extended shift right
22108   // operation on a vector with 64-bit elements.
22109   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
22110   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
22111   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
22112       N0.getOpcode() == ISD::SIGN_EXTEND)) {
22113     SDValue N00 = N0.getOperand(0);
22114
22115     // EXTLOAD has a better solution on AVX2,
22116     // it may be replaced with X86ISD::VSEXT node.
22117     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
22118       if (!ISD::isNormalLoad(N00.getNode()))
22119         return SDValue();
22120
22121     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
22122         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
22123                                   N00, N1);
22124       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
22125     }
22126   }
22127   return SDValue();
22128 }
22129
22130 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
22131                                   TargetLowering::DAGCombinerInfo &DCI,
22132                                   const X86Subtarget *Subtarget) {
22133   if (!DCI.isBeforeLegalizeOps())
22134     return SDValue();
22135
22136   if (!Subtarget->hasFp256())
22137     return SDValue();
22138
22139   EVT VT = N->getValueType(0);
22140   if (VT.isVector() && VT.getSizeInBits() == 256) {
22141     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22142     if (R.getNode())
22143       return R;
22144   }
22145
22146   return SDValue();
22147 }
22148
22149 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
22150                                  const X86Subtarget* Subtarget) {
22151   SDLoc dl(N);
22152   EVT VT = N->getValueType(0);
22153
22154   // Let legalize expand this if it isn't a legal type yet.
22155   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
22156     return SDValue();
22157
22158   EVT ScalarVT = VT.getScalarType();
22159   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
22160       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
22161     return SDValue();
22162
22163   SDValue A = N->getOperand(0);
22164   SDValue B = N->getOperand(1);
22165   SDValue C = N->getOperand(2);
22166
22167   bool NegA = (A.getOpcode() == ISD::FNEG);
22168   bool NegB = (B.getOpcode() == ISD::FNEG);
22169   bool NegC = (C.getOpcode() == ISD::FNEG);
22170
22171   // Negative multiplication when NegA xor NegB
22172   bool NegMul = (NegA != NegB);
22173   if (NegA)
22174     A = A.getOperand(0);
22175   if (NegB)
22176     B = B.getOperand(0);
22177   if (NegC)
22178     C = C.getOperand(0);
22179
22180   unsigned Opcode;
22181   if (!NegMul)
22182     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
22183   else
22184     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
22185
22186   return DAG.getNode(Opcode, dl, VT, A, B, C);
22187 }
22188
22189 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
22190                                   TargetLowering::DAGCombinerInfo &DCI,
22191                                   const X86Subtarget *Subtarget) {
22192   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
22193   //           (and (i32 x86isd::setcc_carry), 1)
22194   // This eliminates the zext. This transformation is necessary because
22195   // ISD::SETCC is always legalized to i8.
22196   SDLoc dl(N);
22197   SDValue N0 = N->getOperand(0);
22198   EVT VT = N->getValueType(0);
22199
22200   if (N0.getOpcode() == ISD::AND &&
22201       N0.hasOneUse() &&
22202       N0.getOperand(0).hasOneUse()) {
22203     SDValue N00 = N0.getOperand(0);
22204     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22205       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
22206       if (!C || C->getZExtValue() != 1)
22207         return SDValue();
22208       return DAG.getNode(ISD::AND, dl, VT,
22209                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22210                                      N00.getOperand(0), N00.getOperand(1)),
22211                          DAG.getConstant(1, VT));
22212     }
22213   }
22214
22215   if (N0.getOpcode() == ISD::TRUNCATE &&
22216       N0.hasOneUse() &&
22217       N0.getOperand(0).hasOneUse()) {
22218     SDValue N00 = N0.getOperand(0);
22219     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
22220       return DAG.getNode(ISD::AND, dl, VT,
22221                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
22222                                      N00.getOperand(0), N00.getOperand(1)),
22223                          DAG.getConstant(1, VT));
22224     }
22225   }
22226   if (VT.is256BitVector()) {
22227     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
22228     if (R.getNode())
22229       return R;
22230   }
22231
22232   return SDValue();
22233 }
22234
22235 // Optimize x == -y --> x+y == 0
22236 //          x != -y --> x+y != 0
22237 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
22238                                       const X86Subtarget* Subtarget) {
22239   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
22240   SDValue LHS = N->getOperand(0);
22241   SDValue RHS = N->getOperand(1);
22242   EVT VT = N->getValueType(0);
22243   SDLoc DL(N);
22244
22245   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
22246     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
22247       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
22248         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22249                                    LHS.getValueType(), RHS, LHS.getOperand(1));
22250         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22251                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22252       }
22253   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
22254     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
22255       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
22256         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
22257                                    RHS.getValueType(), LHS, RHS.getOperand(1));
22258         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
22259                             addV, DAG.getConstant(0, addV.getValueType()), CC);
22260       }
22261
22262   if (VT.getScalarType() == MVT::i1) {
22263     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
22264       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22265     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
22266     if (!IsSEXT0 && !IsVZero0)
22267       return SDValue();
22268     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
22269       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
22270     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
22271
22272     if (!IsSEXT1 && !IsVZero1)
22273       return SDValue();
22274
22275     if (IsSEXT0 && IsVZero1) {
22276       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
22277       if (CC == ISD::SETEQ)
22278         return DAG.getNOT(DL, LHS.getOperand(0), VT);
22279       return LHS.getOperand(0);
22280     }
22281     if (IsSEXT1 && IsVZero0) {
22282       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
22283       if (CC == ISD::SETEQ)
22284         return DAG.getNOT(DL, RHS.getOperand(0), VT);
22285       return RHS.getOperand(0);
22286     }
22287   }
22288
22289   return SDValue();
22290 }
22291
22292 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
22293                                       const X86Subtarget *Subtarget) {
22294   SDLoc dl(N);
22295   MVT VT = N->getOperand(1)->getSimpleValueType(0);
22296   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
22297          "X86insertps is only defined for v4x32");
22298
22299   SDValue Ld = N->getOperand(1);
22300   if (MayFoldLoad(Ld)) {
22301     // Extract the countS bits from the immediate so we can get the proper
22302     // address when narrowing the vector load to a specific element.
22303     // When the second source op is a memory address, interps doesn't use
22304     // countS and just gets an f32 from that address.
22305     unsigned DestIndex =
22306         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
22307     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
22308   } else
22309     return SDValue();
22310
22311   // Create this as a scalar to vector to match the instruction pattern.
22312   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
22313   // countS bits are ignored when loading from memory on insertps, which
22314   // means we don't need to explicitly set them to 0.
22315   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
22316                      LoadScalarToVector, N->getOperand(2));
22317 }
22318
22319 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
22320 // as "sbb reg,reg", since it can be extended without zext and produces
22321 // an all-ones bit which is more useful than 0/1 in some cases.
22322 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
22323                                MVT VT) {
22324   if (VT == MVT::i8)
22325     return DAG.getNode(ISD::AND, DL, VT,
22326                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22327                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
22328                        DAG.getConstant(1, VT));
22329   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
22330   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
22331                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
22332                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
22333 }
22334
22335 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
22336 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
22337                                    TargetLowering::DAGCombinerInfo &DCI,
22338                                    const X86Subtarget *Subtarget) {
22339   SDLoc DL(N);
22340   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
22341   SDValue EFLAGS = N->getOperand(1);
22342
22343   if (CC == X86::COND_A) {
22344     // Try to convert COND_A into COND_B in an attempt to facilitate
22345     // materializing "setb reg".
22346     //
22347     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
22348     // cannot take an immediate as its first operand.
22349     //
22350     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
22351         EFLAGS.getValueType().isInteger() &&
22352         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
22353       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
22354                                    EFLAGS.getNode()->getVTList(),
22355                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
22356       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
22357       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
22358     }
22359   }
22360
22361   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
22362   // a zext and produces an all-ones bit which is more useful than 0/1 in some
22363   // cases.
22364   if (CC == X86::COND_B)
22365     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
22366
22367   SDValue Flags;
22368
22369   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22370   if (Flags.getNode()) {
22371     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22372     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
22373   }
22374
22375   return SDValue();
22376 }
22377
22378 // Optimize branch condition evaluation.
22379 //
22380 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
22381                                     TargetLowering::DAGCombinerInfo &DCI,
22382                                     const X86Subtarget *Subtarget) {
22383   SDLoc DL(N);
22384   SDValue Chain = N->getOperand(0);
22385   SDValue Dest = N->getOperand(1);
22386   SDValue EFLAGS = N->getOperand(3);
22387   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
22388
22389   SDValue Flags;
22390
22391   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
22392   if (Flags.getNode()) {
22393     SDValue Cond = DAG.getConstant(CC, MVT::i8);
22394     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
22395                        Flags);
22396   }
22397
22398   return SDValue();
22399 }
22400
22401 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
22402                                                          SelectionDAG &DAG) {
22403   // Take advantage of vector comparisons producing 0 or -1 in each lane to
22404   // optimize away operation when it's from a constant.
22405   //
22406   // The general transformation is:
22407   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
22408   //       AND(VECTOR_CMP(x,y), constant2)
22409   //    constant2 = UNARYOP(constant)
22410
22411   // Early exit if this isn't a vector operation, the operand of the
22412   // unary operation isn't a bitwise AND, or if the sizes of the operations
22413   // aren't the same.
22414   EVT VT = N->getValueType(0);
22415   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
22416       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
22417       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
22418     return SDValue();
22419
22420   // Now check that the other operand of the AND is a constant. We could
22421   // make the transformation for non-constant splats as well, but it's unclear
22422   // that would be a benefit as it would not eliminate any operations, just
22423   // perform one more step in scalar code before moving to the vector unit.
22424   if (BuildVectorSDNode *BV =
22425           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
22426     // Bail out if the vector isn't a constant.
22427     if (!BV->isConstant())
22428       return SDValue();
22429
22430     // Everything checks out. Build up the new and improved node.
22431     SDLoc DL(N);
22432     EVT IntVT = BV->getValueType(0);
22433     // Create a new constant of the appropriate type for the transformed
22434     // DAG.
22435     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
22436     // The AND node needs bitcasts to/from an integer vector type around it.
22437     SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
22438     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
22439                                  N->getOperand(0)->getOperand(0), MaskConst);
22440     SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
22441     return Res;
22442   }
22443
22444   return SDValue();
22445 }
22446
22447 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
22448                                         const X86TargetLowering *XTLI) {
22449   // First try to optimize away the conversion entirely when it's
22450   // conditionally from a constant. Vectors only.
22451   SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG);
22452   if (Res != SDValue())
22453     return Res;
22454
22455   // Now move on to more general possibilities.
22456   SDValue Op0 = N->getOperand(0);
22457   EVT InVT = Op0->getValueType(0);
22458
22459   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
22460   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
22461     SDLoc dl(N);
22462     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
22463     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
22464     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
22465   }
22466
22467   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
22468   // a 32-bit target where SSE doesn't support i64->FP operations.
22469   if (Op0.getOpcode() == ISD::LOAD) {
22470     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
22471     EVT VT = Ld->getValueType(0);
22472     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
22473         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
22474         !XTLI->getSubtarget()->is64Bit() &&
22475         VT == MVT::i64) {
22476       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
22477                                           Ld->getChain(), Op0, DAG);
22478       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
22479       return FILDChain;
22480     }
22481   }
22482   return SDValue();
22483 }
22484
22485 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
22486 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
22487                                  X86TargetLowering::DAGCombinerInfo &DCI) {
22488   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
22489   // the result is either zero or one (depending on the input carry bit).
22490   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
22491   if (X86::isZeroNode(N->getOperand(0)) &&
22492       X86::isZeroNode(N->getOperand(1)) &&
22493       // We don't have a good way to replace an EFLAGS use, so only do this when
22494       // dead right now.
22495       SDValue(N, 1).use_empty()) {
22496     SDLoc DL(N);
22497     EVT VT = N->getValueType(0);
22498     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
22499     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
22500                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
22501                                            DAG.getConstant(X86::COND_B,MVT::i8),
22502                                            N->getOperand(2)),
22503                                DAG.getConstant(1, VT));
22504     return DCI.CombineTo(N, Res1, CarryOut);
22505   }
22506
22507   return SDValue();
22508 }
22509
22510 // fold (add Y, (sete  X, 0)) -> adc  0, Y
22511 //      (add Y, (setne X, 0)) -> sbb -1, Y
22512 //      (sub (sete  X, 0), Y) -> sbb  0, Y
22513 //      (sub (setne X, 0), Y) -> adc -1, Y
22514 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
22515   SDLoc DL(N);
22516
22517   // Look through ZExts.
22518   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
22519   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
22520     return SDValue();
22521
22522   SDValue SetCC = Ext.getOperand(0);
22523   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
22524     return SDValue();
22525
22526   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
22527   if (CC != X86::COND_E && CC != X86::COND_NE)
22528     return SDValue();
22529
22530   SDValue Cmp = SetCC.getOperand(1);
22531   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
22532       !X86::isZeroNode(Cmp.getOperand(1)) ||
22533       !Cmp.getOperand(0).getValueType().isInteger())
22534     return SDValue();
22535
22536   SDValue CmpOp0 = Cmp.getOperand(0);
22537   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
22538                                DAG.getConstant(1, CmpOp0.getValueType()));
22539
22540   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
22541   if (CC == X86::COND_NE)
22542     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
22543                        DL, OtherVal.getValueType(), OtherVal,
22544                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
22545   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
22546                      DL, OtherVal.getValueType(), OtherVal,
22547                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
22548 }
22549
22550 /// PerformADDCombine - Do target-specific dag combines on integer adds.
22551 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
22552                                  const X86Subtarget *Subtarget) {
22553   EVT VT = N->getValueType(0);
22554   SDValue Op0 = N->getOperand(0);
22555   SDValue Op1 = N->getOperand(1);
22556
22557   // Try to synthesize horizontal adds from adds of shuffles.
22558   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22559        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22560       isHorizontalBinOp(Op0, Op1, true))
22561     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
22562
22563   return OptimizeConditionalInDecrement(N, DAG);
22564 }
22565
22566 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
22567                                  const X86Subtarget *Subtarget) {
22568   SDValue Op0 = N->getOperand(0);
22569   SDValue Op1 = N->getOperand(1);
22570
22571   // X86 can't encode an immediate LHS of a sub. See if we can push the
22572   // negation into a preceding instruction.
22573   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
22574     // If the RHS of the sub is a XOR with one use and a constant, invert the
22575     // immediate. Then add one to the LHS of the sub so we can turn
22576     // X-Y -> X+~Y+1, saving one register.
22577     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
22578         isa<ConstantSDNode>(Op1.getOperand(1))) {
22579       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
22580       EVT VT = Op0.getValueType();
22581       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
22582                                    Op1.getOperand(0),
22583                                    DAG.getConstant(~XorC, VT));
22584       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
22585                          DAG.getConstant(C->getAPIntValue()+1, VT));
22586     }
22587   }
22588
22589   // Try to synthesize horizontal adds from adds of shuffles.
22590   EVT VT = N->getValueType(0);
22591   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
22592        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
22593       isHorizontalBinOp(Op0, Op1, true))
22594     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
22595
22596   return OptimizeConditionalInDecrement(N, DAG);
22597 }
22598
22599 /// performVZEXTCombine - Performs build vector combines
22600 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
22601                                         TargetLowering::DAGCombinerInfo &DCI,
22602                                         const X86Subtarget *Subtarget) {
22603   // (vzext (bitcast (vzext (x)) -> (vzext x)
22604   SDValue In = N->getOperand(0);
22605   while (In.getOpcode() == ISD::BITCAST)
22606     In = In.getOperand(0);
22607
22608   if (In.getOpcode() != X86ISD::VZEXT)
22609     return SDValue();
22610
22611   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
22612                      In.getOperand(0));
22613 }
22614
22615 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
22616                                              DAGCombinerInfo &DCI) const {
22617   SelectionDAG &DAG = DCI.DAG;
22618   switch (N->getOpcode()) {
22619   default: break;
22620   case ISD::EXTRACT_VECTOR_ELT:
22621     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
22622   case ISD::VSELECT:
22623   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
22624   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
22625   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
22626   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
22627   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
22628   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
22629   case ISD::SHL:
22630   case ISD::SRA:
22631   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
22632   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
22633   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
22634   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
22635   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
22636   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
22637   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
22638   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
22639   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
22640   case X86ISD::FXOR:
22641   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
22642   case X86ISD::FMIN:
22643   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
22644   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
22645   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
22646   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
22647   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
22648   case ISD::ANY_EXTEND:
22649   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
22650   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
22651   case ISD::SIGN_EXTEND_INREG:
22652     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
22653   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
22654   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
22655   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
22656   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
22657   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
22658   case X86ISD::SHUFP:       // Handle all target specific shuffles
22659   case X86ISD::PALIGNR:
22660   case X86ISD::UNPCKH:
22661   case X86ISD::UNPCKL:
22662   case X86ISD::MOVHLPS:
22663   case X86ISD::MOVLHPS:
22664   case X86ISD::PSHUFB:
22665   case X86ISD::PSHUFD:
22666   case X86ISD::PSHUFHW:
22667   case X86ISD::PSHUFLW:
22668   case X86ISD::MOVSS:
22669   case X86ISD::MOVSD:
22670   case X86ISD::VPERMILP:
22671   case X86ISD::VPERM2X128:
22672   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
22673   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
22674   case ISD::INTRINSIC_WO_CHAIN:
22675     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
22676   case X86ISD::INSERTPS:
22677     return PerformINSERTPSCombine(N, DAG, Subtarget);
22678   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
22679   }
22680
22681   return SDValue();
22682 }
22683
22684 /// isTypeDesirableForOp - Return true if the target has native support for
22685 /// the specified value type and it is 'desirable' to use the type for the
22686 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
22687 /// instruction encodings are longer and some i16 instructions are slow.
22688 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
22689   if (!isTypeLegal(VT))
22690     return false;
22691   if (VT != MVT::i16)
22692     return true;
22693
22694   switch (Opc) {
22695   default:
22696     return true;
22697   case ISD::LOAD:
22698   case ISD::SIGN_EXTEND:
22699   case ISD::ZERO_EXTEND:
22700   case ISD::ANY_EXTEND:
22701   case ISD::SHL:
22702   case ISD::SRL:
22703   case ISD::SUB:
22704   case ISD::ADD:
22705   case ISD::MUL:
22706   case ISD::AND:
22707   case ISD::OR:
22708   case ISD::XOR:
22709     return false;
22710   }
22711 }
22712
22713 /// IsDesirableToPromoteOp - This method query the target whether it is
22714 /// beneficial for dag combiner to promote the specified node. If true, it
22715 /// should return the desired promotion type by reference.
22716 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
22717   EVT VT = Op.getValueType();
22718   if (VT != MVT::i16)
22719     return false;
22720
22721   bool Promote = false;
22722   bool Commute = false;
22723   switch (Op.getOpcode()) {
22724   default: break;
22725   case ISD::LOAD: {
22726     LoadSDNode *LD = cast<LoadSDNode>(Op);
22727     // If the non-extending load has a single use and it's not live out, then it
22728     // might be folded.
22729     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22730                                                      Op.hasOneUse()*/) {
22731       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22732              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22733         // The only case where we'd want to promote LOAD (rather then it being
22734         // promoted as an operand is when it's only use is liveout.
22735         if (UI->getOpcode() != ISD::CopyToReg)
22736           return false;
22737       }
22738     }
22739     Promote = true;
22740     break;
22741   }
22742   case ISD::SIGN_EXTEND:
22743   case ISD::ZERO_EXTEND:
22744   case ISD::ANY_EXTEND:
22745     Promote = true;
22746     break;
22747   case ISD::SHL:
22748   case ISD::SRL: {
22749     SDValue N0 = Op.getOperand(0);
22750     // Look out for (store (shl (load), x)).
22751     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22752       return false;
22753     Promote = true;
22754     break;
22755   }
22756   case ISD::ADD:
22757   case ISD::MUL:
22758   case ISD::AND:
22759   case ISD::OR:
22760   case ISD::XOR:
22761     Commute = true;
22762     // fallthrough
22763   case ISD::SUB: {
22764     SDValue N0 = Op.getOperand(0);
22765     SDValue N1 = Op.getOperand(1);
22766     if (!Commute && MayFoldLoad(N1))
22767       return false;
22768     // Avoid disabling potential load folding opportunities.
22769     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22770       return false;
22771     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22772       return false;
22773     Promote = true;
22774   }
22775   }
22776
22777   PVT = MVT::i32;
22778   return Promote;
22779 }
22780
22781 //===----------------------------------------------------------------------===//
22782 //                           X86 Inline Assembly Support
22783 //===----------------------------------------------------------------------===//
22784
22785 namespace {
22786   // Helper to match a string separated by whitespace.
22787   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22788     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22789
22790     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22791       StringRef piece(*args[i]);
22792       if (!s.startswith(piece)) // Check if the piece matches.
22793         return false;
22794
22795       s = s.substr(piece.size());
22796       StringRef::size_type pos = s.find_first_not_of(" \t");
22797       if (pos == 0) // We matched a prefix.
22798         return false;
22799
22800       s = s.substr(pos);
22801     }
22802
22803     return s.empty();
22804   }
22805   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22806 }
22807
22808 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22809
22810   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22811     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22812         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22813         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22814
22815       if (AsmPieces.size() == 3)
22816         return true;
22817       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22818         return true;
22819     }
22820   }
22821   return false;
22822 }
22823
22824 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22825   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22826
22827   std::string AsmStr = IA->getAsmString();
22828
22829   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22830   if (!Ty || Ty->getBitWidth() % 16 != 0)
22831     return false;
22832
22833   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22834   SmallVector<StringRef, 4> AsmPieces;
22835   SplitString(AsmStr, AsmPieces, ";\n");
22836
22837   switch (AsmPieces.size()) {
22838   default: return false;
22839   case 1:
22840     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22841     // we will turn this bswap into something that will be lowered to logical
22842     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22843     // lower so don't worry about this.
22844     // bswap $0
22845     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22846         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22847         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22848         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22849         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22850         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22851       // No need to check constraints, nothing other than the equivalent of
22852       // "=r,0" would be valid here.
22853       return IntrinsicLowering::LowerToByteSwap(CI);
22854     }
22855
22856     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22857     if (CI->getType()->isIntegerTy(16) &&
22858         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22859         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22860          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22861       AsmPieces.clear();
22862       const std::string &ConstraintsStr = IA->getConstraintString();
22863       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22864       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22865       if (clobbersFlagRegisters(AsmPieces))
22866         return IntrinsicLowering::LowerToByteSwap(CI);
22867     }
22868     break;
22869   case 3:
22870     if (CI->getType()->isIntegerTy(32) &&
22871         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22872         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22873         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22874         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22875       AsmPieces.clear();
22876       const std::string &ConstraintsStr = IA->getConstraintString();
22877       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22878       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22879       if (clobbersFlagRegisters(AsmPieces))
22880         return IntrinsicLowering::LowerToByteSwap(CI);
22881     }
22882
22883     if (CI->getType()->isIntegerTy(64)) {
22884       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22885       if (Constraints.size() >= 2 &&
22886           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22887           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22888         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22889         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22890             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22891             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22892           return IntrinsicLowering::LowerToByteSwap(CI);
22893       }
22894     }
22895     break;
22896   }
22897   return false;
22898 }
22899
22900 /// getConstraintType - Given a constraint letter, return the type of
22901 /// constraint it is for this target.
22902 X86TargetLowering::ConstraintType
22903 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22904   if (Constraint.size() == 1) {
22905     switch (Constraint[0]) {
22906     case 'R':
22907     case 'q':
22908     case 'Q':
22909     case 'f':
22910     case 't':
22911     case 'u':
22912     case 'y':
22913     case 'x':
22914     case 'Y':
22915     case 'l':
22916       return C_RegisterClass;
22917     case 'a':
22918     case 'b':
22919     case 'c':
22920     case 'd':
22921     case 'S':
22922     case 'D':
22923     case 'A':
22924       return C_Register;
22925     case 'I':
22926     case 'J':
22927     case 'K':
22928     case 'L':
22929     case 'M':
22930     case 'N':
22931     case 'G':
22932     case 'C':
22933     case 'e':
22934     case 'Z':
22935       return C_Other;
22936     default:
22937       break;
22938     }
22939   }
22940   return TargetLowering::getConstraintType(Constraint);
22941 }
22942
22943 /// Examine constraint type and operand type and determine a weight value.
22944 /// This object must already have been set up with the operand type
22945 /// and the current alternative constraint selected.
22946 TargetLowering::ConstraintWeight
22947   X86TargetLowering::getSingleConstraintMatchWeight(
22948     AsmOperandInfo &info, const char *constraint) const {
22949   ConstraintWeight weight = CW_Invalid;
22950   Value *CallOperandVal = info.CallOperandVal;
22951     // If we don't have a value, we can't do a match,
22952     // but allow it at the lowest weight.
22953   if (!CallOperandVal)
22954     return CW_Default;
22955   Type *type = CallOperandVal->getType();
22956   // Look at the constraint type.
22957   switch (*constraint) {
22958   default:
22959     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22960   case 'R':
22961   case 'q':
22962   case 'Q':
22963   case 'a':
22964   case 'b':
22965   case 'c':
22966   case 'd':
22967   case 'S':
22968   case 'D':
22969   case 'A':
22970     if (CallOperandVal->getType()->isIntegerTy())
22971       weight = CW_SpecificReg;
22972     break;
22973   case 'f':
22974   case 't':
22975   case 'u':
22976     if (type->isFloatingPointTy())
22977       weight = CW_SpecificReg;
22978     break;
22979   case 'y':
22980     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22981       weight = CW_SpecificReg;
22982     break;
22983   case 'x':
22984   case 'Y':
22985     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22986         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22987       weight = CW_Register;
22988     break;
22989   case 'I':
22990     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22991       if (C->getZExtValue() <= 31)
22992         weight = CW_Constant;
22993     }
22994     break;
22995   case 'J':
22996     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22997       if (C->getZExtValue() <= 63)
22998         weight = CW_Constant;
22999     }
23000     break;
23001   case 'K':
23002     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23003       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
23004         weight = CW_Constant;
23005     }
23006     break;
23007   case 'L':
23008     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23009       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
23010         weight = CW_Constant;
23011     }
23012     break;
23013   case 'M':
23014     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23015       if (C->getZExtValue() <= 3)
23016         weight = CW_Constant;
23017     }
23018     break;
23019   case 'N':
23020     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23021       if (C->getZExtValue() <= 0xff)
23022         weight = CW_Constant;
23023     }
23024     break;
23025   case 'G':
23026   case 'C':
23027     if (dyn_cast<ConstantFP>(CallOperandVal)) {
23028       weight = CW_Constant;
23029     }
23030     break;
23031   case 'e':
23032     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23033       if ((C->getSExtValue() >= -0x80000000LL) &&
23034           (C->getSExtValue() <= 0x7fffffffLL))
23035         weight = CW_Constant;
23036     }
23037     break;
23038   case 'Z':
23039     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
23040       if (C->getZExtValue() <= 0xffffffff)
23041         weight = CW_Constant;
23042     }
23043     break;
23044   }
23045   return weight;
23046 }
23047
23048 /// LowerXConstraint - try to replace an X constraint, which matches anything,
23049 /// with another that has more specific requirements based on the type of the
23050 /// corresponding operand.
23051 const char *X86TargetLowering::
23052 LowerXConstraint(EVT ConstraintVT) const {
23053   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
23054   // 'f' like normal targets.
23055   if (ConstraintVT.isFloatingPoint()) {
23056     if (Subtarget->hasSSE2())
23057       return "Y";
23058     if (Subtarget->hasSSE1())
23059       return "x";
23060   }
23061
23062   return TargetLowering::LowerXConstraint(ConstraintVT);
23063 }
23064
23065 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
23066 /// vector.  If it is invalid, don't add anything to Ops.
23067 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
23068                                                      std::string &Constraint,
23069                                                      std::vector<SDValue>&Ops,
23070                                                      SelectionDAG &DAG) const {
23071   SDValue Result;
23072
23073   // Only support length 1 constraints for now.
23074   if (Constraint.length() > 1) return;
23075
23076   char ConstraintLetter = Constraint[0];
23077   switch (ConstraintLetter) {
23078   default: break;
23079   case 'I':
23080     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23081       if (C->getZExtValue() <= 31) {
23082         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23083         break;
23084       }
23085     }
23086     return;
23087   case 'J':
23088     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23089       if (C->getZExtValue() <= 63) {
23090         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23091         break;
23092       }
23093     }
23094     return;
23095   case 'K':
23096     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23097       if (isInt<8>(C->getSExtValue())) {
23098         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23099         break;
23100       }
23101     }
23102     return;
23103   case 'N':
23104     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23105       if (C->getZExtValue() <= 255) {
23106         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23107         break;
23108       }
23109     }
23110     return;
23111   case 'e': {
23112     // 32-bit signed value
23113     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23114       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23115                                            C->getSExtValue())) {
23116         // Widen to 64 bits here to get it sign extended.
23117         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
23118         break;
23119       }
23120     // FIXME gcc accepts some relocatable values here too, but only in certain
23121     // memory models; it's complicated.
23122     }
23123     return;
23124   }
23125   case 'Z': {
23126     // 32-bit unsigned value
23127     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
23128       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
23129                                            C->getZExtValue())) {
23130         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
23131         break;
23132       }
23133     }
23134     // FIXME gcc accepts some relocatable values here too, but only in certain
23135     // memory models; it's complicated.
23136     return;
23137   }
23138   case 'i': {
23139     // Literal immediates are always ok.
23140     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
23141       // Widen to 64 bits here to get it sign extended.
23142       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
23143       break;
23144     }
23145
23146     // In any sort of PIC mode addresses need to be computed at runtime by
23147     // adding in a register or some sort of table lookup.  These can't
23148     // be used as immediates.
23149     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
23150       return;
23151
23152     // If we are in non-pic codegen mode, we allow the address of a global (with
23153     // an optional displacement) to be used with 'i'.
23154     GlobalAddressSDNode *GA = nullptr;
23155     int64_t Offset = 0;
23156
23157     // Match either (GA), (GA+C), (GA+C1+C2), etc.
23158     while (1) {
23159       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
23160         Offset += GA->getOffset();
23161         break;
23162       } else if (Op.getOpcode() == ISD::ADD) {
23163         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23164           Offset += C->getZExtValue();
23165           Op = Op.getOperand(0);
23166           continue;
23167         }
23168       } else if (Op.getOpcode() == ISD::SUB) {
23169         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
23170           Offset += -C->getZExtValue();
23171           Op = Op.getOperand(0);
23172           continue;
23173         }
23174       }
23175
23176       // Otherwise, this isn't something we can handle, reject it.
23177       return;
23178     }
23179
23180     const GlobalValue *GV = GA->getGlobal();
23181     // If we require an extra load to get this address, as in PIC mode, we
23182     // can't accept it.
23183     if (isGlobalStubReference(
23184             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
23185       return;
23186
23187     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
23188                                         GA->getValueType(0), Offset);
23189     break;
23190   }
23191   }
23192
23193   if (Result.getNode()) {
23194     Ops.push_back(Result);
23195     return;
23196   }
23197   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
23198 }
23199
23200 std::pair<unsigned, const TargetRegisterClass*>
23201 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
23202                                                 MVT VT) const {
23203   // First, see if this is a constraint that directly corresponds to an LLVM
23204   // register class.
23205   if (Constraint.size() == 1) {
23206     // GCC Constraint Letters
23207     switch (Constraint[0]) {
23208     default: break;
23209       // TODO: Slight differences here in allocation order and leaving
23210       // RIP in the class. Do they matter any more here than they do
23211       // in the normal allocation?
23212     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
23213       if (Subtarget->is64Bit()) {
23214         if (VT == MVT::i32 || VT == MVT::f32)
23215           return std::make_pair(0U, &X86::GR32RegClass);
23216         if (VT == MVT::i16)
23217           return std::make_pair(0U, &X86::GR16RegClass);
23218         if (VT == MVT::i8 || VT == MVT::i1)
23219           return std::make_pair(0U, &X86::GR8RegClass);
23220         if (VT == MVT::i64 || VT == MVT::f64)
23221           return std::make_pair(0U, &X86::GR64RegClass);
23222         break;
23223       }
23224       // 32-bit fallthrough
23225     case 'Q':   // Q_REGS
23226       if (VT == MVT::i32 || VT == MVT::f32)
23227         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
23228       if (VT == MVT::i16)
23229         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
23230       if (VT == MVT::i8 || VT == MVT::i1)
23231         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
23232       if (VT == MVT::i64)
23233         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
23234       break;
23235     case 'r':   // GENERAL_REGS
23236     case 'l':   // INDEX_REGS
23237       if (VT == MVT::i8 || VT == MVT::i1)
23238         return std::make_pair(0U, &X86::GR8RegClass);
23239       if (VT == MVT::i16)
23240         return std::make_pair(0U, &X86::GR16RegClass);
23241       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
23242         return std::make_pair(0U, &X86::GR32RegClass);
23243       return std::make_pair(0U, &X86::GR64RegClass);
23244     case 'R':   // LEGACY_REGS
23245       if (VT == MVT::i8 || VT == MVT::i1)
23246         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
23247       if (VT == MVT::i16)
23248         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
23249       if (VT == MVT::i32 || !Subtarget->is64Bit())
23250         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
23251       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
23252     case 'f':  // FP Stack registers.
23253       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
23254       // value to the correct fpstack register class.
23255       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
23256         return std::make_pair(0U, &X86::RFP32RegClass);
23257       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
23258         return std::make_pair(0U, &X86::RFP64RegClass);
23259       return std::make_pair(0U, &X86::RFP80RegClass);
23260     case 'y':   // MMX_REGS if MMX allowed.
23261       if (!Subtarget->hasMMX()) break;
23262       return std::make_pair(0U, &X86::VR64RegClass);
23263     case 'Y':   // SSE_REGS if SSE2 allowed
23264       if (!Subtarget->hasSSE2()) break;
23265       // FALL THROUGH.
23266     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
23267       if (!Subtarget->hasSSE1()) break;
23268
23269       switch (VT.SimpleTy) {
23270       default: break;
23271       // Scalar SSE types.
23272       case MVT::f32:
23273       case MVT::i32:
23274         return std::make_pair(0U, &X86::FR32RegClass);
23275       case MVT::f64:
23276       case MVT::i64:
23277         return std::make_pair(0U, &X86::FR64RegClass);
23278       // Vector types.
23279       case MVT::v16i8:
23280       case MVT::v8i16:
23281       case MVT::v4i32:
23282       case MVT::v2i64:
23283       case MVT::v4f32:
23284       case MVT::v2f64:
23285         return std::make_pair(0U, &X86::VR128RegClass);
23286       // AVX types.
23287       case MVT::v32i8:
23288       case MVT::v16i16:
23289       case MVT::v8i32:
23290       case MVT::v4i64:
23291       case MVT::v8f32:
23292       case MVT::v4f64:
23293         return std::make_pair(0U, &X86::VR256RegClass);
23294       case MVT::v8f64:
23295       case MVT::v16f32:
23296       case MVT::v16i32:
23297       case MVT::v8i64:
23298         return std::make_pair(0U, &X86::VR512RegClass);
23299       }
23300       break;
23301     }
23302   }
23303
23304   // Use the default implementation in TargetLowering to convert the register
23305   // constraint into a member of a register class.
23306   std::pair<unsigned, const TargetRegisterClass*> Res;
23307   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
23308
23309   // Not found as a standard register?
23310   if (!Res.second) {
23311     // Map st(0) -> st(7) -> ST0
23312     if (Constraint.size() == 7 && Constraint[0] == '{' &&
23313         tolower(Constraint[1]) == 's' &&
23314         tolower(Constraint[2]) == 't' &&
23315         Constraint[3] == '(' &&
23316         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
23317         Constraint[5] == ')' &&
23318         Constraint[6] == '}') {
23319
23320       Res.first = X86::FP0+Constraint[4]-'0';
23321       Res.second = &X86::RFP80RegClass;
23322       return Res;
23323     }
23324
23325     // GCC allows "st(0)" to be called just plain "st".
23326     if (StringRef("{st}").equals_lower(Constraint)) {
23327       Res.first = X86::FP0;
23328       Res.second = &X86::RFP80RegClass;
23329       return Res;
23330     }
23331
23332     // flags -> EFLAGS
23333     if (StringRef("{flags}").equals_lower(Constraint)) {
23334       Res.first = X86::EFLAGS;
23335       Res.second = &X86::CCRRegClass;
23336       return Res;
23337     }
23338
23339     // 'A' means EAX + EDX.
23340     if (Constraint == "A") {
23341       Res.first = X86::EAX;
23342       Res.second = &X86::GR32_ADRegClass;
23343       return Res;
23344     }
23345     return Res;
23346   }
23347
23348   // Otherwise, check to see if this is a register class of the wrong value
23349   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
23350   // turn into {ax},{dx}.
23351   if (Res.second->hasType(VT))
23352     return Res;   // Correct type already, nothing to do.
23353
23354   // All of the single-register GCC register classes map their values onto
23355   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
23356   // really want an 8-bit or 32-bit register, map to the appropriate register
23357   // class and return the appropriate register.
23358   if (Res.second == &X86::GR16RegClass) {
23359     if (VT == MVT::i8 || VT == MVT::i1) {
23360       unsigned DestReg = 0;
23361       switch (Res.first) {
23362       default: break;
23363       case X86::AX: DestReg = X86::AL; break;
23364       case X86::DX: DestReg = X86::DL; break;
23365       case X86::CX: DestReg = X86::CL; break;
23366       case X86::BX: DestReg = X86::BL; break;
23367       }
23368       if (DestReg) {
23369         Res.first = DestReg;
23370         Res.second = &X86::GR8RegClass;
23371       }
23372     } else if (VT == MVT::i32 || VT == MVT::f32) {
23373       unsigned DestReg = 0;
23374       switch (Res.first) {
23375       default: break;
23376       case X86::AX: DestReg = X86::EAX; break;
23377       case X86::DX: DestReg = X86::EDX; break;
23378       case X86::CX: DestReg = X86::ECX; break;
23379       case X86::BX: DestReg = X86::EBX; break;
23380       case X86::SI: DestReg = X86::ESI; break;
23381       case X86::DI: DestReg = X86::EDI; break;
23382       case X86::BP: DestReg = X86::EBP; break;
23383       case X86::SP: DestReg = X86::ESP; break;
23384       }
23385       if (DestReg) {
23386         Res.first = DestReg;
23387         Res.second = &X86::GR32RegClass;
23388       }
23389     } else if (VT == MVT::i64 || VT == MVT::f64) {
23390       unsigned DestReg = 0;
23391       switch (Res.first) {
23392       default: break;
23393       case X86::AX: DestReg = X86::RAX; break;
23394       case X86::DX: DestReg = X86::RDX; break;
23395       case X86::CX: DestReg = X86::RCX; break;
23396       case X86::BX: DestReg = X86::RBX; break;
23397       case X86::SI: DestReg = X86::RSI; break;
23398       case X86::DI: DestReg = X86::RDI; break;
23399       case X86::BP: DestReg = X86::RBP; break;
23400       case X86::SP: DestReg = X86::RSP; break;
23401       }
23402       if (DestReg) {
23403         Res.first = DestReg;
23404         Res.second = &X86::GR64RegClass;
23405       }
23406     }
23407   } else if (Res.second == &X86::FR32RegClass ||
23408              Res.second == &X86::FR64RegClass ||
23409              Res.second == &X86::VR128RegClass ||
23410              Res.second == &X86::VR256RegClass ||
23411              Res.second == &X86::FR32XRegClass ||
23412              Res.second == &X86::FR64XRegClass ||
23413              Res.second == &X86::VR128XRegClass ||
23414              Res.second == &X86::VR256XRegClass ||
23415              Res.second == &X86::VR512RegClass) {
23416     // Handle references to XMM physical registers that got mapped into the
23417     // wrong class.  This can happen with constraints like {xmm0} where the
23418     // target independent register mapper will just pick the first match it can
23419     // find, ignoring the required type.
23420
23421     if (VT == MVT::f32 || VT == MVT::i32)
23422       Res.second = &X86::FR32RegClass;
23423     else if (VT == MVT::f64 || VT == MVT::i64)
23424       Res.second = &X86::FR64RegClass;
23425     else if (X86::VR128RegClass.hasType(VT))
23426       Res.second = &X86::VR128RegClass;
23427     else if (X86::VR256RegClass.hasType(VT))
23428       Res.second = &X86::VR256RegClass;
23429     else if (X86::VR512RegClass.hasType(VT))
23430       Res.second = &X86::VR512RegClass;
23431   }
23432
23433   return Res;
23434 }
23435
23436 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
23437                                             Type *Ty) const {
23438   // Scaling factors are not free at all.
23439   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
23440   // will take 2 allocations in the out of order engine instead of 1
23441   // for plain addressing mode, i.e. inst (reg1).
23442   // E.g.,
23443   // vaddps (%rsi,%drx), %ymm0, %ymm1
23444   // Requires two allocations (one for the load, one for the computation)
23445   // whereas:
23446   // vaddps (%rsi), %ymm0, %ymm1
23447   // Requires just 1 allocation, i.e., freeing allocations for other operations
23448   // and having less micro operations to execute.
23449   //
23450   // For some X86 architectures, this is even worse because for instance for
23451   // stores, the complex addressing mode forces the instruction to use the
23452   // "load" ports instead of the dedicated "store" port.
23453   // E.g., on Haswell:
23454   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
23455   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
23456   if (isLegalAddressingMode(AM, Ty))
23457     // Scale represents reg2 * scale, thus account for 1
23458     // as soon as we use a second register.
23459     return AM.Scale != 0;
23460   return -1;
23461 }
23462
23463 bool X86TargetLowering::isTargetFTOL() const {
23464   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
23465 }