[x86] Fix assertion failure caused by a wrong combine of PSHUFD nodes with different...
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86InstrBuilder.h"
19 #include "X86MachineFunctionInfo.h"
20 #include "X86TargetMachine.h"
21 #include "X86TargetObjectFile.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/VariadicFunction.h"
27 #include "llvm/CodeGen/IntrinsicLowering.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/MachineModuleInfo.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/IR/CallSite.h"
35 #include "llvm/IR/CallingConv.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/DerivedTypes.h"
38 #include "llvm/IR/Function.h"
39 #include "llvm/IR/GlobalAlias.h"
40 #include "llvm/IR/GlobalVariable.h"
41 #include "llvm/IR/Instructions.h"
42 #include "llvm/IR/Intrinsics.h"
43 #include "llvm/MC/MCAsmInfo.h"
44 #include "llvm/MC/MCContext.h"
45 #include "llvm/MC/MCExpr.h"
46 #include "llvm/MC/MCSymbol.h"
47 #include "llvm/Support/CommandLine.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/ErrorHandling.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Target/TargetOptions.h"
52 #include <bitset>
53 #include <numeric>
54 #include <cctype>
55 using namespace llvm;
56
57 #define DEBUG_TYPE "x86-isel"
58
59 STATISTIC(NumTailCalls, "Number of tail calls");
60
61 static cl::opt<bool> ExperimentalVectorWideningLegalization(
62     "x86-experimental-vector-widening-legalization", cl::init(false),
63     cl::desc("Enable an experimental vector type legalization through widening "
64              "rather than promotion."),
65     cl::Hidden);
66
67 static cl::opt<bool> ExperimentalVectorShuffleLowering(
68     "x86-experimental-vector-shuffle-lowering", cl::init(false),
69     cl::desc("Enable an experimental vector shuffle lowering code path."),
70     cl::Hidden);
71
72 // Forward declarations.
73 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
74                        SDValue V2);
75
76 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
77                                 SelectionDAG &DAG, SDLoc dl,
78                                 unsigned vectorWidth) {
79   assert((vectorWidth == 128 || vectorWidth == 256) &&
80          "Unsupported vector width");
81   EVT VT = Vec.getValueType();
82   EVT ElVT = VT.getVectorElementType();
83   unsigned Factor = VT.getSizeInBits()/vectorWidth;
84   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
85                                   VT.getVectorNumElements()/Factor);
86
87   // Extract from UNDEF is UNDEF.
88   if (Vec.getOpcode() == ISD::UNDEF)
89     return DAG.getUNDEF(ResultVT);
90
91   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
92   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
93
94   // This is the index of the first element of the vectorWidth-bit chunk
95   // we want.
96   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
97                                * ElemsPerChunk);
98
99   // If the input is a buildvector just emit a smaller one.
100   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
101     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
102                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
103                                     ElemsPerChunk));
104
105   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
106   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
107                                VecIdx);
108
109   return Result;
110
111 }
112 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
113 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
114 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
115 /// instructions or a simple subregister reference. Idx is an index in the
116 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
117 /// lowering EXTRACT_VECTOR_ELT operations easier.
118 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
119                                    SelectionDAG &DAG, SDLoc dl) {
120   assert((Vec.getValueType().is256BitVector() ||
121           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
122   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
123 }
124
125 /// Generate a DAG to grab 256-bits from a 512-bit vector.
126 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
127                                    SelectionDAG &DAG, SDLoc dl) {
128   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
129   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
130 }
131
132 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
133                                unsigned IdxVal, SelectionDAG &DAG,
134                                SDLoc dl, unsigned vectorWidth) {
135   assert((vectorWidth == 128 || vectorWidth == 256) &&
136          "Unsupported vector width");
137   // Inserting UNDEF is Result
138   if (Vec.getOpcode() == ISD::UNDEF)
139     return Result;
140   EVT VT = Vec.getValueType();
141   EVT ElVT = VT.getVectorElementType();
142   EVT ResultVT = Result.getValueType();
143
144   // Insert the relevant vectorWidth bits.
145   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
146
147   // This is the index of the first element of the vectorWidth-bit chunk
148   // we want.
149   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
150                                * ElemsPerChunk);
151
152   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
153   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
154                      VecIdx);
155 }
156 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
157 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
158 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
159 /// simple superregister reference.  Idx is an index in the 128 bits
160 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
161 /// lowering INSERT_VECTOR_ELT operations easier.
162 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
163                                   unsigned IdxVal, SelectionDAG &DAG,
164                                   SDLoc dl) {
165   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
166   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
167 }
168
169 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
170                                   unsigned IdxVal, SelectionDAG &DAG,
171                                   SDLoc dl) {
172   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
173   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
174 }
175
176 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
177 /// instructions. This is used because creating CONCAT_VECTOR nodes of
178 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
179 /// large BUILD_VECTORS.
180 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
181                                    unsigned NumElems, SelectionDAG &DAG,
182                                    SDLoc dl) {
183   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
184   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
185 }
186
187 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
188                                    unsigned NumElems, SelectionDAG &DAG,
189                                    SDLoc dl) {
190   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
191   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
192 }
193
194 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
195   if (TT.isOSBinFormatMachO()) {
196     if (TT.getArch() == Triple::x86_64)
197       return new X86_64MachoTargetObjectFile();
198     return new TargetLoweringObjectFileMachO();
199   }
200
201   if (TT.isOSLinux())
202     return new X86LinuxTargetObjectFile();
203   if (TT.isOSBinFormatELF())
204     return new TargetLoweringObjectFileELF();
205   if (TT.isKnownWindowsMSVCEnvironment())
206     return new X86WindowsTargetObjectFile();
207   if (TT.isOSBinFormatCOFF())
208     return new TargetLoweringObjectFileCOFF();
209   llvm_unreachable("unknown subtarget type");
210 }
211
212 // FIXME: This should stop caching the target machine as soon as
213 // we can remove resetOperationActions et al.
214 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
215   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
216   Subtarget = &TM.getSubtarget<X86Subtarget>();
217   X86ScalarSSEf64 = Subtarget->hasSSE2();
218   X86ScalarSSEf32 = Subtarget->hasSSE1();
219   TD = getDataLayout();
220
221   resetOperationActions();
222 }
223
224 void X86TargetLowering::resetOperationActions() {
225   const TargetMachine &TM = getTargetMachine();
226   static bool FirstTimeThrough = true;
227
228   // If none of the target options have changed, then we don't need to reset the
229   // operation actions.
230   if (!FirstTimeThrough && TO == TM.Options) return;
231
232   if (!FirstTimeThrough) {
233     // Reinitialize the actions.
234     initActions();
235     FirstTimeThrough = false;
236   }
237
238   TO = TM.Options;
239
240   // Set up the TargetLowering object.
241   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
242
243   // X86 is weird, it always uses i8 for shift amounts and setcc results.
244   setBooleanContents(ZeroOrOneBooleanContent);
245   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
246   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
247
248   // For 64-bit since we have so many registers use the ILP scheduler, for
249   // 32-bit code use the register pressure specific scheduling.
250   // For Atom, always use ILP scheduling.
251   if (Subtarget->isAtom())
252     setSchedulingPreference(Sched::ILP);
253   else if (Subtarget->is64Bit())
254     setSchedulingPreference(Sched::ILP);
255   else
256     setSchedulingPreference(Sched::RegPressure);
257   const X86RegisterInfo *RegInfo =
258     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
259   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
260
261   // Bypass expensive divides on Atom when compiling with O2
262   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
263     addBypassSlowDiv(32, 8);
264     if (Subtarget->is64Bit())
265       addBypassSlowDiv(64, 16);
266   }
267
268   if (Subtarget->isTargetKnownWindowsMSVC()) {
269     // Setup Windows compiler runtime calls.
270     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
271     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
272     setLibcallName(RTLIB::SREM_I64, "_allrem");
273     setLibcallName(RTLIB::UREM_I64, "_aullrem");
274     setLibcallName(RTLIB::MUL_I64, "_allmul");
275     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
276     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
277     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
278     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
279     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
280
281     // The _ftol2 runtime function has an unusual calling conv, which
282     // is modeled by a special pseudo-instruction.
283     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
284     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
285     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
286     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
287   }
288
289   if (Subtarget->isTargetDarwin()) {
290     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
291     setUseUnderscoreSetJmp(false);
292     setUseUnderscoreLongJmp(false);
293   } else if (Subtarget->isTargetWindowsGNU()) {
294     // MS runtime is weird: it exports _setjmp, but longjmp!
295     setUseUnderscoreSetJmp(true);
296     setUseUnderscoreLongJmp(false);
297   } else {
298     setUseUnderscoreSetJmp(true);
299     setUseUnderscoreLongJmp(true);
300   }
301
302   // Set up the register classes.
303   addRegisterClass(MVT::i8, &X86::GR8RegClass);
304   addRegisterClass(MVT::i16, &X86::GR16RegClass);
305   addRegisterClass(MVT::i32, &X86::GR32RegClass);
306   if (Subtarget->is64Bit())
307     addRegisterClass(MVT::i64, &X86::GR64RegClass);
308
309   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
310
311   // We don't accept any truncstore of integer registers.
312   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
313   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
314   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
315   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
316   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
317   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
318
319   // SETOEQ and SETUNE require checking two conditions.
320   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
321   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
322   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
323   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
324   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
325   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
326
327   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
328   // operation.
329   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
330   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
331   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
332
333   if (Subtarget->is64Bit()) {
334     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
335     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
336   } else if (!TM.Options.UseSoftFloat) {
337     // We have an algorithm for SSE2->double, and we turn this into a
338     // 64-bit FILD followed by conditional FADD for other targets.
339     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
340     // We have an algorithm for SSE2, and we turn this into a 64-bit
341     // FILD for other targets.
342     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
343   }
344
345   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
346   // this operation.
347   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
348   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
349
350   if (!TM.Options.UseSoftFloat) {
351     // SSE has no i16 to fp conversion, only i32
352     if (X86ScalarSSEf32) {
353       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
354       // f32 and f64 cases are Legal, f80 case is not
355       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
356     } else {
357       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
358       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
359     }
360   } else {
361     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
362     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
363   }
364
365   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
366   // are Legal, f80 is custom lowered.
367   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
368   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
369
370   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
371   // this operation.
372   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
373   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
374
375   if (X86ScalarSSEf32) {
376     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
377     // f32 and f64 cases are Legal, f80 case is not
378     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
379   } else {
380     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
381     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
382   }
383
384   // Handle FP_TO_UINT by promoting the destination to a larger signed
385   // conversion.
386   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
387   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
388   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
389
390   if (Subtarget->is64Bit()) {
391     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
392     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
393   } else if (!TM.Options.UseSoftFloat) {
394     // Since AVX is a superset of SSE3, only check for SSE here.
395     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
396       // Expand FP_TO_UINT into a select.
397       // FIXME: We would like to use a Custom expander here eventually to do
398       // the optimal thing for SSE vs. the default expansion in the legalizer.
399       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
400     else
401       // With SSE3 we can use fisttpll to convert to a signed i64; without
402       // SSE, we're stuck with a fistpll.
403       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
404   }
405
406   if (isTargetFTOL()) {
407     // Use the _ftol2 runtime function, which has a pseudo-instruction
408     // to handle its weird calling convention.
409     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
410   }
411
412   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
413   if (!X86ScalarSSEf64) {
414     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
415     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
416     if (Subtarget->is64Bit()) {
417       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
418       // Without SSE, i64->f64 goes through memory.
419       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
420     }
421   }
422
423   // Scalar integer divide and remainder are lowered to use operations that
424   // produce two results, to match the available instructions. This exposes
425   // the two-result form to trivial CSE, which is able to combine x/y and x%y
426   // into a single instruction.
427   //
428   // Scalar integer multiply-high is also lowered to use two-result
429   // operations, to match the available instructions. However, plain multiply
430   // (low) operations are left as Legal, as there are single-result
431   // instructions for this in x86. Using the two-result multiply instructions
432   // when both high and low results are needed must be arranged by dagcombine.
433   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
434     MVT VT = IntVTs[i];
435     setOperationAction(ISD::MULHS, VT, Expand);
436     setOperationAction(ISD::MULHU, VT, Expand);
437     setOperationAction(ISD::SDIV, VT, Expand);
438     setOperationAction(ISD::UDIV, VT, Expand);
439     setOperationAction(ISD::SREM, VT, Expand);
440     setOperationAction(ISD::UREM, VT, Expand);
441
442     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
443     setOperationAction(ISD::ADDC, VT, Custom);
444     setOperationAction(ISD::ADDE, VT, Custom);
445     setOperationAction(ISD::SUBC, VT, Custom);
446     setOperationAction(ISD::SUBE, VT, Custom);
447   }
448
449   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
450   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
451   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
452   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
453   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
454   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
455   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
456   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
457   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
458   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
459   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
460   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
461   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
462   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
463   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
464   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
465   if (Subtarget->is64Bit())
466     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
467   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
468   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
469   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
470   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
471   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
472   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
473   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
474   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
475
476   // Promote the i8 variants and force them on up to i32 which has a shorter
477   // encoding.
478   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
479   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
480   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
481   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
482   if (Subtarget->hasBMI()) {
483     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
484     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
485     if (Subtarget->is64Bit())
486       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
487   } else {
488     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
489     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
492   }
493
494   if (Subtarget->hasLZCNT()) {
495     // When promoting the i8 variants, force them to i32 for a shorter
496     // encoding.
497     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
498     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
499     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
500     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
501     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
502     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
505   } else {
506     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
507     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
508     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
509     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
510     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
511     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
512     if (Subtarget->is64Bit()) {
513       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
514       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
515     }
516   }
517
518   // Special handling for half-precision floating point conversions.
519   // If we don't have F16C support, then lower half float conversions
520   // into library calls.
521   if (TM.Options.UseSoftFloat || !Subtarget->hasF16C()) {
522     setOperationAction(ISD::FP16_TO_FP32, MVT::f32, Expand);
523     setOperationAction(ISD::FP32_TO_FP16, MVT::i16, Expand);
524   }
525
526   if (Subtarget->hasPOPCNT()) {
527     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
528   } else {
529     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
530     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
531     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
532     if (Subtarget->is64Bit())
533       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
534   }
535
536   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
537
538   if (!Subtarget->hasMOVBE())
539     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
540
541   // These should be promoted to a larger select which is supported.
542   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
543   // X86 wants to expand cmov itself.
544   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
545   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
546   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
547   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
548   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
549   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
550   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
551   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
552   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
553   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
554   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
555   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
556   if (Subtarget->is64Bit()) {
557     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
558     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
559   }
560   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
561   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
562   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
563   // support continuation, user-level threading, and etc.. As a result, no
564   // other SjLj exception interfaces are implemented and please don't build
565   // your own exception handling based on them.
566   // LLVM/Clang supports zero-cost DWARF exception handling.
567   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
568   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
569
570   // Darwin ABI issue.
571   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
572   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
573   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
574   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
575   if (Subtarget->is64Bit())
576     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
577   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
578   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
579   if (Subtarget->is64Bit()) {
580     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
581     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
582     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
583     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
584     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
585   }
586   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
587   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
588   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
589   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
590   if (Subtarget->is64Bit()) {
591     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
592     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
593     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
594   }
595
596   if (Subtarget->hasSSE1())
597     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
598
599   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
600
601   // Expand certain atomics
602   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
603     MVT VT = IntVTs[i];
604     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
605     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
606     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
607   }
608
609   if (Subtarget->hasCmpxchg16b()) {
610     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
611   }
612
613   // FIXME - use subtarget debug flags
614   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
615       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
616     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
617   }
618
619   if (Subtarget->is64Bit()) {
620     setExceptionPointerRegister(X86::RAX);
621     setExceptionSelectorRegister(X86::RDX);
622   } else {
623     setExceptionPointerRegister(X86::EAX);
624     setExceptionSelectorRegister(X86::EDX);
625   }
626   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
627   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
628
629   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
630   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
631
632   setOperationAction(ISD::TRAP, MVT::Other, Legal);
633   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
634
635   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
636   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
637   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
638   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
639     // TargetInfo::X86_64ABIBuiltinVaList
640     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
641     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
642   } else {
643     // TargetInfo::CharPtrBuiltinVaList
644     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
645     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
646   }
647
648   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
649   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
650
651   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
652                      MVT::i64 : MVT::i32, Custom);
653
654   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
655     // f32 and f64 use SSE.
656     // Set up the FP register classes.
657     addRegisterClass(MVT::f32, &X86::FR32RegClass);
658     addRegisterClass(MVT::f64, &X86::FR64RegClass);
659
660     // Use ANDPD to simulate FABS.
661     setOperationAction(ISD::FABS , MVT::f64, Custom);
662     setOperationAction(ISD::FABS , MVT::f32, Custom);
663
664     // Use XORP to simulate FNEG.
665     setOperationAction(ISD::FNEG , MVT::f64, Custom);
666     setOperationAction(ISD::FNEG , MVT::f32, Custom);
667
668     // Use ANDPD and ORPD to simulate FCOPYSIGN.
669     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
670     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
671
672     // Lower this to FGETSIGNx86 plus an AND.
673     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
674     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
675
676     // We don't support sin/cos/fmod
677     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
678     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
679     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
680     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
681     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
682     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
683
684     // Expand FP immediates into loads from the stack, except for the special
685     // cases we handle.
686     addLegalFPImmediate(APFloat(+0.0)); // xorpd
687     addLegalFPImmediate(APFloat(+0.0f)); // xorps
688   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
689     // Use SSE for f32, x87 for f64.
690     // Set up the FP register classes.
691     addRegisterClass(MVT::f32, &X86::FR32RegClass);
692     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
693
694     // Use ANDPS to simulate FABS.
695     setOperationAction(ISD::FABS , MVT::f32, Custom);
696
697     // Use XORP to simulate FNEG.
698     setOperationAction(ISD::FNEG , MVT::f32, Custom);
699
700     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
701
702     // Use ANDPS and ORPS to simulate FCOPYSIGN.
703     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
704     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
705
706     // We don't support sin/cos/fmod
707     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
708     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
709     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
710
711     // Special cases we handle for FP constants.
712     addLegalFPImmediate(APFloat(+0.0f)); // xorps
713     addLegalFPImmediate(APFloat(+0.0)); // FLD0
714     addLegalFPImmediate(APFloat(+1.0)); // FLD1
715     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
716     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
717
718     if (!TM.Options.UnsafeFPMath) {
719       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
720       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
721       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
722     }
723   } else if (!TM.Options.UseSoftFloat) {
724     // f32 and f64 in x87.
725     // Set up the FP register classes.
726     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
727     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
728
729     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
730     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
731     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
732     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
733
734     if (!TM.Options.UnsafeFPMath) {
735       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
736       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
737       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
738       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
739       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
740       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
741     }
742     addLegalFPImmediate(APFloat(+0.0)); // FLD0
743     addLegalFPImmediate(APFloat(+1.0)); // FLD1
744     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
745     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
746     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
747     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
748     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
749     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
750   }
751
752   // We don't support FMA.
753   setOperationAction(ISD::FMA, MVT::f64, Expand);
754   setOperationAction(ISD::FMA, MVT::f32, Expand);
755
756   // Long double always uses X87.
757   if (!TM.Options.UseSoftFloat) {
758     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
759     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
760     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
761     {
762       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
763       addLegalFPImmediate(TmpFlt);  // FLD0
764       TmpFlt.changeSign();
765       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
766
767       bool ignored;
768       APFloat TmpFlt2(+1.0);
769       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
770                       &ignored);
771       addLegalFPImmediate(TmpFlt2);  // FLD1
772       TmpFlt2.changeSign();
773       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
774     }
775
776     if (!TM.Options.UnsafeFPMath) {
777       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
778       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
779       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
780     }
781
782     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
783     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
784     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
785     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
786     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
787     setOperationAction(ISD::FMA, MVT::f80, Expand);
788   }
789
790   // Always use a library call for pow.
791   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
792   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
793   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
794
795   setOperationAction(ISD::FLOG, MVT::f80, Expand);
796   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
797   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
798   setOperationAction(ISD::FEXP, MVT::f80, Expand);
799   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
800
801   // First set operation action for all vector types to either promote
802   // (for widening) or expand (for scalarization). Then we will selectively
803   // turn on ones that can be effectively codegen'd.
804   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
805            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
806     MVT VT = (MVT::SimpleValueType)i;
807     setOperationAction(ISD::ADD , VT, Expand);
808     setOperationAction(ISD::SUB , VT, Expand);
809     setOperationAction(ISD::FADD, VT, Expand);
810     setOperationAction(ISD::FNEG, VT, Expand);
811     setOperationAction(ISD::FSUB, VT, Expand);
812     setOperationAction(ISD::MUL , VT, Expand);
813     setOperationAction(ISD::FMUL, VT, Expand);
814     setOperationAction(ISD::SDIV, VT, Expand);
815     setOperationAction(ISD::UDIV, VT, Expand);
816     setOperationAction(ISD::FDIV, VT, Expand);
817     setOperationAction(ISD::SREM, VT, Expand);
818     setOperationAction(ISD::UREM, VT, Expand);
819     setOperationAction(ISD::LOAD, VT, Expand);
820     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
821     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
822     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
823     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
824     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
825     setOperationAction(ISD::FABS, VT, Expand);
826     setOperationAction(ISD::FSIN, VT, Expand);
827     setOperationAction(ISD::FSINCOS, VT, Expand);
828     setOperationAction(ISD::FCOS, VT, Expand);
829     setOperationAction(ISD::FSINCOS, VT, Expand);
830     setOperationAction(ISD::FREM, VT, Expand);
831     setOperationAction(ISD::FMA,  VT, Expand);
832     setOperationAction(ISD::FPOWI, VT, Expand);
833     setOperationAction(ISD::FSQRT, VT, Expand);
834     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
835     setOperationAction(ISD::FFLOOR, VT, Expand);
836     setOperationAction(ISD::FCEIL, VT, Expand);
837     setOperationAction(ISD::FTRUNC, VT, Expand);
838     setOperationAction(ISD::FRINT, VT, Expand);
839     setOperationAction(ISD::FNEARBYINT, VT, Expand);
840     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
841     setOperationAction(ISD::MULHS, VT, Expand);
842     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
843     setOperationAction(ISD::MULHU, VT, Expand);
844     setOperationAction(ISD::SDIVREM, VT, Expand);
845     setOperationAction(ISD::UDIVREM, VT, Expand);
846     setOperationAction(ISD::FPOW, VT, Expand);
847     setOperationAction(ISD::CTPOP, VT, Expand);
848     setOperationAction(ISD::CTTZ, VT, Expand);
849     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
850     setOperationAction(ISD::CTLZ, VT, Expand);
851     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
852     setOperationAction(ISD::SHL, VT, Expand);
853     setOperationAction(ISD::SRA, VT, Expand);
854     setOperationAction(ISD::SRL, VT, Expand);
855     setOperationAction(ISD::ROTL, VT, Expand);
856     setOperationAction(ISD::ROTR, VT, Expand);
857     setOperationAction(ISD::BSWAP, VT, Expand);
858     setOperationAction(ISD::SETCC, VT, Expand);
859     setOperationAction(ISD::FLOG, VT, Expand);
860     setOperationAction(ISD::FLOG2, VT, Expand);
861     setOperationAction(ISD::FLOG10, VT, Expand);
862     setOperationAction(ISD::FEXP, VT, Expand);
863     setOperationAction(ISD::FEXP2, VT, Expand);
864     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
865     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
866     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
867     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
868     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
869     setOperationAction(ISD::TRUNCATE, VT, Expand);
870     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
871     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
872     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
873     setOperationAction(ISD::VSELECT, VT, Expand);
874     setOperationAction(ISD::SELECT_CC, VT, Expand);
875     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
876              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
877       setTruncStoreAction(VT,
878                           (MVT::SimpleValueType)InnerVT, Expand);
879     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
880     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
881     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
882   }
883
884   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
885   // with -msoft-float, disable use of MMX as well.
886   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
887     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
888     // No operations on x86mmx supported, everything uses intrinsics.
889   }
890
891   // MMX-sized vectors (other than x86mmx) are expected to be expanded
892   // into smaller operations.
893   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
894   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
895   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
896   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
897   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
898   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
899   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
900   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
901   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
902   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
903   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
904   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
905   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
906   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
907   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
908   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
909   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
910   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
911   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
912   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
913   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
914   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
915   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
916   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
917   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
918   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
919   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
920   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
921   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
922
923   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
924     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
925
926     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
927     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
928     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
929     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
930     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
931     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
932     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
933     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
934     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
935     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
936     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
937     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
938   }
939
940   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
941     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
942
943     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
944     // registers cannot be used even for integer operations.
945     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
946     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
947     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
948     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
949
950     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
951     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
952     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
953     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
954     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
955     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
956     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
957     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
958     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
959     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
960     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
961     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
962     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
963     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
964     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
965     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
966     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
967     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
968     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
969     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
970     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
971     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
972
973     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
974     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
975     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
976     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
977
978     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
979     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
980     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
981     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
982     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
983
984     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
985     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
986       MVT VT = (MVT::SimpleValueType)i;
987       // Do not attempt to custom lower non-power-of-2 vectors
988       if (!isPowerOf2_32(VT.getVectorNumElements()))
989         continue;
990       // Do not attempt to custom lower non-128-bit vectors
991       if (!VT.is128BitVector())
992         continue;
993       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
994       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
995       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
996     }
997
998     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
999     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
1000     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
1001     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
1002     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
1004
1005     if (Subtarget->is64Bit()) {
1006       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1007       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1008     }
1009
1010     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1011     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1012       MVT VT = (MVT::SimpleValueType)i;
1013
1014       // Do not attempt to promote non-128-bit vectors
1015       if (!VT.is128BitVector())
1016         continue;
1017
1018       setOperationAction(ISD::AND,    VT, Promote);
1019       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1020       setOperationAction(ISD::OR,     VT, Promote);
1021       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1022       setOperationAction(ISD::XOR,    VT, Promote);
1023       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1024       setOperationAction(ISD::LOAD,   VT, Promote);
1025       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1026       setOperationAction(ISD::SELECT, VT, Promote);
1027       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1028     }
1029
1030     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1031
1032     // Custom lower v2i64 and v2f64 selects.
1033     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1034     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1035     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1036     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1037
1038     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1039     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1040
1041     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1042     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1043     // As there is no 64-bit GPR available, we need build a special custom
1044     // sequence to convert from v2i32 to v2f32.
1045     if (!Subtarget->is64Bit())
1046       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1047
1048     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1049     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1050
1051     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1052
1053     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1054     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1055     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1056   }
1057
1058   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1059     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1062     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1064     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1065     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1066     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1067     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1068     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1069
1070     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1071     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1072     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1073     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1074     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1075     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1076     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1077     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1078     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1079     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1080
1081     // FIXME: Do we need to handle scalar-to-vector here?
1082     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1083
1084     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1085     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1086     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1087     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1088     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1089     // There is no BLENDI for byte vectors. We don't need to custom lower
1090     // some vselects for now.
1091     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1092
1093     // i8 and i16 vectors are custom , because the source register and source
1094     // source memory operand types are not the same width.  f32 vectors are
1095     // custom since the immediate controlling the insert encodes additional
1096     // information.
1097     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1098     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1099     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1100     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1101
1102     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1103     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1104     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1105     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1106
1107     // FIXME: these should be Legal but thats only for the case where
1108     // the index is constant.  For now custom expand to deal with that.
1109     if (Subtarget->is64Bit()) {
1110       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1111       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1112     }
1113   }
1114
1115   if (Subtarget->hasSSE2()) {
1116     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1117     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1118
1119     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1120     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1121
1122     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1123     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1124
1125     // In the customized shift lowering, the legal cases in AVX2 will be
1126     // recognized.
1127     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1128     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1129
1130     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1131     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1132
1133     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1134   }
1135
1136   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1137     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1138     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1139     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1140     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1141     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1142     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1143
1144     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1145     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1146     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1147
1148     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1149     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1150     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1151     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1152     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1153     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1154     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1155     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1156     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1157     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1158     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1159     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1160
1161     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1162     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1163     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1164     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1165     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1166     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1167     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1168     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1169     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1170     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1171     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1172     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1173
1174     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1175     // even though v8i16 is a legal type.
1176     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1177     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1178     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1179
1180     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1181     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1182     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1183
1184     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1185     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1186
1187     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1188
1189     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1190     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1191
1192     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1193     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1194
1195     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1196     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1197
1198     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1199     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1200     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1201     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1202
1203     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1204     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1205     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1206
1207     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1208     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1209     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1210     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1211
1212     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1213     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1214     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1215     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1216     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1217     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1218     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1219     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1220     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1221     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1222     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1223     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1224
1225     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1226       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1227       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1228       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1229       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1230       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1231       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1232     }
1233
1234     if (Subtarget->hasInt256()) {
1235       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1236       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1237       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1238       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1239
1240       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1241       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1242       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1243       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1244
1245       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1246       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1247       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1248       // Don't lower v32i8 because there is no 128-bit byte mul
1249
1250       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1251       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1252       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1253       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1254
1255       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1256       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1257     } else {
1258       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1259       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1260       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1261       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1262
1263       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1264       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1265       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1266       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1267
1268       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1269       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1270       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1271       // Don't lower v32i8 because there is no 128-bit byte mul
1272     }
1273
1274     // In the customized shift lowering, the legal cases in AVX2 will be
1275     // recognized.
1276     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1277     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1278
1279     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1280     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1281
1282     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1283
1284     // Custom lower several nodes for 256-bit types.
1285     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1286              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1287       MVT VT = (MVT::SimpleValueType)i;
1288
1289       // Extract subvector is special because the value type
1290       // (result) is 128-bit but the source is 256-bit wide.
1291       if (VT.is128BitVector())
1292         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1293
1294       // Do not attempt to custom lower other non-256-bit vectors
1295       if (!VT.is256BitVector())
1296         continue;
1297
1298       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1299       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1300       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1301       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1302       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1303       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1304       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1305     }
1306
1307     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1308     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1309       MVT VT = (MVT::SimpleValueType)i;
1310
1311       // Do not attempt to promote non-256-bit vectors
1312       if (!VT.is256BitVector())
1313         continue;
1314
1315       setOperationAction(ISD::AND,    VT, Promote);
1316       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1317       setOperationAction(ISD::OR,     VT, Promote);
1318       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1319       setOperationAction(ISD::XOR,    VT, Promote);
1320       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1321       setOperationAction(ISD::LOAD,   VT, Promote);
1322       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1323       setOperationAction(ISD::SELECT, VT, Promote);
1324       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1325     }
1326   }
1327
1328   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1329     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1330     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1331     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1332     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1333
1334     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1335     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1336     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1337
1338     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1339     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1340     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1341     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1342     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1343     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1344     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1347     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1348     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1349
1350     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1351     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1352     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1353     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1354     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1355     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1356
1357     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1358     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1359     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1360     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1361     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1362     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1363     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1364     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1365
1366     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1367     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1368     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1370     if (Subtarget->is64Bit()) {
1371       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1372       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1373       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1374       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1375     }
1376     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1377     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1378     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1379     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1380     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1381     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1382     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1383     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1384     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1385     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1386
1387     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1388     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1389     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1390     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1391     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1392     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1393     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1394     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1395     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1396     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1397     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1398     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1399     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1400
1401     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1402     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1403     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1404     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1405     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1406     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1407
1408     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1409     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1410
1411     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1412
1413     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1414     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1415     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1416     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1417     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1418     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1419     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1420     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1421     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1422
1423     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1424     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1425
1426     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1427     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1428
1429     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1430
1431     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1432     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1433
1434     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1435     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1436
1437     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1438     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1439
1440     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1441     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1442     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1443     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1444     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1445     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1446
1447     if (Subtarget->hasCDI()) {
1448       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1449       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1450     }
1451
1452     // Custom lower several nodes.
1453     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1454              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1455       MVT VT = (MVT::SimpleValueType)i;
1456
1457       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1458       // Extract subvector is special because the value type
1459       // (result) is 256/128-bit but the source is 512-bit wide.
1460       if (VT.is128BitVector() || VT.is256BitVector())
1461         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1462
1463       if (VT.getVectorElementType() == MVT::i1)
1464         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1465
1466       // Do not attempt to custom lower other non-512-bit vectors
1467       if (!VT.is512BitVector())
1468         continue;
1469
1470       if ( EltSize >= 32) {
1471         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1472         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1473         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1474         setOperationAction(ISD::VSELECT,             VT, Legal);
1475         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1476         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1477         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1478       }
1479     }
1480     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1481       MVT VT = (MVT::SimpleValueType)i;
1482
1483       // Do not attempt to promote non-256-bit vectors
1484       if (!VT.is512BitVector())
1485         continue;
1486
1487       setOperationAction(ISD::SELECT, VT, Promote);
1488       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1489     }
1490   }// has  AVX-512
1491
1492   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1493   // of this type with custom code.
1494   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1495            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1496     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1497                        Custom);
1498   }
1499
1500   // We want to custom lower some of our intrinsics.
1501   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1502   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1503   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1504   if (!Subtarget->is64Bit())
1505     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1506
1507   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1508   // handle type legalization for these operations here.
1509   //
1510   // FIXME: We really should do custom legalization for addition and
1511   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1512   // than generic legalization for 64-bit multiplication-with-overflow, though.
1513   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1514     // Add/Sub/Mul with overflow operations are custom lowered.
1515     MVT VT = IntVTs[i];
1516     setOperationAction(ISD::SADDO, VT, Custom);
1517     setOperationAction(ISD::UADDO, VT, Custom);
1518     setOperationAction(ISD::SSUBO, VT, Custom);
1519     setOperationAction(ISD::USUBO, VT, Custom);
1520     setOperationAction(ISD::SMULO, VT, Custom);
1521     setOperationAction(ISD::UMULO, VT, Custom);
1522   }
1523
1524   // There are no 8-bit 3-address imul/mul instructions
1525   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1526   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1527
1528   if (!Subtarget->is64Bit()) {
1529     // These libcalls are not available in 32-bit.
1530     setLibcallName(RTLIB::SHL_I128, nullptr);
1531     setLibcallName(RTLIB::SRL_I128, nullptr);
1532     setLibcallName(RTLIB::SRA_I128, nullptr);
1533   }
1534
1535   // Combine sin / cos into one node or libcall if possible.
1536   if (Subtarget->hasSinCos()) {
1537     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1538     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1539     if (Subtarget->isTargetDarwin()) {
1540       // For MacOSX, we don't want to the normal expansion of a libcall to
1541       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1542       // traffic.
1543       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1544       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1545     }
1546   }
1547
1548   if (Subtarget->isTargetWin64()) {
1549     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1550     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1551     setOperationAction(ISD::SREM, MVT::i128, Custom);
1552     setOperationAction(ISD::UREM, MVT::i128, Custom);
1553     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1554     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1555   }
1556
1557   // We have target-specific dag combine patterns for the following nodes:
1558   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1559   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1560   setTargetDAGCombine(ISD::VSELECT);
1561   setTargetDAGCombine(ISD::SELECT);
1562   setTargetDAGCombine(ISD::SHL);
1563   setTargetDAGCombine(ISD::SRA);
1564   setTargetDAGCombine(ISD::SRL);
1565   setTargetDAGCombine(ISD::OR);
1566   setTargetDAGCombine(ISD::AND);
1567   setTargetDAGCombine(ISD::ADD);
1568   setTargetDAGCombine(ISD::FADD);
1569   setTargetDAGCombine(ISD::FSUB);
1570   setTargetDAGCombine(ISD::FMA);
1571   setTargetDAGCombine(ISD::SUB);
1572   setTargetDAGCombine(ISD::LOAD);
1573   setTargetDAGCombine(ISD::STORE);
1574   setTargetDAGCombine(ISD::ZERO_EXTEND);
1575   setTargetDAGCombine(ISD::ANY_EXTEND);
1576   setTargetDAGCombine(ISD::SIGN_EXTEND);
1577   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1578   setTargetDAGCombine(ISD::TRUNCATE);
1579   setTargetDAGCombine(ISD::SINT_TO_FP);
1580   setTargetDAGCombine(ISD::SETCC);
1581   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1582   setTargetDAGCombine(ISD::BUILD_VECTOR);
1583   if (Subtarget->is64Bit())
1584     setTargetDAGCombine(ISD::MUL);
1585   setTargetDAGCombine(ISD::XOR);
1586
1587   computeRegisterProperties();
1588
1589   // On Darwin, -Os means optimize for size without hurting performance,
1590   // do not reduce the limit.
1591   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1592   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1593   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1594   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1595   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1596   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1597   setPrefLoopAlignment(4); // 2^4 bytes.
1598
1599   // Predictable cmov don't hurt on atom because it's in-order.
1600   PredictableSelectIsExpensive = !Subtarget->isAtom();
1601
1602   setPrefFunctionAlignment(4); // 2^4 bytes.
1603 }
1604
1605 TargetLoweringBase::LegalizeTypeAction
1606 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1607   if (ExperimentalVectorWideningLegalization &&
1608       VT.getVectorNumElements() != 1 &&
1609       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1610     return TypeWidenVector;
1611
1612   return TargetLoweringBase::getPreferredVectorAction(VT);
1613 }
1614
1615 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1616   if (!VT.isVector())
1617     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1618
1619   if (Subtarget->hasAVX512())
1620     switch(VT.getVectorNumElements()) {
1621     case  8: return MVT::v8i1;
1622     case 16: return MVT::v16i1;
1623   }
1624
1625   return VT.changeVectorElementTypeToInteger();
1626 }
1627
1628 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1629 /// the desired ByVal argument alignment.
1630 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1631   if (MaxAlign == 16)
1632     return;
1633   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1634     if (VTy->getBitWidth() == 128)
1635       MaxAlign = 16;
1636   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1637     unsigned EltAlign = 0;
1638     getMaxByValAlign(ATy->getElementType(), EltAlign);
1639     if (EltAlign > MaxAlign)
1640       MaxAlign = EltAlign;
1641   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1642     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1643       unsigned EltAlign = 0;
1644       getMaxByValAlign(STy->getElementType(i), EltAlign);
1645       if (EltAlign > MaxAlign)
1646         MaxAlign = EltAlign;
1647       if (MaxAlign == 16)
1648         break;
1649     }
1650   }
1651 }
1652
1653 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1654 /// function arguments in the caller parameter area. For X86, aggregates
1655 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1656 /// are at 4-byte boundaries.
1657 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1658   if (Subtarget->is64Bit()) {
1659     // Max of 8 and alignment of type.
1660     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1661     if (TyAlign > 8)
1662       return TyAlign;
1663     return 8;
1664   }
1665
1666   unsigned Align = 4;
1667   if (Subtarget->hasSSE1())
1668     getMaxByValAlign(Ty, Align);
1669   return Align;
1670 }
1671
1672 /// getOptimalMemOpType - Returns the target specific optimal type for load
1673 /// and store operations as a result of memset, memcpy, and memmove
1674 /// lowering. If DstAlign is zero that means it's safe to destination
1675 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1676 /// means there isn't a need to check it against alignment requirement,
1677 /// probably because the source does not need to be loaded. If 'IsMemset' is
1678 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1679 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1680 /// source is constant so it does not need to be loaded.
1681 /// It returns EVT::Other if the type should be determined using generic
1682 /// target-independent logic.
1683 EVT
1684 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1685                                        unsigned DstAlign, unsigned SrcAlign,
1686                                        bool IsMemset, bool ZeroMemset,
1687                                        bool MemcpyStrSrc,
1688                                        MachineFunction &MF) const {
1689   const Function *F = MF.getFunction();
1690   if ((!IsMemset || ZeroMemset) &&
1691       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1692                                        Attribute::NoImplicitFloat)) {
1693     if (Size >= 16 &&
1694         (Subtarget->isUnalignedMemAccessFast() ||
1695          ((DstAlign == 0 || DstAlign >= 16) &&
1696           (SrcAlign == 0 || SrcAlign >= 16)))) {
1697       if (Size >= 32) {
1698         if (Subtarget->hasInt256())
1699           return MVT::v8i32;
1700         if (Subtarget->hasFp256())
1701           return MVT::v8f32;
1702       }
1703       if (Subtarget->hasSSE2())
1704         return MVT::v4i32;
1705       if (Subtarget->hasSSE1())
1706         return MVT::v4f32;
1707     } else if (!MemcpyStrSrc && Size >= 8 &&
1708                !Subtarget->is64Bit() &&
1709                Subtarget->hasSSE2()) {
1710       // Do not use f64 to lower memcpy if source is string constant. It's
1711       // better to use i32 to avoid the loads.
1712       return MVT::f64;
1713     }
1714   }
1715   if (Subtarget->is64Bit() && Size >= 8)
1716     return MVT::i64;
1717   return MVT::i32;
1718 }
1719
1720 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1721   if (VT == MVT::f32)
1722     return X86ScalarSSEf32;
1723   else if (VT == MVT::f64)
1724     return X86ScalarSSEf64;
1725   return true;
1726 }
1727
1728 bool
1729 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1730                                                  unsigned,
1731                                                  bool *Fast) const {
1732   if (Fast)
1733     *Fast = Subtarget->isUnalignedMemAccessFast();
1734   return true;
1735 }
1736
1737 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1738 /// current function.  The returned value is a member of the
1739 /// MachineJumpTableInfo::JTEntryKind enum.
1740 unsigned X86TargetLowering::getJumpTableEncoding() const {
1741   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1742   // symbol.
1743   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1744       Subtarget->isPICStyleGOT())
1745     return MachineJumpTableInfo::EK_Custom32;
1746
1747   // Otherwise, use the normal jump table encoding heuristics.
1748   return TargetLowering::getJumpTableEncoding();
1749 }
1750
1751 const MCExpr *
1752 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1753                                              const MachineBasicBlock *MBB,
1754                                              unsigned uid,MCContext &Ctx) const{
1755   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1756          Subtarget->isPICStyleGOT());
1757   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1758   // entries.
1759   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1760                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1761 }
1762
1763 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1764 /// jumptable.
1765 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1766                                                     SelectionDAG &DAG) const {
1767   if (!Subtarget->is64Bit())
1768     // This doesn't have SDLoc associated with it, but is not really the
1769     // same as a Register.
1770     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1771   return Table;
1772 }
1773
1774 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1775 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1776 /// MCExpr.
1777 const MCExpr *X86TargetLowering::
1778 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1779                              MCContext &Ctx) const {
1780   // X86-64 uses RIP relative addressing based on the jump table label.
1781   if (Subtarget->isPICStyleRIPRel())
1782     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1783
1784   // Otherwise, the reference is relative to the PIC base.
1785   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1786 }
1787
1788 // FIXME: Why this routine is here? Move to RegInfo!
1789 std::pair<const TargetRegisterClass*, uint8_t>
1790 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1791   const TargetRegisterClass *RRC = nullptr;
1792   uint8_t Cost = 1;
1793   switch (VT.SimpleTy) {
1794   default:
1795     return TargetLowering::findRepresentativeClass(VT);
1796   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1797     RRC = Subtarget->is64Bit() ?
1798       (const TargetRegisterClass*)&X86::GR64RegClass :
1799       (const TargetRegisterClass*)&X86::GR32RegClass;
1800     break;
1801   case MVT::x86mmx:
1802     RRC = &X86::VR64RegClass;
1803     break;
1804   case MVT::f32: case MVT::f64:
1805   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1806   case MVT::v4f32: case MVT::v2f64:
1807   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1808   case MVT::v4f64:
1809     RRC = &X86::VR128RegClass;
1810     break;
1811   }
1812   return std::make_pair(RRC, Cost);
1813 }
1814
1815 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1816                                                unsigned &Offset) const {
1817   if (!Subtarget->isTargetLinux())
1818     return false;
1819
1820   if (Subtarget->is64Bit()) {
1821     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1822     Offset = 0x28;
1823     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1824       AddressSpace = 256;
1825     else
1826       AddressSpace = 257;
1827   } else {
1828     // %gs:0x14 on i386
1829     Offset = 0x14;
1830     AddressSpace = 256;
1831   }
1832   return true;
1833 }
1834
1835 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1836                                             unsigned DestAS) const {
1837   assert(SrcAS != DestAS && "Expected different address spaces!");
1838
1839   return SrcAS < 256 && DestAS < 256;
1840 }
1841
1842 //===----------------------------------------------------------------------===//
1843 //               Return Value Calling Convention Implementation
1844 //===----------------------------------------------------------------------===//
1845
1846 #include "X86GenCallingConv.inc"
1847
1848 bool
1849 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1850                                   MachineFunction &MF, bool isVarArg,
1851                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1852                         LLVMContext &Context) const {
1853   SmallVector<CCValAssign, 16> RVLocs;
1854   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1855                  RVLocs, Context);
1856   return CCInfo.CheckReturn(Outs, RetCC_X86);
1857 }
1858
1859 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1860   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1861   return ScratchRegs;
1862 }
1863
1864 SDValue
1865 X86TargetLowering::LowerReturn(SDValue Chain,
1866                                CallingConv::ID CallConv, bool isVarArg,
1867                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1868                                const SmallVectorImpl<SDValue> &OutVals,
1869                                SDLoc dl, SelectionDAG &DAG) const {
1870   MachineFunction &MF = DAG.getMachineFunction();
1871   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1872
1873   SmallVector<CCValAssign, 16> RVLocs;
1874   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1875                  RVLocs, *DAG.getContext());
1876   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1877
1878   SDValue Flag;
1879   SmallVector<SDValue, 6> RetOps;
1880   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1881   // Operand #1 = Bytes To Pop
1882   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1883                    MVT::i16));
1884
1885   // Copy the result values into the output registers.
1886   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1887     CCValAssign &VA = RVLocs[i];
1888     assert(VA.isRegLoc() && "Can only return in registers!");
1889     SDValue ValToCopy = OutVals[i];
1890     EVT ValVT = ValToCopy.getValueType();
1891
1892     // Promote values to the appropriate types
1893     if (VA.getLocInfo() == CCValAssign::SExt)
1894       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1895     else if (VA.getLocInfo() == CCValAssign::ZExt)
1896       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1897     else if (VA.getLocInfo() == CCValAssign::AExt)
1898       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1899     else if (VA.getLocInfo() == CCValAssign::BCvt)
1900       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1901
1902     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1903            "Unexpected FP-extend for return value.");  
1904
1905     // If this is x86-64, and we disabled SSE, we can't return FP values,
1906     // or SSE or MMX vectors.
1907     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1908          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1909           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1910       report_fatal_error("SSE register return with SSE disabled");
1911     }
1912     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1913     // llvm-gcc has never done it right and no one has noticed, so this
1914     // should be OK for now.
1915     if (ValVT == MVT::f64 &&
1916         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1917       report_fatal_error("SSE2 register return with SSE2 disabled");
1918
1919     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1920     // the RET instruction and handled by the FP Stackifier.
1921     if (VA.getLocReg() == X86::ST0 ||
1922         VA.getLocReg() == X86::ST1) {
1923       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1924       // change the value to the FP stack register class.
1925       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1926         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1927       RetOps.push_back(ValToCopy);
1928       // Don't emit a copytoreg.
1929       continue;
1930     }
1931
1932     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1933     // which is returned in RAX / RDX.
1934     if (Subtarget->is64Bit()) {
1935       if (ValVT == MVT::x86mmx) {
1936         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1937           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1938           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1939                                   ValToCopy);
1940           // If we don't have SSE2 available, convert to v4f32 so the generated
1941           // register is legal.
1942           if (!Subtarget->hasSSE2())
1943             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1944         }
1945       }
1946     }
1947
1948     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1949     Flag = Chain.getValue(1);
1950     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1951   }
1952
1953   // The x86-64 ABIs require that for returning structs by value we copy
1954   // the sret argument into %rax/%eax (depending on ABI) for the return.
1955   // Win32 requires us to put the sret argument to %eax as well.
1956   // We saved the argument into a virtual register in the entry block,
1957   // so now we copy the value out and into %rax/%eax.
1958   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1959       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1960     MachineFunction &MF = DAG.getMachineFunction();
1961     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1962     unsigned Reg = FuncInfo->getSRetReturnReg();
1963     assert(Reg &&
1964            "SRetReturnReg should have been set in LowerFormalArguments().");
1965     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1966
1967     unsigned RetValReg
1968         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1969           X86::RAX : X86::EAX;
1970     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1971     Flag = Chain.getValue(1);
1972
1973     // RAX/EAX now acts like a return value.
1974     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1975   }
1976
1977   RetOps[0] = Chain;  // Update chain.
1978
1979   // Add the flag if we have it.
1980   if (Flag.getNode())
1981     RetOps.push_back(Flag);
1982
1983   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1984 }
1985
1986 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1987   if (N->getNumValues() != 1)
1988     return false;
1989   if (!N->hasNUsesOfValue(1, 0))
1990     return false;
1991
1992   SDValue TCChain = Chain;
1993   SDNode *Copy = *N->use_begin();
1994   if (Copy->getOpcode() == ISD::CopyToReg) {
1995     // If the copy has a glue operand, we conservatively assume it isn't safe to
1996     // perform a tail call.
1997     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1998       return false;
1999     TCChain = Copy->getOperand(0);
2000   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2001     return false;
2002
2003   bool HasRet = false;
2004   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2005        UI != UE; ++UI) {
2006     if (UI->getOpcode() != X86ISD::RET_FLAG)
2007       return false;
2008     HasRet = true;
2009   }
2010
2011   if (!HasRet)
2012     return false;
2013
2014   Chain = TCChain;
2015   return true;
2016 }
2017
2018 MVT
2019 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2020                                             ISD::NodeType ExtendKind) const {
2021   MVT ReturnMVT;
2022   // TODO: Is this also valid on 32-bit?
2023   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2024     ReturnMVT = MVT::i8;
2025   else
2026     ReturnMVT = MVT::i32;
2027
2028   MVT MinVT = getRegisterType(ReturnMVT);
2029   return VT.bitsLT(MinVT) ? MinVT : VT;
2030 }
2031
2032 /// LowerCallResult - Lower the result values of a call into the
2033 /// appropriate copies out of appropriate physical registers.
2034 ///
2035 SDValue
2036 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2037                                    CallingConv::ID CallConv, bool isVarArg,
2038                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2039                                    SDLoc dl, SelectionDAG &DAG,
2040                                    SmallVectorImpl<SDValue> &InVals) const {
2041
2042   // Assign locations to each value returned by this call.
2043   SmallVector<CCValAssign, 16> RVLocs;
2044   bool Is64Bit = Subtarget->is64Bit();
2045   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2046                  DAG.getTarget(), RVLocs, *DAG.getContext());
2047   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2048
2049   // Copy all of the result registers out of their specified physreg.
2050   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2051     CCValAssign &VA = RVLocs[i];
2052     EVT CopyVT = VA.getValVT();
2053
2054     // If this is x86-64, and we disabled SSE, we can't return FP values
2055     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2056         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2057       report_fatal_error("SSE register return with SSE disabled");
2058     }
2059
2060     SDValue Val;
2061
2062     // If this is a call to a function that returns an fp value on the floating
2063     // point stack, we must guarantee the value is popped from the stack, so
2064     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2065     // if the return value is not used. We use the FpPOP_RETVAL instruction
2066     // instead.
2067     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2068       // If we prefer to use the value in xmm registers, copy it out as f80 and
2069       // use a truncate to move it from fp stack reg to xmm reg.
2070       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2071       SDValue Ops[] = { Chain, InFlag };
2072       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2073                                          MVT::Other, MVT::Glue, Ops), 1);
2074       Val = Chain.getValue(0);
2075
2076       // Round the f80 to the right size, which also moves it to the appropriate
2077       // xmm register.
2078       if (CopyVT != VA.getValVT())
2079         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2080                           // This truncation won't change the value.
2081                           DAG.getIntPtrConstant(1));
2082     } else {
2083       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2084                                  CopyVT, InFlag).getValue(1);
2085       Val = Chain.getValue(0);
2086     }
2087     InFlag = Chain.getValue(2);
2088     InVals.push_back(Val);
2089   }
2090
2091   return Chain;
2092 }
2093
2094 //===----------------------------------------------------------------------===//
2095 //                C & StdCall & Fast Calling Convention implementation
2096 //===----------------------------------------------------------------------===//
2097 //  StdCall calling convention seems to be standard for many Windows' API
2098 //  routines and around. It differs from C calling convention just a little:
2099 //  callee should clean up the stack, not caller. Symbols should be also
2100 //  decorated in some fancy way :) It doesn't support any vector arguments.
2101 //  For info on fast calling convention see Fast Calling Convention (tail call)
2102 //  implementation LowerX86_32FastCCCallTo.
2103
2104 /// CallIsStructReturn - Determines whether a call uses struct return
2105 /// semantics.
2106 enum StructReturnType {
2107   NotStructReturn,
2108   RegStructReturn,
2109   StackStructReturn
2110 };
2111 static StructReturnType
2112 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2113   if (Outs.empty())
2114     return NotStructReturn;
2115
2116   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2117   if (!Flags.isSRet())
2118     return NotStructReturn;
2119   if (Flags.isInReg())
2120     return RegStructReturn;
2121   return StackStructReturn;
2122 }
2123
2124 /// ArgsAreStructReturn - Determines whether a function uses struct
2125 /// return semantics.
2126 static StructReturnType
2127 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2128   if (Ins.empty())
2129     return NotStructReturn;
2130
2131   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2132   if (!Flags.isSRet())
2133     return NotStructReturn;
2134   if (Flags.isInReg())
2135     return RegStructReturn;
2136   return StackStructReturn;
2137 }
2138
2139 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2140 /// by "Src" to address "Dst" with size and alignment information specified by
2141 /// the specific parameter attribute. The copy will be passed as a byval
2142 /// function parameter.
2143 static SDValue
2144 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2145                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2146                           SDLoc dl) {
2147   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2148
2149   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2150                        /*isVolatile*/false, /*AlwaysInline=*/true,
2151                        MachinePointerInfo(), MachinePointerInfo());
2152 }
2153
2154 /// IsTailCallConvention - Return true if the calling convention is one that
2155 /// supports tail call optimization.
2156 static bool IsTailCallConvention(CallingConv::ID CC) {
2157   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2158           CC == CallingConv::HiPE);
2159 }
2160
2161 /// \brief Return true if the calling convention is a C calling convention.
2162 static bool IsCCallConvention(CallingConv::ID CC) {
2163   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2164           CC == CallingConv::X86_64_SysV);
2165 }
2166
2167 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2168   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2169     return false;
2170
2171   CallSite CS(CI);
2172   CallingConv::ID CalleeCC = CS.getCallingConv();
2173   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2174     return false;
2175
2176   return true;
2177 }
2178
2179 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2180 /// a tailcall target by changing its ABI.
2181 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2182                                    bool GuaranteedTailCallOpt) {
2183   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2184 }
2185
2186 SDValue
2187 X86TargetLowering::LowerMemArgument(SDValue Chain,
2188                                     CallingConv::ID CallConv,
2189                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2190                                     SDLoc dl, SelectionDAG &DAG,
2191                                     const CCValAssign &VA,
2192                                     MachineFrameInfo *MFI,
2193                                     unsigned i) const {
2194   // Create the nodes corresponding to a load from this parameter slot.
2195   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2196   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2197       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2198   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2199   EVT ValVT;
2200
2201   // If value is passed by pointer we have address passed instead of the value
2202   // itself.
2203   if (VA.getLocInfo() == CCValAssign::Indirect)
2204     ValVT = VA.getLocVT();
2205   else
2206     ValVT = VA.getValVT();
2207
2208   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2209   // changed with more analysis.
2210   // In case of tail call optimization mark all arguments mutable. Since they
2211   // could be overwritten by lowering of arguments in case of a tail call.
2212   if (Flags.isByVal()) {
2213     unsigned Bytes = Flags.getByValSize();
2214     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2215     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2216     return DAG.getFrameIndex(FI, getPointerTy());
2217   } else {
2218     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2219                                     VA.getLocMemOffset(), isImmutable);
2220     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2221     return DAG.getLoad(ValVT, dl, Chain, FIN,
2222                        MachinePointerInfo::getFixedStack(FI),
2223                        false, false, false, 0);
2224   }
2225 }
2226
2227 SDValue
2228 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2229                                         CallingConv::ID CallConv,
2230                                         bool isVarArg,
2231                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2232                                         SDLoc dl,
2233                                         SelectionDAG &DAG,
2234                                         SmallVectorImpl<SDValue> &InVals)
2235                                           const {
2236   MachineFunction &MF = DAG.getMachineFunction();
2237   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2238
2239   const Function* Fn = MF.getFunction();
2240   if (Fn->hasExternalLinkage() &&
2241       Subtarget->isTargetCygMing() &&
2242       Fn->getName() == "main")
2243     FuncInfo->setForceFramePointer(true);
2244
2245   MachineFrameInfo *MFI = MF.getFrameInfo();
2246   bool Is64Bit = Subtarget->is64Bit();
2247   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2248
2249   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2250          "Var args not supported with calling convention fastcc, ghc or hipe");
2251
2252   // Assign locations to all of the incoming arguments.
2253   SmallVector<CCValAssign, 16> ArgLocs;
2254   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2255                  ArgLocs, *DAG.getContext());
2256
2257   // Allocate shadow area for Win64
2258   if (IsWin64)
2259     CCInfo.AllocateStack(32, 8);
2260
2261   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2262
2263   unsigned LastVal = ~0U;
2264   SDValue ArgValue;
2265   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2266     CCValAssign &VA = ArgLocs[i];
2267     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2268     // places.
2269     assert(VA.getValNo() != LastVal &&
2270            "Don't support value assigned to multiple locs yet");
2271     (void)LastVal;
2272     LastVal = VA.getValNo();
2273
2274     if (VA.isRegLoc()) {
2275       EVT RegVT = VA.getLocVT();
2276       const TargetRegisterClass *RC;
2277       if (RegVT == MVT::i32)
2278         RC = &X86::GR32RegClass;
2279       else if (Is64Bit && RegVT == MVT::i64)
2280         RC = &X86::GR64RegClass;
2281       else if (RegVT == MVT::f32)
2282         RC = &X86::FR32RegClass;
2283       else if (RegVT == MVT::f64)
2284         RC = &X86::FR64RegClass;
2285       else if (RegVT.is512BitVector())
2286         RC = &X86::VR512RegClass;
2287       else if (RegVT.is256BitVector())
2288         RC = &X86::VR256RegClass;
2289       else if (RegVT.is128BitVector())
2290         RC = &X86::VR128RegClass;
2291       else if (RegVT == MVT::x86mmx)
2292         RC = &X86::VR64RegClass;
2293       else if (RegVT == MVT::i1)
2294         RC = &X86::VK1RegClass;
2295       else if (RegVT == MVT::v8i1)
2296         RC = &X86::VK8RegClass;
2297       else if (RegVT == MVT::v16i1)
2298         RC = &X86::VK16RegClass;
2299       else
2300         llvm_unreachable("Unknown argument type!");
2301
2302       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2303       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2304
2305       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2306       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2307       // right size.
2308       if (VA.getLocInfo() == CCValAssign::SExt)
2309         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2310                                DAG.getValueType(VA.getValVT()));
2311       else if (VA.getLocInfo() == CCValAssign::ZExt)
2312         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2313                                DAG.getValueType(VA.getValVT()));
2314       else if (VA.getLocInfo() == CCValAssign::BCvt)
2315         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2316
2317       if (VA.isExtInLoc()) {
2318         // Handle MMX values passed in XMM regs.
2319         if (RegVT.isVector())
2320           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2321         else
2322           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2323       }
2324     } else {
2325       assert(VA.isMemLoc());
2326       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2327     }
2328
2329     // If value is passed via pointer - do a load.
2330     if (VA.getLocInfo() == CCValAssign::Indirect)
2331       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2332                              MachinePointerInfo(), false, false, false, 0);
2333
2334     InVals.push_back(ArgValue);
2335   }
2336
2337   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2338     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2339       // The x86-64 ABIs require that for returning structs by value we copy
2340       // the sret argument into %rax/%eax (depending on ABI) for the return.
2341       // Win32 requires us to put the sret argument to %eax as well.
2342       // Save the argument into a virtual register so that we can access it
2343       // from the return points.
2344       if (Ins[i].Flags.isSRet()) {
2345         unsigned Reg = FuncInfo->getSRetReturnReg();
2346         if (!Reg) {
2347           MVT PtrTy = getPointerTy();
2348           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2349           FuncInfo->setSRetReturnReg(Reg);
2350         }
2351         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2352         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2353         break;
2354       }
2355     }
2356   }
2357
2358   unsigned StackSize = CCInfo.getNextStackOffset();
2359   // Align stack specially for tail calls.
2360   if (FuncIsMadeTailCallSafe(CallConv,
2361                              MF.getTarget().Options.GuaranteedTailCallOpt))
2362     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2363
2364   // If the function takes variable number of arguments, make a frame index for
2365   // the start of the first vararg value... for expansion of llvm.va_start.
2366   if (isVarArg) {
2367     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2368                     CallConv != CallingConv::X86_ThisCall)) {
2369       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2370     }
2371     if (Is64Bit) {
2372       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2373
2374       // FIXME: We should really autogenerate these arrays
2375       static const MCPhysReg GPR64ArgRegsWin64[] = {
2376         X86::RCX, X86::RDX, X86::R8,  X86::R9
2377       };
2378       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2379         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2380       };
2381       static const MCPhysReg XMMArgRegs64Bit[] = {
2382         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2383         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2384       };
2385       const MCPhysReg *GPR64ArgRegs;
2386       unsigned NumXMMRegs = 0;
2387
2388       if (IsWin64) {
2389         // The XMM registers which might contain var arg parameters are shadowed
2390         // in their paired GPR.  So we only need to save the GPR to their home
2391         // slots.
2392         TotalNumIntRegs = 4;
2393         GPR64ArgRegs = GPR64ArgRegsWin64;
2394       } else {
2395         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2396         GPR64ArgRegs = GPR64ArgRegs64Bit;
2397
2398         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2399                                                 TotalNumXMMRegs);
2400       }
2401       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2402                                                        TotalNumIntRegs);
2403
2404       bool NoImplicitFloatOps = Fn->getAttributes().
2405         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2406       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2407              "SSE register cannot be used when SSE is disabled!");
2408       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2409                NoImplicitFloatOps) &&
2410              "SSE register cannot be used when SSE is disabled!");
2411       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2412           !Subtarget->hasSSE1())
2413         // Kernel mode asks for SSE to be disabled, so don't push them
2414         // on the stack.
2415         TotalNumXMMRegs = 0;
2416
2417       if (IsWin64) {
2418         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2419         // Get to the caller-allocated home save location.  Add 8 to account
2420         // for the return address.
2421         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2422         FuncInfo->setRegSaveFrameIndex(
2423           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2424         // Fixup to set vararg frame on shadow area (4 x i64).
2425         if (NumIntRegs < 4)
2426           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2427       } else {
2428         // For X86-64, if there are vararg parameters that are passed via
2429         // registers, then we must store them to their spots on the stack so
2430         // they may be loaded by deferencing the result of va_next.
2431         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2432         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2433         FuncInfo->setRegSaveFrameIndex(
2434           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2435                                false));
2436       }
2437
2438       // Store the integer parameter registers.
2439       SmallVector<SDValue, 8> MemOps;
2440       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2441                                         getPointerTy());
2442       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2443       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2444         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2445                                   DAG.getIntPtrConstant(Offset));
2446         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2447                                      &X86::GR64RegClass);
2448         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2449         SDValue Store =
2450           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2451                        MachinePointerInfo::getFixedStack(
2452                          FuncInfo->getRegSaveFrameIndex(), Offset),
2453                        false, false, 0);
2454         MemOps.push_back(Store);
2455         Offset += 8;
2456       }
2457
2458       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2459         // Now store the XMM (fp + vector) parameter registers.
2460         SmallVector<SDValue, 11> SaveXMMOps;
2461         SaveXMMOps.push_back(Chain);
2462
2463         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2464         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2465         SaveXMMOps.push_back(ALVal);
2466
2467         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2468                                FuncInfo->getRegSaveFrameIndex()));
2469         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2470                                FuncInfo->getVarArgsFPOffset()));
2471
2472         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2473           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2474                                        &X86::VR128RegClass);
2475           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2476           SaveXMMOps.push_back(Val);
2477         }
2478         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2479                                      MVT::Other, SaveXMMOps));
2480       }
2481
2482       if (!MemOps.empty())
2483         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2484     }
2485   }
2486
2487   // Some CCs need callee pop.
2488   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2489                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2490     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2491   } else {
2492     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2493     // If this is an sret function, the return should pop the hidden pointer.
2494     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2495         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2496         argsAreStructReturn(Ins) == StackStructReturn)
2497       FuncInfo->setBytesToPopOnReturn(4);
2498   }
2499
2500   if (!Is64Bit) {
2501     // RegSaveFrameIndex is X86-64 only.
2502     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2503     if (CallConv == CallingConv::X86_FastCall ||
2504         CallConv == CallingConv::X86_ThisCall)
2505       // fastcc functions can't have varargs.
2506       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2507   }
2508
2509   FuncInfo->setArgumentStackSize(StackSize);
2510
2511   return Chain;
2512 }
2513
2514 SDValue
2515 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2516                                     SDValue StackPtr, SDValue Arg,
2517                                     SDLoc dl, SelectionDAG &DAG,
2518                                     const CCValAssign &VA,
2519                                     ISD::ArgFlagsTy Flags) const {
2520   unsigned LocMemOffset = VA.getLocMemOffset();
2521   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2522   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2523   if (Flags.isByVal())
2524     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2525
2526   return DAG.getStore(Chain, dl, Arg, PtrOff,
2527                       MachinePointerInfo::getStack(LocMemOffset),
2528                       false, false, 0);
2529 }
2530
2531 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2532 /// optimization is performed and it is required.
2533 SDValue
2534 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2535                                            SDValue &OutRetAddr, SDValue Chain,
2536                                            bool IsTailCall, bool Is64Bit,
2537                                            int FPDiff, SDLoc dl) const {
2538   // Adjust the Return address stack slot.
2539   EVT VT = getPointerTy();
2540   OutRetAddr = getReturnAddressFrameIndex(DAG);
2541
2542   // Load the "old" Return address.
2543   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2544                            false, false, false, 0);
2545   return SDValue(OutRetAddr.getNode(), 1);
2546 }
2547
2548 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2549 /// optimization is performed and it is required (FPDiff!=0).
2550 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2551                                         SDValue Chain, SDValue RetAddrFrIdx,
2552                                         EVT PtrVT, unsigned SlotSize,
2553                                         int FPDiff, SDLoc dl) {
2554   // Store the return address to the appropriate stack slot.
2555   if (!FPDiff) return Chain;
2556   // Calculate the new stack slot for the return address.
2557   int NewReturnAddrFI =
2558     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2559                                          false);
2560   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2561   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2562                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2563                        false, false, 0);
2564   return Chain;
2565 }
2566
2567 SDValue
2568 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2569                              SmallVectorImpl<SDValue> &InVals) const {
2570   SelectionDAG &DAG                     = CLI.DAG;
2571   SDLoc &dl                             = CLI.DL;
2572   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2573   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2574   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2575   SDValue Chain                         = CLI.Chain;
2576   SDValue Callee                        = CLI.Callee;
2577   CallingConv::ID CallConv              = CLI.CallConv;
2578   bool &isTailCall                      = CLI.IsTailCall;
2579   bool isVarArg                         = CLI.IsVarArg;
2580
2581   MachineFunction &MF = DAG.getMachineFunction();
2582   bool Is64Bit        = Subtarget->is64Bit();
2583   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2584   StructReturnType SR = callIsStructReturn(Outs);
2585   bool IsSibcall      = false;
2586
2587   if (MF.getTarget().Options.DisableTailCalls)
2588     isTailCall = false;
2589
2590   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2591   if (IsMustTail) {
2592     // Force this to be a tail call.  The verifier rules are enough to ensure
2593     // that we can lower this successfully without moving the return address
2594     // around.
2595     isTailCall = true;
2596   } else if (isTailCall) {
2597     // Check if it's really possible to do a tail call.
2598     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2599                     isVarArg, SR != NotStructReturn,
2600                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2601                     Outs, OutVals, Ins, DAG);
2602
2603     // Sibcalls are automatically detected tailcalls which do not require
2604     // ABI changes.
2605     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2606       IsSibcall = true;
2607
2608     if (isTailCall)
2609       ++NumTailCalls;
2610   }
2611
2612   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2613          "Var args not supported with calling convention fastcc, ghc or hipe");
2614
2615   // Analyze operands of the call, assigning locations to each operand.
2616   SmallVector<CCValAssign, 16> ArgLocs;
2617   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2618                  ArgLocs, *DAG.getContext());
2619
2620   // Allocate shadow area for Win64
2621   if (IsWin64)
2622     CCInfo.AllocateStack(32, 8);
2623
2624   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2625
2626   // Get a count of how many bytes are to be pushed on the stack.
2627   unsigned NumBytes = CCInfo.getNextStackOffset();
2628   if (IsSibcall)
2629     // This is a sibcall. The memory operands are available in caller's
2630     // own caller's stack.
2631     NumBytes = 0;
2632   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2633            IsTailCallConvention(CallConv))
2634     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2635
2636   int FPDiff = 0;
2637   if (isTailCall && !IsSibcall && !IsMustTail) {
2638     // Lower arguments at fp - stackoffset + fpdiff.
2639     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2640     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2641
2642     FPDiff = NumBytesCallerPushed - NumBytes;
2643
2644     // Set the delta of movement of the returnaddr stackslot.
2645     // But only set if delta is greater than previous delta.
2646     if (FPDiff < X86Info->getTCReturnAddrDelta())
2647       X86Info->setTCReturnAddrDelta(FPDiff);
2648   }
2649
2650   unsigned NumBytesToPush = NumBytes;
2651   unsigned NumBytesToPop = NumBytes;
2652
2653   // If we have an inalloca argument, all stack space has already been allocated
2654   // for us and be right at the top of the stack.  We don't support multiple
2655   // arguments passed in memory when using inalloca.
2656   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2657     NumBytesToPush = 0;
2658     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2659            "an inalloca argument must be the only memory argument");
2660   }
2661
2662   if (!IsSibcall)
2663     Chain = DAG.getCALLSEQ_START(
2664         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2665
2666   SDValue RetAddrFrIdx;
2667   // Load return address for tail calls.
2668   if (isTailCall && FPDiff)
2669     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2670                                     Is64Bit, FPDiff, dl);
2671
2672   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2673   SmallVector<SDValue, 8> MemOpChains;
2674   SDValue StackPtr;
2675
2676   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2677   // of tail call optimization arguments are handle later.
2678   const X86RegisterInfo *RegInfo =
2679     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2680   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2681     // Skip inalloca arguments, they have already been written.
2682     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2683     if (Flags.isInAlloca())
2684       continue;
2685
2686     CCValAssign &VA = ArgLocs[i];
2687     EVT RegVT = VA.getLocVT();
2688     SDValue Arg = OutVals[i];
2689     bool isByVal = Flags.isByVal();
2690
2691     // Promote the value if needed.
2692     switch (VA.getLocInfo()) {
2693     default: llvm_unreachable("Unknown loc info!");
2694     case CCValAssign::Full: break;
2695     case CCValAssign::SExt:
2696       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2697       break;
2698     case CCValAssign::ZExt:
2699       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2700       break;
2701     case CCValAssign::AExt:
2702       if (RegVT.is128BitVector()) {
2703         // Special case: passing MMX values in XMM registers.
2704         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2705         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2706         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2707       } else
2708         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2709       break;
2710     case CCValAssign::BCvt:
2711       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2712       break;
2713     case CCValAssign::Indirect: {
2714       // Store the argument.
2715       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2716       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2717       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2718                            MachinePointerInfo::getFixedStack(FI),
2719                            false, false, 0);
2720       Arg = SpillSlot;
2721       break;
2722     }
2723     }
2724
2725     if (VA.isRegLoc()) {
2726       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2727       if (isVarArg && IsWin64) {
2728         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2729         // shadow reg if callee is a varargs function.
2730         unsigned ShadowReg = 0;
2731         switch (VA.getLocReg()) {
2732         case X86::XMM0: ShadowReg = X86::RCX; break;
2733         case X86::XMM1: ShadowReg = X86::RDX; break;
2734         case X86::XMM2: ShadowReg = X86::R8; break;
2735         case X86::XMM3: ShadowReg = X86::R9; break;
2736         }
2737         if (ShadowReg)
2738           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2739       }
2740     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2741       assert(VA.isMemLoc());
2742       if (!StackPtr.getNode())
2743         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2744                                       getPointerTy());
2745       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2746                                              dl, DAG, VA, Flags));
2747     }
2748   }
2749
2750   if (!MemOpChains.empty())
2751     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2752
2753   if (Subtarget->isPICStyleGOT()) {
2754     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2755     // GOT pointer.
2756     if (!isTailCall) {
2757       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2758                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2759     } else {
2760       // If we are tail calling and generating PIC/GOT style code load the
2761       // address of the callee into ECX. The value in ecx is used as target of
2762       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2763       // for tail calls on PIC/GOT architectures. Normally we would just put the
2764       // address of GOT into ebx and then call target@PLT. But for tail calls
2765       // ebx would be restored (since ebx is callee saved) before jumping to the
2766       // target@PLT.
2767
2768       // Note: The actual moving to ECX is done further down.
2769       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2770       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2771           !G->getGlobal()->hasProtectedVisibility())
2772         Callee = LowerGlobalAddress(Callee, DAG);
2773       else if (isa<ExternalSymbolSDNode>(Callee))
2774         Callee = LowerExternalSymbol(Callee, DAG);
2775     }
2776   }
2777
2778   if (Is64Bit && isVarArg && !IsWin64) {
2779     // From AMD64 ABI document:
2780     // For calls that may call functions that use varargs or stdargs
2781     // (prototype-less calls or calls to functions containing ellipsis (...) in
2782     // the declaration) %al is used as hidden argument to specify the number
2783     // of SSE registers used. The contents of %al do not need to match exactly
2784     // the number of registers, but must be an ubound on the number of SSE
2785     // registers used and is in the range 0 - 8 inclusive.
2786
2787     // Count the number of XMM registers allocated.
2788     static const MCPhysReg XMMArgRegs[] = {
2789       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2790       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2791     };
2792     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2793     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2794            && "SSE registers cannot be used when SSE is disabled");
2795
2796     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2797                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2798   }
2799
2800   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2801   // don't need this because the eligibility check rejects calls that require
2802   // shuffling arguments passed in memory.
2803   if (!IsSibcall && isTailCall) {
2804     // Force all the incoming stack arguments to be loaded from the stack
2805     // before any new outgoing arguments are stored to the stack, because the
2806     // outgoing stack slots may alias the incoming argument stack slots, and
2807     // the alias isn't otherwise explicit. This is slightly more conservative
2808     // than necessary, because it means that each store effectively depends
2809     // on every argument instead of just those arguments it would clobber.
2810     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2811
2812     SmallVector<SDValue, 8> MemOpChains2;
2813     SDValue FIN;
2814     int FI = 0;
2815     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2816       CCValAssign &VA = ArgLocs[i];
2817       if (VA.isRegLoc())
2818         continue;
2819       assert(VA.isMemLoc());
2820       SDValue Arg = OutVals[i];
2821       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2822       // Skip inalloca arguments.  They don't require any work.
2823       if (Flags.isInAlloca())
2824         continue;
2825       // Create frame index.
2826       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2827       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2828       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2829       FIN = DAG.getFrameIndex(FI, getPointerTy());
2830
2831       if (Flags.isByVal()) {
2832         // Copy relative to framepointer.
2833         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2834         if (!StackPtr.getNode())
2835           StackPtr = DAG.getCopyFromReg(Chain, dl,
2836                                         RegInfo->getStackRegister(),
2837                                         getPointerTy());
2838         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2839
2840         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2841                                                          ArgChain,
2842                                                          Flags, DAG, dl));
2843       } else {
2844         // Store relative to framepointer.
2845         MemOpChains2.push_back(
2846           DAG.getStore(ArgChain, dl, Arg, FIN,
2847                        MachinePointerInfo::getFixedStack(FI),
2848                        false, false, 0));
2849       }
2850     }
2851
2852     if (!MemOpChains2.empty())
2853       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2854
2855     // Store the return address to the appropriate stack slot.
2856     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2857                                      getPointerTy(), RegInfo->getSlotSize(),
2858                                      FPDiff, dl);
2859   }
2860
2861   // Build a sequence of copy-to-reg nodes chained together with token chain
2862   // and flag operands which copy the outgoing args into registers.
2863   SDValue InFlag;
2864   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2865     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2866                              RegsToPass[i].second, InFlag);
2867     InFlag = Chain.getValue(1);
2868   }
2869
2870   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2871     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2872     // In the 64-bit large code model, we have to make all calls
2873     // through a register, since the call instruction's 32-bit
2874     // pc-relative offset may not be large enough to hold the whole
2875     // address.
2876   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2877     // If the callee is a GlobalAddress node (quite common, every direct call
2878     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2879     // it.
2880
2881     // We should use extra load for direct calls to dllimported functions in
2882     // non-JIT mode.
2883     const GlobalValue *GV = G->getGlobal();
2884     if (!GV->hasDLLImportStorageClass()) {
2885       unsigned char OpFlags = 0;
2886       bool ExtraLoad = false;
2887       unsigned WrapperKind = ISD::DELETED_NODE;
2888
2889       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2890       // external symbols most go through the PLT in PIC mode.  If the symbol
2891       // has hidden or protected visibility, or if it is static or local, then
2892       // we don't need to use the PLT - we can directly call it.
2893       if (Subtarget->isTargetELF() &&
2894           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2895           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2896         OpFlags = X86II::MO_PLT;
2897       } else if (Subtarget->isPICStyleStubAny() &&
2898                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2899                  (!Subtarget->getTargetTriple().isMacOSX() ||
2900                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2901         // PC-relative references to external symbols should go through $stub,
2902         // unless we're building with the leopard linker or later, which
2903         // automatically synthesizes these stubs.
2904         OpFlags = X86II::MO_DARWIN_STUB;
2905       } else if (Subtarget->isPICStyleRIPRel() &&
2906                  isa<Function>(GV) &&
2907                  cast<Function>(GV)->getAttributes().
2908                    hasAttribute(AttributeSet::FunctionIndex,
2909                                 Attribute::NonLazyBind)) {
2910         // If the function is marked as non-lazy, generate an indirect call
2911         // which loads from the GOT directly. This avoids runtime overhead
2912         // at the cost of eager binding (and one extra byte of encoding).
2913         OpFlags = X86II::MO_GOTPCREL;
2914         WrapperKind = X86ISD::WrapperRIP;
2915         ExtraLoad = true;
2916       }
2917
2918       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2919                                           G->getOffset(), OpFlags);
2920
2921       // Add a wrapper if needed.
2922       if (WrapperKind != ISD::DELETED_NODE)
2923         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2924       // Add extra indirection if needed.
2925       if (ExtraLoad)
2926         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2927                              MachinePointerInfo::getGOT(),
2928                              false, false, false, 0);
2929     }
2930   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2931     unsigned char OpFlags = 0;
2932
2933     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2934     // external symbols should go through the PLT.
2935     if (Subtarget->isTargetELF() &&
2936         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2937       OpFlags = X86II::MO_PLT;
2938     } else if (Subtarget->isPICStyleStubAny() &&
2939                (!Subtarget->getTargetTriple().isMacOSX() ||
2940                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2941       // PC-relative references to external symbols should go through $stub,
2942       // unless we're building with the leopard linker or later, which
2943       // automatically synthesizes these stubs.
2944       OpFlags = X86II::MO_DARWIN_STUB;
2945     }
2946
2947     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2948                                          OpFlags);
2949   }
2950
2951   // Returns a chain & a flag for retval copy to use.
2952   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2953   SmallVector<SDValue, 8> Ops;
2954
2955   if (!IsSibcall && isTailCall) {
2956     Chain = DAG.getCALLSEQ_END(Chain,
2957                                DAG.getIntPtrConstant(NumBytesToPop, true),
2958                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2959     InFlag = Chain.getValue(1);
2960   }
2961
2962   Ops.push_back(Chain);
2963   Ops.push_back(Callee);
2964
2965   if (isTailCall)
2966     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2967
2968   // Add argument registers to the end of the list so that they are known live
2969   // into the call.
2970   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2971     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2972                                   RegsToPass[i].second.getValueType()));
2973
2974   // Add a register mask operand representing the call-preserved registers.
2975   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2976   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2977   assert(Mask && "Missing call preserved mask for calling convention");
2978   Ops.push_back(DAG.getRegisterMask(Mask));
2979
2980   if (InFlag.getNode())
2981     Ops.push_back(InFlag);
2982
2983   if (isTailCall) {
2984     // We used to do:
2985     //// If this is the first return lowered for this function, add the regs
2986     //// to the liveout set for the function.
2987     // This isn't right, although it's probably harmless on x86; liveouts
2988     // should be computed from returns not tail calls.  Consider a void
2989     // function making a tail call to a function returning int.
2990     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2991   }
2992
2993   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2994   InFlag = Chain.getValue(1);
2995
2996   // Create the CALLSEQ_END node.
2997   unsigned NumBytesForCalleeToPop;
2998   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2999                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3000     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3001   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3002            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3003            SR == StackStructReturn)
3004     // If this is a call to a struct-return function, the callee
3005     // pops the hidden struct pointer, so we have to push it back.
3006     // This is common for Darwin/X86, Linux & Mingw32 targets.
3007     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3008     NumBytesForCalleeToPop = 4;
3009   else
3010     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3011
3012   // Returns a flag for retval copy to use.
3013   if (!IsSibcall) {
3014     Chain = DAG.getCALLSEQ_END(Chain,
3015                                DAG.getIntPtrConstant(NumBytesToPop, true),
3016                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3017                                                      true),
3018                                InFlag, dl);
3019     InFlag = Chain.getValue(1);
3020   }
3021
3022   // Handle result values, copying them out of physregs into vregs that we
3023   // return.
3024   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3025                          Ins, dl, DAG, InVals);
3026 }
3027
3028 //===----------------------------------------------------------------------===//
3029 //                Fast Calling Convention (tail call) implementation
3030 //===----------------------------------------------------------------------===//
3031
3032 //  Like std call, callee cleans arguments, convention except that ECX is
3033 //  reserved for storing the tail called function address. Only 2 registers are
3034 //  free for argument passing (inreg). Tail call optimization is performed
3035 //  provided:
3036 //                * tailcallopt is enabled
3037 //                * caller/callee are fastcc
3038 //  On X86_64 architecture with GOT-style position independent code only local
3039 //  (within module) calls are supported at the moment.
3040 //  To keep the stack aligned according to platform abi the function
3041 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3042 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3043 //  If a tail called function callee has more arguments than the caller the
3044 //  caller needs to make sure that there is room to move the RETADDR to. This is
3045 //  achieved by reserving an area the size of the argument delta right after the
3046 //  original REtADDR, but before the saved framepointer or the spilled registers
3047 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3048 //  stack layout:
3049 //    arg1
3050 //    arg2
3051 //    RETADDR
3052 //    [ new RETADDR
3053 //      move area ]
3054 //    (possible EBP)
3055 //    ESI
3056 //    EDI
3057 //    local1 ..
3058
3059 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3060 /// for a 16 byte align requirement.
3061 unsigned
3062 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3063                                                SelectionDAG& DAG) const {
3064   MachineFunction &MF = DAG.getMachineFunction();
3065   const TargetMachine &TM = MF.getTarget();
3066   const X86RegisterInfo *RegInfo =
3067     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3068   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3069   unsigned StackAlignment = TFI.getStackAlignment();
3070   uint64_t AlignMask = StackAlignment - 1;
3071   int64_t Offset = StackSize;
3072   unsigned SlotSize = RegInfo->getSlotSize();
3073   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3074     // Number smaller than 12 so just add the difference.
3075     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3076   } else {
3077     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3078     Offset = ((~AlignMask) & Offset) + StackAlignment +
3079       (StackAlignment-SlotSize);
3080   }
3081   return Offset;
3082 }
3083
3084 /// MatchingStackOffset - Return true if the given stack call argument is
3085 /// already available in the same position (relatively) of the caller's
3086 /// incoming argument stack.
3087 static
3088 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3089                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3090                          const X86InstrInfo *TII) {
3091   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3092   int FI = INT_MAX;
3093   if (Arg.getOpcode() == ISD::CopyFromReg) {
3094     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3095     if (!TargetRegisterInfo::isVirtualRegister(VR))
3096       return false;
3097     MachineInstr *Def = MRI->getVRegDef(VR);
3098     if (!Def)
3099       return false;
3100     if (!Flags.isByVal()) {
3101       if (!TII->isLoadFromStackSlot(Def, FI))
3102         return false;
3103     } else {
3104       unsigned Opcode = Def->getOpcode();
3105       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3106           Def->getOperand(1).isFI()) {
3107         FI = Def->getOperand(1).getIndex();
3108         Bytes = Flags.getByValSize();
3109       } else
3110         return false;
3111     }
3112   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3113     if (Flags.isByVal())
3114       // ByVal argument is passed in as a pointer but it's now being
3115       // dereferenced. e.g.
3116       // define @foo(%struct.X* %A) {
3117       //   tail call @bar(%struct.X* byval %A)
3118       // }
3119       return false;
3120     SDValue Ptr = Ld->getBasePtr();
3121     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3122     if (!FINode)
3123       return false;
3124     FI = FINode->getIndex();
3125   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3126     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3127     FI = FINode->getIndex();
3128     Bytes = Flags.getByValSize();
3129   } else
3130     return false;
3131
3132   assert(FI != INT_MAX);
3133   if (!MFI->isFixedObjectIndex(FI))
3134     return false;
3135   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3136 }
3137
3138 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3139 /// for tail call optimization. Targets which want to do tail call
3140 /// optimization should implement this function.
3141 bool
3142 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3143                                                      CallingConv::ID CalleeCC,
3144                                                      bool isVarArg,
3145                                                      bool isCalleeStructRet,
3146                                                      bool isCallerStructRet,
3147                                                      Type *RetTy,
3148                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3149                                     const SmallVectorImpl<SDValue> &OutVals,
3150                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3151                                                      SelectionDAG &DAG) const {
3152   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3153     return false;
3154
3155   // If -tailcallopt is specified, make fastcc functions tail-callable.
3156   const MachineFunction &MF = DAG.getMachineFunction();
3157   const Function *CallerF = MF.getFunction();
3158
3159   // If the function return type is x86_fp80 and the callee return type is not,
3160   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3161   // perform a tailcall optimization here.
3162   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3163     return false;
3164
3165   CallingConv::ID CallerCC = CallerF->getCallingConv();
3166   bool CCMatch = CallerCC == CalleeCC;
3167   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3168   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3169
3170   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3171     if (IsTailCallConvention(CalleeCC) && CCMatch)
3172       return true;
3173     return false;
3174   }
3175
3176   // Look for obvious safe cases to perform tail call optimization that do not
3177   // require ABI changes. This is what gcc calls sibcall.
3178
3179   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3180   // emit a special epilogue.
3181   const X86RegisterInfo *RegInfo =
3182     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3183   if (RegInfo->needsStackRealignment(MF))
3184     return false;
3185
3186   // Also avoid sibcall optimization if either caller or callee uses struct
3187   // return semantics.
3188   if (isCalleeStructRet || isCallerStructRet)
3189     return false;
3190
3191   // An stdcall/thiscall caller is expected to clean up its arguments; the
3192   // callee isn't going to do that.
3193   // FIXME: this is more restrictive than needed. We could produce a tailcall
3194   // when the stack adjustment matches. For example, with a thiscall that takes
3195   // only one argument.
3196   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3197                    CallerCC == CallingConv::X86_ThisCall))
3198     return false;
3199
3200   // Do not sibcall optimize vararg calls unless all arguments are passed via
3201   // registers.
3202   if (isVarArg && !Outs.empty()) {
3203
3204     // Optimizing for varargs on Win64 is unlikely to be safe without
3205     // additional testing.
3206     if (IsCalleeWin64 || IsCallerWin64)
3207       return false;
3208
3209     SmallVector<CCValAssign, 16> ArgLocs;
3210     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3211                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3212
3213     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3214     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3215       if (!ArgLocs[i].isRegLoc())
3216         return false;
3217   }
3218
3219   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3220   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3221   // this into a sibcall.
3222   bool Unused = false;
3223   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3224     if (!Ins[i].Used) {
3225       Unused = true;
3226       break;
3227     }
3228   }
3229   if (Unused) {
3230     SmallVector<CCValAssign, 16> RVLocs;
3231     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3232                    DAG.getTarget(), RVLocs, *DAG.getContext());
3233     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3234     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3235       CCValAssign &VA = RVLocs[i];
3236       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3237         return false;
3238     }
3239   }
3240
3241   // If the calling conventions do not match, then we'd better make sure the
3242   // results are returned in the same way as what the caller expects.
3243   if (!CCMatch) {
3244     SmallVector<CCValAssign, 16> RVLocs1;
3245     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3246                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3247     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3248
3249     SmallVector<CCValAssign, 16> RVLocs2;
3250     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3251                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3252     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3253
3254     if (RVLocs1.size() != RVLocs2.size())
3255       return false;
3256     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3257       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3258         return false;
3259       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3260         return false;
3261       if (RVLocs1[i].isRegLoc()) {
3262         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3263           return false;
3264       } else {
3265         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3266           return false;
3267       }
3268     }
3269   }
3270
3271   // If the callee takes no arguments then go on to check the results of the
3272   // call.
3273   if (!Outs.empty()) {
3274     // Check if stack adjustment is needed. For now, do not do this if any
3275     // argument is passed on the stack.
3276     SmallVector<CCValAssign, 16> ArgLocs;
3277     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3278                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3279
3280     // Allocate shadow area for Win64
3281     if (IsCalleeWin64)
3282       CCInfo.AllocateStack(32, 8);
3283
3284     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3285     if (CCInfo.getNextStackOffset()) {
3286       MachineFunction &MF = DAG.getMachineFunction();
3287       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3288         return false;
3289
3290       // Check if the arguments are already laid out in the right way as
3291       // the caller's fixed stack objects.
3292       MachineFrameInfo *MFI = MF.getFrameInfo();
3293       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3294       const X86InstrInfo *TII =
3295           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3296       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3297         CCValAssign &VA = ArgLocs[i];
3298         SDValue Arg = OutVals[i];
3299         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3300         if (VA.getLocInfo() == CCValAssign::Indirect)
3301           return false;
3302         if (!VA.isRegLoc()) {
3303           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3304                                    MFI, MRI, TII))
3305             return false;
3306         }
3307       }
3308     }
3309
3310     // If the tailcall address may be in a register, then make sure it's
3311     // possible to register allocate for it. In 32-bit, the call address can
3312     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3313     // callee-saved registers are restored. These happen to be the same
3314     // registers used to pass 'inreg' arguments so watch out for those.
3315     if (!Subtarget->is64Bit() &&
3316         ((!isa<GlobalAddressSDNode>(Callee) &&
3317           !isa<ExternalSymbolSDNode>(Callee)) ||
3318          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3319       unsigned NumInRegs = 0;
3320       // In PIC we need an extra register to formulate the address computation
3321       // for the callee.
3322       unsigned MaxInRegs =
3323         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3324
3325       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3326         CCValAssign &VA = ArgLocs[i];
3327         if (!VA.isRegLoc())
3328           continue;
3329         unsigned Reg = VA.getLocReg();
3330         switch (Reg) {
3331         default: break;
3332         case X86::EAX: case X86::EDX: case X86::ECX:
3333           if (++NumInRegs == MaxInRegs)
3334             return false;
3335           break;
3336         }
3337       }
3338     }
3339   }
3340
3341   return true;
3342 }
3343
3344 FastISel *
3345 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3346                                   const TargetLibraryInfo *libInfo) const {
3347   return X86::createFastISel(funcInfo, libInfo);
3348 }
3349
3350 //===----------------------------------------------------------------------===//
3351 //                           Other Lowering Hooks
3352 //===----------------------------------------------------------------------===//
3353
3354 static bool MayFoldLoad(SDValue Op) {
3355   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3356 }
3357
3358 static bool MayFoldIntoStore(SDValue Op) {
3359   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3360 }
3361
3362 static bool isTargetShuffle(unsigned Opcode) {
3363   switch(Opcode) {
3364   default: return false;
3365   case X86ISD::PSHUFD:
3366   case X86ISD::PSHUFHW:
3367   case X86ISD::PSHUFLW:
3368   case X86ISD::SHUFP:
3369   case X86ISD::PALIGNR:
3370   case X86ISD::MOVLHPS:
3371   case X86ISD::MOVLHPD:
3372   case X86ISD::MOVHLPS:
3373   case X86ISD::MOVLPS:
3374   case X86ISD::MOVLPD:
3375   case X86ISD::MOVSHDUP:
3376   case X86ISD::MOVSLDUP:
3377   case X86ISD::MOVDDUP:
3378   case X86ISD::MOVSS:
3379   case X86ISD::MOVSD:
3380   case X86ISD::UNPCKL:
3381   case X86ISD::UNPCKH:
3382   case X86ISD::VPERMILP:
3383   case X86ISD::VPERM2X128:
3384   case X86ISD::VPERMI:
3385     return true;
3386   }
3387 }
3388
3389 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3390                                     SDValue V1, SelectionDAG &DAG) {
3391   switch(Opc) {
3392   default: llvm_unreachable("Unknown x86 shuffle node");
3393   case X86ISD::MOVSHDUP:
3394   case X86ISD::MOVSLDUP:
3395   case X86ISD::MOVDDUP:
3396     return DAG.getNode(Opc, dl, VT, V1);
3397   }
3398 }
3399
3400 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3401                                     SDValue V1, unsigned TargetMask,
3402                                     SelectionDAG &DAG) {
3403   switch(Opc) {
3404   default: llvm_unreachable("Unknown x86 shuffle node");
3405   case X86ISD::PSHUFD:
3406   case X86ISD::PSHUFHW:
3407   case X86ISD::PSHUFLW:
3408   case X86ISD::VPERMILP:
3409   case X86ISD::VPERMI:
3410     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3411   }
3412 }
3413
3414 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3415                                     SDValue V1, SDValue V2, unsigned TargetMask,
3416                                     SelectionDAG &DAG) {
3417   switch(Opc) {
3418   default: llvm_unreachable("Unknown x86 shuffle node");
3419   case X86ISD::PALIGNR:
3420   case X86ISD::SHUFP:
3421   case X86ISD::VPERM2X128:
3422     return DAG.getNode(Opc, dl, VT, V1, V2,
3423                        DAG.getConstant(TargetMask, MVT::i8));
3424   }
3425 }
3426
3427 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3428                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3429   switch(Opc) {
3430   default: llvm_unreachable("Unknown x86 shuffle node");
3431   case X86ISD::MOVLHPS:
3432   case X86ISD::MOVLHPD:
3433   case X86ISD::MOVHLPS:
3434   case X86ISD::MOVLPS:
3435   case X86ISD::MOVLPD:
3436   case X86ISD::MOVSS:
3437   case X86ISD::MOVSD:
3438   case X86ISD::UNPCKL:
3439   case X86ISD::UNPCKH:
3440     return DAG.getNode(Opc, dl, VT, V1, V2);
3441   }
3442 }
3443
3444 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3445   MachineFunction &MF = DAG.getMachineFunction();
3446   const X86RegisterInfo *RegInfo =
3447     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3448   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3449   int ReturnAddrIndex = FuncInfo->getRAIndex();
3450
3451   if (ReturnAddrIndex == 0) {
3452     // Set up a frame object for the return address.
3453     unsigned SlotSize = RegInfo->getSlotSize();
3454     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3455                                                            -(int64_t)SlotSize,
3456                                                            false);
3457     FuncInfo->setRAIndex(ReturnAddrIndex);
3458   }
3459
3460   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3461 }
3462
3463 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3464                                        bool hasSymbolicDisplacement) {
3465   // Offset should fit into 32 bit immediate field.
3466   if (!isInt<32>(Offset))
3467     return false;
3468
3469   // If we don't have a symbolic displacement - we don't have any extra
3470   // restrictions.
3471   if (!hasSymbolicDisplacement)
3472     return true;
3473
3474   // FIXME: Some tweaks might be needed for medium code model.
3475   if (M != CodeModel::Small && M != CodeModel::Kernel)
3476     return false;
3477
3478   // For small code model we assume that latest object is 16MB before end of 31
3479   // bits boundary. We may also accept pretty large negative constants knowing
3480   // that all objects are in the positive half of address space.
3481   if (M == CodeModel::Small && Offset < 16*1024*1024)
3482     return true;
3483
3484   // For kernel code model we know that all object resist in the negative half
3485   // of 32bits address space. We may not accept negative offsets, since they may
3486   // be just off and we may accept pretty large positive ones.
3487   if (M == CodeModel::Kernel && Offset > 0)
3488     return true;
3489
3490   return false;
3491 }
3492
3493 /// isCalleePop - Determines whether the callee is required to pop its
3494 /// own arguments. Callee pop is necessary to support tail calls.
3495 bool X86::isCalleePop(CallingConv::ID CallingConv,
3496                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3497   if (IsVarArg)
3498     return false;
3499
3500   switch (CallingConv) {
3501   default:
3502     return false;
3503   case CallingConv::X86_StdCall:
3504     return !is64Bit;
3505   case CallingConv::X86_FastCall:
3506     return !is64Bit;
3507   case CallingConv::X86_ThisCall:
3508     return !is64Bit;
3509   case CallingConv::Fast:
3510     return TailCallOpt;
3511   case CallingConv::GHC:
3512     return TailCallOpt;
3513   case CallingConv::HiPE:
3514     return TailCallOpt;
3515   }
3516 }
3517
3518 /// \brief Return true if the condition is an unsigned comparison operation.
3519 static bool isX86CCUnsigned(unsigned X86CC) {
3520   switch (X86CC) {
3521   default: llvm_unreachable("Invalid integer condition!");
3522   case X86::COND_E:     return true;
3523   case X86::COND_G:     return false;
3524   case X86::COND_GE:    return false;
3525   case X86::COND_L:     return false;
3526   case X86::COND_LE:    return false;
3527   case X86::COND_NE:    return true;
3528   case X86::COND_B:     return true;
3529   case X86::COND_A:     return true;
3530   case X86::COND_BE:    return true;
3531   case X86::COND_AE:    return true;
3532   }
3533   llvm_unreachable("covered switch fell through?!");
3534 }
3535
3536 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3537 /// specific condition code, returning the condition code and the LHS/RHS of the
3538 /// comparison to make.
3539 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3540                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3541   if (!isFP) {
3542     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3543       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3544         // X > -1   -> X == 0, jump !sign.
3545         RHS = DAG.getConstant(0, RHS.getValueType());
3546         return X86::COND_NS;
3547       }
3548       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3549         // X < 0   -> X == 0, jump on sign.
3550         return X86::COND_S;
3551       }
3552       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3553         // X < 1   -> X <= 0
3554         RHS = DAG.getConstant(0, RHS.getValueType());
3555         return X86::COND_LE;
3556       }
3557     }
3558
3559     switch (SetCCOpcode) {
3560     default: llvm_unreachable("Invalid integer condition!");
3561     case ISD::SETEQ:  return X86::COND_E;
3562     case ISD::SETGT:  return X86::COND_G;
3563     case ISD::SETGE:  return X86::COND_GE;
3564     case ISD::SETLT:  return X86::COND_L;
3565     case ISD::SETLE:  return X86::COND_LE;
3566     case ISD::SETNE:  return X86::COND_NE;
3567     case ISD::SETULT: return X86::COND_B;
3568     case ISD::SETUGT: return X86::COND_A;
3569     case ISD::SETULE: return X86::COND_BE;
3570     case ISD::SETUGE: return X86::COND_AE;
3571     }
3572   }
3573
3574   // First determine if it is required or is profitable to flip the operands.
3575
3576   // If LHS is a foldable load, but RHS is not, flip the condition.
3577   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3578       !ISD::isNON_EXTLoad(RHS.getNode())) {
3579     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3580     std::swap(LHS, RHS);
3581   }
3582
3583   switch (SetCCOpcode) {
3584   default: break;
3585   case ISD::SETOLT:
3586   case ISD::SETOLE:
3587   case ISD::SETUGT:
3588   case ISD::SETUGE:
3589     std::swap(LHS, RHS);
3590     break;
3591   }
3592
3593   // On a floating point condition, the flags are set as follows:
3594   // ZF  PF  CF   op
3595   //  0 | 0 | 0 | X > Y
3596   //  0 | 0 | 1 | X < Y
3597   //  1 | 0 | 0 | X == Y
3598   //  1 | 1 | 1 | unordered
3599   switch (SetCCOpcode) {
3600   default: llvm_unreachable("Condcode should be pre-legalized away");
3601   case ISD::SETUEQ:
3602   case ISD::SETEQ:   return X86::COND_E;
3603   case ISD::SETOLT:              // flipped
3604   case ISD::SETOGT:
3605   case ISD::SETGT:   return X86::COND_A;
3606   case ISD::SETOLE:              // flipped
3607   case ISD::SETOGE:
3608   case ISD::SETGE:   return X86::COND_AE;
3609   case ISD::SETUGT:              // flipped
3610   case ISD::SETULT:
3611   case ISD::SETLT:   return X86::COND_B;
3612   case ISD::SETUGE:              // flipped
3613   case ISD::SETULE:
3614   case ISD::SETLE:   return X86::COND_BE;
3615   case ISD::SETONE:
3616   case ISD::SETNE:   return X86::COND_NE;
3617   case ISD::SETUO:   return X86::COND_P;
3618   case ISD::SETO:    return X86::COND_NP;
3619   case ISD::SETOEQ:
3620   case ISD::SETUNE:  return X86::COND_INVALID;
3621   }
3622 }
3623
3624 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3625 /// code. Current x86 isa includes the following FP cmov instructions:
3626 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3627 static bool hasFPCMov(unsigned X86CC) {
3628   switch (X86CC) {
3629   default:
3630     return false;
3631   case X86::COND_B:
3632   case X86::COND_BE:
3633   case X86::COND_E:
3634   case X86::COND_P:
3635   case X86::COND_A:
3636   case X86::COND_AE:
3637   case X86::COND_NE:
3638   case X86::COND_NP:
3639     return true;
3640   }
3641 }
3642
3643 /// isFPImmLegal - Returns true if the target can instruction select the
3644 /// specified FP immediate natively. If false, the legalizer will
3645 /// materialize the FP immediate as a load from a constant pool.
3646 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3647   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3648     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3649       return true;
3650   }
3651   return false;
3652 }
3653
3654 /// \brief Returns true if it is beneficial to convert a load of a constant
3655 /// to just the constant itself.
3656 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3657                                                           Type *Ty) const {
3658   assert(Ty->isIntegerTy());
3659
3660   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3661   if (BitSize == 0 || BitSize > 64)
3662     return false;
3663   return true;
3664 }
3665
3666 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3667 /// the specified range (L, H].
3668 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3669   return (Val < 0) || (Val >= Low && Val < Hi);
3670 }
3671
3672 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3673 /// specified value.
3674 static bool isUndefOrEqual(int Val, int CmpVal) {
3675   return (Val < 0 || Val == CmpVal);
3676 }
3677
3678 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3679 /// from position Pos and ending in Pos+Size, falls within the specified
3680 /// sequential range (L, L+Pos]. or is undef.
3681 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3682                                        unsigned Pos, unsigned Size, int Low) {
3683   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3684     if (!isUndefOrEqual(Mask[i], Low))
3685       return false;
3686   return true;
3687 }
3688
3689 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3690 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3691 /// the second operand.
3692 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3693   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3694     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3695   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3696     return (Mask[0] < 2 && Mask[1] < 2);
3697   return false;
3698 }
3699
3700 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3701 /// is suitable for input to PSHUFHW.
3702 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3703   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3704     return false;
3705
3706   // Lower quadword copied in order or undef.
3707   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3708     return false;
3709
3710   // Upper quadword shuffled.
3711   for (unsigned i = 4; i != 8; ++i)
3712     if (!isUndefOrInRange(Mask[i], 4, 8))
3713       return false;
3714
3715   if (VT == MVT::v16i16) {
3716     // Lower quadword copied in order or undef.
3717     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3718       return false;
3719
3720     // Upper quadword shuffled.
3721     for (unsigned i = 12; i != 16; ++i)
3722       if (!isUndefOrInRange(Mask[i], 12, 16))
3723         return false;
3724   }
3725
3726   return true;
3727 }
3728
3729 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3730 /// is suitable for input to PSHUFLW.
3731 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3732   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3733     return false;
3734
3735   // Upper quadword copied in order.
3736   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3737     return false;
3738
3739   // Lower quadword shuffled.
3740   for (unsigned i = 0; i != 4; ++i)
3741     if (!isUndefOrInRange(Mask[i], 0, 4))
3742       return false;
3743
3744   if (VT == MVT::v16i16) {
3745     // Upper quadword copied in order.
3746     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3747       return false;
3748
3749     // Lower quadword shuffled.
3750     for (unsigned i = 8; i != 12; ++i)
3751       if (!isUndefOrInRange(Mask[i], 8, 12))
3752         return false;
3753   }
3754
3755   return true;
3756 }
3757
3758 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3759 /// is suitable for input to PALIGNR.
3760 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3761                           const X86Subtarget *Subtarget) {
3762   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3763       (VT.is256BitVector() && !Subtarget->hasInt256()))
3764     return false;
3765
3766   unsigned NumElts = VT.getVectorNumElements();
3767   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3768   unsigned NumLaneElts = NumElts/NumLanes;
3769
3770   // Do not handle 64-bit element shuffles with palignr.
3771   if (NumLaneElts == 2)
3772     return false;
3773
3774   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3775     unsigned i;
3776     for (i = 0; i != NumLaneElts; ++i) {
3777       if (Mask[i+l] >= 0)
3778         break;
3779     }
3780
3781     // Lane is all undef, go to next lane
3782     if (i == NumLaneElts)
3783       continue;
3784
3785     int Start = Mask[i+l];
3786
3787     // Make sure its in this lane in one of the sources
3788     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3789         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3790       return false;
3791
3792     // If not lane 0, then we must match lane 0
3793     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3794       return false;
3795
3796     // Correct second source to be contiguous with first source
3797     if (Start >= (int)NumElts)
3798       Start -= NumElts - NumLaneElts;
3799
3800     // Make sure we're shifting in the right direction.
3801     if (Start <= (int)(i+l))
3802       return false;
3803
3804     Start -= i;
3805
3806     // Check the rest of the elements to see if they are consecutive.
3807     for (++i; i != NumLaneElts; ++i) {
3808       int Idx = Mask[i+l];
3809
3810       // Make sure its in this lane
3811       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3812           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3813         return false;
3814
3815       // If not lane 0, then we must match lane 0
3816       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3817         return false;
3818
3819       if (Idx >= (int)NumElts)
3820         Idx -= NumElts - NumLaneElts;
3821
3822       if (!isUndefOrEqual(Idx, Start+i))
3823         return false;
3824
3825     }
3826   }
3827
3828   return true;
3829 }
3830
3831 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3832 /// the two vector operands have swapped position.
3833 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3834                                      unsigned NumElems) {
3835   for (unsigned i = 0; i != NumElems; ++i) {
3836     int idx = Mask[i];
3837     if (idx < 0)
3838       continue;
3839     else if (idx < (int)NumElems)
3840       Mask[i] = idx + NumElems;
3841     else
3842       Mask[i] = idx - NumElems;
3843   }
3844 }
3845
3846 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3847 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3848 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3849 /// reverse of what x86 shuffles want.
3850 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3851
3852   unsigned NumElems = VT.getVectorNumElements();
3853   unsigned NumLanes = VT.getSizeInBits()/128;
3854   unsigned NumLaneElems = NumElems/NumLanes;
3855
3856   if (NumLaneElems != 2 && NumLaneElems != 4)
3857     return false;
3858
3859   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3860   bool symetricMaskRequired =
3861     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3862
3863   // VSHUFPSY divides the resulting vector into 4 chunks.
3864   // The sources are also splitted into 4 chunks, and each destination
3865   // chunk must come from a different source chunk.
3866   //
3867   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3868   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3869   //
3870   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3871   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3872   //
3873   // VSHUFPDY divides the resulting vector into 4 chunks.
3874   // The sources are also splitted into 4 chunks, and each destination
3875   // chunk must come from a different source chunk.
3876   //
3877   //  SRC1 =>      X3       X2       X1       X0
3878   //  SRC2 =>      Y3       Y2       Y1       Y0
3879   //
3880   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3881   //
3882   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3883   unsigned HalfLaneElems = NumLaneElems/2;
3884   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3885     for (unsigned i = 0; i != NumLaneElems; ++i) {
3886       int Idx = Mask[i+l];
3887       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3888       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3889         return false;
3890       // For VSHUFPSY, the mask of the second half must be the same as the
3891       // first but with the appropriate offsets. This works in the same way as
3892       // VPERMILPS works with masks.
3893       if (!symetricMaskRequired || Idx < 0)
3894         continue;
3895       if (MaskVal[i] < 0) {
3896         MaskVal[i] = Idx - l;
3897         continue;
3898       }
3899       if ((signed)(Idx - l) != MaskVal[i])
3900         return false;
3901     }
3902   }
3903
3904   return true;
3905 }
3906
3907 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3908 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3909 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3910   if (!VT.is128BitVector())
3911     return false;
3912
3913   unsigned NumElems = VT.getVectorNumElements();
3914
3915   if (NumElems != 4)
3916     return false;
3917
3918   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3919   return isUndefOrEqual(Mask[0], 6) &&
3920          isUndefOrEqual(Mask[1], 7) &&
3921          isUndefOrEqual(Mask[2], 2) &&
3922          isUndefOrEqual(Mask[3], 3);
3923 }
3924
3925 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3926 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3927 /// <2, 3, 2, 3>
3928 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3929   if (!VT.is128BitVector())
3930     return false;
3931
3932   unsigned NumElems = VT.getVectorNumElements();
3933
3934   if (NumElems != 4)
3935     return false;
3936
3937   return isUndefOrEqual(Mask[0], 2) &&
3938          isUndefOrEqual(Mask[1], 3) &&
3939          isUndefOrEqual(Mask[2], 2) &&
3940          isUndefOrEqual(Mask[3], 3);
3941 }
3942
3943 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3944 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3945 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3946   if (!VT.is128BitVector())
3947     return false;
3948
3949   unsigned NumElems = VT.getVectorNumElements();
3950
3951   if (NumElems != 2 && NumElems != 4)
3952     return false;
3953
3954   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3955     if (!isUndefOrEqual(Mask[i], i + NumElems))
3956       return false;
3957
3958   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3959     if (!isUndefOrEqual(Mask[i], i))
3960       return false;
3961
3962   return true;
3963 }
3964
3965 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3966 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3967 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3968   if (!VT.is128BitVector())
3969     return false;
3970
3971   unsigned NumElems = VT.getVectorNumElements();
3972
3973   if (NumElems != 2 && NumElems != 4)
3974     return false;
3975
3976   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3977     if (!isUndefOrEqual(Mask[i], i))
3978       return false;
3979
3980   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3981     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3982       return false;
3983
3984   return true;
3985 }
3986
3987 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3988 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3989 /// i. e: If all but one element come from the same vector.
3990 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3991   // TODO: Deal with AVX's VINSERTPS
3992   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3993     return false;
3994
3995   unsigned CorrectPosV1 = 0;
3996   unsigned CorrectPosV2 = 0;
3997   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3998     if (Mask[i] == -1) {
3999       ++CorrectPosV1;
4000       ++CorrectPosV2;
4001       continue;
4002     }
4003
4004     if (Mask[i] == i)
4005       ++CorrectPosV1;
4006     else if (Mask[i] == i + 4)
4007       ++CorrectPosV2;
4008   }
4009
4010   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
4011     // We have 3 elements (undefs count as elements from any vector) from one
4012     // vector, and one from another.
4013     return true;
4014
4015   return false;
4016 }
4017
4018 //
4019 // Some special combinations that can be optimized.
4020 //
4021 static
4022 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4023                                SelectionDAG &DAG) {
4024   MVT VT = SVOp->getSimpleValueType(0);
4025   SDLoc dl(SVOp);
4026
4027   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4028     return SDValue();
4029
4030   ArrayRef<int> Mask = SVOp->getMask();
4031
4032   // These are the special masks that may be optimized.
4033   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4034   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4035   bool MatchEvenMask = true;
4036   bool MatchOddMask  = true;
4037   for (int i=0; i<8; ++i) {
4038     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4039       MatchEvenMask = false;
4040     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4041       MatchOddMask = false;
4042   }
4043
4044   if (!MatchEvenMask && !MatchOddMask)
4045     return SDValue();
4046
4047   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4048
4049   SDValue Op0 = SVOp->getOperand(0);
4050   SDValue Op1 = SVOp->getOperand(1);
4051
4052   if (MatchEvenMask) {
4053     // Shift the second operand right to 32 bits.
4054     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4055     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4056   } else {
4057     // Shift the first operand left to 32 bits.
4058     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4059     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4060   }
4061   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4062   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4063 }
4064
4065 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4066 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4067 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4068                          bool HasInt256, bool V2IsSplat = false) {
4069
4070   assert(VT.getSizeInBits() >= 128 &&
4071          "Unsupported vector type for unpckl");
4072
4073   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4074   unsigned NumLanes;
4075   unsigned NumOf256BitLanes;
4076   unsigned NumElts = VT.getVectorNumElements();
4077   if (VT.is256BitVector()) {
4078     if (NumElts != 4 && NumElts != 8 &&
4079         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4080     return false;
4081     NumLanes = 2;
4082     NumOf256BitLanes = 1;
4083   } else if (VT.is512BitVector()) {
4084     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4085            "Unsupported vector type for unpckh");
4086     NumLanes = 2;
4087     NumOf256BitLanes = 2;
4088   } else {
4089     NumLanes = 1;
4090     NumOf256BitLanes = 1;
4091   }
4092
4093   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4094   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4095
4096   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4097     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4098       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4099         int BitI  = Mask[l256*NumEltsInStride+l+i];
4100         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4101         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4102           return false;
4103         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4104           return false;
4105         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4106           return false;
4107       }
4108     }
4109   }
4110   return true;
4111 }
4112
4113 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4114 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4115 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4116                          bool HasInt256, bool V2IsSplat = false) {
4117   assert(VT.getSizeInBits() >= 128 &&
4118          "Unsupported vector type for unpckh");
4119
4120   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4121   unsigned NumLanes;
4122   unsigned NumOf256BitLanes;
4123   unsigned NumElts = VT.getVectorNumElements();
4124   if (VT.is256BitVector()) {
4125     if (NumElts != 4 && NumElts != 8 &&
4126         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4127     return false;
4128     NumLanes = 2;
4129     NumOf256BitLanes = 1;
4130   } else if (VT.is512BitVector()) {
4131     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4132            "Unsupported vector type for unpckh");
4133     NumLanes = 2;
4134     NumOf256BitLanes = 2;
4135   } else {
4136     NumLanes = 1;
4137     NumOf256BitLanes = 1;
4138   }
4139
4140   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4141   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4142
4143   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4144     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4145       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4146         int BitI  = Mask[l256*NumEltsInStride+l+i];
4147         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4148         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4149           return false;
4150         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4151           return false;
4152         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4153           return false;
4154       }
4155     }
4156   }
4157   return true;
4158 }
4159
4160 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4161 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4162 /// <0, 0, 1, 1>
4163 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4164   unsigned NumElts = VT.getVectorNumElements();
4165   bool Is256BitVec = VT.is256BitVector();
4166
4167   if (VT.is512BitVector())
4168     return false;
4169   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4170          "Unsupported vector type for unpckh");
4171
4172   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4173       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4174     return false;
4175
4176   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4177   // FIXME: Need a better way to get rid of this, there's no latency difference
4178   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4179   // the former later. We should also remove the "_undef" special mask.
4180   if (NumElts == 4 && Is256BitVec)
4181     return false;
4182
4183   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4184   // independently on 128-bit lanes.
4185   unsigned NumLanes = VT.getSizeInBits()/128;
4186   unsigned NumLaneElts = NumElts/NumLanes;
4187
4188   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4189     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4190       int BitI  = Mask[l+i];
4191       int BitI1 = Mask[l+i+1];
4192
4193       if (!isUndefOrEqual(BitI, j))
4194         return false;
4195       if (!isUndefOrEqual(BitI1, j))
4196         return false;
4197     }
4198   }
4199
4200   return true;
4201 }
4202
4203 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4204 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4205 /// <2, 2, 3, 3>
4206 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4207   unsigned NumElts = VT.getVectorNumElements();
4208
4209   if (VT.is512BitVector())
4210     return false;
4211
4212   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4213          "Unsupported vector type for unpckh");
4214
4215   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4216       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4217     return false;
4218
4219   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4220   // independently on 128-bit lanes.
4221   unsigned NumLanes = VT.getSizeInBits()/128;
4222   unsigned NumLaneElts = NumElts/NumLanes;
4223
4224   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4225     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4226       int BitI  = Mask[l+i];
4227       int BitI1 = Mask[l+i+1];
4228       if (!isUndefOrEqual(BitI, j))
4229         return false;
4230       if (!isUndefOrEqual(BitI1, j))
4231         return false;
4232     }
4233   }
4234   return true;
4235 }
4236
4237 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4238 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4239 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4240   if (!VT.is512BitVector())
4241     return false;
4242
4243   unsigned NumElts = VT.getVectorNumElements();
4244   unsigned HalfSize = NumElts/2;
4245   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4246     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4247       *Imm = 1;
4248       return true;
4249     }
4250   }
4251   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4252     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4253       *Imm = 0;
4254       return true;
4255     }
4256   }
4257   return false;
4258 }
4259
4260 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4261 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4262 /// MOVSD, and MOVD, i.e. setting the lowest element.
4263 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4264   if (VT.getVectorElementType().getSizeInBits() < 32)
4265     return false;
4266   if (!VT.is128BitVector())
4267     return false;
4268
4269   unsigned NumElts = VT.getVectorNumElements();
4270
4271   if (!isUndefOrEqual(Mask[0], NumElts))
4272     return false;
4273
4274   for (unsigned i = 1; i != NumElts; ++i)
4275     if (!isUndefOrEqual(Mask[i], i))
4276       return false;
4277
4278   return true;
4279 }
4280
4281 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4282 /// as permutations between 128-bit chunks or halves. As an example: this
4283 /// shuffle bellow:
4284 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4285 /// The first half comes from the second half of V1 and the second half from the
4286 /// the second half of V2.
4287 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4288   if (!HasFp256 || !VT.is256BitVector())
4289     return false;
4290
4291   // The shuffle result is divided into half A and half B. In total the two
4292   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4293   // B must come from C, D, E or F.
4294   unsigned HalfSize = VT.getVectorNumElements()/2;
4295   bool MatchA = false, MatchB = false;
4296
4297   // Check if A comes from one of C, D, E, F.
4298   for (unsigned Half = 0; Half != 4; ++Half) {
4299     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4300       MatchA = true;
4301       break;
4302     }
4303   }
4304
4305   // Check if B comes from one of C, D, E, F.
4306   for (unsigned Half = 0; Half != 4; ++Half) {
4307     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4308       MatchB = true;
4309       break;
4310     }
4311   }
4312
4313   return MatchA && MatchB;
4314 }
4315
4316 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4317 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4318 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4319   MVT VT = SVOp->getSimpleValueType(0);
4320
4321   unsigned HalfSize = VT.getVectorNumElements()/2;
4322
4323   unsigned FstHalf = 0, SndHalf = 0;
4324   for (unsigned i = 0; i < HalfSize; ++i) {
4325     if (SVOp->getMaskElt(i) > 0) {
4326       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4327       break;
4328     }
4329   }
4330   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4331     if (SVOp->getMaskElt(i) > 0) {
4332       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4333       break;
4334     }
4335   }
4336
4337   return (FstHalf | (SndHalf << 4));
4338 }
4339
4340 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4341 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4342   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4343   if (EltSize < 32)
4344     return false;
4345
4346   unsigned NumElts = VT.getVectorNumElements();
4347   Imm8 = 0;
4348   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4349     for (unsigned i = 0; i != NumElts; ++i) {
4350       if (Mask[i] < 0)
4351         continue;
4352       Imm8 |= Mask[i] << (i*2);
4353     }
4354     return true;
4355   }
4356
4357   unsigned LaneSize = 4;
4358   SmallVector<int, 4> MaskVal(LaneSize, -1);
4359
4360   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4361     for (unsigned i = 0; i != LaneSize; ++i) {
4362       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4363         return false;
4364       if (Mask[i+l] < 0)
4365         continue;
4366       if (MaskVal[i] < 0) {
4367         MaskVal[i] = Mask[i+l] - l;
4368         Imm8 |= MaskVal[i] << (i*2);
4369         continue;
4370       }
4371       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4372         return false;
4373     }
4374   }
4375   return true;
4376 }
4377
4378 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4379 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4380 /// Note that VPERMIL mask matching is different depending whether theunderlying
4381 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4382 /// to the same elements of the low, but to the higher half of the source.
4383 /// In VPERMILPD the two lanes could be shuffled independently of each other
4384 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4385 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4386   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4387   if (VT.getSizeInBits() < 256 || EltSize < 32)
4388     return false;
4389   bool symetricMaskRequired = (EltSize == 32);
4390   unsigned NumElts = VT.getVectorNumElements();
4391
4392   unsigned NumLanes = VT.getSizeInBits()/128;
4393   unsigned LaneSize = NumElts/NumLanes;
4394   // 2 or 4 elements in one lane
4395
4396   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4397   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4398     for (unsigned i = 0; i != LaneSize; ++i) {
4399       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4400         return false;
4401       if (symetricMaskRequired) {
4402         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4403           ExpectedMaskVal[i] = Mask[i+l] - l;
4404           continue;
4405         }
4406         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4407           return false;
4408       }
4409     }
4410   }
4411   return true;
4412 }
4413
4414 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4415 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4416 /// element of vector 2 and the other elements to come from vector 1 in order.
4417 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4418                                bool V2IsSplat = false, bool V2IsUndef = false) {
4419   if (!VT.is128BitVector())
4420     return false;
4421
4422   unsigned NumOps = VT.getVectorNumElements();
4423   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4424     return false;
4425
4426   if (!isUndefOrEqual(Mask[0], 0))
4427     return false;
4428
4429   for (unsigned i = 1; i != NumOps; ++i)
4430     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4431           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4432           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4433       return false;
4434
4435   return true;
4436 }
4437
4438 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4439 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4440 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4441 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4442                            const X86Subtarget *Subtarget) {
4443   if (!Subtarget->hasSSE3())
4444     return false;
4445
4446   unsigned NumElems = VT.getVectorNumElements();
4447
4448   if ((VT.is128BitVector() && NumElems != 4) ||
4449       (VT.is256BitVector() && NumElems != 8) ||
4450       (VT.is512BitVector() && NumElems != 16))
4451     return false;
4452
4453   // "i+1" is the value the indexed mask element must have
4454   for (unsigned i = 0; i != NumElems; i += 2)
4455     if (!isUndefOrEqual(Mask[i], i+1) ||
4456         !isUndefOrEqual(Mask[i+1], i+1))
4457       return false;
4458
4459   return true;
4460 }
4461
4462 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4463 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4464 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4465 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4466                            const X86Subtarget *Subtarget) {
4467   if (!Subtarget->hasSSE3())
4468     return false;
4469
4470   unsigned NumElems = VT.getVectorNumElements();
4471
4472   if ((VT.is128BitVector() && NumElems != 4) ||
4473       (VT.is256BitVector() && NumElems != 8) ||
4474       (VT.is512BitVector() && NumElems != 16))
4475     return false;
4476
4477   // "i" is the value the indexed mask element must have
4478   for (unsigned i = 0; i != NumElems; i += 2)
4479     if (!isUndefOrEqual(Mask[i], i) ||
4480         !isUndefOrEqual(Mask[i+1], i))
4481       return false;
4482
4483   return true;
4484 }
4485
4486 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4487 /// specifies a shuffle of elements that is suitable for input to 256-bit
4488 /// version of MOVDDUP.
4489 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4490   if (!HasFp256 || !VT.is256BitVector())
4491     return false;
4492
4493   unsigned NumElts = VT.getVectorNumElements();
4494   if (NumElts != 4)
4495     return false;
4496
4497   for (unsigned i = 0; i != NumElts/2; ++i)
4498     if (!isUndefOrEqual(Mask[i], 0))
4499       return false;
4500   for (unsigned i = NumElts/2; i != NumElts; ++i)
4501     if (!isUndefOrEqual(Mask[i], NumElts/2))
4502       return false;
4503   return true;
4504 }
4505
4506 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4507 /// specifies a shuffle of elements that is suitable for input to 128-bit
4508 /// version of MOVDDUP.
4509 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4510   if (!VT.is128BitVector())
4511     return false;
4512
4513   unsigned e = VT.getVectorNumElements() / 2;
4514   for (unsigned i = 0; i != e; ++i)
4515     if (!isUndefOrEqual(Mask[i], i))
4516       return false;
4517   for (unsigned i = 0; i != e; ++i)
4518     if (!isUndefOrEqual(Mask[e+i], i))
4519       return false;
4520   return true;
4521 }
4522
4523 /// isVEXTRACTIndex - Return true if the specified
4524 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4525 /// suitable for instruction that extract 128 or 256 bit vectors
4526 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4527   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4528   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4529     return false;
4530
4531   // The index should be aligned on a vecWidth-bit boundary.
4532   uint64_t Index =
4533     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4534
4535   MVT VT = N->getSimpleValueType(0);
4536   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4537   bool Result = (Index * ElSize) % vecWidth == 0;
4538
4539   return Result;
4540 }
4541
4542 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4543 /// operand specifies a subvector insert that is suitable for input to
4544 /// insertion of 128 or 256-bit subvectors
4545 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4546   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4547   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4548     return false;
4549   // The index should be aligned on a vecWidth-bit boundary.
4550   uint64_t Index =
4551     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4552
4553   MVT VT = N->getSimpleValueType(0);
4554   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4555   bool Result = (Index * ElSize) % vecWidth == 0;
4556
4557   return Result;
4558 }
4559
4560 bool X86::isVINSERT128Index(SDNode *N) {
4561   return isVINSERTIndex(N, 128);
4562 }
4563
4564 bool X86::isVINSERT256Index(SDNode *N) {
4565   return isVINSERTIndex(N, 256);
4566 }
4567
4568 bool X86::isVEXTRACT128Index(SDNode *N) {
4569   return isVEXTRACTIndex(N, 128);
4570 }
4571
4572 bool X86::isVEXTRACT256Index(SDNode *N) {
4573   return isVEXTRACTIndex(N, 256);
4574 }
4575
4576 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4577 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4578 /// Handles 128-bit and 256-bit.
4579 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4580   MVT VT = N->getSimpleValueType(0);
4581
4582   assert((VT.getSizeInBits() >= 128) &&
4583          "Unsupported vector type for PSHUF/SHUFP");
4584
4585   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4586   // independently on 128-bit lanes.
4587   unsigned NumElts = VT.getVectorNumElements();
4588   unsigned NumLanes = VT.getSizeInBits()/128;
4589   unsigned NumLaneElts = NumElts/NumLanes;
4590
4591   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4592          "Only supports 2, 4 or 8 elements per lane");
4593
4594   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4595   unsigned Mask = 0;
4596   for (unsigned i = 0; i != NumElts; ++i) {
4597     int Elt = N->getMaskElt(i);
4598     if (Elt < 0) continue;
4599     Elt &= NumLaneElts - 1;
4600     unsigned ShAmt = (i << Shift) % 8;
4601     Mask |= Elt << ShAmt;
4602   }
4603
4604   return Mask;
4605 }
4606
4607 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4608 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4609 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4610   MVT VT = N->getSimpleValueType(0);
4611
4612   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4613          "Unsupported vector type for PSHUFHW");
4614
4615   unsigned NumElts = VT.getVectorNumElements();
4616
4617   unsigned Mask = 0;
4618   for (unsigned l = 0; l != NumElts; l += 8) {
4619     // 8 nodes per lane, but we only care about the last 4.
4620     for (unsigned i = 0; i < 4; ++i) {
4621       int Elt = N->getMaskElt(l+i+4);
4622       if (Elt < 0) continue;
4623       Elt &= 0x3; // only 2-bits.
4624       Mask |= Elt << (i * 2);
4625     }
4626   }
4627
4628   return Mask;
4629 }
4630
4631 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4632 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4633 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4634   MVT VT = N->getSimpleValueType(0);
4635
4636   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4637          "Unsupported vector type for PSHUFHW");
4638
4639   unsigned NumElts = VT.getVectorNumElements();
4640
4641   unsigned Mask = 0;
4642   for (unsigned l = 0; l != NumElts; l += 8) {
4643     // 8 nodes per lane, but we only care about the first 4.
4644     for (unsigned i = 0; i < 4; ++i) {
4645       int Elt = N->getMaskElt(l+i);
4646       if (Elt < 0) continue;
4647       Elt &= 0x3; // only 2-bits
4648       Mask |= Elt << (i * 2);
4649     }
4650   }
4651
4652   return Mask;
4653 }
4654
4655 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4656 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4657 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4658   MVT VT = SVOp->getSimpleValueType(0);
4659   unsigned EltSize = VT.is512BitVector() ? 1 :
4660     VT.getVectorElementType().getSizeInBits() >> 3;
4661
4662   unsigned NumElts = VT.getVectorNumElements();
4663   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4664   unsigned NumLaneElts = NumElts/NumLanes;
4665
4666   int Val = 0;
4667   unsigned i;
4668   for (i = 0; i != NumElts; ++i) {
4669     Val = SVOp->getMaskElt(i);
4670     if (Val >= 0)
4671       break;
4672   }
4673   if (Val >= (int)NumElts)
4674     Val -= NumElts - NumLaneElts;
4675
4676   assert(Val - i > 0 && "PALIGNR imm should be positive");
4677   return (Val - i) * EltSize;
4678 }
4679
4680 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4681   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4682   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4683     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4684
4685   uint64_t Index =
4686     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4687
4688   MVT VecVT = N->getOperand(0).getSimpleValueType();
4689   MVT ElVT = VecVT.getVectorElementType();
4690
4691   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4692   return Index / NumElemsPerChunk;
4693 }
4694
4695 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4696   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4697   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4698     llvm_unreachable("Illegal insert subvector for VINSERT");
4699
4700   uint64_t Index =
4701     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4702
4703   MVT VecVT = N->getSimpleValueType(0);
4704   MVT ElVT = VecVT.getVectorElementType();
4705
4706   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4707   return Index / NumElemsPerChunk;
4708 }
4709
4710 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4711 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4712 /// and VINSERTI128 instructions.
4713 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4714   return getExtractVEXTRACTImmediate(N, 128);
4715 }
4716
4717 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4718 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4719 /// and VINSERTI64x4 instructions.
4720 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4721   return getExtractVEXTRACTImmediate(N, 256);
4722 }
4723
4724 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4725 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4726 /// and VINSERTI128 instructions.
4727 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4728   return getInsertVINSERTImmediate(N, 128);
4729 }
4730
4731 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4732 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4733 /// and VINSERTI64x4 instructions.
4734 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4735   return getInsertVINSERTImmediate(N, 256);
4736 }
4737
4738 /// isZero - Returns true if Elt is a constant integer zero
4739 static bool isZero(SDValue V) {
4740   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4741   return C && C->isNullValue();
4742 }
4743
4744 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4745 /// constant +0.0.
4746 bool X86::isZeroNode(SDValue Elt) {
4747   if (isZero(Elt))
4748     return true;
4749   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4750     return CFP->getValueAPF().isPosZero();
4751   return false;
4752 }
4753
4754 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4755 /// their permute mask.
4756 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4757                                     SelectionDAG &DAG) {
4758   MVT VT = SVOp->getSimpleValueType(0);
4759   unsigned NumElems = VT.getVectorNumElements();
4760   SmallVector<int, 8> MaskVec;
4761
4762   for (unsigned i = 0; i != NumElems; ++i) {
4763     int Idx = SVOp->getMaskElt(i);
4764     if (Idx >= 0) {
4765       if (Idx < (int)NumElems)
4766         Idx += NumElems;
4767       else
4768         Idx -= NumElems;
4769     }
4770     MaskVec.push_back(Idx);
4771   }
4772   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4773                               SVOp->getOperand(0), &MaskVec[0]);
4774 }
4775
4776 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4777 /// match movhlps. The lower half elements should come from upper half of
4778 /// V1 (and in order), and the upper half elements should come from the upper
4779 /// half of V2 (and in order).
4780 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4781   if (!VT.is128BitVector())
4782     return false;
4783   if (VT.getVectorNumElements() != 4)
4784     return false;
4785   for (unsigned i = 0, e = 2; i != e; ++i)
4786     if (!isUndefOrEqual(Mask[i], i+2))
4787       return false;
4788   for (unsigned i = 2; i != 4; ++i)
4789     if (!isUndefOrEqual(Mask[i], i+4))
4790       return false;
4791   return true;
4792 }
4793
4794 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4795 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4796 /// required.
4797 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4798   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4799     return false;
4800   N = N->getOperand(0).getNode();
4801   if (!ISD::isNON_EXTLoad(N))
4802     return false;
4803   if (LD)
4804     *LD = cast<LoadSDNode>(N);
4805   return true;
4806 }
4807
4808 // Test whether the given value is a vector value which will be legalized
4809 // into a load.
4810 static bool WillBeConstantPoolLoad(SDNode *N) {
4811   if (N->getOpcode() != ISD::BUILD_VECTOR)
4812     return false;
4813
4814   // Check for any non-constant elements.
4815   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4816     switch (N->getOperand(i).getNode()->getOpcode()) {
4817     case ISD::UNDEF:
4818     case ISD::ConstantFP:
4819     case ISD::Constant:
4820       break;
4821     default:
4822       return false;
4823     }
4824
4825   // Vectors of all-zeros and all-ones are materialized with special
4826   // instructions rather than being loaded.
4827   return !ISD::isBuildVectorAllZeros(N) &&
4828          !ISD::isBuildVectorAllOnes(N);
4829 }
4830
4831 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4832 /// match movlp{s|d}. The lower half elements should come from lower half of
4833 /// V1 (and in order), and the upper half elements should come from the upper
4834 /// half of V2 (and in order). And since V1 will become the source of the
4835 /// MOVLP, it must be either a vector load or a scalar load to vector.
4836 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4837                                ArrayRef<int> Mask, MVT VT) {
4838   if (!VT.is128BitVector())
4839     return false;
4840
4841   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4842     return false;
4843   // Is V2 is a vector load, don't do this transformation. We will try to use
4844   // load folding shufps op.
4845   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4846     return false;
4847
4848   unsigned NumElems = VT.getVectorNumElements();
4849
4850   if (NumElems != 2 && NumElems != 4)
4851     return false;
4852   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4853     if (!isUndefOrEqual(Mask[i], i))
4854       return false;
4855   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4856     if (!isUndefOrEqual(Mask[i], i+NumElems))
4857       return false;
4858   return true;
4859 }
4860
4861 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4862 /// all the same.
4863 static bool isSplatVector(SDNode *N) {
4864   if (N->getOpcode() != ISD::BUILD_VECTOR)
4865     return false;
4866
4867   SDValue SplatValue = N->getOperand(0);
4868   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4869     if (N->getOperand(i) != SplatValue)
4870       return false;
4871   return true;
4872 }
4873
4874 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4875 /// to an zero vector.
4876 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4877 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4878   SDValue V1 = N->getOperand(0);
4879   SDValue V2 = N->getOperand(1);
4880   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4881   for (unsigned i = 0; i != NumElems; ++i) {
4882     int Idx = N->getMaskElt(i);
4883     if (Idx >= (int)NumElems) {
4884       unsigned Opc = V2.getOpcode();
4885       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4886         continue;
4887       if (Opc != ISD::BUILD_VECTOR ||
4888           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4889         return false;
4890     } else if (Idx >= 0) {
4891       unsigned Opc = V1.getOpcode();
4892       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4893         continue;
4894       if (Opc != ISD::BUILD_VECTOR ||
4895           !X86::isZeroNode(V1.getOperand(Idx)))
4896         return false;
4897     }
4898   }
4899   return true;
4900 }
4901
4902 /// getZeroVector - Returns a vector of specified type with all zero elements.
4903 ///
4904 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4905                              SelectionDAG &DAG, SDLoc dl) {
4906   assert(VT.isVector() && "Expected a vector type");
4907
4908   // Always build SSE zero vectors as <4 x i32> bitcasted
4909   // to their dest type. This ensures they get CSE'd.
4910   SDValue Vec;
4911   if (VT.is128BitVector()) {  // SSE
4912     if (Subtarget->hasSSE2()) {  // SSE2
4913       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4914       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4915     } else { // SSE1
4916       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4917       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4918     }
4919   } else if (VT.is256BitVector()) { // AVX
4920     if (Subtarget->hasInt256()) { // AVX2
4921       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4922       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4923       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4924     } else {
4925       // 256-bit logic and arithmetic instructions in AVX are all
4926       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4927       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4928       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4929       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4930     }
4931   } else if (VT.is512BitVector()) { // AVX-512
4932       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4933       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4934                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4935       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4936   } else if (VT.getScalarType() == MVT::i1) {
4937     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4938     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4939     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4940     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4941   } else
4942     llvm_unreachable("Unexpected vector type");
4943
4944   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4945 }
4946
4947 /// getOnesVector - Returns a vector of specified type with all bits set.
4948 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4949 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4950 /// Then bitcast to their original type, ensuring they get CSE'd.
4951 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4952                              SDLoc dl) {
4953   assert(VT.isVector() && "Expected a vector type");
4954
4955   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4956   SDValue Vec;
4957   if (VT.is256BitVector()) {
4958     if (HasInt256) { // AVX2
4959       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4960       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4961     } else { // AVX
4962       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4963       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4964     }
4965   } else if (VT.is128BitVector()) {
4966     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4967   } else
4968     llvm_unreachable("Unexpected vector type");
4969
4970   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4971 }
4972
4973 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4974 /// that point to V2 points to its first element.
4975 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4976   for (unsigned i = 0; i != NumElems; ++i) {
4977     if (Mask[i] > (int)NumElems) {
4978       Mask[i] = NumElems;
4979     }
4980   }
4981 }
4982
4983 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4984 /// operation of specified width.
4985 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4986                        SDValue V2) {
4987   unsigned NumElems = VT.getVectorNumElements();
4988   SmallVector<int, 8> Mask;
4989   Mask.push_back(NumElems);
4990   for (unsigned i = 1; i != NumElems; ++i)
4991     Mask.push_back(i);
4992   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4993 }
4994
4995 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4996 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4997                           SDValue V2) {
4998   unsigned NumElems = VT.getVectorNumElements();
4999   SmallVector<int, 8> Mask;
5000   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
5001     Mask.push_back(i);
5002     Mask.push_back(i + NumElems);
5003   }
5004   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5005 }
5006
5007 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
5008 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
5009                           SDValue V2) {
5010   unsigned NumElems = VT.getVectorNumElements();
5011   SmallVector<int, 8> Mask;
5012   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
5013     Mask.push_back(i + Half);
5014     Mask.push_back(i + NumElems + Half);
5015   }
5016   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5017 }
5018
5019 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5020 // a generic shuffle instruction because the target has no such instructions.
5021 // Generate shuffles which repeat i16 and i8 several times until they can be
5022 // represented by v4f32 and then be manipulated by target suported shuffles.
5023 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5024   MVT VT = V.getSimpleValueType();
5025   int NumElems = VT.getVectorNumElements();
5026   SDLoc dl(V);
5027
5028   while (NumElems > 4) {
5029     if (EltNo < NumElems/2) {
5030       V = getUnpackl(DAG, dl, VT, V, V);
5031     } else {
5032       V = getUnpackh(DAG, dl, VT, V, V);
5033       EltNo -= NumElems/2;
5034     }
5035     NumElems >>= 1;
5036   }
5037   return V;
5038 }
5039
5040 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5041 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5042   MVT VT = V.getSimpleValueType();
5043   SDLoc dl(V);
5044
5045   if (VT.is128BitVector()) {
5046     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5047     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5048     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5049                              &SplatMask[0]);
5050   } else if (VT.is256BitVector()) {
5051     // To use VPERMILPS to splat scalars, the second half of indicies must
5052     // refer to the higher part, which is a duplication of the lower one,
5053     // because VPERMILPS can only handle in-lane permutations.
5054     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5055                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5056
5057     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5058     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5059                              &SplatMask[0]);
5060   } else
5061     llvm_unreachable("Vector size not supported");
5062
5063   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5064 }
5065
5066 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5067 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5068   MVT SrcVT = SV->getSimpleValueType(0);
5069   SDValue V1 = SV->getOperand(0);
5070   SDLoc dl(SV);
5071
5072   int EltNo = SV->getSplatIndex();
5073   int NumElems = SrcVT.getVectorNumElements();
5074   bool Is256BitVec = SrcVT.is256BitVector();
5075
5076   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5077          "Unknown how to promote splat for type");
5078
5079   // Extract the 128-bit part containing the splat element and update
5080   // the splat element index when it refers to the higher register.
5081   if (Is256BitVec) {
5082     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5083     if (EltNo >= NumElems/2)
5084       EltNo -= NumElems/2;
5085   }
5086
5087   // All i16 and i8 vector types can't be used directly by a generic shuffle
5088   // instruction because the target has no such instruction. Generate shuffles
5089   // which repeat i16 and i8 several times until they fit in i32, and then can
5090   // be manipulated by target suported shuffles.
5091   MVT EltVT = SrcVT.getVectorElementType();
5092   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5093     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5094
5095   // Recreate the 256-bit vector and place the same 128-bit vector
5096   // into the low and high part. This is necessary because we want
5097   // to use VPERM* to shuffle the vectors
5098   if (Is256BitVec) {
5099     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5100   }
5101
5102   return getLegalSplat(DAG, V1, EltNo);
5103 }
5104
5105 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5106 /// vector of zero or undef vector.  This produces a shuffle where the low
5107 /// element of V2 is swizzled into the zero/undef vector, landing at element
5108 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5109 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5110                                            bool IsZero,
5111                                            const X86Subtarget *Subtarget,
5112                                            SelectionDAG &DAG) {
5113   MVT VT = V2.getSimpleValueType();
5114   SDValue V1 = IsZero
5115     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5116   unsigned NumElems = VT.getVectorNumElements();
5117   SmallVector<int, 16> MaskVec;
5118   for (unsigned i = 0; i != NumElems; ++i)
5119     // If this is the insertion idx, put the low elt of V2 here.
5120     MaskVec.push_back(i == Idx ? NumElems : i);
5121   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5122 }
5123
5124 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5125 /// target specific opcode. Returns true if the Mask could be calculated.
5126 /// Sets IsUnary to true if only uses one source.
5127 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5128                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5129   unsigned NumElems = VT.getVectorNumElements();
5130   SDValue ImmN;
5131
5132   IsUnary = false;
5133   switch(N->getOpcode()) {
5134   case X86ISD::SHUFP:
5135     ImmN = N->getOperand(N->getNumOperands()-1);
5136     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5137     break;
5138   case X86ISD::UNPCKH:
5139     DecodeUNPCKHMask(VT, Mask);
5140     break;
5141   case X86ISD::UNPCKL:
5142     DecodeUNPCKLMask(VT, Mask);
5143     break;
5144   case X86ISD::MOVHLPS:
5145     DecodeMOVHLPSMask(NumElems, Mask);
5146     break;
5147   case X86ISD::MOVLHPS:
5148     DecodeMOVLHPSMask(NumElems, Mask);
5149     break;
5150   case X86ISD::PALIGNR:
5151     ImmN = N->getOperand(N->getNumOperands()-1);
5152     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5153     break;
5154   case X86ISD::PSHUFD:
5155   case X86ISD::VPERMILP:
5156     ImmN = N->getOperand(N->getNumOperands()-1);
5157     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5158     IsUnary = true;
5159     break;
5160   case X86ISD::PSHUFHW:
5161     ImmN = N->getOperand(N->getNumOperands()-1);
5162     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5163     IsUnary = true;
5164     break;
5165   case X86ISD::PSHUFLW:
5166     ImmN = N->getOperand(N->getNumOperands()-1);
5167     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5168     IsUnary = true;
5169     break;
5170   case X86ISD::VPERMI:
5171     ImmN = N->getOperand(N->getNumOperands()-1);
5172     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5173     IsUnary = true;
5174     break;
5175   case X86ISD::MOVSS:
5176   case X86ISD::MOVSD: {
5177     // The index 0 always comes from the first element of the second source,
5178     // this is why MOVSS and MOVSD are used in the first place. The other
5179     // elements come from the other positions of the first source vector
5180     Mask.push_back(NumElems);
5181     for (unsigned i = 1; i != NumElems; ++i) {
5182       Mask.push_back(i);
5183     }
5184     break;
5185   }
5186   case X86ISD::VPERM2X128:
5187     ImmN = N->getOperand(N->getNumOperands()-1);
5188     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5189     if (Mask.empty()) return false;
5190     break;
5191   case X86ISD::MOVDDUP:
5192   case X86ISD::MOVLHPD:
5193   case X86ISD::MOVLPD:
5194   case X86ISD::MOVLPS:
5195   case X86ISD::MOVSHDUP:
5196   case X86ISD::MOVSLDUP:
5197     // Not yet implemented
5198     return false;
5199   default: llvm_unreachable("unknown target shuffle node");
5200   }
5201
5202   return true;
5203 }
5204
5205 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5206 /// element of the result of the vector shuffle.
5207 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5208                                    unsigned Depth) {
5209   if (Depth == 6)
5210     return SDValue();  // Limit search depth.
5211
5212   SDValue V = SDValue(N, 0);
5213   EVT VT = V.getValueType();
5214   unsigned Opcode = V.getOpcode();
5215
5216   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5217   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5218     int Elt = SV->getMaskElt(Index);
5219
5220     if (Elt < 0)
5221       return DAG.getUNDEF(VT.getVectorElementType());
5222
5223     unsigned NumElems = VT.getVectorNumElements();
5224     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5225                                          : SV->getOperand(1);
5226     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5227   }
5228
5229   // Recurse into target specific vector shuffles to find scalars.
5230   if (isTargetShuffle(Opcode)) {
5231     MVT ShufVT = V.getSimpleValueType();
5232     unsigned NumElems = ShufVT.getVectorNumElements();
5233     SmallVector<int, 16> ShuffleMask;
5234     bool IsUnary;
5235
5236     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5237       return SDValue();
5238
5239     int Elt = ShuffleMask[Index];
5240     if (Elt < 0)
5241       return DAG.getUNDEF(ShufVT.getVectorElementType());
5242
5243     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5244                                          : N->getOperand(1);
5245     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5246                                Depth+1);
5247   }
5248
5249   // Actual nodes that may contain scalar elements
5250   if (Opcode == ISD::BITCAST) {
5251     V = V.getOperand(0);
5252     EVT SrcVT = V.getValueType();
5253     unsigned NumElems = VT.getVectorNumElements();
5254
5255     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5256       return SDValue();
5257   }
5258
5259   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5260     return (Index == 0) ? V.getOperand(0)
5261                         : DAG.getUNDEF(VT.getVectorElementType());
5262
5263   if (V.getOpcode() == ISD::BUILD_VECTOR)
5264     return V.getOperand(Index);
5265
5266   return SDValue();
5267 }
5268
5269 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5270 /// shuffle operation which come from a consecutively from a zero. The
5271 /// search can start in two different directions, from left or right.
5272 /// We count undefs as zeros until PreferredNum is reached.
5273 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5274                                          unsigned NumElems, bool ZerosFromLeft,
5275                                          SelectionDAG &DAG,
5276                                          unsigned PreferredNum = -1U) {
5277   unsigned NumZeros = 0;
5278   for (unsigned i = 0; i != NumElems; ++i) {
5279     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5280     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5281     if (!Elt.getNode())
5282       break;
5283
5284     if (X86::isZeroNode(Elt))
5285       ++NumZeros;
5286     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5287       NumZeros = std::min(NumZeros + 1, PreferredNum);
5288     else
5289       break;
5290   }
5291
5292   return NumZeros;
5293 }
5294
5295 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5296 /// correspond consecutively to elements from one of the vector operands,
5297 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5298 static
5299 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5300                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5301                               unsigned NumElems, unsigned &OpNum) {
5302   bool SeenV1 = false;
5303   bool SeenV2 = false;
5304
5305   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5306     int Idx = SVOp->getMaskElt(i);
5307     // Ignore undef indicies
5308     if (Idx < 0)
5309       continue;
5310
5311     if (Idx < (int)NumElems)
5312       SeenV1 = true;
5313     else
5314       SeenV2 = true;
5315
5316     // Only accept consecutive elements from the same vector
5317     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5318       return false;
5319   }
5320
5321   OpNum = SeenV1 ? 0 : 1;
5322   return true;
5323 }
5324
5325 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5326 /// logical left shift of a vector.
5327 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5328                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5329   unsigned NumElems =
5330     SVOp->getSimpleValueType(0).getVectorNumElements();
5331   unsigned NumZeros = getNumOfConsecutiveZeros(
5332       SVOp, NumElems, false /* check zeros from right */, DAG,
5333       SVOp->getMaskElt(0));
5334   unsigned OpSrc;
5335
5336   if (!NumZeros)
5337     return false;
5338
5339   // Considering the elements in the mask that are not consecutive zeros,
5340   // check if they consecutively come from only one of the source vectors.
5341   //
5342   //               V1 = {X, A, B, C}     0
5343   //                         \  \  \    /
5344   //   vector_shuffle V1, V2 <1, 2, 3, X>
5345   //
5346   if (!isShuffleMaskConsecutive(SVOp,
5347             0,                   // Mask Start Index
5348             NumElems-NumZeros,   // Mask End Index(exclusive)
5349             NumZeros,            // Where to start looking in the src vector
5350             NumElems,            // Number of elements in vector
5351             OpSrc))              // Which source operand ?
5352     return false;
5353
5354   isLeft = false;
5355   ShAmt = NumZeros;
5356   ShVal = SVOp->getOperand(OpSrc);
5357   return true;
5358 }
5359
5360 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5361 /// logical left shift of a vector.
5362 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5363                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5364   unsigned NumElems =
5365     SVOp->getSimpleValueType(0).getVectorNumElements();
5366   unsigned NumZeros = getNumOfConsecutiveZeros(
5367       SVOp, NumElems, true /* check zeros from left */, DAG,
5368       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5369   unsigned OpSrc;
5370
5371   if (!NumZeros)
5372     return false;
5373
5374   // Considering the elements in the mask that are not consecutive zeros,
5375   // check if they consecutively come from only one of the source vectors.
5376   //
5377   //                           0    { A, B, X, X } = V2
5378   //                          / \    /  /
5379   //   vector_shuffle V1, V2 <X, X, 4, 5>
5380   //
5381   if (!isShuffleMaskConsecutive(SVOp,
5382             NumZeros,     // Mask Start Index
5383             NumElems,     // Mask End Index(exclusive)
5384             0,            // Where to start looking in the src vector
5385             NumElems,     // Number of elements in vector
5386             OpSrc))       // Which source operand ?
5387     return false;
5388
5389   isLeft = true;
5390   ShAmt = NumZeros;
5391   ShVal = SVOp->getOperand(OpSrc);
5392   return true;
5393 }
5394
5395 /// isVectorShift - Returns true if the shuffle can be implemented as a
5396 /// logical left or right shift of a vector.
5397 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5398                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5399   // Although the logic below support any bitwidth size, there are no
5400   // shift instructions which handle more than 128-bit vectors.
5401   if (!SVOp->getSimpleValueType(0).is128BitVector())
5402     return false;
5403
5404   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5405       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5406     return true;
5407
5408   return false;
5409 }
5410
5411 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5412 ///
5413 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5414                                        unsigned NumNonZero, unsigned NumZero,
5415                                        SelectionDAG &DAG,
5416                                        const X86Subtarget* Subtarget,
5417                                        const TargetLowering &TLI) {
5418   if (NumNonZero > 8)
5419     return SDValue();
5420
5421   SDLoc dl(Op);
5422   SDValue V;
5423   bool First = true;
5424   for (unsigned i = 0; i < 16; ++i) {
5425     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5426     if (ThisIsNonZero && First) {
5427       if (NumZero)
5428         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5429       else
5430         V = DAG.getUNDEF(MVT::v8i16);
5431       First = false;
5432     }
5433
5434     if ((i & 1) != 0) {
5435       SDValue ThisElt, LastElt;
5436       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5437       if (LastIsNonZero) {
5438         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5439                               MVT::i16, Op.getOperand(i-1));
5440       }
5441       if (ThisIsNonZero) {
5442         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5443         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5444                               ThisElt, DAG.getConstant(8, MVT::i8));
5445         if (LastIsNonZero)
5446           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5447       } else
5448         ThisElt = LastElt;
5449
5450       if (ThisElt.getNode())
5451         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5452                         DAG.getIntPtrConstant(i/2));
5453     }
5454   }
5455
5456   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5457 }
5458
5459 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5460 ///
5461 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5462                                      unsigned NumNonZero, unsigned NumZero,
5463                                      SelectionDAG &DAG,
5464                                      const X86Subtarget* Subtarget,
5465                                      const TargetLowering &TLI) {
5466   if (NumNonZero > 4)
5467     return SDValue();
5468
5469   SDLoc dl(Op);
5470   SDValue V;
5471   bool First = true;
5472   for (unsigned i = 0; i < 8; ++i) {
5473     bool isNonZero = (NonZeros & (1 << i)) != 0;
5474     if (isNonZero) {
5475       if (First) {
5476         if (NumZero)
5477           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5478         else
5479           V = DAG.getUNDEF(MVT::v8i16);
5480         First = false;
5481       }
5482       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5483                       MVT::v8i16, V, Op.getOperand(i),
5484                       DAG.getIntPtrConstant(i));
5485     }
5486   }
5487
5488   return V;
5489 }
5490
5491 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5492 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5493                                      unsigned NonZeros, unsigned NumNonZero,
5494                                      unsigned NumZero, SelectionDAG &DAG,
5495                                      const X86Subtarget *Subtarget,
5496                                      const TargetLowering &TLI) {
5497   // We know there's at least one non-zero element
5498   unsigned FirstNonZeroIdx = 0;
5499   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5500   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5501          X86::isZeroNode(FirstNonZero)) {
5502     ++FirstNonZeroIdx;
5503     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5504   }
5505
5506   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5507       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5508     return SDValue();
5509
5510   SDValue V = FirstNonZero.getOperand(0);
5511   MVT VVT = V.getSimpleValueType();
5512   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5513     return SDValue();
5514
5515   unsigned FirstNonZeroDst =
5516       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5517   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5518   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5519   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5520
5521   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5522     SDValue Elem = Op.getOperand(Idx);
5523     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5524       continue;
5525
5526     // TODO: What else can be here? Deal with it.
5527     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5528       return SDValue();
5529
5530     // TODO: Some optimizations are still possible here
5531     // ex: Getting one element from a vector, and the rest from another.
5532     if (Elem.getOperand(0) != V)
5533       return SDValue();
5534
5535     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5536     if (Dst == Idx)
5537       ++CorrectIdx;
5538     else if (IncorrectIdx == -1U) {
5539       IncorrectIdx = Idx;
5540       IncorrectDst = Dst;
5541     } else
5542       // There was already one element with an incorrect index.
5543       // We can't optimize this case to an insertps.
5544       return SDValue();
5545   }
5546
5547   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5548     SDLoc dl(Op);
5549     EVT VT = Op.getSimpleValueType();
5550     unsigned ElementMoveMask = 0;
5551     if (IncorrectIdx == -1U)
5552       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5553     else
5554       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5555
5556     SDValue InsertpsMask =
5557         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5558     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5559   }
5560
5561   return SDValue();
5562 }
5563
5564 /// getVShift - Return a vector logical shift node.
5565 ///
5566 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5567                          unsigned NumBits, SelectionDAG &DAG,
5568                          const TargetLowering &TLI, SDLoc dl) {
5569   assert(VT.is128BitVector() && "Unknown type for VShift");
5570   EVT ShVT = MVT::v2i64;
5571   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5572   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5573   return DAG.getNode(ISD::BITCAST, dl, VT,
5574                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5575                              DAG.getConstant(NumBits,
5576                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5577 }
5578
5579 static SDValue
5580 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5581
5582   // Check if the scalar load can be widened into a vector load. And if
5583   // the address is "base + cst" see if the cst can be "absorbed" into
5584   // the shuffle mask.
5585   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5586     SDValue Ptr = LD->getBasePtr();
5587     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5588       return SDValue();
5589     EVT PVT = LD->getValueType(0);
5590     if (PVT != MVT::i32 && PVT != MVT::f32)
5591       return SDValue();
5592
5593     int FI = -1;
5594     int64_t Offset = 0;
5595     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5596       FI = FINode->getIndex();
5597       Offset = 0;
5598     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5599                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5600       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5601       Offset = Ptr.getConstantOperandVal(1);
5602       Ptr = Ptr.getOperand(0);
5603     } else {
5604       return SDValue();
5605     }
5606
5607     // FIXME: 256-bit vector instructions don't require a strict alignment,
5608     // improve this code to support it better.
5609     unsigned RequiredAlign = VT.getSizeInBits()/8;
5610     SDValue Chain = LD->getChain();
5611     // Make sure the stack object alignment is at least 16 or 32.
5612     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5613     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5614       if (MFI->isFixedObjectIndex(FI)) {
5615         // Can't change the alignment. FIXME: It's possible to compute
5616         // the exact stack offset and reference FI + adjust offset instead.
5617         // If someone *really* cares about this. That's the way to implement it.
5618         return SDValue();
5619       } else {
5620         MFI->setObjectAlignment(FI, RequiredAlign);
5621       }
5622     }
5623
5624     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5625     // Ptr + (Offset & ~15).
5626     if (Offset < 0)
5627       return SDValue();
5628     if ((Offset % RequiredAlign) & 3)
5629       return SDValue();
5630     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5631     if (StartOffset)
5632       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5633                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5634
5635     int EltNo = (Offset - StartOffset) >> 2;
5636     unsigned NumElems = VT.getVectorNumElements();
5637
5638     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5639     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5640                              LD->getPointerInfo().getWithOffset(StartOffset),
5641                              false, false, false, 0);
5642
5643     SmallVector<int, 8> Mask;
5644     for (unsigned i = 0; i != NumElems; ++i)
5645       Mask.push_back(EltNo);
5646
5647     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5648   }
5649
5650   return SDValue();
5651 }
5652
5653 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5654 /// vector of type 'VT', see if the elements can be replaced by a single large
5655 /// load which has the same value as a build_vector whose operands are 'elts'.
5656 ///
5657 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5658 ///
5659 /// FIXME: we'd also like to handle the case where the last elements are zero
5660 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5661 /// There's even a handy isZeroNode for that purpose.
5662 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5663                                         SDLoc &DL, SelectionDAG &DAG,
5664                                         bool isAfterLegalize) {
5665   EVT EltVT = VT.getVectorElementType();
5666   unsigned NumElems = Elts.size();
5667
5668   LoadSDNode *LDBase = nullptr;
5669   unsigned LastLoadedElt = -1U;
5670
5671   // For each element in the initializer, see if we've found a load or an undef.
5672   // If we don't find an initial load element, or later load elements are
5673   // non-consecutive, bail out.
5674   for (unsigned i = 0; i < NumElems; ++i) {
5675     SDValue Elt = Elts[i];
5676
5677     if (!Elt.getNode() ||
5678         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5679       return SDValue();
5680     if (!LDBase) {
5681       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5682         return SDValue();
5683       LDBase = cast<LoadSDNode>(Elt.getNode());
5684       LastLoadedElt = i;
5685       continue;
5686     }
5687     if (Elt.getOpcode() == ISD::UNDEF)
5688       continue;
5689
5690     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5691     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5692       return SDValue();
5693     LastLoadedElt = i;
5694   }
5695
5696   // If we have found an entire vector of loads and undefs, then return a large
5697   // load of the entire vector width starting at the base pointer.  If we found
5698   // consecutive loads for the low half, generate a vzext_load node.
5699   if (LastLoadedElt == NumElems - 1) {
5700
5701     if (isAfterLegalize &&
5702         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5703       return SDValue();
5704
5705     SDValue NewLd = SDValue();
5706
5707     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5708       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5709                           LDBase->getPointerInfo(),
5710                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5711                           LDBase->isInvariant(), 0);
5712     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5713                         LDBase->getPointerInfo(),
5714                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5715                         LDBase->isInvariant(), LDBase->getAlignment());
5716
5717     if (LDBase->hasAnyUseOfValue(1)) {
5718       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5719                                      SDValue(LDBase, 1),
5720                                      SDValue(NewLd.getNode(), 1));
5721       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5722       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5723                              SDValue(NewLd.getNode(), 1));
5724     }
5725
5726     return NewLd;
5727   }
5728   if (NumElems == 4 && LastLoadedElt == 1 &&
5729       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5730     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5731     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5732     SDValue ResNode =
5733         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5734                                 LDBase->getPointerInfo(),
5735                                 LDBase->getAlignment(),
5736                                 false/*isVolatile*/, true/*ReadMem*/,
5737                                 false/*WriteMem*/);
5738
5739     // Make sure the newly-created LOAD is in the same position as LDBase in
5740     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5741     // update uses of LDBase's output chain to use the TokenFactor.
5742     if (LDBase->hasAnyUseOfValue(1)) {
5743       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5744                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5745       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5746       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5747                              SDValue(ResNode.getNode(), 1));
5748     }
5749
5750     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5751   }
5752   return SDValue();
5753 }
5754
5755 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5756 /// to generate a splat value for the following cases:
5757 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5758 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5759 /// a scalar load, or a constant.
5760 /// The VBROADCAST node is returned when a pattern is found,
5761 /// or SDValue() otherwise.
5762 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5763                                     SelectionDAG &DAG) {
5764   if (!Subtarget->hasFp256())
5765     return SDValue();
5766
5767   MVT VT = Op.getSimpleValueType();
5768   SDLoc dl(Op);
5769
5770   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5771          "Unsupported vector type for broadcast.");
5772
5773   SDValue Ld;
5774   bool ConstSplatVal;
5775
5776   switch (Op.getOpcode()) {
5777     default:
5778       // Unknown pattern found.
5779       return SDValue();
5780
5781     case ISD::BUILD_VECTOR: {
5782       // The BUILD_VECTOR node must be a splat.
5783       if (!isSplatVector(Op.getNode()))
5784         return SDValue();
5785
5786       Ld = Op.getOperand(0);
5787       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5788                      Ld.getOpcode() == ISD::ConstantFP);
5789
5790       // The suspected load node has several users. Make sure that all
5791       // of its users are from the BUILD_VECTOR node.
5792       // Constants may have multiple users.
5793       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5794         return SDValue();
5795       break;
5796     }
5797
5798     case ISD::VECTOR_SHUFFLE: {
5799       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5800
5801       // Shuffles must have a splat mask where the first element is
5802       // broadcasted.
5803       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5804         return SDValue();
5805
5806       SDValue Sc = Op.getOperand(0);
5807       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5808           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5809
5810         if (!Subtarget->hasInt256())
5811           return SDValue();
5812
5813         // Use the register form of the broadcast instruction available on AVX2.
5814         if (VT.getSizeInBits() >= 256)
5815           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5816         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5817       }
5818
5819       Ld = Sc.getOperand(0);
5820       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5821                        Ld.getOpcode() == ISD::ConstantFP);
5822
5823       // The scalar_to_vector node and the suspected
5824       // load node must have exactly one user.
5825       // Constants may have multiple users.
5826
5827       // AVX-512 has register version of the broadcast
5828       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5829         Ld.getValueType().getSizeInBits() >= 32;
5830       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5831           !hasRegVer))
5832         return SDValue();
5833       break;
5834     }
5835   }
5836
5837   bool IsGE256 = (VT.getSizeInBits() >= 256);
5838
5839   // Handle the broadcasting a single constant scalar from the constant pool
5840   // into a vector. On Sandybridge it is still better to load a constant vector
5841   // from the constant pool and not to broadcast it from a scalar.
5842   if (ConstSplatVal && Subtarget->hasInt256()) {
5843     EVT CVT = Ld.getValueType();
5844     assert(!CVT.isVector() && "Must not broadcast a vector type");
5845     unsigned ScalarSize = CVT.getSizeInBits();
5846
5847     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5848       const Constant *C = nullptr;
5849       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5850         C = CI->getConstantIntValue();
5851       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5852         C = CF->getConstantFPValue();
5853
5854       assert(C && "Invalid constant type");
5855
5856       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5857       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5858       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5859       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5860                        MachinePointerInfo::getConstantPool(),
5861                        false, false, false, Alignment);
5862
5863       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5864     }
5865   }
5866
5867   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5868   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5869
5870   // Handle AVX2 in-register broadcasts.
5871   if (!IsLoad && Subtarget->hasInt256() &&
5872       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5873     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5874
5875   // The scalar source must be a normal load.
5876   if (!IsLoad)
5877     return SDValue();
5878
5879   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5880     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5881
5882   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5883   // double since there is no vbroadcastsd xmm
5884   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5885     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5886       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5887   }
5888
5889   // Unsupported broadcast.
5890   return SDValue();
5891 }
5892
5893 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5894 /// underlying vector and index.
5895 ///
5896 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5897 /// index.
5898 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5899                                          SDValue ExtIdx) {
5900   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5901   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5902     return Idx;
5903
5904   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5905   // lowered this:
5906   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5907   // to:
5908   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5909   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5910   //                           undef)
5911   //                       Constant<0>)
5912   // In this case the vector is the extract_subvector expression and the index
5913   // is 2, as specified by the shuffle.
5914   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5915   SDValue ShuffleVec = SVOp->getOperand(0);
5916   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5917   assert(ShuffleVecVT.getVectorElementType() ==
5918          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5919
5920   int ShuffleIdx = SVOp->getMaskElt(Idx);
5921   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5922     ExtractedFromVec = ShuffleVec;
5923     return ShuffleIdx;
5924   }
5925   return Idx;
5926 }
5927
5928 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5929   MVT VT = Op.getSimpleValueType();
5930
5931   // Skip if insert_vec_elt is not supported.
5932   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5933   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5934     return SDValue();
5935
5936   SDLoc DL(Op);
5937   unsigned NumElems = Op.getNumOperands();
5938
5939   SDValue VecIn1;
5940   SDValue VecIn2;
5941   SmallVector<unsigned, 4> InsertIndices;
5942   SmallVector<int, 8> Mask(NumElems, -1);
5943
5944   for (unsigned i = 0; i != NumElems; ++i) {
5945     unsigned Opc = Op.getOperand(i).getOpcode();
5946
5947     if (Opc == ISD::UNDEF)
5948       continue;
5949
5950     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5951       // Quit if more than 1 elements need inserting.
5952       if (InsertIndices.size() > 1)
5953         return SDValue();
5954
5955       InsertIndices.push_back(i);
5956       continue;
5957     }
5958
5959     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5960     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5961     // Quit if non-constant index.
5962     if (!isa<ConstantSDNode>(ExtIdx))
5963       return SDValue();
5964     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5965
5966     // Quit if extracted from vector of different type.
5967     if (ExtractedFromVec.getValueType() != VT)
5968       return SDValue();
5969
5970     if (!VecIn1.getNode())
5971       VecIn1 = ExtractedFromVec;
5972     else if (VecIn1 != ExtractedFromVec) {
5973       if (!VecIn2.getNode())
5974         VecIn2 = ExtractedFromVec;
5975       else if (VecIn2 != ExtractedFromVec)
5976         // Quit if more than 2 vectors to shuffle
5977         return SDValue();
5978     }
5979
5980     if (ExtractedFromVec == VecIn1)
5981       Mask[i] = Idx;
5982     else if (ExtractedFromVec == VecIn2)
5983       Mask[i] = Idx + NumElems;
5984   }
5985
5986   if (!VecIn1.getNode())
5987     return SDValue();
5988
5989   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5990   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5991   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5992     unsigned Idx = InsertIndices[i];
5993     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5994                      DAG.getIntPtrConstant(Idx));
5995   }
5996
5997   return NV;
5998 }
5999
6000 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
6001 SDValue
6002 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
6003
6004   MVT VT = Op.getSimpleValueType();
6005   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
6006          "Unexpected type in LowerBUILD_VECTORvXi1!");
6007
6008   SDLoc dl(Op);
6009   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6010     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
6011     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6012     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6013   }
6014
6015   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6016     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6017     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6018     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6019   }
6020
6021   bool AllContants = true;
6022   uint64_t Immediate = 0;
6023   int NonConstIdx = -1;
6024   bool IsSplat = true;
6025   unsigned NumNonConsts = 0;
6026   unsigned NumConsts = 0;
6027   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6028     SDValue In = Op.getOperand(idx);
6029     if (In.getOpcode() == ISD::UNDEF)
6030       continue;
6031     if (!isa<ConstantSDNode>(In)) {
6032       AllContants = false;
6033       NonConstIdx = idx;
6034       NumNonConsts++;
6035     }
6036     else {
6037       NumConsts++;
6038       if (cast<ConstantSDNode>(In)->getZExtValue())
6039       Immediate |= (1ULL << idx);
6040     }
6041     if (In != Op.getOperand(0))
6042       IsSplat = false;
6043   }
6044
6045   if (AllContants) {
6046     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6047       DAG.getConstant(Immediate, MVT::i16));
6048     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6049                        DAG.getIntPtrConstant(0));
6050   }
6051
6052   if (NumNonConsts == 1 && NonConstIdx != 0) {
6053     SDValue DstVec;
6054     if (NumConsts) {
6055       SDValue VecAsImm = DAG.getConstant(Immediate,
6056                                          MVT::getIntegerVT(VT.getSizeInBits()));
6057       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6058     }
6059     else 
6060       DstVec = DAG.getUNDEF(VT);
6061     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6062                        Op.getOperand(NonConstIdx),
6063                        DAG.getIntPtrConstant(NonConstIdx));
6064   }
6065   if (!IsSplat && (NonConstIdx != 0))
6066     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6067   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6068   SDValue Select;
6069   if (IsSplat)
6070     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6071                           DAG.getConstant(-1, SelectVT),
6072                           DAG.getConstant(0, SelectVT));
6073   else
6074     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6075                          DAG.getConstant((Immediate | 1), SelectVT),
6076                          DAG.getConstant(Immediate, SelectVT));
6077   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6078 }
6079
6080 /// \brief Return true if \p N implements a horizontal binop and return the
6081 /// operands for the horizontal binop into V0 and V1.
6082 /// 
6083 /// This is a helper function of PerformBUILD_VECTORCombine.
6084 /// This function checks that the build_vector \p N in input implements a
6085 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6086 /// operation to match.
6087 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6088 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6089 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6090 /// arithmetic sub.
6091 ///
6092 /// This function only analyzes elements of \p N whose indices are
6093 /// in range [BaseIdx, LastIdx).
6094 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6095                               SelectionDAG &DAG,
6096                               unsigned BaseIdx, unsigned LastIdx,
6097                               SDValue &V0, SDValue &V1) {
6098   EVT VT = N->getValueType(0);
6099
6100   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6101   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6102          "Invalid Vector in input!");
6103   
6104   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6105   bool CanFold = true;
6106   unsigned ExpectedVExtractIdx = BaseIdx;
6107   unsigned NumElts = LastIdx - BaseIdx;
6108   V0 = DAG.getUNDEF(VT);
6109   V1 = DAG.getUNDEF(VT);
6110
6111   // Check if N implements a horizontal binop.
6112   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6113     SDValue Op = N->getOperand(i + BaseIdx);
6114
6115     // Skip UNDEFs.
6116     if (Op->getOpcode() == ISD::UNDEF) {
6117       // Update the expected vector extract index.
6118       if (i * 2 == NumElts)
6119         ExpectedVExtractIdx = BaseIdx;
6120       ExpectedVExtractIdx += 2;
6121       continue;
6122     }
6123
6124     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6125
6126     if (!CanFold)
6127       break;
6128
6129     SDValue Op0 = Op.getOperand(0);
6130     SDValue Op1 = Op.getOperand(1);
6131
6132     // Try to match the following pattern:
6133     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6134     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6135         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6136         Op0.getOperand(0) == Op1.getOperand(0) &&
6137         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6138         isa<ConstantSDNode>(Op1.getOperand(1)));
6139     if (!CanFold)
6140       break;
6141
6142     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6143     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6144
6145     if (i * 2 < NumElts) {
6146       if (V0.getOpcode() == ISD::UNDEF)
6147         V0 = Op0.getOperand(0);
6148     } else {
6149       if (V1.getOpcode() == ISD::UNDEF)
6150         V1 = Op0.getOperand(0);
6151       if (i * 2 == NumElts)
6152         ExpectedVExtractIdx = BaseIdx;
6153     }
6154
6155     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6156     if (I0 == ExpectedVExtractIdx)
6157       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6158     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6159       // Try to match the following dag sequence:
6160       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6161       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6162     } else
6163       CanFold = false;
6164
6165     ExpectedVExtractIdx += 2;
6166   }
6167
6168   return CanFold;
6169 }
6170
6171 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6172 /// a concat_vector. 
6173 ///
6174 /// This is a helper function of PerformBUILD_VECTORCombine.
6175 /// This function expects two 256-bit vectors called V0 and V1.
6176 /// At first, each vector is split into two separate 128-bit vectors.
6177 /// Then, the resulting 128-bit vectors are used to implement two
6178 /// horizontal binary operations. 
6179 ///
6180 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6181 ///
6182 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6183 /// the two new horizontal binop.
6184 /// When Mode is set, the first horizontal binop dag node would take as input
6185 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6186 /// horizontal binop dag node would take as input the lower 128-bit of V1
6187 /// and the upper 128-bit of V1.
6188 ///   Example:
6189 ///     HADD V0_LO, V0_HI
6190 ///     HADD V1_LO, V1_HI
6191 ///
6192 /// Otherwise, the first horizontal binop dag node takes as input the lower
6193 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6194 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6195 ///   Example:
6196 ///     HADD V0_LO, V1_LO
6197 ///     HADD V0_HI, V1_HI
6198 ///
6199 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6200 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6201 /// the upper 128-bits of the result.
6202 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6203                                      SDLoc DL, SelectionDAG &DAG,
6204                                      unsigned X86Opcode, bool Mode,
6205                                      bool isUndefLO, bool isUndefHI) {
6206   EVT VT = V0.getValueType();
6207   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6208          "Invalid nodes in input!");
6209
6210   unsigned NumElts = VT.getVectorNumElements();
6211   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6212   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6213   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6214   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6215   EVT NewVT = V0_LO.getValueType();
6216
6217   SDValue LO = DAG.getUNDEF(NewVT);
6218   SDValue HI = DAG.getUNDEF(NewVT);
6219
6220   if (Mode) {
6221     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6222     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6223       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6224     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6225       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6226   } else {
6227     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6228     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6229                        V1_LO->getOpcode() != ISD::UNDEF))
6230       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6231
6232     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6233                        V1_HI->getOpcode() != ISD::UNDEF))
6234       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6235   }
6236
6237   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6238 }
6239
6240 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6241 /// sequence of 'vadd + vsub + blendi'.
6242 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6243                            const X86Subtarget *Subtarget) {
6244   SDLoc DL(BV);
6245   EVT VT = BV->getValueType(0);
6246   unsigned NumElts = VT.getVectorNumElements();
6247   SDValue InVec0 = DAG.getUNDEF(VT);
6248   SDValue InVec1 = DAG.getUNDEF(VT);
6249
6250   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6251           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6252
6253   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6254   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6255   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6256     return SDValue();
6257
6258   // Odd-numbered elements in the input build vector are obtained from
6259   // adding two integer/float elements.
6260   // Even-numbered elements in the input build vector are obtained from
6261   // subtracting two integer/float elements.
6262   unsigned ExpectedOpcode = ISD::FSUB;
6263   unsigned NextExpectedOpcode = ISD::FADD;
6264   bool AddFound = false;
6265   bool SubFound = false;
6266
6267   for (unsigned i = 0, e = NumElts; i != e; i++) {
6268     SDValue Op = BV->getOperand(i);
6269       
6270     // Skip 'undef' values.
6271     unsigned Opcode = Op.getOpcode();
6272     if (Opcode == ISD::UNDEF) {
6273       std::swap(ExpectedOpcode, NextExpectedOpcode);
6274       continue;
6275     }
6276       
6277     // Early exit if we found an unexpected opcode.
6278     if (Opcode != ExpectedOpcode)
6279       return SDValue();
6280
6281     SDValue Op0 = Op.getOperand(0);
6282     SDValue Op1 = Op.getOperand(1);
6283
6284     // Try to match the following pattern:
6285     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6286     // Early exit if we cannot match that sequence.
6287     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6288         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6289         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6290         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6291         Op0.getOperand(1) != Op1.getOperand(1))
6292       return SDValue();
6293
6294     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6295     if (I0 != i)
6296       return SDValue();
6297
6298     // We found a valid add/sub node. Update the information accordingly.
6299     if (i & 1)
6300       AddFound = true;
6301     else
6302       SubFound = true;
6303
6304     // Update InVec0 and InVec1.
6305     if (InVec0.getOpcode() == ISD::UNDEF)
6306       InVec0 = Op0.getOperand(0);
6307     if (InVec1.getOpcode() == ISD::UNDEF)
6308       InVec1 = Op1.getOperand(0);
6309
6310     // Make sure that operands in input to each add/sub node always
6311     // come from a same pair of vectors.
6312     if (InVec0 != Op0.getOperand(0)) {
6313       if (ExpectedOpcode == ISD::FSUB)
6314         return SDValue();
6315
6316       // FADD is commutable. Try to commute the operands
6317       // and then test again.
6318       std::swap(Op0, Op1);
6319       if (InVec0 != Op0.getOperand(0))
6320         return SDValue();
6321     }
6322
6323     if (InVec1 != Op1.getOperand(0))
6324       return SDValue();
6325
6326     // Update the pair of expected opcodes.
6327     std::swap(ExpectedOpcode, NextExpectedOpcode);
6328   }
6329
6330   // Don't try to fold this build_vector into a VSELECT if it has
6331   // too many UNDEF operands.
6332   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6333       InVec1.getOpcode() != ISD::UNDEF) {
6334     // Emit a sequence of vector add and sub followed by a VSELECT.
6335     // The new VSELECT will be lowered into a BLENDI.
6336     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6337     // and emit a single ADDSUB instruction.
6338     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6339     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6340
6341     // Construct the VSELECT mask.
6342     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6343     EVT SVT = MaskVT.getVectorElementType();
6344     unsigned SVTBits = SVT.getSizeInBits();
6345     SmallVector<SDValue, 8> Ops;
6346
6347     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6348       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6349                             APInt::getAllOnesValue(SVTBits);
6350       SDValue Constant = DAG.getConstant(Value, SVT);
6351       Ops.push_back(Constant);
6352     }
6353
6354     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6355     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6356   }
6357   
6358   return SDValue();
6359 }
6360
6361 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6362                                           const X86Subtarget *Subtarget) {
6363   SDLoc DL(N);
6364   EVT VT = N->getValueType(0);
6365   unsigned NumElts = VT.getVectorNumElements();
6366   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6367   SDValue InVec0, InVec1;
6368
6369   // Try to match an ADDSUB.
6370   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6371       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6372     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6373     if (Value.getNode())
6374       return Value;
6375   }
6376
6377   // Try to match horizontal ADD/SUB.
6378   unsigned NumUndefsLO = 0;
6379   unsigned NumUndefsHI = 0;
6380   unsigned Half = NumElts/2;
6381
6382   // Count the number of UNDEF operands in the build_vector in input.
6383   for (unsigned i = 0, e = Half; i != e; ++i)
6384     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6385       NumUndefsLO++;
6386
6387   for (unsigned i = Half, e = NumElts; i != e; ++i)
6388     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6389       NumUndefsHI++;
6390
6391   // Early exit if this is either a build_vector of all UNDEFs or all the
6392   // operands but one are UNDEF.
6393   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6394     return SDValue();
6395
6396   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6397     // Try to match an SSE3 float HADD/HSUB.
6398     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6399       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6400     
6401     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6402       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6403   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6404     // Try to match an SSSE3 integer HADD/HSUB.
6405     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6406       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6407     
6408     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6409       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6410   }
6411   
6412   if (!Subtarget->hasAVX())
6413     return SDValue();
6414
6415   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6416     // Try to match an AVX horizontal add/sub of packed single/double
6417     // precision floating point values from 256-bit vectors.
6418     SDValue InVec2, InVec3;
6419     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6420         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6421         ((InVec0.getOpcode() == ISD::UNDEF ||
6422           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6423         ((InVec1.getOpcode() == ISD::UNDEF ||
6424           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6425       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6426
6427     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6428         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6429         ((InVec0.getOpcode() == ISD::UNDEF ||
6430           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6431         ((InVec1.getOpcode() == ISD::UNDEF ||
6432           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6433       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6434   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6435     // Try to match an AVX2 horizontal add/sub of signed integers.
6436     SDValue InVec2, InVec3;
6437     unsigned X86Opcode;
6438     bool CanFold = true;
6439
6440     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6441         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6442         ((InVec0.getOpcode() == ISD::UNDEF ||
6443           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6444         ((InVec1.getOpcode() == ISD::UNDEF ||
6445           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6446       X86Opcode = X86ISD::HADD;
6447     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6448         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6449         ((InVec0.getOpcode() == ISD::UNDEF ||
6450           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6451         ((InVec1.getOpcode() == ISD::UNDEF ||
6452           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6453       X86Opcode = X86ISD::HSUB;
6454     else
6455       CanFold = false;
6456
6457     if (CanFold) {
6458       // Fold this build_vector into a single horizontal add/sub.
6459       // Do this only if the target has AVX2.
6460       if (Subtarget->hasAVX2())
6461         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6462  
6463       // Do not try to expand this build_vector into a pair of horizontal
6464       // add/sub if we can emit a pair of scalar add/sub.
6465       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6466         return SDValue();
6467
6468       // Convert this build_vector into a pair of horizontal binop followed by
6469       // a concat vector.
6470       bool isUndefLO = NumUndefsLO == Half;
6471       bool isUndefHI = NumUndefsHI == Half;
6472       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6473                                    isUndefLO, isUndefHI);
6474     }
6475   }
6476
6477   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6478        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6479     unsigned X86Opcode;
6480     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6481       X86Opcode = X86ISD::HADD;
6482     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6483       X86Opcode = X86ISD::HSUB;
6484     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6485       X86Opcode = X86ISD::FHADD;
6486     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6487       X86Opcode = X86ISD::FHSUB;
6488     else
6489       return SDValue();
6490
6491     // Don't try to expand this build_vector into a pair of horizontal add/sub
6492     // if we can simply emit a pair of scalar add/sub.
6493     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6494       return SDValue();
6495
6496     // Convert this build_vector into two horizontal add/sub followed by
6497     // a concat vector.
6498     bool isUndefLO = NumUndefsLO == Half;
6499     bool isUndefHI = NumUndefsHI == Half;
6500     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6501                                  isUndefLO, isUndefHI);
6502   }
6503
6504   return SDValue();
6505 }
6506
6507 SDValue
6508 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6509   SDLoc dl(Op);
6510
6511   MVT VT = Op.getSimpleValueType();
6512   MVT ExtVT = VT.getVectorElementType();
6513   unsigned NumElems = Op.getNumOperands();
6514
6515   // Generate vectors for predicate vectors.
6516   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6517     return LowerBUILD_VECTORvXi1(Op, DAG);
6518
6519   // Vectors containing all zeros can be matched by pxor and xorps later
6520   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6521     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6522     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6523     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6524       return Op;
6525
6526     return getZeroVector(VT, Subtarget, DAG, dl);
6527   }
6528
6529   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6530   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6531   // vpcmpeqd on 256-bit vectors.
6532   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6533     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6534       return Op;
6535
6536     if (!VT.is512BitVector())
6537       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6538   }
6539
6540   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6541   if (Broadcast.getNode())
6542     return Broadcast;
6543
6544   unsigned EVTBits = ExtVT.getSizeInBits();
6545
6546   unsigned NumZero  = 0;
6547   unsigned NumNonZero = 0;
6548   unsigned NonZeros = 0;
6549   bool IsAllConstants = true;
6550   SmallSet<SDValue, 8> Values;
6551   for (unsigned i = 0; i < NumElems; ++i) {
6552     SDValue Elt = Op.getOperand(i);
6553     if (Elt.getOpcode() == ISD::UNDEF)
6554       continue;
6555     Values.insert(Elt);
6556     if (Elt.getOpcode() != ISD::Constant &&
6557         Elt.getOpcode() != ISD::ConstantFP)
6558       IsAllConstants = false;
6559     if (X86::isZeroNode(Elt))
6560       NumZero++;
6561     else {
6562       NonZeros |= (1 << i);
6563       NumNonZero++;
6564     }
6565   }
6566
6567   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6568   if (NumNonZero == 0)
6569     return DAG.getUNDEF(VT);
6570
6571   // Special case for single non-zero, non-undef, element.
6572   if (NumNonZero == 1) {
6573     unsigned Idx = countTrailingZeros(NonZeros);
6574     SDValue Item = Op.getOperand(Idx);
6575
6576     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6577     // the value are obviously zero, truncate the value to i32 and do the
6578     // insertion that way.  Only do this if the value is non-constant or if the
6579     // value is a constant being inserted into element 0.  It is cheaper to do
6580     // a constant pool load than it is to do a movd + shuffle.
6581     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6582         (!IsAllConstants || Idx == 0)) {
6583       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6584         // Handle SSE only.
6585         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6586         EVT VecVT = MVT::v4i32;
6587         unsigned VecElts = 4;
6588
6589         // Truncate the value (which may itself be a constant) to i32, and
6590         // convert it to a vector with movd (S2V+shuffle to zero extend).
6591         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6592         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6593         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6594
6595         // Now we have our 32-bit value zero extended in the low element of
6596         // a vector.  If Idx != 0, swizzle it into place.
6597         if (Idx != 0) {
6598           SmallVector<int, 4> Mask;
6599           Mask.push_back(Idx);
6600           for (unsigned i = 1; i != VecElts; ++i)
6601             Mask.push_back(i);
6602           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6603                                       &Mask[0]);
6604         }
6605         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6606       }
6607     }
6608
6609     // If we have a constant or non-constant insertion into the low element of
6610     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6611     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6612     // depending on what the source datatype is.
6613     if (Idx == 0) {
6614       if (NumZero == 0)
6615         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6616
6617       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6618           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6619         if (VT.is256BitVector() || VT.is512BitVector()) {
6620           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6621           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6622                              Item, DAG.getIntPtrConstant(0));
6623         }
6624         assert(VT.is128BitVector() && "Expected an SSE value type!");
6625         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6626         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6627         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6628       }
6629
6630       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6631         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6632         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6633         if (VT.is256BitVector()) {
6634           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6635           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6636         } else {
6637           assert(VT.is128BitVector() && "Expected an SSE value type!");
6638           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6639         }
6640         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6641       }
6642     }
6643
6644     // Is it a vector logical left shift?
6645     if (NumElems == 2 && Idx == 1 &&
6646         X86::isZeroNode(Op.getOperand(0)) &&
6647         !X86::isZeroNode(Op.getOperand(1))) {
6648       unsigned NumBits = VT.getSizeInBits();
6649       return getVShift(true, VT,
6650                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6651                                    VT, Op.getOperand(1)),
6652                        NumBits/2, DAG, *this, dl);
6653     }
6654
6655     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6656       return SDValue();
6657
6658     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6659     // is a non-constant being inserted into an element other than the low one,
6660     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6661     // movd/movss) to move this into the low element, then shuffle it into
6662     // place.
6663     if (EVTBits == 32) {
6664       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6665
6666       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6667       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6668       SmallVector<int, 8> MaskVec;
6669       for (unsigned i = 0; i != NumElems; ++i)
6670         MaskVec.push_back(i == Idx ? 0 : 1);
6671       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6672     }
6673   }
6674
6675   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6676   if (Values.size() == 1) {
6677     if (EVTBits == 32) {
6678       // Instead of a shuffle like this:
6679       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6680       // Check if it's possible to issue this instead.
6681       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6682       unsigned Idx = countTrailingZeros(NonZeros);
6683       SDValue Item = Op.getOperand(Idx);
6684       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6685         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6686     }
6687     return SDValue();
6688   }
6689
6690   // A vector full of immediates; various special cases are already
6691   // handled, so this is best done with a single constant-pool load.
6692   if (IsAllConstants)
6693     return SDValue();
6694
6695   // For AVX-length vectors, build the individual 128-bit pieces and use
6696   // shuffles to put them in place.
6697   if (VT.is256BitVector() || VT.is512BitVector()) {
6698     SmallVector<SDValue, 64> V;
6699     for (unsigned i = 0; i != NumElems; ++i)
6700       V.push_back(Op.getOperand(i));
6701
6702     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6703
6704     // Build both the lower and upper subvector.
6705     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6706                                 makeArrayRef(&V[0], NumElems/2));
6707     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6708                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6709
6710     // Recreate the wider vector with the lower and upper part.
6711     if (VT.is256BitVector())
6712       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6713     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6714   }
6715
6716   // Let legalizer expand 2-wide build_vectors.
6717   if (EVTBits == 64) {
6718     if (NumNonZero == 1) {
6719       // One half is zero or undef.
6720       unsigned Idx = countTrailingZeros(NonZeros);
6721       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6722                                  Op.getOperand(Idx));
6723       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6724     }
6725     return SDValue();
6726   }
6727
6728   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6729   if (EVTBits == 8 && NumElems == 16) {
6730     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6731                                         Subtarget, *this);
6732     if (V.getNode()) return V;
6733   }
6734
6735   if (EVTBits == 16 && NumElems == 8) {
6736     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6737                                       Subtarget, *this);
6738     if (V.getNode()) return V;
6739   }
6740
6741   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6742   if (EVTBits == 32 && NumElems == 4) {
6743     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6744                                       NumZero, DAG, Subtarget, *this);
6745     if (V.getNode())
6746       return V;
6747   }
6748
6749   // If element VT is == 32 bits, turn it into a number of shuffles.
6750   SmallVector<SDValue, 8> V(NumElems);
6751   if (NumElems == 4 && NumZero > 0) {
6752     for (unsigned i = 0; i < 4; ++i) {
6753       bool isZero = !(NonZeros & (1 << i));
6754       if (isZero)
6755         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6756       else
6757         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6758     }
6759
6760     for (unsigned i = 0; i < 2; ++i) {
6761       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6762         default: break;
6763         case 0:
6764           V[i] = V[i*2];  // Must be a zero vector.
6765           break;
6766         case 1:
6767           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6768           break;
6769         case 2:
6770           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6771           break;
6772         case 3:
6773           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6774           break;
6775       }
6776     }
6777
6778     bool Reverse1 = (NonZeros & 0x3) == 2;
6779     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6780     int MaskVec[] = {
6781       Reverse1 ? 1 : 0,
6782       Reverse1 ? 0 : 1,
6783       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6784       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6785     };
6786     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6787   }
6788
6789   if (Values.size() > 1 && VT.is128BitVector()) {
6790     // Check for a build vector of consecutive loads.
6791     for (unsigned i = 0; i < NumElems; ++i)
6792       V[i] = Op.getOperand(i);
6793
6794     // Check for elements which are consecutive loads.
6795     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6796     if (LD.getNode())
6797       return LD;
6798
6799     // Check for a build vector from mostly shuffle plus few inserting.
6800     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6801     if (Sh.getNode())
6802       return Sh;
6803
6804     // For SSE 4.1, use insertps to put the high elements into the low element.
6805     if (getSubtarget()->hasSSE41()) {
6806       SDValue Result;
6807       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6808         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6809       else
6810         Result = DAG.getUNDEF(VT);
6811
6812       for (unsigned i = 1; i < NumElems; ++i) {
6813         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6814         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6815                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6816       }
6817       return Result;
6818     }
6819
6820     // Otherwise, expand into a number of unpckl*, start by extending each of
6821     // our (non-undef) elements to the full vector width with the element in the
6822     // bottom slot of the vector (which generates no code for SSE).
6823     for (unsigned i = 0; i < NumElems; ++i) {
6824       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6825         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6826       else
6827         V[i] = DAG.getUNDEF(VT);
6828     }
6829
6830     // Next, we iteratively mix elements, e.g. for v4f32:
6831     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6832     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6833     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6834     unsigned EltStride = NumElems >> 1;
6835     while (EltStride != 0) {
6836       for (unsigned i = 0; i < EltStride; ++i) {
6837         // If V[i+EltStride] is undef and this is the first round of mixing,
6838         // then it is safe to just drop this shuffle: V[i] is already in the
6839         // right place, the one element (since it's the first round) being
6840         // inserted as undef can be dropped.  This isn't safe for successive
6841         // rounds because they will permute elements within both vectors.
6842         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6843             EltStride == NumElems/2)
6844           continue;
6845
6846         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6847       }
6848       EltStride >>= 1;
6849     }
6850     return V[0];
6851   }
6852   return SDValue();
6853 }
6854
6855 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6856 // to create 256-bit vectors from two other 128-bit ones.
6857 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6858   SDLoc dl(Op);
6859   MVT ResVT = Op.getSimpleValueType();
6860
6861   assert((ResVT.is256BitVector() ||
6862           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6863
6864   SDValue V1 = Op.getOperand(0);
6865   SDValue V2 = Op.getOperand(1);
6866   unsigned NumElems = ResVT.getVectorNumElements();
6867   if(ResVT.is256BitVector())
6868     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6869
6870   if (Op.getNumOperands() == 4) {
6871     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6872                                 ResVT.getVectorNumElements()/2);
6873     SDValue V3 = Op.getOperand(2);
6874     SDValue V4 = Op.getOperand(3);
6875     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6876       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6877   }
6878   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6879 }
6880
6881 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6882   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6883   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6884          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6885           Op.getNumOperands() == 4)));
6886
6887   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6888   // from two other 128-bit ones.
6889
6890   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6891   return LowerAVXCONCAT_VECTORS(Op, DAG);
6892 }
6893
6894
6895 //===----------------------------------------------------------------------===//
6896 // Vector shuffle lowering
6897 //
6898 // This is an experimental code path for lowering vector shuffles on x86. It is
6899 // designed to handle arbitrary vector shuffles and blends, gracefully
6900 // degrading performance as necessary. It works hard to recognize idiomatic
6901 // shuffles and lower them to optimal instruction patterns without leaving
6902 // a framework that allows reasonably efficient handling of all vector shuffle
6903 // patterns.
6904 //===----------------------------------------------------------------------===//
6905
6906 /// \brief Tiny helper function to identify a no-op mask.
6907 ///
6908 /// This is a somewhat boring predicate function. It checks whether the mask
6909 /// array input, which is assumed to be a single-input shuffle mask of the kind
6910 /// used by the X86 shuffle instructions (not a fully general
6911 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6912 /// in-place shuffle are 'no-op's.
6913 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6914   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6915     if (Mask[i] != -1 && Mask[i] != i)
6916       return false;
6917   return true;
6918 }
6919
6920 /// \brief Helper function to classify a mask as a single-input mask.
6921 ///
6922 /// This isn't a generic single-input test because in the vector shuffle
6923 /// lowering we canonicalize single inputs to be the first input operand. This
6924 /// means we can more quickly test for a single input by only checking whether
6925 /// an input from the second operand exists. We also assume that the size of
6926 /// mask corresponds to the size of the input vectors which isn't true in the
6927 /// fully general case.
6928 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6929   for (int M : Mask)
6930     if (M >= (int)Mask.size())
6931       return false;
6932   return true;
6933 }
6934
6935 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6936 ///
6937 /// This helper function produces an 8-bit shuffle immediate corresponding to
6938 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6939 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6940 /// example.
6941 ///
6942 /// NB: We rely heavily on "undef" masks preserving the input lane.
6943 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask,
6944                                           SelectionDAG &DAG) {
6945   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6946   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6947   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6948   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6949   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6950
6951   unsigned Imm = 0;
6952   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6953   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6954   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6955   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6956   return DAG.getConstant(Imm, MVT::i8);
6957 }
6958
6959 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
6960 ///
6961 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
6962 /// support for floating point shuffles but not integer shuffles. These
6963 /// instructions will incur a domain crossing penalty on some chips though so
6964 /// it is better to avoid lowering through this for integer vectors where
6965 /// possible.
6966 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6967                                        const X86Subtarget *Subtarget,
6968                                        SelectionDAG &DAG) {
6969   SDLoc DL(Op);
6970   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
6971   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6972   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
6973   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6974   ArrayRef<int> Mask = SVOp->getMask();
6975   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
6976
6977   if (isSingleInputShuffleMask(Mask)) {
6978     // Straight shuffle of a single input vector. Simulate this by using the
6979     // single input as both of the "inputs" to this instruction..
6980     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
6981     return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V1,
6982                        DAG.getConstant(SHUFPDMask, MVT::i8));
6983   }
6984   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
6985   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
6986
6987   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
6988   return DAG.getNode(X86ISD::SHUFP, SDLoc(Op), MVT::v2f64, V1, V2,
6989                      DAG.getConstant(SHUFPDMask, MVT::i8));
6990 }
6991
6992 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
6993 ///
6994 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
6995 /// the integer unit to minimize domain crossing penalties. However, for blends
6996 /// it falls back to the floating point shuffle operation with appropriate bit
6997 /// casting.
6998 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
6999                                        const X86Subtarget *Subtarget,
7000                                        SelectionDAG &DAG) {
7001   SDLoc DL(Op);
7002   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7003   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7004   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7005   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7006   ArrayRef<int> Mask = SVOp->getMask();
7007   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7008
7009   if (isSingleInputShuffleMask(Mask)) {
7010     // Straight shuffle of a single input vector. For everything from SSE2
7011     // onward this has a single fast instruction with no scary immediates.
7012     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7013     V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V1);
7014     int WidenedMask[4] = {
7015         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7016         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7017     return DAG.getNode(
7018         ISD::BITCAST, DL, MVT::v2i64,
7019         DAG.getNode(X86ISD::PSHUFD, SDLoc(Op), MVT::v4i32, V1,
7020                     getV4X86ShuffleImm8ForMask(WidenedMask, DAG)));
7021   }
7022
7023   // We implement this with SHUFPD which is pretty lame because it will likely
7024   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7025   // However, all the alternatives are still more cycles and newer chips don't
7026   // have this problem. It would be really nice if x86 had better shuffles here.
7027   V1 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V1);
7028   V2 = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, V2);
7029   return DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7030                      DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7031 }
7032
7033 /// \brief Lower 4-lane 32-bit floating point shuffles.
7034 ///
7035 /// Uses instructions exclusively from the floating point unit to minimize
7036 /// domain crossing penalties, as these are sufficient to implement all v4f32
7037 /// shuffles.
7038 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7039                                        const X86Subtarget *Subtarget,
7040                                        SelectionDAG &DAG) {
7041   SDLoc DL(Op);
7042   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7043   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7044   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7046   ArrayRef<int> Mask = SVOp->getMask();
7047   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7048
7049   SDValue LowV = V1, HighV = V2;
7050   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7051
7052   int NumV2Elements =
7053       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7054
7055   if (NumV2Elements == 0)
7056     // Straight shuffle of a single input vector. We pass the input vector to
7057     // both operands to simulate this with a SHUFPS.
7058     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7059                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7060
7061   if (NumV2Elements == 1) {
7062     int V2Index =
7063         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7064         Mask.begin();
7065     // Compute the index adjacent to V2Index and in the same half by toggling
7066     // the low bit.
7067     int V2AdjIndex = V2Index ^ 1;
7068
7069     if (Mask[V2AdjIndex] == -1) {
7070       // Handles all the cases where we have a single V2 element and an undef.
7071       // This will only ever happen in the high lanes because we commute the
7072       // vector otherwise.
7073       if (V2Index < 2)
7074         std::swap(LowV, HighV);
7075       NewMask[V2Index] -= 4;
7076     } else {
7077       // Handle the case where the V2 element ends up adjacent to a V1 element.
7078       // To make this work, blend them together as the first step.
7079       int V1Index = V2AdjIndex;
7080       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7081       V2 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V2, V1,
7082                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7083
7084       // Now proceed to reconstruct the final blend as we have the necessary
7085       // high or low half formed.
7086       if (V2Index < 2) {
7087         LowV = V2;
7088         HighV = V1;
7089       } else {
7090         HighV = V2;
7091       }
7092       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7093       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7094     }
7095   } else if (NumV2Elements == 2) {
7096     if (Mask[0] < 4 && Mask[1] < 4) {
7097       // Handle the easy case where we have V1 in the low lanes and V2 in the
7098       // high lanes. We never see this reversed because we sort the shuffle.
7099       NewMask[2] -= 4;
7100       NewMask[3] -= 4;
7101     } else {
7102       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7103       // trying to place elements directly, just blend them and set up the final
7104       // shuffle to place them.
7105
7106       // The first two blend mask elements are for V1, the second two are for
7107       // V2.
7108       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7109                           Mask[2] < 4 ? Mask[2] : Mask[3],
7110                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7111                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7112       V1 = DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V2,
7113                        getV4X86ShuffleImm8ForMask(BlendMask, DAG));
7114
7115       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7116       // a blend.
7117       LowV = HighV = V1;
7118       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7119       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7120       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7121       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7122     }
7123   }
7124   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, LowV, HighV,
7125                      getV4X86ShuffleImm8ForMask(NewMask, DAG));
7126 }
7127
7128 /// \brief Lower 4-lane i32 vector shuffles.
7129 ///
7130 /// We try to handle these with integer-domain shuffles where we can, but for
7131 /// blends we use the floating point domain blend instructions.
7132 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7133                                        const X86Subtarget *Subtarget,
7134                                        SelectionDAG &DAG) {
7135   SDLoc DL(Op);
7136   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7137   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7138   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7139   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7140   ArrayRef<int> Mask = SVOp->getMask();
7141   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7142
7143   if (isSingleInputShuffleMask(Mask))
7144     // Straight shuffle of a single input vector. For everything from SSE2
7145     // onward this has a single fast instruction with no scary immediates.
7146     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7147                        getV4X86ShuffleImm8ForMask(Mask, DAG));
7148
7149   // We implement this with SHUFPS because it can blend from two vectors.
7150   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7151   // up the inputs, bypassing domain shift penalties that we would encur if we
7152   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7153   // relevant.
7154   return DAG.getNode(ISD::BITCAST, DL, MVT::v4i32,
7155                      DAG.getVectorShuffle(
7156                          MVT::v4f32, DL,
7157                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V1),
7158                          DAG.getNode(ISD::BITCAST, DL, MVT::v4f32, V2), Mask));
7159 }
7160
7161 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
7162 /// shuffle lowering, and the most complex part.
7163 ///
7164 /// The lowering strategy is to try to form pairs of input lanes which are
7165 /// targeted at the same half of the final vector, and then use a dword shuffle
7166 /// to place them onto the right half, and finally unpack the paired lanes into
7167 /// their final position.
7168 ///
7169 /// The exact breakdown of how to form these dword pairs and align them on the
7170 /// correct sides is really tricky. See the comments within the function for
7171 /// more of the details.
7172 static SDValue lowerV8I16SingleInputVectorShuffle(
7173     SDLoc DL, SDValue V, MutableArrayRef<int> Mask,
7174     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7175   assert(V.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7176   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
7177   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
7178
7179   SmallVector<int, 4> LoInputs;
7180   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
7181                [](int M) { return M >= 0; });
7182   std::sort(LoInputs.begin(), LoInputs.end());
7183   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
7184   SmallVector<int, 4> HiInputs;
7185   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
7186                [](int M) { return M >= 0; });
7187   std::sort(HiInputs.begin(), HiInputs.end());
7188   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
7189   int NumLToL =
7190       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
7191   int NumHToL = LoInputs.size() - NumLToL;
7192   int NumLToH =
7193       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
7194   int NumHToH = HiInputs.size() - NumLToH;
7195   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
7196   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
7197   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
7198   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
7199
7200   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
7201   // such inputs we can swap two of the dwords across the half mark and end up
7202   // with <=2 inputs to each half in each half. Once there, we can fall through
7203   // to the generic code below. For example:
7204   //
7205   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
7206   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
7207   //
7208   // Before we had 3-1 in the low half and 3-1 in the high half. Afterward, 2-2
7209   // and 2-2.
7210   auto balanceSides = [&](ArrayRef<int> ThreeInputs, int OneInput,
7211                           int ThreeInputHalfSum, int OneInputHalfOffset) {
7212     // Compute the index of dword with only one word among the three inputs in
7213     // a half by taking the sum of the half with three inputs and subtracting
7214     // the sum of the actual three inputs. The difference is the remaining
7215     // slot.
7216     int DWordA = (ThreeInputHalfSum -
7217                   std::accumulate(ThreeInputs.begin(), ThreeInputs.end(), 0)) /
7218                  2;
7219     int DWordB = OneInputHalfOffset / 2 + (OneInput / 2 + 1) % 2;
7220
7221     int PSHUFDMask[] = {0, 1, 2, 3};
7222     PSHUFDMask[DWordA] = DWordB;
7223     PSHUFDMask[DWordB] = DWordA;
7224     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7225                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7226                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7227                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7228
7229     // Adjust the mask to match the new locations of A and B.
7230     for (int &M : Mask)
7231       if (M != -1 && M/2 == DWordA)
7232         M = 2 * DWordB + M % 2;
7233       else if (M != -1 && M/2 == DWordB)
7234         M = 2 * DWordA + M % 2;
7235
7236     // Recurse back into this routine to re-compute state now that this isn't
7237     // a 3 and 1 problem.
7238     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7239                                 Mask);
7240   };
7241   if (NumLToL == 3 && NumHToL == 1)
7242     return balanceSides(LToLInputs, HToLInputs[0], 0 + 1 + 2 + 3, 4);
7243   else if (NumLToL == 1 && NumHToL == 3)
7244     return balanceSides(HToLInputs, LToLInputs[0], 4 + 5 + 6 + 7, 0);
7245   else if (NumLToH == 1 && NumHToH == 3)
7246     return balanceSides(HToHInputs, LToHInputs[0], 4 + 5 + 6 + 7, 0);
7247   else if (NumLToH == 3 && NumHToH == 1)
7248     return balanceSides(LToHInputs, HToHInputs[0], 0 + 1 + 2 + 3, 4);
7249
7250   // At this point there are at most two inputs to the low and high halves from
7251   // each half. That means the inputs can always be grouped into dwords and
7252   // those dwords can then be moved to the correct half with a dword shuffle.
7253   // We use at most one low and one high word shuffle to collect these paired
7254   // inputs into dwords, and finally a dword shuffle to place them.
7255   int PSHUFLMask[4] = {-1, -1, -1, -1};
7256   int PSHUFHMask[4] = {-1, -1, -1, -1};
7257   int PSHUFDMask[4] = {-1, -1, -1, -1};
7258
7259   // First fix the masks for all the inputs that are staying in their
7260   // original halves. This will then dictate the targets of the cross-half
7261   // shuffles.
7262   auto fixInPlaceInputs = [&PSHUFDMask](
7263       ArrayRef<int> InPlaceInputs, MutableArrayRef<int> SourceHalfMask,
7264       MutableArrayRef<int> HalfMask, int HalfOffset) {
7265     if (InPlaceInputs.empty())
7266       return;
7267     if (InPlaceInputs.size() == 1) {
7268       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7269           InPlaceInputs[0] - HalfOffset;
7270       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
7271       return;
7272     }
7273
7274     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
7275     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
7276         InPlaceInputs[0] - HalfOffset;
7277     // Put the second input next to the first so that they are packed into
7278     // a dword. We find the adjacent index by toggling the low bit.
7279     int AdjIndex = InPlaceInputs[0] ^ 1;
7280     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
7281     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
7282     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
7283   };
7284   if (!HToLInputs.empty())
7285     fixInPlaceInputs(LToLInputs, PSHUFLMask, LoMask, 0);
7286   if (!LToHInputs.empty())
7287     fixInPlaceInputs(HToHInputs, PSHUFHMask, HiMask, 4);
7288
7289   // Now gather the cross-half inputs and place them into a free dword of
7290   // their target half.
7291   // FIXME: This operation could almost certainly be simplified dramatically to
7292   // look more like the 3-1 fixing operation.
7293   auto moveInputsToRightHalf = [&PSHUFDMask](
7294       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
7295       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
7296       int SourceOffset, int DestOffset) {
7297     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
7298       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
7299     };
7300     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
7301                                                int Word) {
7302       int LowWord = Word & ~1;
7303       int HighWord = Word | 1;
7304       return isWordClobbered(SourceHalfMask, LowWord) ||
7305              isWordClobbered(SourceHalfMask, HighWord);
7306     };
7307
7308     if (IncomingInputs.empty())
7309       return;
7310
7311     if (ExistingInputs.empty()) {
7312       // Map any dwords with inputs from them into the right half.
7313       for (int Input : IncomingInputs) {
7314         // If the source half mask maps over the inputs, turn those into
7315         // swaps and use the swapped lane.
7316         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
7317           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
7318             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
7319                 Input - SourceOffset;
7320             // We have to swap the uses in our half mask in one sweep.
7321             for (int &M : HalfMask)
7322               if (M == SourceHalfMask[Input - SourceOffset])
7323                 M = Input;
7324               else if (M == Input)
7325                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7326           } else {
7327             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
7328                        Input - SourceOffset &&
7329                    "Previous placement doesn't match!");
7330           }
7331           // Note that this correctly re-maps both when we do a swap and when
7332           // we observe the other side of the swap above. We rely on that to
7333           // avoid swapping the members of the input list directly.
7334           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
7335         }
7336
7337         // Map the input's dword into the correct half.
7338         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
7339           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
7340         else
7341           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
7342                      Input / 2 &&
7343                  "Previous placement doesn't match!");
7344       }
7345
7346       // And just directly shift any other-half mask elements to be same-half
7347       // as we will have mirrored the dword containing the element into the
7348       // same position within that half.
7349       for (int &M : HalfMask)
7350         if (M >= SourceOffset && M < SourceOffset + 4) {
7351           M = M - SourceOffset + DestOffset;
7352           assert(M >= 0 && "This should never wrap below zero!");
7353         }
7354       return;
7355     }
7356
7357     // Ensure we have the input in a viable dword of its current half. This
7358     // is particularly tricky because the original position may be clobbered
7359     // by inputs being moved and *staying* in that half.
7360     if (IncomingInputs.size() == 1) {
7361       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7362         int InputFixed = std::find(std::begin(SourceHalfMask),
7363                                    std::end(SourceHalfMask), -1) -
7364                          std::begin(SourceHalfMask) + SourceOffset;
7365         SourceHalfMask[InputFixed - SourceOffset] =
7366             IncomingInputs[0] - SourceOffset;
7367         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
7368                      InputFixed);
7369         IncomingInputs[0] = InputFixed;
7370       }
7371     } else if (IncomingInputs.size() == 2) {
7372       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
7373           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
7374         int SourceDWordBase = !isDWordClobbered(SourceHalfMask, 0) ? 0 : 2;
7375         assert(!isDWordClobbered(SourceHalfMask, SourceDWordBase) &&
7376                "Not all dwords can be clobbered!");
7377         SourceHalfMask[SourceDWordBase] = IncomingInputs[0] - SourceOffset;
7378         SourceHalfMask[SourceDWordBase + 1] = IncomingInputs[1] - SourceOffset;
7379         for (int &M : HalfMask)
7380           if (M == IncomingInputs[0])
7381             M = SourceDWordBase + SourceOffset;
7382           else if (M == IncomingInputs[1])
7383             M = SourceDWordBase + 1 + SourceOffset;
7384         IncomingInputs[0] = SourceDWordBase + SourceOffset;
7385         IncomingInputs[1] = SourceDWordBase + 1 + SourceOffset;
7386       }
7387     } else {
7388       llvm_unreachable("Unhandled input size!");
7389     }
7390
7391     // Now hoist the DWord down to the right half.
7392     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
7393     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
7394     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
7395     for (int Input : IncomingInputs)
7396       std::replace(HalfMask.begin(), HalfMask.end(), Input,
7397                    FreeDWord * 2 + Input % 2);
7398   };
7399   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask,
7400                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
7401   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask,
7402                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
7403
7404   // Now enact all the shuffles we've computed to move the inputs into their
7405   // target half.
7406   if (!isNoopShuffleMask(PSHUFLMask))
7407     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7408                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DAG));
7409   if (!isNoopShuffleMask(PSHUFHMask))
7410     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7411                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DAG));
7412   if (!isNoopShuffleMask(PSHUFDMask))
7413     V = DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7414                     DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7415                                 DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V),
7416                                 getV4X86ShuffleImm8ForMask(PSHUFDMask, DAG)));
7417
7418   // At this point, each half should contain all its inputs, and we can then
7419   // just shuffle them into their final position.
7420   assert(std::count_if(LoMask.begin(), LoMask.end(),
7421                        [](int M) { return M >= 4; }) == 0 &&
7422          "Failed to lift all the high half inputs to the low mask!");
7423   assert(std::count_if(HiMask.begin(), HiMask.end(),
7424                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
7425          "Failed to lift all the low half inputs to the high mask!");
7426
7427   // Do a half shuffle for the low mask.
7428   if (!isNoopShuffleMask(LoMask))
7429     V = DAG.getNode(X86ISD::PSHUFLW, DL, MVT::v8i16, V,
7430                     getV4X86ShuffleImm8ForMask(LoMask, DAG));
7431
7432   // Do a half shuffle with the high mask after shifting its values down.
7433   for (int &M : HiMask)
7434     if (M >= 0)
7435       M -= 4;
7436   if (!isNoopShuffleMask(HiMask))
7437     V = DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16, V,
7438                     getV4X86ShuffleImm8ForMask(HiMask, DAG));
7439
7440   return V;
7441 }
7442
7443 /// \brief Detect whether the mask pattern should be lowered through
7444 /// interleaving.
7445 ///
7446 /// This essentially tests whether viewing the mask as an interleaving of two
7447 /// sub-sequences reduces the cross-input traffic of a blend operation. If so,
7448 /// lowering it through interleaving is a significantly better strategy.
7449 static bool shouldLowerAsInterleaving(ArrayRef<int> Mask) {
7450   int NumEvenInputs[2] = {0, 0};
7451   int NumOddInputs[2] = {0, 0};
7452   int NumLoInputs[2] = {0, 0};
7453   int NumHiInputs[2] = {0, 0};
7454   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
7455     if (Mask[i] < 0)
7456       continue;
7457
7458     int InputIdx = Mask[i] >= Size;
7459
7460     if (i < Size / 2)
7461       ++NumLoInputs[InputIdx];
7462     else
7463       ++NumHiInputs[InputIdx];
7464
7465     if ((i % 2) == 0)
7466       ++NumEvenInputs[InputIdx];
7467     else
7468       ++NumOddInputs[InputIdx];
7469   }
7470
7471   // The minimum number of cross-input results for both the interleaved and
7472   // split cases. If interleaving results in fewer cross-input results, return
7473   // true.
7474   int InterleavedCrosses = std::min(NumEvenInputs[1] + NumOddInputs[0],
7475                                     NumEvenInputs[0] + NumOddInputs[1]);
7476   int SplitCrosses = std::min(NumLoInputs[1] + NumHiInputs[0],
7477                               NumLoInputs[0] + NumHiInputs[1]);
7478   return InterleavedCrosses < SplitCrosses;
7479 }
7480
7481 /// \brief Blend two v8i16 vectors using a naive unpack strategy.
7482 ///
7483 /// This strategy only works when the inputs from each vector fit into a single
7484 /// half of that vector, and generally there are not so many inputs as to leave
7485 /// the in-place shuffles required highly constrained (and thus expensive). It
7486 /// shifts all the inputs into a single side of both input vectors and then
7487 /// uses an unpack to interleave these inputs in a single vector. At that
7488 /// point, we will fall back on the generic single input shuffle lowering.
7489 static SDValue lowerV8I16BasicBlendVectorShuffle(SDLoc DL, SDValue V1,
7490                                                  SDValue V2,
7491                                                  MutableArrayRef<int> Mask,
7492                                                  const X86Subtarget *Subtarget,
7493                                                  SelectionDAG &DAG) {
7494   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7495   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad input type!");
7496   SmallVector<int, 3> LoV1Inputs, HiV1Inputs, LoV2Inputs, HiV2Inputs;
7497   for (int i = 0; i < 8; ++i)
7498     if (Mask[i] >= 0 && Mask[i] < 4)
7499       LoV1Inputs.push_back(i);
7500     else if (Mask[i] >= 4 && Mask[i] < 8)
7501       HiV1Inputs.push_back(i);
7502     else if (Mask[i] >= 8 && Mask[i] < 12)
7503       LoV2Inputs.push_back(i);
7504     else if (Mask[i] >= 12)
7505       HiV2Inputs.push_back(i);
7506
7507   int NumV1Inputs = LoV1Inputs.size() + HiV1Inputs.size();
7508   int NumV2Inputs = LoV2Inputs.size() + HiV2Inputs.size();
7509   (void)NumV1Inputs;
7510   (void)NumV2Inputs;
7511   assert(NumV1Inputs > 0 && NumV1Inputs <= 3 && "At most 3 inputs supported");
7512   assert(NumV2Inputs > 0 && NumV2Inputs <= 3 && "At most 3 inputs supported");
7513   assert(NumV1Inputs + NumV2Inputs <= 4 && "At most 4 combined inputs");
7514
7515   bool MergeFromLo = LoV1Inputs.size() + LoV2Inputs.size() >=
7516                      HiV1Inputs.size() + HiV2Inputs.size();
7517
7518   auto moveInputsToHalf = [&](SDValue V, ArrayRef<int> LoInputs,
7519                               ArrayRef<int> HiInputs, bool MoveToLo,
7520                               int MaskOffset) {
7521     ArrayRef<int> GoodInputs = MoveToLo ? LoInputs : HiInputs;
7522     ArrayRef<int> BadInputs = MoveToLo ? HiInputs : LoInputs;
7523     if (BadInputs.empty())
7524       return V;
7525
7526     int MoveMask[] = {-1, -1, -1, -1, -1, -1, -1, -1};
7527     int MoveOffset = MoveToLo ? 0 : 4;
7528
7529     if (GoodInputs.empty()) {
7530       for (int BadInput : BadInputs) {
7531         MoveMask[Mask[BadInput] % 4 + MoveOffset] = Mask[BadInput] - MaskOffset;
7532         Mask[BadInput] = Mask[BadInput] % 4 + MoveOffset + MaskOffset;
7533       }
7534     } else {
7535       if (GoodInputs.size() == 2) {
7536         // If the low inputs are spread across two dwords, pack them into
7537         // a single dword.
7538         MoveMask[Mask[GoodInputs[0]] % 2 + MoveOffset] =
7539             Mask[GoodInputs[0]] - MaskOffset;
7540         MoveMask[Mask[GoodInputs[1]] % 2 + MoveOffset] =
7541             Mask[GoodInputs[1]] - MaskOffset;
7542         Mask[GoodInputs[0]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7543         Mask[GoodInputs[1]] = Mask[GoodInputs[0]] % 2 + MoveOffset + MaskOffset;
7544       } else {
7545         // Otherwise pin the low inputs.
7546         for (int GoodInput : GoodInputs)
7547           MoveMask[Mask[GoodInput] - MaskOffset] = Mask[GoodInput] - MaskOffset;
7548       }
7549
7550       int MoveMaskIdx =
7551           std::find(std::begin(MoveMask) + MoveOffset, std::end(MoveMask), -1) -
7552           std::begin(MoveMask);
7553       assert(MoveMaskIdx >= MoveOffset && "Established above");
7554
7555       if (BadInputs.size() == 2) {
7556         assert(MoveMask[MoveMaskIdx] == -1 && "Expected empty slot");
7557         assert(MoveMask[MoveMaskIdx + 1] == -1 && "Expected empty slot");
7558         MoveMask[MoveMaskIdx + Mask[BadInputs[0]] % 2] =
7559             Mask[BadInputs[0]] - MaskOffset;
7560         MoveMask[MoveMaskIdx + Mask[BadInputs[1]] % 2] =
7561             Mask[BadInputs[1]] - MaskOffset;
7562         Mask[BadInputs[0]] = MoveMaskIdx + Mask[BadInputs[0]] % 2 + MaskOffset;
7563         Mask[BadInputs[1]] = MoveMaskIdx + Mask[BadInputs[1]] % 2 + MaskOffset;
7564       } else {
7565         assert(BadInputs.size() == 1 && "All sizes handled");
7566         MoveMask[MoveMaskIdx] = Mask[BadInputs[0]] - MaskOffset;
7567         Mask[BadInputs[0]] = MoveMaskIdx + MaskOffset;
7568       }
7569     }
7570
7571     return DAG.getVectorShuffle(MVT::v8i16, DL, V, DAG.getUNDEF(MVT::v8i16),
7572                                 MoveMask);
7573   };
7574   V1 = moveInputsToHalf(V1, LoV1Inputs, HiV1Inputs, MergeFromLo,
7575                         /*MaskOffset*/ 0);
7576   V2 = moveInputsToHalf(V2, LoV2Inputs, HiV2Inputs, MergeFromLo,
7577                         /*MaskOffset*/ 8);
7578
7579   // FIXME: Select an interleaving of the merge of V1 and V2 that minimizes
7580   // cross-half traffic in the final shuffle.
7581
7582   // Munge the mask to be a single-input mask after the unpack merges the
7583   // results.
7584   for (int &M : Mask)
7585     if (M != -1)
7586       M = 2 * (M % 4) + (M / 8);
7587
7588   return DAG.getVectorShuffle(
7589       MVT::v8i16, DL, DAG.getNode(MergeFromLo ? X86ISD::UNPCKL : X86ISD::UNPCKH,
7590                                   DL, MVT::v8i16, V1, V2),
7591       DAG.getUNDEF(MVT::v8i16), Mask);
7592 }
7593
7594 /// \brief Generic lowering of 8-lane i16 shuffles.
7595 ///
7596 /// This handles both single-input shuffles and combined shuffle/blends with
7597 /// two inputs. The single input shuffles are immediately delegated to
7598 /// a dedicated lowering routine.
7599 ///
7600 /// The blends are lowered in one of three fundamental ways. If there are few
7601 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
7602 /// of the input is significantly cheaper when lowered as an interleaving of
7603 /// the two inputs, try to interleave them. Otherwise, blend the low and high
7604 /// halves of the inputs separately (making them have relatively few inputs)
7605 /// and then concatenate them.
7606 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7607                                        const X86Subtarget *Subtarget,
7608                                        SelectionDAG &DAG) {
7609   SDLoc DL(Op);
7610   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
7611   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7612   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
7613   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7614   ArrayRef<int> OrigMask = SVOp->getMask();
7615   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
7616                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
7617   MutableArrayRef<int> Mask(MaskStorage);
7618
7619   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
7620
7621   auto isV1 = [](int M) { return M >= 0 && M < 8; };
7622   auto isV2 = [](int M) { return M >= 8; };
7623
7624   int NumV1Inputs = std::count_if(Mask.begin(), Mask.end(), isV1);
7625   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
7626
7627   if (NumV2Inputs == 0)
7628     return lowerV8I16SingleInputVectorShuffle(DL, V1, Mask, Subtarget, DAG);
7629
7630   assert(NumV1Inputs > 0 && "All single-input shuffles should be canonicalized "
7631                             "to be V1-input shuffles.");
7632
7633   if (NumV1Inputs + NumV2Inputs <= 4)
7634     return lowerV8I16BasicBlendVectorShuffle(DL, V1, V2, Mask, Subtarget, DAG);
7635
7636   // Check whether an interleaving lowering is likely to be more efficient.
7637   // This isn't perfect but it is a strong heuristic that tends to work well on
7638   // the kinds of shuffles that show up in practice.
7639   //
7640   // FIXME: Handle 1x, 2x, and 4x interleaving.
7641   if (shouldLowerAsInterleaving(Mask)) {
7642     // FIXME: Figure out whether we should pack these into the low or high
7643     // halves.
7644
7645     int EMask[8], OMask[8];
7646     for (int i = 0; i < 4; ++i) {
7647       EMask[i] = Mask[2*i];
7648       OMask[i] = Mask[2*i + 1];
7649       EMask[i + 4] = -1;
7650       OMask[i + 4] = -1;
7651     }
7652
7653     SDValue Evens = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, EMask);
7654     SDValue Odds = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, OMask);
7655
7656     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, Evens, Odds);
7657   }
7658
7659   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7660   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7661
7662   for (int i = 0; i < 4; ++i) {
7663     LoBlendMask[i] = Mask[i];
7664     HiBlendMask[i] = Mask[i + 4];
7665   }
7666
7667   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, LoBlendMask);
7668   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1, V2, HiBlendMask);
7669   LoV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, LoV);
7670   HiV = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, HiV);
7671
7672   return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7673                      DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, LoV, HiV));
7674 }
7675
7676 /// \brief Generic lowering of v16i8 shuffles.
7677 ///
7678 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
7679 /// detect any complexity reducing interleaving. If that doesn't help, it uses
7680 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
7681 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
7682 /// back together.
7683 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7684                                        const X86Subtarget *Subtarget,
7685                                        SelectionDAG &DAG) {
7686   SDLoc DL(Op);
7687   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
7688   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7689   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
7690   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7691   ArrayRef<int> OrigMask = SVOp->getMask();
7692   assert(OrigMask.size() == 16 && "Unexpected mask size for v16 shuffle!");
7693   int MaskStorage[16] = {
7694       OrigMask[0],  OrigMask[1],  OrigMask[2],  OrigMask[3],
7695       OrigMask[4],  OrigMask[5],  OrigMask[6],  OrigMask[7],
7696       OrigMask[8],  OrigMask[9],  OrigMask[10], OrigMask[11],
7697       OrigMask[12], OrigMask[13], OrigMask[14], OrigMask[15]};
7698   MutableArrayRef<int> Mask(MaskStorage);
7699   MutableArrayRef<int> LoMask = Mask.slice(0, 8);
7700   MutableArrayRef<int> HiMask = Mask.slice(8, 8);
7701
7702   // For single-input shuffles, there are some nicer lowering tricks we can use.
7703   if (isSingleInputShuffleMask(Mask)) {
7704     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
7705     // Notably, this handles splat and partial-splat shuffles more efficiently.
7706     //
7707     // FIXME: We should check for other patterns which can be widened into an
7708     // i16 shuffle as well.
7709     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
7710       for (int i = 0; i < 16; i += 2) {
7711         if (Mask[i] != Mask[i + 1])
7712           return false;
7713       }
7714       return true;
7715     };
7716     if (canWidenViaDuplication(Mask)) {
7717       SmallVector<int, 4> LoInputs;
7718       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
7719                    [](int M) { return M >= 0 && M < 8; });
7720       std::sort(LoInputs.begin(), LoInputs.end());
7721       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
7722                      LoInputs.end());
7723       SmallVector<int, 4> HiInputs;
7724       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
7725                    [](int M) { return M >= 8; });
7726       std::sort(HiInputs.begin(), HiInputs.end());
7727       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
7728                      HiInputs.end());
7729
7730       bool TargetLo = LoInputs.size() >= HiInputs.size();
7731       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
7732       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
7733
7734       int ByteMask[16];
7735       SmallDenseMap<int, int, 8> LaneMap;
7736       for (int i = 0; i < 16; ++i)
7737         ByteMask[i] = -1;
7738       for (int I : InPlaceInputs) {
7739         ByteMask[I] = I;
7740         LaneMap[I] = I;
7741       }
7742       int FreeByteIdx = 0;
7743       int TargetOffset = TargetLo ? 0 : 8;
7744       for (int I : MovingInputs) {
7745         // Walk the free index into the byte mask until we find an unoccupied
7746         // spot. We bound this to 8 steps to catch bugs, the pigeonhole
7747         // principle indicates that there *must* be a spot as we can only have
7748         // 8 duplicated inputs. We have to walk the index using modular
7749         // arithmetic to wrap around as necessary.
7750         // FIXME: We could do a much better job of picking an inexpensive slot
7751         // so this doesn't go through the worst case for the byte shuffle.
7752         for (int j = 0; j < 8 && ByteMask[FreeByteIdx + TargetOffset] != -1;
7753              ++j, FreeByteIdx = (FreeByteIdx + 1) % 8)
7754           ;
7755         assert(ByteMask[FreeByteIdx + TargetOffset] == -1 &&
7756                "Failed to find a free byte!");
7757         ByteMask[FreeByteIdx + TargetOffset] = I;
7758         LaneMap[I] = FreeByteIdx + TargetOffset;
7759       }
7760       V1 = DAG.getVectorShuffle(MVT::v16i8, DL, V1, DAG.getUNDEF(MVT::v16i8),
7761                                 ByteMask);
7762       for (int &M : Mask)
7763         if (M != -1)
7764           M = LaneMap[M];
7765
7766       // Unpack the bytes to form the i16s that will be shuffled into place.
7767       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7768                        MVT::v16i8, V1, V1);
7769
7770       int I16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7771       for (int i = 0; i < 16; i += 2) {
7772         if (Mask[i] != -1)
7773           I16Shuffle[i / 2] = Mask[i] - (TargetLo ? 0 : 8);
7774         assert(I16Shuffle[i / 2] < 8 && "Invalid v8 shuffle mask!");
7775       }
7776       return DAG.getVectorShuffle(MVT::v8i16, DL,
7777                                   DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V1),
7778                                   DAG.getUNDEF(MVT::v8i16), I16Shuffle);
7779     }
7780   }
7781
7782   // Check whether an interleaving lowering is likely to be more efficient.
7783   // This isn't perfect but it is a strong heuristic that tends to work well on
7784   // the kinds of shuffles that show up in practice.
7785   //
7786   // FIXME: We need to handle other interleaving widths (i16, i32, ...).
7787   if (shouldLowerAsInterleaving(Mask)) {
7788     // FIXME: Figure out whether we should pack these into the low or high
7789     // halves.
7790
7791     int EMask[16], OMask[16];
7792     for (int i = 0; i < 8; ++i) {
7793       EMask[i] = Mask[2*i];
7794       OMask[i] = Mask[2*i + 1];
7795       EMask[i + 8] = -1;
7796       OMask[i + 8] = -1;
7797     }
7798
7799     SDValue Evens = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, EMask);
7800     SDValue Odds = DAG.getVectorShuffle(MVT::v16i8, DL, V1, V2, OMask);
7801
7802     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, Evens, Odds);
7803   }
7804   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
7805   SDValue LoV1 =
7806       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7807                   DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, Zero));
7808   SDValue HiV1 =
7809       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7810                   DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, Zero));
7811   SDValue LoV2 =
7812       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7813                   DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V2, Zero));
7814   SDValue HiV2 =
7815       DAG.getNode(ISD::BITCAST, DL, MVT::v8i16,
7816                   DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V2, Zero));
7817
7818   int V1LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7819   int V1HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7820   int V2LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7821   int V2HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
7822
7823   auto buildBlendMasks = [](MutableArrayRef<int> HalfMask,
7824                             MutableArrayRef<int> V1HalfBlendMask,
7825                             MutableArrayRef<int> V2HalfBlendMask) {
7826     for (int i = 0; i < 8; ++i)
7827       if (HalfMask[i] >= 0 && HalfMask[i] < 16) {
7828         V1HalfBlendMask[i] = HalfMask[i];
7829         HalfMask[i] = i;
7830       } else if (HalfMask[i] >= 16) {
7831         V2HalfBlendMask[i] = HalfMask[i] - 16;
7832         HalfMask[i] = i + 8;
7833       }
7834   };
7835   buildBlendMasks(LoMask, V1LoBlendMask, V2LoBlendMask);
7836   buildBlendMasks(HiMask, V1HiBlendMask, V2HiBlendMask);
7837
7838   SDValue V1Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1LoBlendMask);
7839   SDValue V2Lo = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2LoBlendMask);
7840   SDValue V1Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV1, HiV1, V1HiBlendMask);
7841   SDValue V2Hi = DAG.getVectorShuffle(MVT::v8i16, DL, LoV2, HiV2, V2HiBlendMask);
7842
7843   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Lo, V2Lo, LoMask);
7844   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, V1Hi, V2Hi, HiMask);
7845
7846   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
7847 }
7848
7849 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
7850 ///
7851 /// This routine breaks down the specific type of 128-bit shuffle and
7852 /// dispatches to the lowering routines accordingly.
7853 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7854                                         MVT VT, const X86Subtarget *Subtarget,
7855                                         SelectionDAG &DAG) {
7856   switch (VT.SimpleTy) {
7857   case MVT::v2i64:
7858     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7859   case MVT::v2f64:
7860     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
7861   case MVT::v4i32:
7862     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7863   case MVT::v4f32:
7864     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
7865   case MVT::v8i16:
7866     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
7867   case MVT::v16i8:
7868     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
7869
7870   default:
7871     llvm_unreachable("Unimplemented!");
7872   }
7873 }
7874
7875 /// \brief Tiny helper function to test whether adjacent masks are sequential.
7876 static bool areAdjacentMasksSequential(ArrayRef<int> Mask) {
7877   for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7878     if (Mask[i] + 1 != Mask[i+1])
7879       return false;
7880
7881   return true;
7882 }
7883
7884 /// \brief Top-level lowering for x86 vector shuffles.
7885 ///
7886 /// This handles decomposition, canonicalization, and lowering of all x86
7887 /// vector shuffles. Most of the specific lowering strategies are encapsulated
7888 /// above in helper routines. The canonicalization attempts to widen shuffles
7889 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
7890 /// s.t. only one of the two inputs needs to be tested, etc.
7891 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7892                                   SelectionDAG &DAG) {
7893   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7894   ArrayRef<int> Mask = SVOp->getMask();
7895   SDValue V1 = Op.getOperand(0);
7896   SDValue V2 = Op.getOperand(1);
7897   MVT VT = Op.getSimpleValueType();
7898   int NumElements = VT.getVectorNumElements();
7899   SDLoc dl(Op);
7900
7901   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7902
7903   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7904   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7905   if (V1IsUndef && V2IsUndef)
7906     return DAG.getUNDEF(VT);
7907
7908   // When we create a shuffle node we put the UNDEF node to second operand,
7909   // but in some cases the first operand may be transformed to UNDEF.
7910   // In this case we should just commute the node.
7911   if (V1IsUndef)
7912     return CommuteVectorShuffle(SVOp, DAG);
7913
7914   // Check for non-undef masks pointing at an undef vector and make the masks
7915   // undef as well. This makes it easier to match the shuffle based solely on
7916   // the mask.
7917   if (V2IsUndef)
7918     for (int M : Mask)
7919       if (M >= NumElements) {
7920         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
7921         for (int &M : NewMask)
7922           if (M >= NumElements)
7923             M = -1;
7924         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
7925       }
7926
7927   // Check for a shuffle of a splat, and return just the splat. While DAG
7928   // combining will do a similar transformation, this shows up with the
7929   // internally created shuffles and so we handle it specially here as we won't
7930   // have another chance to DAG-combine the generic shuffle instructions.
7931   if (V2IsUndef) {
7932     SDValue V = V1;
7933
7934     // Look through any bitcasts. These can't change the size, just the number
7935     // of elements which we check later.
7936     while (V.getOpcode() == ISD::BITCAST)
7937       V = V->getOperand(0);
7938
7939     // A splat should always show up as a build vector node.
7940     if (V.getOpcode() == ISD::BUILD_VECTOR) {
7941       SDValue Base;
7942       bool AllSame = true;
7943       for (unsigned i = 0; i != V->getNumOperands(); ++i)
7944         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
7945           Base = V->getOperand(i);
7946           break;
7947         }
7948       // Splat of <u, u, ..., u>, return <u, u, ..., u>
7949       if (!Base)
7950         return V1;
7951       for (unsigned i = 0; i != V->getNumOperands(); ++i)
7952         if (V->getOperand(i) != Base) {
7953           AllSame = false;
7954           break;
7955         }
7956       // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
7957       // number of elements match or the value splatted is a zero constant.
7958       if (AllSame) {
7959         if (V.getValueType().getVectorNumElements() == (unsigned)NumElements)
7960           return V1;
7961         if (auto *C = dyn_cast<ConstantSDNode>(Base))
7962           if (C->isNullValue())
7963             return V1;
7964       }
7965     }
7966   }
7967
7968   // For integer vector shuffles, try to collapse them into a shuffle of fewer
7969   // lanes but wider integers. We cap this to not form integers larger than i64
7970   // but it might be interesting to form i128 integers to handle flipping the
7971   // low and high halves of AVX 256-bit vectors.
7972   if (VT.isInteger() && VT.getScalarSizeInBits() < 64 &&
7973       areAdjacentMasksSequential(Mask)) {
7974     SmallVector<int, 8> NewMask;
7975     for (int i = 0, Size = Mask.size(); i < Size; i += 2)
7976       NewMask.push_back(Mask[i] / 2);
7977     MVT NewVT =
7978         MVT::getVectorVT(MVT::getIntegerVT(VT.getScalarSizeInBits() * 2),
7979                          VT.getVectorNumElements() / 2);
7980     V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, V1);
7981     V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, V2);
7982     return DAG.getNode(ISD::BITCAST, dl, VT,
7983                        DAG.getVectorShuffle(NewVT, dl, V1, V2, NewMask));
7984   }
7985
7986   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
7987   for (int M : SVOp->getMask())
7988     if (M < 0)
7989       ++NumUndefElements;
7990     else if (M < NumElements)
7991       ++NumV1Elements;
7992     else
7993       ++NumV2Elements;
7994
7995   // Commute the shuffle as needed such that more elements come from V1 than
7996   // V2. This allows us to match the shuffle pattern strictly on how many
7997   // elements come from V1 without handling the symmetric cases.
7998   if (NumV2Elements > NumV1Elements)
7999     return CommuteVectorShuffle(SVOp, DAG);
8000
8001   // When the number of V1 and V2 elements are the same, try to minimize the
8002   // number of uses of V2 in the low half of the vector.
8003   if (NumV1Elements == NumV2Elements) {
8004     int LowV1Elements = 0, LowV2Elements = 0;
8005     for (int M : SVOp->getMask().slice(0, NumElements / 2))
8006       if (M >= NumElements)
8007         ++LowV2Elements;
8008       else if (M >= 0)
8009         ++LowV1Elements;
8010     if (LowV2Elements > LowV1Elements)
8011       return CommuteVectorShuffle(SVOp, DAG);
8012   }
8013
8014   // For each vector width, delegate to a specialized lowering routine.
8015   if (VT.getSizeInBits() == 128)
8016     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
8017
8018   llvm_unreachable("Unimplemented!");
8019 }
8020
8021
8022 //===----------------------------------------------------------------------===//
8023 // Legacy vector shuffle lowering
8024 //
8025 // This code is the legacy code handling vector shuffles until the above
8026 // replaces its functionality and performance.
8027 //===----------------------------------------------------------------------===//
8028
8029 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
8030                         bool hasInt256, unsigned *MaskOut = nullptr) {
8031   MVT EltVT = VT.getVectorElementType();
8032
8033   // There is no blend with immediate in AVX-512.
8034   if (VT.is512BitVector())
8035     return false;
8036
8037   if (!hasSSE41 || EltVT == MVT::i8)
8038     return false;
8039   if (!hasInt256 && VT == MVT::v16i16)
8040     return false;
8041
8042   unsigned MaskValue = 0;
8043   unsigned NumElems = VT.getVectorNumElements();
8044   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8045   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8046   unsigned NumElemsInLane = NumElems / NumLanes;
8047
8048   // Blend for v16i16 should be symetric for the both lanes.
8049   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8050
8051     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
8052     int EltIdx = MaskVals[i];
8053
8054     if ((EltIdx < 0 || EltIdx == (int)i) &&
8055         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
8056       continue;
8057
8058     if (((unsigned)EltIdx == (i + NumElems)) &&
8059         (SndLaneEltIdx < 0 ||
8060          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
8061       MaskValue |= (1 << i);
8062     else
8063       return false;
8064   }
8065
8066   if (MaskOut)
8067     *MaskOut = MaskValue;
8068   return true;
8069 }
8070
8071 // Try to lower a shuffle node into a simple blend instruction.
8072 // This function assumes isBlendMask returns true for this
8073 // SuffleVectorSDNode
8074 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
8075                                           unsigned MaskValue,
8076                                           const X86Subtarget *Subtarget,
8077                                           SelectionDAG &DAG) {
8078   MVT VT = SVOp->getSimpleValueType(0);
8079   MVT EltVT = VT.getVectorElementType();
8080   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
8081                      Subtarget->hasInt256() && "Trying to lower a "
8082                                                "VECTOR_SHUFFLE to a Blend but "
8083                                                "with the wrong mask"));
8084   SDValue V1 = SVOp->getOperand(0);
8085   SDValue V2 = SVOp->getOperand(1);
8086   SDLoc dl(SVOp);
8087   unsigned NumElems = VT.getVectorNumElements();
8088
8089   // Convert i32 vectors to floating point if it is not AVX2.
8090   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8091   MVT BlendVT = VT;
8092   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8093     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8094                                NumElems);
8095     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
8096     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
8097   }
8098
8099   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
8100                             DAG.getConstant(MaskValue, MVT::i32));
8101   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8102 }
8103
8104 /// In vector type \p VT, return true if the element at index \p InputIdx
8105 /// falls on a different 128-bit lane than \p OutputIdx.
8106 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
8107                                      unsigned OutputIdx) {
8108   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
8109   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
8110 }
8111
8112 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
8113 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
8114 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
8115 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
8116 /// zero.
8117 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
8118                          SelectionDAG &DAG) {
8119   MVT VT = V1.getSimpleValueType();
8120   assert(VT.is128BitVector() || VT.is256BitVector());
8121
8122   MVT EltVT = VT.getVectorElementType();
8123   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
8124   unsigned NumElts = VT.getVectorNumElements();
8125
8126   SmallVector<SDValue, 32> PshufbMask;
8127   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
8128     int InputIdx = MaskVals[OutputIdx];
8129     unsigned InputByteIdx;
8130
8131     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
8132       InputByteIdx = 0x80;
8133     else {
8134       // Cross lane is not allowed.
8135       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
8136         return SDValue();
8137       InputByteIdx = InputIdx * EltSizeInBytes;
8138       // Index is an byte offset within the 128-bit lane.
8139       InputByteIdx &= 0xf;
8140     }
8141
8142     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
8143       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
8144       if (InputByteIdx != 0x80)
8145         ++InputByteIdx;
8146     }
8147   }
8148
8149   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
8150   if (ShufVT != VT)
8151     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
8152   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
8153                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
8154 }
8155
8156 // v8i16 shuffles - Prefer shuffles in the following order:
8157 // 1. [all]   pshuflw, pshufhw, optional move
8158 // 2. [ssse3] 1 x pshufb
8159 // 3. [ssse3] 2 x pshufb + 1 x por
8160 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
8161 static SDValue
8162 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
8163                          SelectionDAG &DAG) {
8164   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8165   SDValue V1 = SVOp->getOperand(0);
8166   SDValue V2 = SVOp->getOperand(1);
8167   SDLoc dl(SVOp);
8168   SmallVector<int, 8> MaskVals;
8169
8170   // Determine if more than 1 of the words in each of the low and high quadwords
8171   // of the result come from the same quadword of one of the two inputs.  Undef
8172   // mask values count as coming from any quadword, for better codegen.
8173   //
8174   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
8175   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
8176   unsigned LoQuad[] = { 0, 0, 0, 0 };
8177   unsigned HiQuad[] = { 0, 0, 0, 0 };
8178   // Indices of quads used.
8179   std::bitset<4> InputQuads;
8180   for (unsigned i = 0; i < 8; ++i) {
8181     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
8182     int EltIdx = SVOp->getMaskElt(i);
8183     MaskVals.push_back(EltIdx);
8184     if (EltIdx < 0) {
8185       ++Quad[0];
8186       ++Quad[1];
8187       ++Quad[2];
8188       ++Quad[3];
8189       continue;
8190     }
8191     ++Quad[EltIdx / 4];
8192     InputQuads.set(EltIdx / 4);
8193   }
8194
8195   int BestLoQuad = -1;
8196   unsigned MaxQuad = 1;
8197   for (unsigned i = 0; i < 4; ++i) {
8198     if (LoQuad[i] > MaxQuad) {
8199       BestLoQuad = i;
8200       MaxQuad = LoQuad[i];
8201     }
8202   }
8203
8204   int BestHiQuad = -1;
8205   MaxQuad = 1;
8206   for (unsigned i = 0; i < 4; ++i) {
8207     if (HiQuad[i] > MaxQuad) {
8208       BestHiQuad = i;
8209       MaxQuad = HiQuad[i];
8210     }
8211   }
8212
8213   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
8214   // of the two input vectors, shuffle them into one input vector so only a
8215   // single pshufb instruction is necessary. If there are more than 2 input
8216   // quads, disable the next transformation since it does not help SSSE3.
8217   bool V1Used = InputQuads[0] || InputQuads[1];
8218   bool V2Used = InputQuads[2] || InputQuads[3];
8219   if (Subtarget->hasSSSE3()) {
8220     if (InputQuads.count() == 2 && V1Used && V2Used) {
8221       BestLoQuad = InputQuads[0] ? 0 : 1;
8222       BestHiQuad = InputQuads[2] ? 2 : 3;
8223     }
8224     if (InputQuads.count() > 2) {
8225       BestLoQuad = -1;
8226       BestHiQuad = -1;
8227     }
8228   }
8229
8230   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
8231   // the shuffle mask.  If a quad is scored as -1, that means that it contains
8232   // words from all 4 input quadwords.
8233   SDValue NewV;
8234   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
8235     int MaskV[] = {
8236       BestLoQuad < 0 ? 0 : BestLoQuad,
8237       BestHiQuad < 0 ? 1 : BestHiQuad
8238     };
8239     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
8240                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
8241                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
8242     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
8243
8244     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
8245     // source words for the shuffle, to aid later transformations.
8246     bool AllWordsInNewV = true;
8247     bool InOrder[2] = { true, true };
8248     for (unsigned i = 0; i != 8; ++i) {
8249       int idx = MaskVals[i];
8250       if (idx != (int)i)
8251         InOrder[i/4] = false;
8252       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
8253         continue;
8254       AllWordsInNewV = false;
8255       break;
8256     }
8257
8258     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
8259     if (AllWordsInNewV) {
8260       for (int i = 0; i != 8; ++i) {
8261         int idx = MaskVals[i];
8262         if (idx < 0)
8263           continue;
8264         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
8265         if ((idx != i) && idx < 4)
8266           pshufhw = false;
8267         if ((idx != i) && idx > 3)
8268           pshuflw = false;
8269       }
8270       V1 = NewV;
8271       V2Used = false;
8272       BestLoQuad = 0;
8273       BestHiQuad = 1;
8274     }
8275
8276     // If we've eliminated the use of V2, and the new mask is a pshuflw or
8277     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
8278     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
8279       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
8280       unsigned TargetMask = 0;
8281       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
8282                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
8283       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8284       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
8285                              getShufflePSHUFLWImmediate(SVOp);
8286       V1 = NewV.getOperand(0);
8287       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
8288     }
8289   }
8290
8291   // Promote splats to a larger type which usually leads to more efficient code.
8292   // FIXME: Is this true if pshufb is available?
8293   if (SVOp->isSplat())
8294     return PromoteSplat(SVOp, DAG);
8295
8296   // If we have SSSE3, and all words of the result are from 1 input vector,
8297   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
8298   // is present, fall back to case 4.
8299   if (Subtarget->hasSSSE3()) {
8300     SmallVector<SDValue,16> pshufbMask;
8301
8302     // If we have elements from both input vectors, set the high bit of the
8303     // shuffle mask element to zero out elements that come from V2 in the V1
8304     // mask, and elements that come from V1 in the V2 mask, so that the two
8305     // results can be OR'd together.
8306     bool TwoInputs = V1Used && V2Used;
8307     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
8308     if (!TwoInputs)
8309       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8310
8311     // Calculate the shuffle mask for the second input, shuffle it, and
8312     // OR it with the first shuffled input.
8313     CommuteVectorShuffleMask(MaskVals, 8);
8314     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
8315     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8316     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8317   }
8318
8319   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
8320   // and update MaskVals with new element order.
8321   std::bitset<8> InOrder;
8322   if (BestLoQuad >= 0) {
8323     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
8324     for (int i = 0; i != 4; ++i) {
8325       int idx = MaskVals[i];
8326       if (idx < 0) {
8327         InOrder.set(i);
8328       } else if ((idx / 4) == BestLoQuad) {
8329         MaskV[i] = idx & 3;
8330         InOrder.set(i);
8331       }
8332     }
8333     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8334                                 &MaskV[0]);
8335
8336     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8337       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8338       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
8339                                   NewV.getOperand(0),
8340                                   getShufflePSHUFLWImmediate(SVOp), DAG);
8341     }
8342   }
8343
8344   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
8345   // and update MaskVals with the new element order.
8346   if (BestHiQuad >= 0) {
8347     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
8348     for (unsigned i = 4; i != 8; ++i) {
8349       int idx = MaskVals[i];
8350       if (idx < 0) {
8351         InOrder.set(i);
8352       } else if ((idx / 4) == BestHiQuad) {
8353         MaskV[i] = (idx & 3) + 4;
8354         InOrder.set(i);
8355       }
8356     }
8357     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
8358                                 &MaskV[0]);
8359
8360     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
8361       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
8362       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
8363                                   NewV.getOperand(0),
8364                                   getShufflePSHUFHWImmediate(SVOp), DAG);
8365     }
8366   }
8367
8368   // In case BestHi & BestLo were both -1, which means each quadword has a word
8369   // from each of the four input quadwords, calculate the InOrder bitvector now
8370   // before falling through to the insert/extract cleanup.
8371   if (BestLoQuad == -1 && BestHiQuad == -1) {
8372     NewV = V1;
8373     for (int i = 0; i != 8; ++i)
8374       if (MaskVals[i] < 0 || MaskVals[i] == i)
8375         InOrder.set(i);
8376   }
8377
8378   // The other elements are put in the right place using pextrw and pinsrw.
8379   for (unsigned i = 0; i != 8; ++i) {
8380     if (InOrder[i])
8381       continue;
8382     int EltIdx = MaskVals[i];
8383     if (EltIdx < 0)
8384       continue;
8385     SDValue ExtOp = (EltIdx < 8) ?
8386       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
8387                   DAG.getIntPtrConstant(EltIdx)) :
8388       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
8389                   DAG.getIntPtrConstant(EltIdx - 8));
8390     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
8391                        DAG.getIntPtrConstant(i));
8392   }
8393   return NewV;
8394 }
8395
8396 /// \brief v16i16 shuffles
8397 ///
8398 /// FIXME: We only support generation of a single pshufb currently.  We can
8399 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
8400 /// well (e.g 2 x pshufb + 1 x por).
8401 static SDValue
8402 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
8403   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8404   SDValue V1 = SVOp->getOperand(0);
8405   SDValue V2 = SVOp->getOperand(1);
8406   SDLoc dl(SVOp);
8407
8408   if (V2.getOpcode() != ISD::UNDEF)
8409     return SDValue();
8410
8411   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8412   return getPSHUFB(MaskVals, V1, dl, DAG);
8413 }
8414
8415 // v16i8 shuffles - Prefer shuffles in the following order:
8416 // 1. [ssse3] 1 x pshufb
8417 // 2. [ssse3] 2 x pshufb + 1 x por
8418 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
8419 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
8420                                         const X86Subtarget* Subtarget,
8421                                         SelectionDAG &DAG) {
8422   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
8423   SDValue V1 = SVOp->getOperand(0);
8424   SDValue V2 = SVOp->getOperand(1);
8425   SDLoc dl(SVOp);
8426   ArrayRef<int> MaskVals = SVOp->getMask();
8427
8428   // Promote splats to a larger type which usually leads to more efficient code.
8429   // FIXME: Is this true if pshufb is available?
8430   if (SVOp->isSplat())
8431     return PromoteSplat(SVOp, DAG);
8432
8433   // If we have SSSE3, case 1 is generated when all result bytes come from
8434   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
8435   // present, fall back to case 3.
8436
8437   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
8438   if (Subtarget->hasSSSE3()) {
8439     SmallVector<SDValue,16> pshufbMask;
8440
8441     // If all result elements are from one input vector, then only translate
8442     // undef mask values to 0x80 (zero out result) in the pshufb mask.
8443     //
8444     // Otherwise, we have elements from both input vectors, and must zero out
8445     // elements that come from V2 in the first mask, and V1 in the second mask
8446     // so that we can OR them together.
8447     for (unsigned i = 0; i != 16; ++i) {
8448       int EltIdx = MaskVals[i];
8449       if (EltIdx < 0 || EltIdx >= 16)
8450         EltIdx = 0x80;
8451       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8452     }
8453     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
8454                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8455                                  MVT::v16i8, pshufbMask));
8456
8457     // As PSHUFB will zero elements with negative indices, it's safe to ignore
8458     // the 2nd operand if it's undefined or zero.
8459     if (V2.getOpcode() == ISD::UNDEF ||
8460         ISD::isBuildVectorAllZeros(V2.getNode()))
8461       return V1;
8462
8463     // Calculate the shuffle mask for the second input, shuffle it, and
8464     // OR it with the first shuffled input.
8465     pshufbMask.clear();
8466     for (unsigned i = 0; i != 16; ++i) {
8467       int EltIdx = MaskVals[i];
8468       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
8469       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
8470     }
8471     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
8472                      DAG.getNode(ISD::BUILD_VECTOR, dl,
8473                                  MVT::v16i8, pshufbMask));
8474     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
8475   }
8476
8477   // No SSSE3 - Calculate in place words and then fix all out of place words
8478   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
8479   // the 16 different words that comprise the two doublequadword input vectors.
8480   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
8481   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
8482   SDValue NewV = V1;
8483   for (int i = 0; i != 8; ++i) {
8484     int Elt0 = MaskVals[i*2];
8485     int Elt1 = MaskVals[i*2+1];
8486
8487     // This word of the result is all undef, skip it.
8488     if (Elt0 < 0 && Elt1 < 0)
8489       continue;
8490
8491     // This word of the result is already in the correct place, skip it.
8492     if ((Elt0 == i*2) && (Elt1 == i*2+1))
8493       continue;
8494
8495     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
8496     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
8497     SDValue InsElt;
8498
8499     // If Elt0 and Elt1 are defined, are consecutive, and can be load
8500     // using a single extract together, load it and store it.
8501     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
8502       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8503                            DAG.getIntPtrConstant(Elt1 / 2));
8504       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8505                         DAG.getIntPtrConstant(i));
8506       continue;
8507     }
8508
8509     // If Elt1 is defined, extract it from the appropriate source.  If the
8510     // source byte is not also odd, shift the extracted word left 8 bits
8511     // otherwise clear the bottom 8 bits if we need to do an or.
8512     if (Elt1 >= 0) {
8513       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
8514                            DAG.getIntPtrConstant(Elt1 / 2));
8515       if ((Elt1 & 1) == 0)
8516         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
8517                              DAG.getConstant(8,
8518                                   TLI.getShiftAmountTy(InsElt.getValueType())));
8519       else if (Elt0 >= 0)
8520         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
8521                              DAG.getConstant(0xFF00, MVT::i16));
8522     }
8523     // If Elt0 is defined, extract it from the appropriate source.  If the
8524     // source byte is not also even, shift the extracted word right 8 bits. If
8525     // Elt1 was also defined, OR the extracted values together before
8526     // inserting them in the result.
8527     if (Elt0 >= 0) {
8528       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
8529                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
8530       if ((Elt0 & 1) != 0)
8531         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
8532                               DAG.getConstant(8,
8533                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
8534       else if (Elt1 >= 0)
8535         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
8536                              DAG.getConstant(0x00FF, MVT::i16));
8537       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
8538                          : InsElt0;
8539     }
8540     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
8541                        DAG.getIntPtrConstant(i));
8542   }
8543   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
8544 }
8545
8546 // v32i8 shuffles - Translate to VPSHUFB if possible.
8547 static
8548 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
8549                                  const X86Subtarget *Subtarget,
8550                                  SelectionDAG &DAG) {
8551   MVT VT = SVOp->getSimpleValueType(0);
8552   SDValue V1 = SVOp->getOperand(0);
8553   SDValue V2 = SVOp->getOperand(1);
8554   SDLoc dl(SVOp);
8555   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
8556
8557   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8558   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
8559   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
8560
8561   // VPSHUFB may be generated if
8562   // (1) one of input vector is undefined or zeroinitializer.
8563   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
8564   // And (2) the mask indexes don't cross the 128-bit lane.
8565   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
8566       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
8567     return SDValue();
8568
8569   if (V1IsAllZero && !V2IsAllZero) {
8570     CommuteVectorShuffleMask(MaskVals, 32);
8571     V1 = V2;
8572   }
8573   return getPSHUFB(MaskVals, V1, dl, DAG);
8574 }
8575
8576 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
8577 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
8578 /// done when every pair / quad of shuffle mask elements point to elements in
8579 /// the right sequence. e.g.
8580 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
8581 static
8582 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
8583                                  SelectionDAG &DAG) {
8584   MVT VT = SVOp->getSimpleValueType(0);
8585   SDLoc dl(SVOp);
8586   unsigned NumElems = VT.getVectorNumElements();
8587   MVT NewVT;
8588   unsigned Scale;
8589   switch (VT.SimpleTy) {
8590   default: llvm_unreachable("Unexpected!");
8591   case MVT::v2i64:
8592   case MVT::v2f64:
8593            return SDValue(SVOp, 0);
8594   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
8595   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
8596   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
8597   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
8598   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
8599   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
8600   }
8601
8602   SmallVector<int, 8> MaskVec;
8603   for (unsigned i = 0; i != NumElems; i += Scale) {
8604     int StartIdx = -1;
8605     for (unsigned j = 0; j != Scale; ++j) {
8606       int EltIdx = SVOp->getMaskElt(i+j);
8607       if (EltIdx < 0)
8608         continue;
8609       if (StartIdx < 0)
8610         StartIdx = (EltIdx / Scale);
8611       if (EltIdx != (int)(StartIdx*Scale + j))
8612         return SDValue();
8613     }
8614     MaskVec.push_back(StartIdx);
8615   }
8616
8617   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
8618   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
8619   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
8620 }
8621
8622 /// getVZextMovL - Return a zero-extending vector move low node.
8623 ///
8624 static SDValue getVZextMovL(MVT VT, MVT OpVT,
8625                             SDValue SrcOp, SelectionDAG &DAG,
8626                             const X86Subtarget *Subtarget, SDLoc dl) {
8627   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
8628     LoadSDNode *LD = nullptr;
8629     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
8630       LD = dyn_cast<LoadSDNode>(SrcOp);
8631     if (!LD) {
8632       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
8633       // instead.
8634       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
8635       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
8636           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8637           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
8638           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
8639         // PR2108
8640         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
8641         return DAG.getNode(ISD::BITCAST, dl, VT,
8642                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8643                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
8644                                                    OpVT,
8645                                                    SrcOp.getOperand(0)
8646                                                           .getOperand(0))));
8647       }
8648     }
8649   }
8650
8651   return DAG.getNode(ISD::BITCAST, dl, VT,
8652                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
8653                                  DAG.getNode(ISD::BITCAST, dl,
8654                                              OpVT, SrcOp)));
8655 }
8656
8657 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
8658 /// which could not be matched by any known target speficic shuffle
8659 static SDValue
8660 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8661
8662   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
8663   if (NewOp.getNode())
8664     return NewOp;
8665
8666   MVT VT = SVOp->getSimpleValueType(0);
8667
8668   unsigned NumElems = VT.getVectorNumElements();
8669   unsigned NumLaneElems = NumElems / 2;
8670
8671   SDLoc dl(SVOp);
8672   MVT EltVT = VT.getVectorElementType();
8673   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
8674   SDValue Output[2];
8675
8676   SmallVector<int, 16> Mask;
8677   for (unsigned l = 0; l < 2; ++l) {
8678     // Build a shuffle mask for the output, discovering on the fly which
8679     // input vectors to use as shuffle operands (recorded in InputUsed).
8680     // If building a suitable shuffle vector proves too hard, then bail
8681     // out with UseBuildVector set.
8682     bool UseBuildVector = false;
8683     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
8684     unsigned LaneStart = l * NumLaneElems;
8685     for (unsigned i = 0; i != NumLaneElems; ++i) {
8686       // The mask element.  This indexes into the input.
8687       int Idx = SVOp->getMaskElt(i+LaneStart);
8688       if (Idx < 0) {
8689         // the mask element does not index into any input vector.
8690         Mask.push_back(-1);
8691         continue;
8692       }
8693
8694       // The input vector this mask element indexes into.
8695       int Input = Idx / NumLaneElems;
8696
8697       // Turn the index into an offset from the start of the input vector.
8698       Idx -= Input * NumLaneElems;
8699
8700       // Find or create a shuffle vector operand to hold this input.
8701       unsigned OpNo;
8702       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
8703         if (InputUsed[OpNo] == Input)
8704           // This input vector is already an operand.
8705           break;
8706         if (InputUsed[OpNo] < 0) {
8707           // Create a new operand for this input vector.
8708           InputUsed[OpNo] = Input;
8709           break;
8710         }
8711       }
8712
8713       if (OpNo >= array_lengthof(InputUsed)) {
8714         // More than two input vectors used!  Give up on trying to create a
8715         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
8716         UseBuildVector = true;
8717         break;
8718       }
8719
8720       // Add the mask index for the new shuffle vector.
8721       Mask.push_back(Idx + OpNo * NumLaneElems);
8722     }
8723
8724     if (UseBuildVector) {
8725       SmallVector<SDValue, 16> SVOps;
8726       for (unsigned i = 0; i != NumLaneElems; ++i) {
8727         // The mask element.  This indexes into the input.
8728         int Idx = SVOp->getMaskElt(i+LaneStart);
8729         if (Idx < 0) {
8730           SVOps.push_back(DAG.getUNDEF(EltVT));
8731           continue;
8732         }
8733
8734         // The input vector this mask element indexes into.
8735         int Input = Idx / NumElems;
8736
8737         // Turn the index into an offset from the start of the input vector.
8738         Idx -= Input * NumElems;
8739
8740         // Extract the vector element by hand.
8741         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
8742                                     SVOp->getOperand(Input),
8743                                     DAG.getIntPtrConstant(Idx)));
8744       }
8745
8746       // Construct the output using a BUILD_VECTOR.
8747       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
8748     } else if (InputUsed[0] < 0) {
8749       // No input vectors were used! The result is undefined.
8750       Output[l] = DAG.getUNDEF(NVT);
8751     } else {
8752       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
8753                                         (InputUsed[0] % 2) * NumLaneElems,
8754                                         DAG, dl);
8755       // If only one input was used, use an undefined vector for the other.
8756       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
8757         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
8758                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
8759       // At least one input vector was used. Create a new shuffle vector.
8760       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
8761     }
8762
8763     Mask.clear();
8764   }
8765
8766   // Concatenate the result back
8767   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
8768 }
8769
8770 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
8771 /// 4 elements, and match them with several different shuffle types.
8772 static SDValue
8773 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
8774   SDValue V1 = SVOp->getOperand(0);
8775   SDValue V2 = SVOp->getOperand(1);
8776   SDLoc dl(SVOp);
8777   MVT VT = SVOp->getSimpleValueType(0);
8778
8779   assert(VT.is128BitVector() && "Unsupported vector size");
8780
8781   std::pair<int, int> Locs[4];
8782   int Mask1[] = { -1, -1, -1, -1 };
8783   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
8784
8785   unsigned NumHi = 0;
8786   unsigned NumLo = 0;
8787   for (unsigned i = 0; i != 4; ++i) {
8788     int Idx = PermMask[i];
8789     if (Idx < 0) {
8790       Locs[i] = std::make_pair(-1, -1);
8791     } else {
8792       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
8793       if (Idx < 4) {
8794         Locs[i] = std::make_pair(0, NumLo);
8795         Mask1[NumLo] = Idx;
8796         NumLo++;
8797       } else {
8798         Locs[i] = std::make_pair(1, NumHi);
8799         if (2+NumHi < 4)
8800           Mask1[2+NumHi] = Idx;
8801         NumHi++;
8802       }
8803     }
8804   }
8805
8806   if (NumLo <= 2 && NumHi <= 2) {
8807     // If no more than two elements come from either vector. This can be
8808     // implemented with two shuffles. First shuffle gather the elements.
8809     // The second shuffle, which takes the first shuffle as both of its
8810     // vector operands, put the elements into the right order.
8811     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8812
8813     int Mask2[] = { -1, -1, -1, -1 };
8814
8815     for (unsigned i = 0; i != 4; ++i)
8816       if (Locs[i].first != -1) {
8817         unsigned Idx = (i < 2) ? 0 : 4;
8818         Idx += Locs[i].first * 2 + Locs[i].second;
8819         Mask2[i] = Idx;
8820       }
8821
8822     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
8823   }
8824
8825   if (NumLo == 3 || NumHi == 3) {
8826     // Otherwise, we must have three elements from one vector, call it X, and
8827     // one element from the other, call it Y.  First, use a shufps to build an
8828     // intermediate vector with the one element from Y and the element from X
8829     // that will be in the same half in the final destination (the indexes don't
8830     // matter). Then, use a shufps to build the final vector, taking the half
8831     // containing the element from Y from the intermediate, and the other half
8832     // from X.
8833     if (NumHi == 3) {
8834       // Normalize it so the 3 elements come from V1.
8835       CommuteVectorShuffleMask(PermMask, 4);
8836       std::swap(V1, V2);
8837     }
8838
8839     // Find the element from V2.
8840     unsigned HiIndex;
8841     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
8842       int Val = PermMask[HiIndex];
8843       if (Val < 0)
8844         continue;
8845       if (Val >= 4)
8846         break;
8847     }
8848
8849     Mask1[0] = PermMask[HiIndex];
8850     Mask1[1] = -1;
8851     Mask1[2] = PermMask[HiIndex^1];
8852     Mask1[3] = -1;
8853     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8854
8855     if (HiIndex >= 2) {
8856       Mask1[0] = PermMask[0];
8857       Mask1[1] = PermMask[1];
8858       Mask1[2] = HiIndex & 1 ? 6 : 4;
8859       Mask1[3] = HiIndex & 1 ? 4 : 6;
8860       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
8861     }
8862
8863     Mask1[0] = HiIndex & 1 ? 2 : 0;
8864     Mask1[1] = HiIndex & 1 ? 0 : 2;
8865     Mask1[2] = PermMask[2];
8866     Mask1[3] = PermMask[3];
8867     if (Mask1[2] >= 0)
8868       Mask1[2] += 4;
8869     if (Mask1[3] >= 0)
8870       Mask1[3] += 4;
8871     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
8872   }
8873
8874   // Break it into (shuffle shuffle_hi, shuffle_lo).
8875   int LoMask[] = { -1, -1, -1, -1 };
8876   int HiMask[] = { -1, -1, -1, -1 };
8877
8878   int *MaskPtr = LoMask;
8879   unsigned MaskIdx = 0;
8880   unsigned LoIdx = 0;
8881   unsigned HiIdx = 2;
8882   for (unsigned i = 0; i != 4; ++i) {
8883     if (i == 2) {
8884       MaskPtr = HiMask;
8885       MaskIdx = 1;
8886       LoIdx = 0;
8887       HiIdx = 2;
8888     }
8889     int Idx = PermMask[i];
8890     if (Idx < 0) {
8891       Locs[i] = std::make_pair(-1, -1);
8892     } else if (Idx < 4) {
8893       Locs[i] = std::make_pair(MaskIdx, LoIdx);
8894       MaskPtr[LoIdx] = Idx;
8895       LoIdx++;
8896     } else {
8897       Locs[i] = std::make_pair(MaskIdx, HiIdx);
8898       MaskPtr[HiIdx] = Idx;
8899       HiIdx++;
8900     }
8901   }
8902
8903   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
8904   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
8905   int MaskOps[] = { -1, -1, -1, -1 };
8906   for (unsigned i = 0; i != 4; ++i)
8907     if (Locs[i].first != -1)
8908       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
8909   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
8910 }
8911
8912 static bool MayFoldVectorLoad(SDValue V) {
8913   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
8914     V = V.getOperand(0);
8915
8916   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
8917     V = V.getOperand(0);
8918   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
8919       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
8920     // BUILD_VECTOR (load), undef
8921     V = V.getOperand(0);
8922
8923   return MayFoldLoad(V);
8924 }
8925
8926 static
8927 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
8928   MVT VT = Op.getSimpleValueType();
8929
8930   // Canonizalize to v2f64.
8931   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
8932   return DAG.getNode(ISD::BITCAST, dl, VT,
8933                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
8934                                           V1, DAG));
8935 }
8936
8937 static
8938 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
8939                         bool HasSSE2) {
8940   SDValue V1 = Op.getOperand(0);
8941   SDValue V2 = Op.getOperand(1);
8942   MVT VT = Op.getSimpleValueType();
8943
8944   assert(VT != MVT::v2i64 && "unsupported shuffle type");
8945
8946   if (HasSSE2 && VT == MVT::v2f64)
8947     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
8948
8949   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
8950   return DAG.getNode(ISD::BITCAST, dl, VT,
8951                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
8952                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
8953                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
8954 }
8955
8956 static
8957 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
8958   SDValue V1 = Op.getOperand(0);
8959   SDValue V2 = Op.getOperand(1);
8960   MVT VT = Op.getSimpleValueType();
8961
8962   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
8963          "unsupported shuffle type");
8964
8965   if (V2.getOpcode() == ISD::UNDEF)
8966     V2 = V1;
8967
8968   // v4i32 or v4f32
8969   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
8970 }
8971
8972 static
8973 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
8974   SDValue V1 = Op.getOperand(0);
8975   SDValue V2 = Op.getOperand(1);
8976   MVT VT = Op.getSimpleValueType();
8977   unsigned NumElems = VT.getVectorNumElements();
8978
8979   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
8980   // operand of these instructions is only memory, so check if there's a
8981   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
8982   // same masks.
8983   bool CanFoldLoad = false;
8984
8985   // Trivial case, when V2 comes from a load.
8986   if (MayFoldVectorLoad(V2))
8987     CanFoldLoad = true;
8988
8989   // When V1 is a load, it can be folded later into a store in isel, example:
8990   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
8991   //    turns into:
8992   //  (MOVLPSmr addr:$src1, VR128:$src2)
8993   // So, recognize this potential and also use MOVLPS or MOVLPD
8994   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
8995     CanFoldLoad = true;
8996
8997   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8998   if (CanFoldLoad) {
8999     if (HasSSE2 && NumElems == 2)
9000       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
9001
9002     if (NumElems == 4)
9003       // If we don't care about the second element, proceed to use movss.
9004       if (SVOp->getMaskElt(1) != -1)
9005         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
9006   }
9007
9008   // movl and movlp will both match v2i64, but v2i64 is never matched by
9009   // movl earlier because we make it strict to avoid messing with the movlp load
9010   // folding logic (see the code above getMOVLP call). Match it here then,
9011   // this is horrible, but will stay like this until we move all shuffle
9012   // matching to x86 specific nodes. Note that for the 1st condition all
9013   // types are matched with movsd.
9014   if (HasSSE2) {
9015     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
9016     // as to remove this logic from here, as much as possible
9017     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
9018       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9019     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9020   }
9021
9022   assert(VT != MVT::v4i32 && "unsupported shuffle type");
9023
9024   // Invert the operand order and use SHUFPS to match it.
9025   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
9026                               getShuffleSHUFImmediate(SVOp), DAG);
9027 }
9028
9029 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
9030                                          SelectionDAG &DAG) {
9031   SDLoc dl(Load);
9032   MVT VT = Load->getSimpleValueType(0);
9033   MVT EVT = VT.getVectorElementType();
9034   SDValue Addr = Load->getOperand(1);
9035   SDValue NewAddr = DAG.getNode(
9036       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
9037       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
9038
9039   SDValue NewLoad =
9040       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
9041                   DAG.getMachineFunction().getMachineMemOperand(
9042                       Load->getMemOperand(), 0, EVT.getStoreSize()));
9043   return NewLoad;
9044 }
9045
9046 // It is only safe to call this function if isINSERTPSMask is true for
9047 // this shufflevector mask.
9048 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
9049                            SelectionDAG &DAG) {
9050   // Generate an insertps instruction when inserting an f32 from memory onto a
9051   // v4f32 or when copying a member from one v4f32 to another.
9052   // We also use it for transferring i32 from one register to another,
9053   // since it simply copies the same bits.
9054   // If we're transferring an i32 from memory to a specific element in a
9055   // register, we output a generic DAG that will match the PINSRD
9056   // instruction.
9057   MVT VT = SVOp->getSimpleValueType(0);
9058   MVT EVT = VT.getVectorElementType();
9059   SDValue V1 = SVOp->getOperand(0);
9060   SDValue V2 = SVOp->getOperand(1);
9061   auto Mask = SVOp->getMask();
9062   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
9063          "unsupported vector type for insertps/pinsrd");
9064
9065   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
9066   auto FromV2Predicate = [](const int &i) { return i >= 4; };
9067   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
9068
9069   SDValue From;
9070   SDValue To;
9071   unsigned DestIndex;
9072   if (FromV1 == 1) {
9073     From = V1;
9074     To = V2;
9075     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
9076                 Mask.begin();
9077   } else {
9078     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
9079            "More than one element from V1 and from V2, or no elements from one "
9080            "of the vectors. This case should not have returned true from "
9081            "isINSERTPSMask");
9082     From = V2;
9083     To = V1;
9084     DestIndex =
9085         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
9086   }
9087
9088   unsigned SrcIndex = Mask[DestIndex] % 4;
9089   if (MayFoldLoad(From)) {
9090     // Trivial case, when From comes from a load and is only used by the
9091     // shuffle. Make it use insertps from the vector that we need from that
9092     // load.
9093     SDValue NewLoad =
9094         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
9095     if (!NewLoad.getNode())
9096       return SDValue();
9097
9098     if (EVT == MVT::f32) {
9099       // Create this as a scalar to vector to match the instruction pattern.
9100       SDValue LoadScalarToVector =
9101           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
9102       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
9103       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
9104                          InsertpsMask);
9105     } else { // EVT == MVT::i32
9106       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
9107       // instruction, to match the PINSRD instruction, which loads an i32 to a
9108       // certain vector element.
9109       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
9110                          DAG.getConstant(DestIndex, MVT::i32));
9111     }
9112   }
9113
9114   // Vector-element-to-vector
9115   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
9116   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
9117 }
9118
9119 // Reduce a vector shuffle to zext.
9120 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
9121                                     SelectionDAG &DAG) {
9122   // PMOVZX is only available from SSE41.
9123   if (!Subtarget->hasSSE41())
9124     return SDValue();
9125
9126   MVT VT = Op.getSimpleValueType();
9127
9128   // Only AVX2 support 256-bit vector integer extending.
9129   if (!Subtarget->hasInt256() && VT.is256BitVector())
9130     return SDValue();
9131
9132   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9133   SDLoc DL(Op);
9134   SDValue V1 = Op.getOperand(0);
9135   SDValue V2 = Op.getOperand(1);
9136   unsigned NumElems = VT.getVectorNumElements();
9137
9138   // Extending is an unary operation and the element type of the source vector
9139   // won't be equal to or larger than i64.
9140   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
9141       VT.getVectorElementType() == MVT::i64)
9142     return SDValue();
9143
9144   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
9145   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
9146   while ((1U << Shift) < NumElems) {
9147     if (SVOp->getMaskElt(1U << Shift) == 1)
9148       break;
9149     Shift += 1;
9150     // The maximal ratio is 8, i.e. from i8 to i64.
9151     if (Shift > 3)
9152       return SDValue();
9153   }
9154
9155   // Check the shuffle mask.
9156   unsigned Mask = (1U << Shift) - 1;
9157   for (unsigned i = 0; i != NumElems; ++i) {
9158     int EltIdx = SVOp->getMaskElt(i);
9159     if ((i & Mask) != 0 && EltIdx != -1)
9160       return SDValue();
9161     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
9162       return SDValue();
9163   }
9164
9165   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
9166   MVT NeVT = MVT::getIntegerVT(NBits);
9167   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
9168
9169   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
9170     return SDValue();
9171
9172   // Simplify the operand as it's prepared to be fed into shuffle.
9173   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
9174   if (V1.getOpcode() == ISD::BITCAST &&
9175       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
9176       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
9177       V1.getOperand(0).getOperand(0)
9178         .getSimpleValueType().getSizeInBits() == SignificantBits) {
9179     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
9180     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
9181     ConstantSDNode *CIdx =
9182       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
9183     // If it's foldable, i.e. normal load with single use, we will let code
9184     // selection to fold it. Otherwise, we will short the conversion sequence.
9185     if (CIdx && CIdx->getZExtValue() == 0 &&
9186         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
9187       MVT FullVT = V.getSimpleValueType();
9188       MVT V1VT = V1.getSimpleValueType();
9189       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
9190         // The "ext_vec_elt" node is wider than the result node.
9191         // In this case we should extract subvector from V.
9192         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
9193         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
9194         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
9195                                         FullVT.getVectorNumElements()/Ratio);
9196         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
9197                         DAG.getIntPtrConstant(0));
9198       }
9199       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
9200     }
9201   }
9202
9203   return DAG.getNode(ISD::BITCAST, DL, VT,
9204                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
9205 }
9206
9207 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
9208                                       SelectionDAG &DAG) {
9209   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9210   MVT VT = Op.getSimpleValueType();
9211   SDLoc dl(Op);
9212   SDValue V1 = Op.getOperand(0);
9213   SDValue V2 = Op.getOperand(1);
9214
9215   if (isZeroShuffle(SVOp))
9216     return getZeroVector(VT, Subtarget, DAG, dl);
9217
9218   // Handle splat operations
9219   if (SVOp->isSplat()) {
9220     // Use vbroadcast whenever the splat comes from a foldable load
9221     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
9222     if (Broadcast.getNode())
9223       return Broadcast;
9224   }
9225
9226   // Check integer expanding shuffles.
9227   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
9228   if (NewOp.getNode())
9229     return NewOp;
9230
9231   // If the shuffle can be profitably rewritten as a narrower shuffle, then
9232   // do it!
9233   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
9234       VT == MVT::v32i8) {
9235     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9236     if (NewOp.getNode())
9237       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
9238   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
9239     // FIXME: Figure out a cleaner way to do this.
9240     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
9241       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9242       if (NewOp.getNode()) {
9243         MVT NewVT = NewOp.getSimpleValueType();
9244         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
9245                                NewVT, true, false))
9246           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
9247                               dl);
9248       }
9249     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
9250       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
9251       if (NewOp.getNode()) {
9252         MVT NewVT = NewOp.getSimpleValueType();
9253         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
9254           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
9255                               dl);
9256       }
9257     }
9258   }
9259   return SDValue();
9260 }
9261
9262 SDValue
9263 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
9264   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9265   SDValue V1 = Op.getOperand(0);
9266   SDValue V2 = Op.getOperand(1);
9267   MVT VT = Op.getSimpleValueType();
9268   SDLoc dl(Op);
9269   unsigned NumElems = VT.getVectorNumElements();
9270   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
9271   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
9272   bool V1IsSplat = false;
9273   bool V2IsSplat = false;
9274   bool HasSSE2 = Subtarget->hasSSE2();
9275   bool HasFp256    = Subtarget->hasFp256();
9276   bool HasInt256   = Subtarget->hasInt256();
9277   MachineFunction &MF = DAG.getMachineFunction();
9278   bool OptForSize = MF.getFunction()->getAttributes().
9279     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
9280
9281   // Check if we should use the experimental vector shuffle lowering. If so,
9282   // delegate completely to that code path.
9283   if (ExperimentalVectorShuffleLowering)
9284     return lowerVectorShuffle(Op, Subtarget, DAG);
9285
9286   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
9287
9288   if (V1IsUndef && V2IsUndef)
9289     return DAG.getUNDEF(VT);
9290
9291   // When we create a shuffle node we put the UNDEF node to second operand,
9292   // but in some cases the first operand may be transformed to UNDEF.
9293   // In this case we should just commute the node.
9294   if (V1IsUndef)
9295     return CommuteVectorShuffle(SVOp, DAG);
9296
9297   // Vector shuffle lowering takes 3 steps:
9298   //
9299   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
9300   //    narrowing and commutation of operands should be handled.
9301   // 2) Matching of shuffles with known shuffle masks to x86 target specific
9302   //    shuffle nodes.
9303   // 3) Rewriting of unmatched masks into new generic shuffle operations,
9304   //    so the shuffle can be broken into other shuffles and the legalizer can
9305   //    try the lowering again.
9306   //
9307   // The general idea is that no vector_shuffle operation should be left to
9308   // be matched during isel, all of them must be converted to a target specific
9309   // node here.
9310
9311   // Normalize the input vectors. Here splats, zeroed vectors, profitable
9312   // narrowing and commutation of operands should be handled. The actual code
9313   // doesn't include all of those, work in progress...
9314   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
9315   if (NewOp.getNode())
9316     return NewOp;
9317
9318   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
9319
9320   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
9321   // unpckh_undef). Only use pshufd if speed is more important than size.
9322   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9323     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9324   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9325     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9326
9327   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
9328       V2IsUndef && MayFoldVectorLoad(V1))
9329     return getMOVDDup(Op, dl, V1, DAG);
9330
9331   if (isMOVHLPS_v_undef_Mask(M, VT))
9332     return getMOVHighToLow(Op, dl, DAG);
9333
9334   // Use to match splats
9335   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
9336       (VT == MVT::v2f64 || VT == MVT::v2i64))
9337     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9338
9339   if (isPSHUFDMask(M, VT)) {
9340     // The actual implementation will match the mask in the if above and then
9341     // during isel it can match several different instructions, not only pshufd
9342     // as its name says, sad but true, emulate the behavior for now...
9343     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
9344       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
9345
9346     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
9347
9348     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
9349       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
9350
9351     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
9352       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
9353                                   DAG);
9354
9355     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
9356                                 TargetMask, DAG);
9357   }
9358
9359   if (isPALIGNRMask(M, VT, Subtarget))
9360     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
9361                                 getShufflePALIGNRImmediate(SVOp),
9362                                 DAG);
9363
9364   // Check if this can be converted into a logical shift.
9365   bool isLeft = false;
9366   unsigned ShAmt = 0;
9367   SDValue ShVal;
9368   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
9369   if (isShift && ShVal.hasOneUse()) {
9370     // If the shifted value has multiple uses, it may be cheaper to use
9371     // v_set0 + movlhps or movhlps, etc.
9372     MVT EltVT = VT.getVectorElementType();
9373     ShAmt *= EltVT.getSizeInBits();
9374     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9375   }
9376
9377   if (isMOVLMask(M, VT)) {
9378     if (ISD::isBuildVectorAllZeros(V1.getNode()))
9379       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
9380     if (!isMOVLPMask(M, VT)) {
9381       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
9382         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
9383
9384       if (VT == MVT::v4i32 || VT == MVT::v4f32)
9385         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
9386     }
9387   }
9388
9389   // FIXME: fold these into legal mask.
9390   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
9391     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
9392
9393   if (isMOVHLPSMask(M, VT))
9394     return getMOVHighToLow(Op, dl, DAG);
9395
9396   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
9397     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
9398
9399   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
9400     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
9401
9402   if (isMOVLPMask(M, VT))
9403     return getMOVLP(Op, dl, DAG, HasSSE2);
9404
9405   if (ShouldXformToMOVHLPS(M, VT) ||
9406       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
9407     return CommuteVectorShuffle(SVOp, DAG);
9408
9409   if (isShift) {
9410     // No better options. Use a vshldq / vsrldq.
9411     MVT EltVT = VT.getVectorElementType();
9412     ShAmt *= EltVT.getSizeInBits();
9413     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
9414   }
9415
9416   bool Commuted = false;
9417   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
9418   // 1,1,1,1 -> v8i16 though.
9419   V1IsSplat = isSplatVector(V1.getNode());
9420   V2IsSplat = isSplatVector(V2.getNode());
9421
9422   // Canonicalize the splat or undef, if present, to be on the RHS.
9423   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
9424     CommuteVectorShuffleMask(M, NumElems);
9425     std::swap(V1, V2);
9426     std::swap(V1IsSplat, V2IsSplat);
9427     Commuted = true;
9428   }
9429
9430   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
9431     // Shuffling low element of v1 into undef, just return v1.
9432     if (V2IsUndef)
9433       return V1;
9434     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
9435     // the instruction selector will not match, so get a canonical MOVL with
9436     // swapped operands to undo the commute.
9437     return getMOVL(DAG, dl, VT, V2, V1);
9438   }
9439
9440   if (isUNPCKLMask(M, VT, HasInt256))
9441     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9442
9443   if (isUNPCKHMask(M, VT, HasInt256))
9444     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9445
9446   if (V2IsSplat) {
9447     // Normalize mask so all entries that point to V2 points to its first
9448     // element then try to match unpck{h|l} again. If match, return a
9449     // new vector_shuffle with the corrected mask.p
9450     SmallVector<int, 8> NewMask(M.begin(), M.end());
9451     NormalizeMask(NewMask, NumElems);
9452     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
9453       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9454     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
9455       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9456   }
9457
9458   if (Commuted) {
9459     // Commute is back and try unpck* again.
9460     // FIXME: this seems wrong.
9461     CommuteVectorShuffleMask(M, NumElems);
9462     std::swap(V1, V2);
9463     std::swap(V1IsSplat, V2IsSplat);
9464
9465     if (isUNPCKLMask(M, VT, HasInt256))
9466       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
9467
9468     if (isUNPCKHMask(M, VT, HasInt256))
9469       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
9470   }
9471
9472   // Normalize the node to match x86 shuffle ops if needed
9473   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
9474     return CommuteVectorShuffle(SVOp, DAG);
9475
9476   // The checks below are all present in isShuffleMaskLegal, but they are
9477   // inlined here right now to enable us to directly emit target specific
9478   // nodes, and remove one by one until they don't return Op anymore.
9479
9480   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
9481       SVOp->getSplatIndex() == 0 && V2IsUndef) {
9482     if (VT == MVT::v2f64 || VT == MVT::v2i64)
9483       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9484   }
9485
9486   if (isPSHUFHWMask(M, VT, HasInt256))
9487     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
9488                                 getShufflePSHUFHWImmediate(SVOp),
9489                                 DAG);
9490
9491   if (isPSHUFLWMask(M, VT, HasInt256))
9492     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
9493                                 getShufflePSHUFLWImmediate(SVOp),
9494                                 DAG);
9495
9496   unsigned MaskValue;
9497   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
9498                   &MaskValue))
9499     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
9500
9501   if (isSHUFPMask(M, VT))
9502     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
9503                                 getShuffleSHUFImmediate(SVOp), DAG);
9504
9505   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
9506     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
9507   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
9508     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
9509
9510   //===--------------------------------------------------------------------===//
9511   // Generate target specific nodes for 128 or 256-bit shuffles only
9512   // supported in the AVX instruction set.
9513   //
9514
9515   // Handle VMOVDDUPY permutations
9516   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
9517     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
9518
9519   // Handle VPERMILPS/D* permutations
9520   if (isVPERMILPMask(M, VT)) {
9521     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
9522       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
9523                                   getShuffleSHUFImmediate(SVOp), DAG);
9524     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
9525                                 getShuffleSHUFImmediate(SVOp), DAG);
9526   }
9527
9528   unsigned Idx;
9529   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
9530     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
9531                               Idx*(NumElems/2), DAG, dl);
9532
9533   // Handle VPERM2F128/VPERM2I128 permutations
9534   if (isVPERM2X128Mask(M, VT, HasFp256))
9535     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
9536                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
9537
9538   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
9539     return getINSERTPS(SVOp, dl, DAG);
9540
9541   unsigned Imm8;
9542   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
9543     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
9544
9545   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
9546       VT.is512BitVector()) {
9547     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
9548     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
9549     SmallVector<SDValue, 16> permclMask;
9550     for (unsigned i = 0; i != NumElems; ++i) {
9551       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
9552     }
9553
9554     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
9555     if (V2IsUndef)
9556       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
9557       return DAG.getNode(X86ISD::VPERMV, dl, VT,
9558                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
9559     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
9560                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
9561   }
9562
9563   //===--------------------------------------------------------------------===//
9564   // Since no target specific shuffle was selected for this generic one,
9565   // lower it into other known shuffles. FIXME: this isn't true yet, but
9566   // this is the plan.
9567   //
9568
9569   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
9570   if (VT == MVT::v8i16) {
9571     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
9572     if (NewOp.getNode())
9573       return NewOp;
9574   }
9575
9576   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
9577     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
9578     if (NewOp.getNode())
9579       return NewOp;
9580   }
9581
9582   if (VT == MVT::v16i8) {
9583     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
9584     if (NewOp.getNode())
9585       return NewOp;
9586   }
9587
9588   if (VT == MVT::v32i8) {
9589     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
9590     if (NewOp.getNode())
9591       return NewOp;
9592   }
9593
9594   // Handle all 128-bit wide vectors with 4 elements, and match them with
9595   // several different shuffle types.
9596   if (NumElems == 4 && VT.is128BitVector())
9597     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
9598
9599   // Handle general 256-bit shuffles
9600   if (VT.is256BitVector())
9601     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
9602
9603   return SDValue();
9604 }
9605
9606 // This function assumes its argument is a BUILD_VECTOR of constants or
9607 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
9608 // true.
9609 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
9610                                     unsigned &MaskValue) {
9611   MaskValue = 0;
9612   unsigned NumElems = BuildVector->getNumOperands();
9613   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
9614   unsigned NumLanes = (NumElems - 1) / 8 + 1;
9615   unsigned NumElemsInLane = NumElems / NumLanes;
9616
9617   // Blend for v16i16 should be symetric for the both lanes.
9618   for (unsigned i = 0; i < NumElemsInLane; ++i) {
9619     SDValue EltCond = BuildVector->getOperand(i);
9620     SDValue SndLaneEltCond =
9621         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
9622
9623     int Lane1Cond = -1, Lane2Cond = -1;
9624     if (isa<ConstantSDNode>(EltCond))
9625       Lane1Cond = !isZero(EltCond);
9626     if (isa<ConstantSDNode>(SndLaneEltCond))
9627       Lane2Cond = !isZero(SndLaneEltCond);
9628
9629     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
9630       // Lane1Cond != 0, means we want the first argument.
9631       // Lane1Cond == 0, means we want the second argument.
9632       // The encoding of this argument is 0 for the first argument, 1
9633       // for the second. Therefore, invert the condition.
9634       MaskValue |= !Lane1Cond << i;
9635     else if (Lane1Cond < 0)
9636       MaskValue |= !Lane2Cond << i;
9637     else
9638       return false;
9639   }
9640   return true;
9641 }
9642
9643 // Try to lower a vselect node into a simple blend instruction.
9644 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
9645                                    SelectionDAG &DAG) {
9646   SDValue Cond = Op.getOperand(0);
9647   SDValue LHS = Op.getOperand(1);
9648   SDValue RHS = Op.getOperand(2);
9649   SDLoc dl(Op);
9650   MVT VT = Op.getSimpleValueType();
9651   MVT EltVT = VT.getVectorElementType();
9652   unsigned NumElems = VT.getVectorNumElements();
9653
9654   // There is no blend with immediate in AVX-512.
9655   if (VT.is512BitVector())
9656     return SDValue();
9657
9658   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
9659     return SDValue();
9660   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
9661     return SDValue();
9662
9663   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
9664     return SDValue();
9665
9666   // Check the mask for BLEND and build the value.
9667   unsigned MaskValue = 0;
9668   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
9669     return SDValue();
9670
9671   // Convert i32 vectors to floating point if it is not AVX2.
9672   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
9673   MVT BlendVT = VT;
9674   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
9675     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
9676                                NumElems);
9677     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
9678     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
9679   }
9680
9681   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
9682                             DAG.getConstant(MaskValue, MVT::i32));
9683   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
9684 }
9685
9686 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
9687   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
9688   if (BlendOp.getNode())
9689     return BlendOp;
9690
9691   // Some types for vselect were previously set to Expand, not Legal or
9692   // Custom. Return an empty SDValue so we fall-through to Expand, after
9693   // the Custom lowering phase.
9694   MVT VT = Op.getSimpleValueType();
9695   switch (VT.SimpleTy) {
9696   default:
9697     break;
9698   case MVT::v8i16:
9699   case MVT::v16i16:
9700     return SDValue();
9701   }
9702
9703   // We couldn't create a "Blend with immediate" node.
9704   // This node should still be legal, but we'll have to emit a blendv*
9705   // instruction.
9706   return Op;
9707 }
9708
9709 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9710   MVT VT = Op.getSimpleValueType();
9711   SDLoc dl(Op);
9712
9713   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
9714     return SDValue();
9715
9716   if (VT.getSizeInBits() == 8) {
9717     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
9718                                   Op.getOperand(0), Op.getOperand(1));
9719     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9720                                   DAG.getValueType(VT));
9721     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9722   }
9723
9724   if (VT.getSizeInBits() == 16) {
9725     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9726     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
9727     if (Idx == 0)
9728       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9729                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9730                                      DAG.getNode(ISD::BITCAST, dl,
9731                                                  MVT::v4i32,
9732                                                  Op.getOperand(0)),
9733                                      Op.getOperand(1)));
9734     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
9735                                   Op.getOperand(0), Op.getOperand(1));
9736     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
9737                                   DAG.getValueType(VT));
9738     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9739   }
9740
9741   if (VT == MVT::f32) {
9742     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
9743     // the result back to FR32 register. It's only worth matching if the
9744     // result has a single use which is a store or a bitcast to i32.  And in
9745     // the case of a store, it's not worth it if the index is a constant 0,
9746     // because a MOVSSmr can be used instead, which is smaller and faster.
9747     if (!Op.hasOneUse())
9748       return SDValue();
9749     SDNode *User = *Op.getNode()->use_begin();
9750     if ((User->getOpcode() != ISD::STORE ||
9751          (isa<ConstantSDNode>(Op.getOperand(1)) &&
9752           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
9753         (User->getOpcode() != ISD::BITCAST ||
9754          User->getValueType(0) != MVT::i32))
9755       return SDValue();
9756     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9757                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
9758                                               Op.getOperand(0)),
9759                                               Op.getOperand(1));
9760     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
9761   }
9762
9763   if (VT == MVT::i32 || VT == MVT::i64) {
9764     // ExtractPS/pextrq works with constant index.
9765     if (isa<ConstantSDNode>(Op.getOperand(1)))
9766       return Op;
9767   }
9768   return SDValue();
9769 }
9770
9771 /// Extract one bit from mask vector, like v16i1 or v8i1.
9772 /// AVX-512 feature.
9773 SDValue
9774 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
9775   SDValue Vec = Op.getOperand(0);
9776   SDLoc dl(Vec);
9777   MVT VecVT = Vec.getSimpleValueType();
9778   SDValue Idx = Op.getOperand(1);
9779   MVT EltVT = Op.getSimpleValueType();
9780
9781   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
9782
9783   // variable index can't be handled in mask registers,
9784   // extend vector to VR512
9785   if (!isa<ConstantSDNode>(Idx)) {
9786     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9787     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
9788     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
9789                               ExtVT.getVectorElementType(), Ext, Idx);
9790     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
9791   }
9792
9793   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9794   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9795   unsigned MaxSift = rc->getSize()*8 - 1;
9796   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
9797                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
9798   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
9799                     DAG.getConstant(MaxSift, MVT::i8));
9800   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
9801                        DAG.getIntPtrConstant(0));
9802 }
9803
9804 SDValue
9805 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
9806                                            SelectionDAG &DAG) const {
9807   SDLoc dl(Op);
9808   SDValue Vec = Op.getOperand(0);
9809   MVT VecVT = Vec.getSimpleValueType();
9810   SDValue Idx = Op.getOperand(1);
9811
9812   if (Op.getSimpleValueType() == MVT::i1)
9813     return ExtractBitFromMaskVector(Op, DAG);
9814
9815   if (!isa<ConstantSDNode>(Idx)) {
9816     if (VecVT.is512BitVector() ||
9817         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
9818          VecVT.getVectorElementType().getSizeInBits() == 32)) {
9819
9820       MVT MaskEltVT =
9821         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
9822       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
9823                                     MaskEltVT.getSizeInBits());
9824
9825       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
9826       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
9827                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
9828                                 Idx, DAG.getConstant(0, getPointerTy()));
9829       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
9830       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
9831                         Perm, DAG.getConstant(0, getPointerTy()));
9832     }
9833     return SDValue();
9834   }
9835
9836   // If this is a 256-bit vector result, first extract the 128-bit vector and
9837   // then extract the element from the 128-bit vector.
9838   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
9839
9840     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9841     // Get the 128-bit vector.
9842     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
9843     MVT EltVT = VecVT.getVectorElementType();
9844
9845     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
9846
9847     //if (IdxVal >= NumElems/2)
9848     //  IdxVal -= NumElems/2;
9849     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
9850     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
9851                        DAG.getConstant(IdxVal, MVT::i32));
9852   }
9853
9854   assert(VecVT.is128BitVector() && "Unexpected vector length");
9855
9856   if (Subtarget->hasSSE41()) {
9857     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
9858     if (Res.getNode())
9859       return Res;
9860   }
9861
9862   MVT VT = Op.getSimpleValueType();
9863   // TODO: handle v16i8.
9864   if (VT.getSizeInBits() == 16) {
9865     SDValue Vec = Op.getOperand(0);
9866     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9867     if (Idx == 0)
9868       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
9869                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
9870                                      DAG.getNode(ISD::BITCAST, dl,
9871                                                  MVT::v4i32, Vec),
9872                                      Op.getOperand(1)));
9873     // Transform it so it match pextrw which produces a 32-bit result.
9874     MVT EltVT = MVT::i32;
9875     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
9876                                   Op.getOperand(0), Op.getOperand(1));
9877     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
9878                                   DAG.getValueType(VT));
9879     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
9880   }
9881
9882   if (VT.getSizeInBits() == 32) {
9883     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9884     if (Idx == 0)
9885       return Op;
9886
9887     // SHUFPS the element to the lowest double word, then movss.
9888     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
9889     MVT VVT = Op.getOperand(0).getSimpleValueType();
9890     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9891                                        DAG.getUNDEF(VVT), Mask);
9892     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9893                        DAG.getIntPtrConstant(0));
9894   }
9895
9896   if (VT.getSizeInBits() == 64) {
9897     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
9898     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
9899     //        to match extract_elt for f64.
9900     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
9901     if (Idx == 0)
9902       return Op;
9903
9904     // UNPCKHPD the element to the lowest double word, then movsd.
9905     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
9906     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
9907     int Mask[2] = { 1, -1 };
9908     MVT VVT = Op.getOperand(0).getSimpleValueType();
9909     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
9910                                        DAG.getUNDEF(VVT), Mask);
9911     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
9912                        DAG.getIntPtrConstant(0));
9913   }
9914
9915   return SDValue();
9916 }
9917
9918 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
9919   MVT VT = Op.getSimpleValueType();
9920   MVT EltVT = VT.getVectorElementType();
9921   SDLoc dl(Op);
9922
9923   SDValue N0 = Op.getOperand(0);
9924   SDValue N1 = Op.getOperand(1);
9925   SDValue N2 = Op.getOperand(2);
9926
9927   if (!VT.is128BitVector())
9928     return SDValue();
9929
9930   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
9931       isa<ConstantSDNode>(N2)) {
9932     unsigned Opc;
9933     if (VT == MVT::v8i16)
9934       Opc = X86ISD::PINSRW;
9935     else if (VT == MVT::v16i8)
9936       Opc = X86ISD::PINSRB;
9937     else
9938       Opc = X86ISD::PINSRB;
9939
9940     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
9941     // argument.
9942     if (N1.getValueType() != MVT::i32)
9943       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
9944     if (N2.getValueType() != MVT::i32)
9945       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
9946     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
9947   }
9948
9949   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
9950     // Bits [7:6] of the constant are the source select.  This will always be
9951     //  zero here.  The DAG Combiner may combine an extract_elt index into these
9952     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
9953     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
9954     // Bits [5:4] of the constant are the destination select.  This is the
9955     //  value of the incoming immediate.
9956     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
9957     //   combine either bitwise AND or insert of float 0.0 to set these bits.
9958     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
9959     // Create this as a scalar to vector..
9960     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
9961     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
9962   }
9963
9964   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
9965     // PINSR* works with constant index.
9966     return Op;
9967   }
9968   return SDValue();
9969 }
9970
9971 /// Insert one bit to mask vector, like v16i1 or v8i1.
9972 /// AVX-512 feature.
9973 SDValue 
9974 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
9975   SDLoc dl(Op);
9976   SDValue Vec = Op.getOperand(0);
9977   SDValue Elt = Op.getOperand(1);
9978   SDValue Idx = Op.getOperand(2);
9979   MVT VecVT = Vec.getSimpleValueType();
9980
9981   if (!isa<ConstantSDNode>(Idx)) {
9982     // Non constant index. Extend source and destination,
9983     // insert element and then truncate the result.
9984     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
9985     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
9986     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
9987       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
9988       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
9989     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
9990   }
9991
9992   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
9993   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
9994   if (Vec.getOpcode() == ISD::UNDEF)
9995     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
9996                        DAG.getConstant(IdxVal, MVT::i8));
9997   const TargetRegisterClass* rc = getRegClassFor(VecVT);
9998   unsigned MaxSift = rc->getSize()*8 - 1;
9999   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10000                     DAG.getConstant(MaxSift, MVT::i8));
10001   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
10002                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
10003   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10004 }
10005 SDValue
10006 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
10007   MVT VT = Op.getSimpleValueType();
10008   MVT EltVT = VT.getVectorElementType();
10009   
10010   if (EltVT == MVT::i1)
10011     return InsertBitToMaskVector(Op, DAG);
10012
10013   SDLoc dl(Op);
10014   SDValue N0 = Op.getOperand(0);
10015   SDValue N1 = Op.getOperand(1);
10016   SDValue N2 = Op.getOperand(2);
10017
10018   // If this is a 256-bit vector result, first extract the 128-bit vector,
10019   // insert the element into the extracted half and then place it back.
10020   if (VT.is256BitVector() || VT.is512BitVector()) {
10021     if (!isa<ConstantSDNode>(N2))
10022       return SDValue();
10023
10024     // Get the desired 128-bit vector half.
10025     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
10026     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10027
10028     // Insert the element into the desired half.
10029     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
10030     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
10031
10032     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10033                     DAG.getConstant(IdxIn128, MVT::i32));
10034
10035     // Insert the changed part back to the 256-bit vector
10036     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10037   }
10038
10039   if (Subtarget->hasSSE41())
10040     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
10041
10042   if (EltVT == MVT::i8)
10043     return SDValue();
10044
10045   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
10046     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10047     // as its second argument.
10048     if (N1.getValueType() != MVT::i32)
10049       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10050     if (N2.getValueType() != MVT::i32)
10051       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
10052     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10053   }
10054   return SDValue();
10055 }
10056
10057 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10058   SDLoc dl(Op);
10059   MVT OpVT = Op.getSimpleValueType();
10060
10061   // If this is a 256-bit vector result, first insert into a 128-bit
10062   // vector and then insert into the 256-bit vector.
10063   if (!OpVT.is128BitVector()) {
10064     // Insert into a 128-bit vector.
10065     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10066     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10067                                  OpVT.getVectorNumElements() / SizeFactor);
10068
10069     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10070
10071     // Insert the 128-bit vector.
10072     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10073   }
10074
10075   if (OpVT == MVT::v1i64 &&
10076       Op.getOperand(0).getValueType() == MVT::i64)
10077     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10078
10079   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10080   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10081   return DAG.getNode(ISD::BITCAST, dl, OpVT,
10082                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
10083 }
10084
10085 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10086 // a simple subregister reference or explicit instructions to grab
10087 // upper bits of a vector.
10088 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10089                                       SelectionDAG &DAG) {
10090   SDLoc dl(Op);
10091   SDValue In =  Op.getOperand(0);
10092   SDValue Idx = Op.getOperand(1);
10093   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10094   MVT ResVT   = Op.getSimpleValueType();
10095   MVT InVT    = In.getSimpleValueType();
10096
10097   if (Subtarget->hasFp256()) {
10098     if (ResVT.is128BitVector() &&
10099         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10100         isa<ConstantSDNode>(Idx)) {
10101       return Extract128BitVector(In, IdxVal, DAG, dl);
10102     }
10103     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10104         isa<ConstantSDNode>(Idx)) {
10105       return Extract256BitVector(In, IdxVal, DAG, dl);
10106     }
10107   }
10108   return SDValue();
10109 }
10110
10111 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10112 // simple superregister reference or explicit instructions to insert
10113 // the upper bits of a vector.
10114 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10115                                      SelectionDAG &DAG) {
10116   if (Subtarget->hasFp256()) {
10117     SDLoc dl(Op.getNode());
10118     SDValue Vec = Op.getNode()->getOperand(0);
10119     SDValue SubVec = Op.getNode()->getOperand(1);
10120     SDValue Idx = Op.getNode()->getOperand(2);
10121
10122     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
10123          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
10124         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
10125         isa<ConstantSDNode>(Idx)) {
10126       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10127       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
10128     }
10129
10130     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
10131         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
10132         isa<ConstantSDNode>(Idx)) {
10133       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10134       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
10135     }
10136   }
10137   return SDValue();
10138 }
10139
10140 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
10141 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
10142 // one of the above mentioned nodes. It has to be wrapped because otherwise
10143 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
10144 // be used to form addressing mode. These wrapped nodes will be selected
10145 // into MOV32ri.
10146 SDValue
10147 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
10148   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
10149
10150   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10151   // global base reg.
10152   unsigned char OpFlag = 0;
10153   unsigned WrapperKind = X86ISD::Wrapper;
10154   CodeModel::Model M = DAG.getTarget().getCodeModel();
10155
10156   if (Subtarget->isPICStyleRIPRel() &&
10157       (M == CodeModel::Small || M == CodeModel::Kernel))
10158     WrapperKind = X86ISD::WrapperRIP;
10159   else if (Subtarget->isPICStyleGOT())
10160     OpFlag = X86II::MO_GOTOFF;
10161   else if (Subtarget->isPICStyleStubPIC())
10162     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10163
10164   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
10165                                              CP->getAlignment(),
10166                                              CP->getOffset(), OpFlag);
10167   SDLoc DL(CP);
10168   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10169   // With PIC, the address is actually $g + Offset.
10170   if (OpFlag) {
10171     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10172                          DAG.getNode(X86ISD::GlobalBaseReg,
10173                                      SDLoc(), getPointerTy()),
10174                          Result);
10175   }
10176
10177   return Result;
10178 }
10179
10180 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
10181   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
10182
10183   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10184   // global base reg.
10185   unsigned char OpFlag = 0;
10186   unsigned WrapperKind = X86ISD::Wrapper;
10187   CodeModel::Model M = DAG.getTarget().getCodeModel();
10188
10189   if (Subtarget->isPICStyleRIPRel() &&
10190       (M == CodeModel::Small || M == CodeModel::Kernel))
10191     WrapperKind = X86ISD::WrapperRIP;
10192   else if (Subtarget->isPICStyleGOT())
10193     OpFlag = X86II::MO_GOTOFF;
10194   else if (Subtarget->isPICStyleStubPIC())
10195     OpFlag = X86II::MO_PIC_BASE_OFFSET;
10196
10197   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
10198                                           OpFlag);
10199   SDLoc DL(JT);
10200   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10201
10202   // With PIC, the address is actually $g + Offset.
10203   if (OpFlag)
10204     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10205                          DAG.getNode(X86ISD::GlobalBaseReg,
10206                                      SDLoc(), getPointerTy()),
10207                          Result);
10208
10209   return Result;
10210 }
10211
10212 SDValue
10213 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
10214   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
10215
10216   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10217   // global base reg.
10218   unsigned char OpFlag = 0;
10219   unsigned WrapperKind = X86ISD::Wrapper;
10220   CodeModel::Model M = DAG.getTarget().getCodeModel();
10221
10222   if (Subtarget->isPICStyleRIPRel() &&
10223       (M == CodeModel::Small || M == CodeModel::Kernel)) {
10224     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
10225       OpFlag = X86II::MO_GOTPCREL;
10226     WrapperKind = X86ISD::WrapperRIP;
10227   } else if (Subtarget->isPICStyleGOT()) {
10228     OpFlag = X86II::MO_GOT;
10229   } else if (Subtarget->isPICStyleStubPIC()) {
10230     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
10231   } else if (Subtarget->isPICStyleStubNoDynamic()) {
10232     OpFlag = X86II::MO_DARWIN_NONLAZY;
10233   }
10234
10235   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
10236
10237   SDLoc DL(Op);
10238   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10239
10240   // With PIC, the address is actually $g + Offset.
10241   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
10242       !Subtarget->is64Bit()) {
10243     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10244                          DAG.getNode(X86ISD::GlobalBaseReg,
10245                                      SDLoc(), getPointerTy()),
10246                          Result);
10247   }
10248
10249   // For symbols that require a load from a stub to get the address, emit the
10250   // load.
10251   if (isGlobalStubReference(OpFlag))
10252     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
10253                          MachinePointerInfo::getGOT(), false, false, false, 0);
10254
10255   return Result;
10256 }
10257
10258 SDValue
10259 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
10260   // Create the TargetBlockAddressAddress node.
10261   unsigned char OpFlags =
10262     Subtarget->ClassifyBlockAddressReference();
10263   CodeModel::Model M = DAG.getTarget().getCodeModel();
10264   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
10265   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
10266   SDLoc dl(Op);
10267   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
10268                                              OpFlags);
10269
10270   if (Subtarget->isPICStyleRIPRel() &&
10271       (M == CodeModel::Small || M == CodeModel::Kernel))
10272     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10273   else
10274     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10275
10276   // With PIC, the address is actually $g + Offset.
10277   if (isGlobalRelativeToPICBase(OpFlags)) {
10278     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10279                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10280                          Result);
10281   }
10282
10283   return Result;
10284 }
10285
10286 SDValue
10287 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
10288                                       int64_t Offset, SelectionDAG &DAG) const {
10289   // Create the TargetGlobalAddress node, folding in the constant
10290   // offset if it is legal.
10291   unsigned char OpFlags =
10292       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
10293   CodeModel::Model M = DAG.getTarget().getCodeModel();
10294   SDValue Result;
10295   if (OpFlags == X86II::MO_NO_FLAG &&
10296       X86::isOffsetSuitableForCodeModel(Offset, M)) {
10297     // A direct static reference to a global.
10298     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
10299     Offset = 0;
10300   } else {
10301     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
10302   }
10303
10304   if (Subtarget->isPICStyleRIPRel() &&
10305       (M == CodeModel::Small || M == CodeModel::Kernel))
10306     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
10307   else
10308     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
10309
10310   // With PIC, the address is actually $g + Offset.
10311   if (isGlobalRelativeToPICBase(OpFlags)) {
10312     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
10313                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
10314                          Result);
10315   }
10316
10317   // For globals that require a load from a stub to get the address, emit the
10318   // load.
10319   if (isGlobalStubReference(OpFlags))
10320     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
10321                          MachinePointerInfo::getGOT(), false, false, false, 0);
10322
10323   // If there was a non-zero offset that we didn't fold, create an explicit
10324   // addition for it.
10325   if (Offset != 0)
10326     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
10327                          DAG.getConstant(Offset, getPointerTy()));
10328
10329   return Result;
10330 }
10331
10332 SDValue
10333 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
10334   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
10335   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
10336   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
10337 }
10338
10339 static SDValue
10340 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
10341            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
10342            unsigned char OperandFlags, bool LocalDynamic = false) {
10343   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10344   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10345   SDLoc dl(GA);
10346   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10347                                            GA->getValueType(0),
10348                                            GA->getOffset(),
10349                                            OperandFlags);
10350
10351   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
10352                                            : X86ISD::TLSADDR;
10353
10354   if (InFlag) {
10355     SDValue Ops[] = { Chain,  TGA, *InFlag };
10356     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10357   } else {
10358     SDValue Ops[]  = { Chain, TGA };
10359     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
10360   }
10361
10362   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
10363   MFI->setAdjustsStack(true);
10364
10365   SDValue Flag = Chain.getValue(1);
10366   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
10367 }
10368
10369 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
10370 static SDValue
10371 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10372                                 const EVT PtrVT) {
10373   SDValue InFlag;
10374   SDLoc dl(GA);  // ? function entry point might be better
10375   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10376                                    DAG.getNode(X86ISD::GlobalBaseReg,
10377                                                SDLoc(), PtrVT), InFlag);
10378   InFlag = Chain.getValue(1);
10379
10380   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
10381 }
10382
10383 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
10384 static SDValue
10385 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10386                                 const EVT PtrVT) {
10387   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
10388                     X86::RAX, X86II::MO_TLSGD);
10389 }
10390
10391 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
10392                                            SelectionDAG &DAG,
10393                                            const EVT PtrVT,
10394                                            bool is64Bit) {
10395   SDLoc dl(GA);
10396
10397   // Get the start address of the TLS block for this module.
10398   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
10399       .getInfo<X86MachineFunctionInfo>();
10400   MFI->incNumLocalDynamicTLSAccesses();
10401
10402   SDValue Base;
10403   if (is64Bit) {
10404     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
10405                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
10406   } else {
10407     SDValue InFlag;
10408     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
10409         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
10410     InFlag = Chain.getValue(1);
10411     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
10412                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
10413   }
10414
10415   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
10416   // of Base.
10417
10418   // Build x@dtpoff.
10419   unsigned char OperandFlags = X86II::MO_DTPOFF;
10420   unsigned WrapperKind = X86ISD::Wrapper;
10421   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10422                                            GA->getValueType(0),
10423                                            GA->getOffset(), OperandFlags);
10424   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10425
10426   // Add x@dtpoff with the base.
10427   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
10428 }
10429
10430 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
10431 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
10432                                    const EVT PtrVT, TLSModel::Model model,
10433                                    bool is64Bit, bool isPIC) {
10434   SDLoc dl(GA);
10435
10436   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
10437   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
10438                                                          is64Bit ? 257 : 256));
10439
10440   SDValue ThreadPointer =
10441       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
10442                   MachinePointerInfo(Ptr), false, false, false, 0);
10443
10444   unsigned char OperandFlags = 0;
10445   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
10446   // initialexec.
10447   unsigned WrapperKind = X86ISD::Wrapper;
10448   if (model == TLSModel::LocalExec) {
10449     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
10450   } else if (model == TLSModel::InitialExec) {
10451     if (is64Bit) {
10452       OperandFlags = X86II::MO_GOTTPOFF;
10453       WrapperKind = X86ISD::WrapperRIP;
10454     } else {
10455       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
10456     }
10457   } else {
10458     llvm_unreachable("Unexpected model");
10459   }
10460
10461   // emit "addl x@ntpoff,%eax" (local exec)
10462   // or "addl x@indntpoff,%eax" (initial exec)
10463   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
10464   SDValue TGA =
10465       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
10466                                  GA->getOffset(), OperandFlags);
10467   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
10468
10469   if (model == TLSModel::InitialExec) {
10470     if (isPIC && !is64Bit) {
10471       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
10472                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
10473                            Offset);
10474     }
10475
10476     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
10477                          MachinePointerInfo::getGOT(), false, false, false, 0);
10478   }
10479
10480   // The address of the thread local variable is the add of the thread
10481   // pointer with the offset of the variable.
10482   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
10483 }
10484
10485 SDValue
10486 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
10487
10488   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
10489   const GlobalValue *GV = GA->getGlobal();
10490
10491   if (Subtarget->isTargetELF()) {
10492     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
10493
10494     switch (model) {
10495       case TLSModel::GeneralDynamic:
10496         if (Subtarget->is64Bit())
10497           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
10498         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
10499       case TLSModel::LocalDynamic:
10500         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
10501                                            Subtarget->is64Bit());
10502       case TLSModel::InitialExec:
10503       case TLSModel::LocalExec:
10504         return LowerToTLSExecModel(
10505             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
10506             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
10507     }
10508     llvm_unreachable("Unknown TLS model.");
10509   }
10510
10511   if (Subtarget->isTargetDarwin()) {
10512     // Darwin only has one model of TLS.  Lower to that.
10513     unsigned char OpFlag = 0;
10514     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
10515                            X86ISD::WrapperRIP : X86ISD::Wrapper;
10516
10517     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
10518     // global base reg.
10519     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
10520                  !Subtarget->is64Bit();
10521     if (PIC32)
10522       OpFlag = X86II::MO_TLVP_PIC_BASE;
10523     else
10524       OpFlag = X86II::MO_TLVP;
10525     SDLoc DL(Op);
10526     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
10527                                                 GA->getValueType(0),
10528                                                 GA->getOffset(), OpFlag);
10529     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
10530
10531     // With PIC32, the address is actually $g + Offset.
10532     if (PIC32)
10533       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
10534                            DAG.getNode(X86ISD::GlobalBaseReg,
10535                                        SDLoc(), getPointerTy()),
10536                            Offset);
10537
10538     // Lowering the machine isd will make sure everything is in the right
10539     // location.
10540     SDValue Chain = DAG.getEntryNode();
10541     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
10542     SDValue Args[] = { Chain, Offset };
10543     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
10544
10545     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
10546     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10547     MFI->setAdjustsStack(true);
10548
10549     // And our return value (tls address) is in the standard call return value
10550     // location.
10551     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
10552     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
10553                               Chain.getValue(1));
10554   }
10555
10556   if (Subtarget->isTargetKnownWindowsMSVC() ||
10557       Subtarget->isTargetWindowsGNU()) {
10558     // Just use the implicit TLS architecture
10559     // Need to generate someting similar to:
10560     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
10561     //                                  ; from TEB
10562     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
10563     //   mov     rcx, qword [rdx+rcx*8]
10564     //   mov     eax, .tls$:tlsvar
10565     //   [rax+rcx] contains the address
10566     // Windows 64bit: gs:0x58
10567     // Windows 32bit: fs:__tls_array
10568
10569     SDLoc dl(GA);
10570     SDValue Chain = DAG.getEntryNode();
10571
10572     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
10573     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
10574     // use its literal value of 0x2C.
10575     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
10576                                         ? Type::getInt8PtrTy(*DAG.getContext(),
10577                                                              256)
10578                                         : Type::getInt32PtrTy(*DAG.getContext(),
10579                                                               257));
10580
10581     SDValue TlsArray =
10582         Subtarget->is64Bit()
10583             ? DAG.getIntPtrConstant(0x58)
10584             : (Subtarget->isTargetWindowsGNU()
10585                    ? DAG.getIntPtrConstant(0x2C)
10586                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
10587
10588     SDValue ThreadPointer =
10589         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
10590                     MachinePointerInfo(Ptr), false, false, false, 0);
10591
10592     // Load the _tls_index variable
10593     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
10594     if (Subtarget->is64Bit())
10595       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
10596                            IDX, MachinePointerInfo(), MVT::i32,
10597                            false, false, 0);
10598     else
10599       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
10600                         false, false, false, 0);
10601
10602     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
10603                                     getPointerTy());
10604     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
10605
10606     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
10607     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
10608                       false, false, false, 0);
10609
10610     // Get the offset of start of .tls section
10611     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
10612                                              GA->getValueType(0),
10613                                              GA->getOffset(), X86II::MO_SECREL);
10614     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
10615
10616     // The address of the thread local variable is the add of the thread
10617     // pointer with the offset of the variable.
10618     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
10619   }
10620
10621   llvm_unreachable("TLS not implemented for this target.");
10622 }
10623
10624 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
10625 /// and take a 2 x i32 value to shift plus a shift amount.
10626 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
10627   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
10628   MVT VT = Op.getSimpleValueType();
10629   unsigned VTBits = VT.getSizeInBits();
10630   SDLoc dl(Op);
10631   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
10632   SDValue ShOpLo = Op.getOperand(0);
10633   SDValue ShOpHi = Op.getOperand(1);
10634   SDValue ShAmt  = Op.getOperand(2);
10635   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
10636   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
10637   // during isel.
10638   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10639                                   DAG.getConstant(VTBits - 1, MVT::i8));
10640   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
10641                                      DAG.getConstant(VTBits - 1, MVT::i8))
10642                        : DAG.getConstant(0, VT);
10643
10644   SDValue Tmp2, Tmp3;
10645   if (Op.getOpcode() == ISD::SHL_PARTS) {
10646     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
10647     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
10648   } else {
10649     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
10650     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
10651   }
10652
10653   // If the shift amount is larger or equal than the width of a part we can't
10654   // rely on the results of shld/shrd. Insert a test and select the appropriate
10655   // values for large shift amounts.
10656   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
10657                                 DAG.getConstant(VTBits, MVT::i8));
10658   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
10659                              AndNode, DAG.getConstant(0, MVT::i8));
10660
10661   SDValue Hi, Lo;
10662   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
10663   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
10664   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
10665
10666   if (Op.getOpcode() == ISD::SHL_PARTS) {
10667     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10668     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10669   } else {
10670     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
10671     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
10672   }
10673
10674   SDValue Ops[2] = { Lo, Hi };
10675   return DAG.getMergeValues(Ops, dl);
10676 }
10677
10678 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
10679                                            SelectionDAG &DAG) const {
10680   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
10681
10682   if (SrcVT.isVector())
10683     return SDValue();
10684
10685   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
10686          "Unknown SINT_TO_FP to lower!");
10687
10688   // These are really Legal; return the operand so the caller accepts it as
10689   // Legal.
10690   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
10691     return Op;
10692   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
10693       Subtarget->is64Bit()) {
10694     return Op;
10695   }
10696
10697   SDLoc dl(Op);
10698   unsigned Size = SrcVT.getSizeInBits()/8;
10699   MachineFunction &MF = DAG.getMachineFunction();
10700   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
10701   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10702   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10703                                StackSlot,
10704                                MachinePointerInfo::getFixedStack(SSFI),
10705                                false, false, 0);
10706   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
10707 }
10708
10709 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
10710                                      SDValue StackSlot,
10711                                      SelectionDAG &DAG) const {
10712   // Build the FILD
10713   SDLoc DL(Op);
10714   SDVTList Tys;
10715   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
10716   if (useSSE)
10717     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
10718   else
10719     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
10720
10721   unsigned ByteSize = SrcVT.getSizeInBits()/8;
10722
10723   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
10724   MachineMemOperand *MMO;
10725   if (FI) {
10726     int SSFI = FI->getIndex();
10727     MMO =
10728       DAG.getMachineFunction()
10729       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10730                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
10731   } else {
10732     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
10733     StackSlot = StackSlot.getOperand(1);
10734   }
10735   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
10736   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
10737                                            X86ISD::FILD, DL,
10738                                            Tys, Ops, SrcVT, MMO);
10739
10740   if (useSSE) {
10741     Chain = Result.getValue(1);
10742     SDValue InFlag = Result.getValue(2);
10743
10744     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
10745     // shouldn't be necessary except that RFP cannot be live across
10746     // multiple blocks. When stackifier is fixed, they can be uncoupled.
10747     MachineFunction &MF = DAG.getMachineFunction();
10748     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
10749     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
10750     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
10751     Tys = DAG.getVTList(MVT::Other);
10752     SDValue Ops[] = {
10753       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
10754     };
10755     MachineMemOperand *MMO =
10756       DAG.getMachineFunction()
10757       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10758                             MachineMemOperand::MOStore, SSFISize, SSFISize);
10759
10760     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
10761                                     Ops, Op.getValueType(), MMO);
10762     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
10763                          MachinePointerInfo::getFixedStack(SSFI),
10764                          false, false, false, 0);
10765   }
10766
10767   return Result;
10768 }
10769
10770 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
10771 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
10772                                                SelectionDAG &DAG) const {
10773   // This algorithm is not obvious. Here it is what we're trying to output:
10774   /*
10775      movq       %rax,  %xmm0
10776      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
10777      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
10778      #ifdef __SSE3__
10779        haddpd   %xmm0, %xmm0
10780      #else
10781        pshufd   $0x4e, %xmm0, %xmm1
10782        addpd    %xmm1, %xmm0
10783      #endif
10784   */
10785
10786   SDLoc dl(Op);
10787   LLVMContext *Context = DAG.getContext();
10788
10789   // Build some magic constants.
10790   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
10791   Constant *C0 = ConstantDataVector::get(*Context, CV0);
10792   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
10793
10794   SmallVector<Constant*,2> CV1;
10795   CV1.push_back(
10796     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10797                                       APInt(64, 0x4330000000000000ULL))));
10798   CV1.push_back(
10799     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10800                                       APInt(64, 0x4530000000000000ULL))));
10801   Constant *C1 = ConstantVector::get(CV1);
10802   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
10803
10804   // Load the 64-bit value into an XMM register.
10805   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
10806                             Op.getOperand(0));
10807   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
10808                               MachinePointerInfo::getConstantPool(),
10809                               false, false, false, 16);
10810   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
10811                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
10812                               CLod0);
10813
10814   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
10815                               MachinePointerInfo::getConstantPool(),
10816                               false, false, false, 16);
10817   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
10818   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
10819   SDValue Result;
10820
10821   if (Subtarget->hasSSE3()) {
10822     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
10823     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
10824   } else {
10825     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
10826     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
10827                                            S2F, 0x4E, DAG);
10828     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
10829                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
10830                          Sub);
10831   }
10832
10833   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
10834                      DAG.getIntPtrConstant(0));
10835 }
10836
10837 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
10838 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
10839                                                SelectionDAG &DAG) const {
10840   SDLoc dl(Op);
10841   // FP constant to bias correct the final result.
10842   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
10843                                    MVT::f64);
10844
10845   // Load the 32-bit value into an XMM register.
10846   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
10847                              Op.getOperand(0));
10848
10849   // Zero out the upper parts of the register.
10850   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
10851
10852   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10853                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
10854                      DAG.getIntPtrConstant(0));
10855
10856   // Or the load with the bias.
10857   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
10858                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10859                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10860                                                    MVT::v2f64, Load)),
10861                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
10862                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
10863                                                    MVT::v2f64, Bias)));
10864   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
10865                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
10866                    DAG.getIntPtrConstant(0));
10867
10868   // Subtract the bias.
10869   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
10870
10871   // Handle final rounding.
10872   EVT DestVT = Op.getValueType();
10873
10874   if (DestVT.bitsLT(MVT::f64))
10875     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
10876                        DAG.getIntPtrConstant(0));
10877   if (DestVT.bitsGT(MVT::f64))
10878     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
10879
10880   // Handle final rounding.
10881   return Sub;
10882 }
10883
10884 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
10885                                                SelectionDAG &DAG) const {
10886   SDValue N0 = Op.getOperand(0);
10887   MVT SVT = N0.getSimpleValueType();
10888   SDLoc dl(Op);
10889
10890   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
10891           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
10892          "Custom UINT_TO_FP is not supported!");
10893
10894   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
10895   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
10896                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
10897 }
10898
10899 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
10900                                            SelectionDAG &DAG) const {
10901   SDValue N0 = Op.getOperand(0);
10902   SDLoc dl(Op);
10903
10904   if (Op.getValueType().isVector())
10905     return lowerUINT_TO_FP_vec(Op, DAG);
10906
10907   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
10908   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
10909   // the optimization here.
10910   if (DAG.SignBitIsZero(N0))
10911     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
10912
10913   MVT SrcVT = N0.getSimpleValueType();
10914   MVT DstVT = Op.getSimpleValueType();
10915   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
10916     return LowerUINT_TO_FP_i64(Op, DAG);
10917   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
10918     return LowerUINT_TO_FP_i32(Op, DAG);
10919   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
10920     return SDValue();
10921
10922   // Make a 64-bit buffer, and use it to build an FILD.
10923   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
10924   if (SrcVT == MVT::i32) {
10925     SDValue WordOff = DAG.getConstant(4, getPointerTy());
10926     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
10927                                      getPointerTy(), StackSlot, WordOff);
10928     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10929                                   StackSlot, MachinePointerInfo(),
10930                                   false, false, 0);
10931     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
10932                                   OffsetSlot, MachinePointerInfo(),
10933                                   false, false, 0);
10934     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
10935     return Fild;
10936   }
10937
10938   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
10939   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
10940                                StackSlot, MachinePointerInfo(),
10941                                false, false, 0);
10942   // For i64 source, we need to add the appropriate power of 2 if the input
10943   // was negative.  This is the same as the optimization in
10944   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
10945   // we must be careful to do the computation in x87 extended precision, not
10946   // in SSE. (The generic code can't know it's OK to do this, or how to.)
10947   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
10948   MachineMemOperand *MMO =
10949     DAG.getMachineFunction()
10950     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
10951                           MachineMemOperand::MOLoad, 8, 8);
10952
10953   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
10954   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
10955   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
10956                                          MVT::i64, MMO);
10957
10958   APInt FF(32, 0x5F800000ULL);
10959
10960   // Check whether the sign bit is set.
10961   SDValue SignSet = DAG.getSetCC(dl,
10962                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
10963                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
10964                                  ISD::SETLT);
10965
10966   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
10967   SDValue FudgePtr = DAG.getConstantPool(
10968                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
10969                                          getPointerTy());
10970
10971   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
10972   SDValue Zero = DAG.getIntPtrConstant(0);
10973   SDValue Four = DAG.getIntPtrConstant(4);
10974   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
10975                                Zero, Four);
10976   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
10977
10978   // Load the value out, extending it from f32 to f80.
10979   // FIXME: Avoid the extend by constructing the right constant pool?
10980   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
10981                                  FudgePtr, MachinePointerInfo::getConstantPool(),
10982                                  MVT::f32, false, false, 4);
10983   // Extend everything to 80 bits to force it to be done on x87.
10984   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
10985   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
10986 }
10987
10988 std::pair<SDValue,SDValue>
10989 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
10990                                     bool IsSigned, bool IsReplace) const {
10991   SDLoc DL(Op);
10992
10993   EVT DstTy = Op.getValueType();
10994
10995   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
10996     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
10997     DstTy = MVT::i64;
10998   }
10999
11000   assert(DstTy.getSimpleVT() <= MVT::i64 &&
11001          DstTy.getSimpleVT() >= MVT::i16 &&
11002          "Unknown FP_TO_INT to lower!");
11003
11004   // These are really Legal.
11005   if (DstTy == MVT::i32 &&
11006       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11007     return std::make_pair(SDValue(), SDValue());
11008   if (Subtarget->is64Bit() &&
11009       DstTy == MVT::i64 &&
11010       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
11011     return std::make_pair(SDValue(), SDValue());
11012
11013   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
11014   // stack slot, or into the FTOL runtime function.
11015   MachineFunction &MF = DAG.getMachineFunction();
11016   unsigned MemSize = DstTy.getSizeInBits()/8;
11017   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11018   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11019
11020   unsigned Opc;
11021   if (!IsSigned && isIntegerTypeFTOL(DstTy))
11022     Opc = X86ISD::WIN_FTOL;
11023   else
11024     switch (DstTy.getSimpleVT().SimpleTy) {
11025     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
11026     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
11027     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
11028     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
11029     }
11030
11031   SDValue Chain = DAG.getEntryNode();
11032   SDValue Value = Op.getOperand(0);
11033   EVT TheVT = Op.getOperand(0).getValueType();
11034   // FIXME This causes a redundant load/store if the SSE-class value is already
11035   // in memory, such as if it is on the callstack.
11036   if (isScalarFPTypeInSSEReg(TheVT)) {
11037     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
11038     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
11039                          MachinePointerInfo::getFixedStack(SSFI),
11040                          false, false, 0);
11041     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
11042     SDValue Ops[] = {
11043       Chain, StackSlot, DAG.getValueType(TheVT)
11044     };
11045
11046     MachineMemOperand *MMO =
11047       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11048                               MachineMemOperand::MOLoad, MemSize, MemSize);
11049     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
11050     Chain = Value.getValue(1);
11051     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
11052     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11053   }
11054
11055   MachineMemOperand *MMO =
11056     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11057                             MachineMemOperand::MOStore, MemSize, MemSize);
11058
11059   if (Opc != X86ISD::WIN_FTOL) {
11060     // Build the FP_TO_INT*_IN_MEM
11061     SDValue Ops[] = { Chain, Value, StackSlot };
11062     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
11063                                            Ops, DstTy, MMO);
11064     return std::make_pair(FIST, StackSlot);
11065   } else {
11066     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
11067       DAG.getVTList(MVT::Other, MVT::Glue),
11068       Chain, Value);
11069     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
11070       MVT::i32, ftol.getValue(1));
11071     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
11072       MVT::i32, eax.getValue(2));
11073     SDValue Ops[] = { eax, edx };
11074     SDValue pair = IsReplace
11075       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
11076       : DAG.getMergeValues(Ops, DL);
11077     return std::make_pair(pair, SDValue());
11078   }
11079 }
11080
11081 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
11082                               const X86Subtarget *Subtarget) {
11083   MVT VT = Op->getSimpleValueType(0);
11084   SDValue In = Op->getOperand(0);
11085   MVT InVT = In.getSimpleValueType();
11086   SDLoc dl(Op);
11087
11088   // Optimize vectors in AVX mode:
11089   //
11090   //   v8i16 -> v8i32
11091   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
11092   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
11093   //   Concat upper and lower parts.
11094   //
11095   //   v4i32 -> v4i64
11096   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
11097   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
11098   //   Concat upper and lower parts.
11099   //
11100
11101   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
11102       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
11103       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
11104     return SDValue();
11105
11106   if (Subtarget->hasInt256())
11107     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
11108
11109   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
11110   SDValue Undef = DAG.getUNDEF(InVT);
11111   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
11112   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11113   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
11114
11115   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
11116                              VT.getVectorNumElements()/2);
11117
11118   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
11119   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
11120
11121   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11122 }
11123
11124 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
11125                                         SelectionDAG &DAG) {
11126   MVT VT = Op->getSimpleValueType(0);
11127   SDValue In = Op->getOperand(0);
11128   MVT InVT = In.getSimpleValueType();
11129   SDLoc DL(Op);
11130   unsigned int NumElts = VT.getVectorNumElements();
11131   if (NumElts != 8 && NumElts != 16)
11132     return SDValue();
11133
11134   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11135     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
11136
11137   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
11138   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11139   // Now we have only mask extension
11140   assert(InVT.getVectorElementType() == MVT::i1);
11141   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
11142   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11143   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11144   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11145   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11146                            MachinePointerInfo::getConstantPool(),
11147                            false, false, false, Alignment);
11148
11149   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
11150   if (VT.is512BitVector())
11151     return Brcst;
11152   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
11153 }
11154
11155 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11156                                SelectionDAG &DAG) {
11157   if (Subtarget->hasFp256()) {
11158     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11159     if (Res.getNode())
11160       return Res;
11161   }
11162
11163   return SDValue();
11164 }
11165
11166 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11167                                 SelectionDAG &DAG) {
11168   SDLoc DL(Op);
11169   MVT VT = Op.getSimpleValueType();
11170   SDValue In = Op.getOperand(0);
11171   MVT SVT = In.getSimpleValueType();
11172
11173   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
11174     return LowerZERO_EXTEND_AVX512(Op, DAG);
11175
11176   if (Subtarget->hasFp256()) {
11177     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
11178     if (Res.getNode())
11179       return Res;
11180   }
11181
11182   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
11183          VT.getVectorNumElements() != SVT.getVectorNumElements());
11184   return SDValue();
11185 }
11186
11187 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
11188   SDLoc DL(Op);
11189   MVT VT = Op.getSimpleValueType();
11190   SDValue In = Op.getOperand(0);
11191   MVT InVT = In.getSimpleValueType();
11192
11193   if (VT == MVT::i1) {
11194     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
11195            "Invalid scalar TRUNCATE operation");
11196     if (InVT == MVT::i32)
11197       return SDValue();
11198     if (InVT.getSizeInBits() == 64)
11199       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
11200     else if (InVT.getSizeInBits() < 32)
11201       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
11202     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
11203   }
11204   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
11205          "Invalid TRUNCATE operation");
11206
11207   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
11208     if (VT.getVectorElementType().getSizeInBits() >=8)
11209       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
11210
11211     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11212     unsigned NumElts = InVT.getVectorNumElements();
11213     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
11214     if (InVT.getSizeInBits() < 512) {
11215       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
11216       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
11217       InVT = ExtVT;
11218     }
11219     
11220     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
11221     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
11222     SDValue CP = DAG.getConstantPool(C, getPointerTy());
11223     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11224     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
11225                            MachinePointerInfo::getConstantPool(),
11226                            false, false, false, Alignment);
11227     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
11228     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
11229     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
11230   }
11231
11232   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
11233     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
11234     if (Subtarget->hasInt256()) {
11235       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
11236       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
11237       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
11238                                 ShufMask);
11239       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
11240                          DAG.getIntPtrConstant(0));
11241     }
11242
11243     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11244                                DAG.getIntPtrConstant(0));
11245     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11246                                DAG.getIntPtrConstant(2));
11247     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11248     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11249     static const int ShufMask[] = {0, 2, 4, 6};
11250     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
11251   }
11252
11253   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
11254     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
11255     if (Subtarget->hasInt256()) {
11256       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
11257
11258       SmallVector<SDValue,32> pshufbMask;
11259       for (unsigned i = 0; i < 2; ++i) {
11260         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
11261         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
11262         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
11263         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
11264         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
11265         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
11266         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
11267         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
11268         for (unsigned j = 0; j < 8; ++j)
11269           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
11270       }
11271       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
11272       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
11273       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
11274
11275       static const int ShufMask[] = {0,  2,  -1,  -1};
11276       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
11277                                 &ShufMask[0]);
11278       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
11279                        DAG.getIntPtrConstant(0));
11280       return DAG.getNode(ISD::BITCAST, DL, VT, In);
11281     }
11282
11283     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11284                                DAG.getIntPtrConstant(0));
11285
11286     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
11287                                DAG.getIntPtrConstant(4));
11288
11289     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
11290     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
11291
11292     // The PSHUFB mask:
11293     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
11294                                    -1, -1, -1, -1, -1, -1, -1, -1};
11295
11296     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
11297     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
11298     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
11299
11300     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
11301     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
11302
11303     // The MOVLHPS Mask:
11304     static const int ShufMask2[] = {0, 1, 4, 5};
11305     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
11306     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
11307   }
11308
11309   // Handle truncation of V256 to V128 using shuffles.
11310   if (!VT.is128BitVector() || !InVT.is256BitVector())
11311     return SDValue();
11312
11313   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
11314
11315   unsigned NumElems = VT.getVectorNumElements();
11316   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
11317
11318   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
11319   // Prepare truncation shuffle mask
11320   for (unsigned i = 0; i != NumElems; ++i)
11321     MaskVec[i] = i * 2;
11322   SDValue V = DAG.getVectorShuffle(NVT, DL,
11323                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
11324                                    DAG.getUNDEF(NVT), &MaskVec[0]);
11325   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
11326                      DAG.getIntPtrConstant(0));
11327 }
11328
11329 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
11330                                            SelectionDAG &DAG) const {
11331   assert(!Op.getSimpleValueType().isVector());
11332
11333   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11334     /*IsSigned=*/ true, /*IsReplace=*/ false);
11335   SDValue FIST = Vals.first, StackSlot = Vals.second;
11336   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
11337   if (!FIST.getNode()) return Op;
11338
11339   if (StackSlot.getNode())
11340     // Load the result.
11341     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11342                        FIST, StackSlot, MachinePointerInfo(),
11343                        false, false, false, 0);
11344
11345   // The node is the result.
11346   return FIST;
11347 }
11348
11349 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
11350                                            SelectionDAG &DAG) const {
11351   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
11352     /*IsSigned=*/ false, /*IsReplace=*/ false);
11353   SDValue FIST = Vals.first, StackSlot = Vals.second;
11354   assert(FIST.getNode() && "Unexpected failure");
11355
11356   if (StackSlot.getNode())
11357     // Load the result.
11358     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
11359                        FIST, StackSlot, MachinePointerInfo(),
11360                        false, false, false, 0);
11361
11362   // The node is the result.
11363   return FIST;
11364 }
11365
11366 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
11367   SDLoc DL(Op);
11368   MVT VT = Op.getSimpleValueType();
11369   SDValue In = Op.getOperand(0);
11370   MVT SVT = In.getSimpleValueType();
11371
11372   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
11373
11374   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
11375                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
11376                                  In, DAG.getUNDEF(SVT)));
11377 }
11378
11379 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
11380   LLVMContext *Context = DAG.getContext();
11381   SDLoc dl(Op);
11382   MVT VT = Op.getSimpleValueType();
11383   MVT EltVT = VT;
11384   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11385   if (VT.isVector()) {
11386     EltVT = VT.getVectorElementType();
11387     NumElts = VT.getVectorNumElements();
11388   }
11389   Constant *C;
11390   if (EltVT == MVT::f64)
11391     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11392                                           APInt(64, ~(1ULL << 63))));
11393   else
11394     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11395                                           APInt(32, ~(1U << 31))));
11396   C = ConstantVector::getSplat(NumElts, C);
11397   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11398   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11399   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11400   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11401                              MachinePointerInfo::getConstantPool(),
11402                              false, false, false, Alignment);
11403   if (VT.isVector()) {
11404     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11405     return DAG.getNode(ISD::BITCAST, dl, VT,
11406                        DAG.getNode(ISD::AND, dl, ANDVT,
11407                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
11408                                                Op.getOperand(0)),
11409                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
11410   }
11411   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
11412 }
11413
11414 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
11415   LLVMContext *Context = DAG.getContext();
11416   SDLoc dl(Op);
11417   MVT VT = Op.getSimpleValueType();
11418   MVT EltVT = VT;
11419   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
11420   if (VT.isVector()) {
11421     EltVT = VT.getVectorElementType();
11422     NumElts = VT.getVectorNumElements();
11423   }
11424   Constant *C;
11425   if (EltVT == MVT::f64)
11426     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11427                                           APInt(64, 1ULL << 63)));
11428   else
11429     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
11430                                           APInt(32, 1U << 31)));
11431   C = ConstantVector::getSplat(NumElts, C);
11432   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11433   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
11434   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11435   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11436                              MachinePointerInfo::getConstantPool(),
11437                              false, false, false, Alignment);
11438   if (VT.isVector()) {
11439     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
11440     return DAG.getNode(ISD::BITCAST, dl, VT,
11441                        DAG.getNode(ISD::XOR, dl, XORVT,
11442                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
11443                                                Op.getOperand(0)),
11444                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
11445   }
11446
11447   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
11448 }
11449
11450 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
11451   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11452   LLVMContext *Context = DAG.getContext();
11453   SDValue Op0 = Op.getOperand(0);
11454   SDValue Op1 = Op.getOperand(1);
11455   SDLoc dl(Op);
11456   MVT VT = Op.getSimpleValueType();
11457   MVT SrcVT = Op1.getSimpleValueType();
11458
11459   // If second operand is smaller, extend it first.
11460   if (SrcVT.bitsLT(VT)) {
11461     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
11462     SrcVT = VT;
11463   }
11464   // And if it is bigger, shrink it first.
11465   if (SrcVT.bitsGT(VT)) {
11466     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
11467     SrcVT = VT;
11468   }
11469
11470   // At this point the operands and the result should have the same
11471   // type, and that won't be f80 since that is not custom lowered.
11472
11473   // First get the sign bit of second operand.
11474   SmallVector<Constant*,4> CV;
11475   if (SrcVT == MVT::f64) {
11476     const fltSemantics &Sem = APFloat::IEEEdouble;
11477     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
11478     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11479   } else {
11480     const fltSemantics &Sem = APFloat::IEEEsingle;
11481     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
11482     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11483     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11484     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11485   }
11486   Constant *C = ConstantVector::get(CV);
11487   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11488   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
11489                               MachinePointerInfo::getConstantPool(),
11490                               false, false, false, 16);
11491   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
11492
11493   // Shift sign bit right or left if the two operands have different types.
11494   if (SrcVT.bitsGT(VT)) {
11495     // Op0 is MVT::f32, Op1 is MVT::f64.
11496     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
11497     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
11498                           DAG.getConstant(32, MVT::i32));
11499     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
11500     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
11501                           DAG.getIntPtrConstant(0));
11502   }
11503
11504   // Clear first operand sign bit.
11505   CV.clear();
11506   if (VT == MVT::f64) {
11507     const fltSemantics &Sem = APFloat::IEEEdouble;
11508     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11509                                                    APInt(64, ~(1ULL << 63)))));
11510     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
11511   } else {
11512     const fltSemantics &Sem = APFloat::IEEEsingle;
11513     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
11514                                                    APInt(32, ~(1U << 31)))));
11515     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11516     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11517     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
11518   }
11519   C = ConstantVector::get(CV);
11520   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
11521   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
11522                               MachinePointerInfo::getConstantPool(),
11523                               false, false, false, 16);
11524   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
11525
11526   // Or the value with the sign bit.
11527   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
11528 }
11529
11530 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
11531   SDValue N0 = Op.getOperand(0);
11532   SDLoc dl(Op);
11533   MVT VT = Op.getSimpleValueType();
11534
11535   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
11536   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
11537                                   DAG.getConstant(1, VT));
11538   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
11539 }
11540
11541 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
11542 //
11543 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
11544                                       SelectionDAG &DAG) {
11545   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
11546
11547   if (!Subtarget->hasSSE41())
11548     return SDValue();
11549
11550   if (!Op->hasOneUse())
11551     return SDValue();
11552
11553   SDNode *N = Op.getNode();
11554   SDLoc DL(N);
11555
11556   SmallVector<SDValue, 8> Opnds;
11557   DenseMap<SDValue, unsigned> VecInMap;
11558   SmallVector<SDValue, 8> VecIns;
11559   EVT VT = MVT::Other;
11560
11561   // Recognize a special case where a vector is casted into wide integer to
11562   // test all 0s.
11563   Opnds.push_back(N->getOperand(0));
11564   Opnds.push_back(N->getOperand(1));
11565
11566   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
11567     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
11568     // BFS traverse all OR'd operands.
11569     if (I->getOpcode() == ISD::OR) {
11570       Opnds.push_back(I->getOperand(0));
11571       Opnds.push_back(I->getOperand(1));
11572       // Re-evaluate the number of nodes to be traversed.
11573       e += 2; // 2 more nodes (LHS and RHS) are pushed.
11574       continue;
11575     }
11576
11577     // Quit if a non-EXTRACT_VECTOR_ELT
11578     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
11579       return SDValue();
11580
11581     // Quit if without a constant index.
11582     SDValue Idx = I->getOperand(1);
11583     if (!isa<ConstantSDNode>(Idx))
11584       return SDValue();
11585
11586     SDValue ExtractedFromVec = I->getOperand(0);
11587     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
11588     if (M == VecInMap.end()) {
11589       VT = ExtractedFromVec.getValueType();
11590       // Quit if not 128/256-bit vector.
11591       if (!VT.is128BitVector() && !VT.is256BitVector())
11592         return SDValue();
11593       // Quit if not the same type.
11594       if (VecInMap.begin() != VecInMap.end() &&
11595           VT != VecInMap.begin()->first.getValueType())
11596         return SDValue();
11597       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
11598       VecIns.push_back(ExtractedFromVec);
11599     }
11600     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
11601   }
11602
11603   assert((VT.is128BitVector() || VT.is256BitVector()) &&
11604          "Not extracted from 128-/256-bit vector.");
11605
11606   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
11607
11608   for (DenseMap<SDValue, unsigned>::const_iterator
11609         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
11610     // Quit if not all elements are used.
11611     if (I->second != FullMask)
11612       return SDValue();
11613   }
11614
11615   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
11616
11617   // Cast all vectors into TestVT for PTEST.
11618   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
11619     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
11620
11621   // If more than one full vectors are evaluated, OR them first before PTEST.
11622   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
11623     // Each iteration will OR 2 nodes and append the result until there is only
11624     // 1 node left, i.e. the final OR'd value of all vectors.
11625     SDValue LHS = VecIns[Slot];
11626     SDValue RHS = VecIns[Slot + 1];
11627     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
11628   }
11629
11630   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
11631                      VecIns.back(), VecIns.back());
11632 }
11633
11634 /// \brief return true if \c Op has a use that doesn't just read flags.
11635 static bool hasNonFlagsUse(SDValue Op) {
11636   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
11637        ++UI) {
11638     SDNode *User = *UI;
11639     unsigned UOpNo = UI.getOperandNo();
11640     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
11641       // Look pass truncate.
11642       UOpNo = User->use_begin().getOperandNo();
11643       User = *User->use_begin();
11644     }
11645
11646     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
11647         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
11648       return true;
11649   }
11650   return false;
11651 }
11652
11653 /// Emit nodes that will be selected as "test Op0,Op0", or something
11654 /// equivalent.
11655 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
11656                                     SelectionDAG &DAG) const {
11657   if (Op.getValueType() == MVT::i1)
11658     // KORTEST instruction should be selected
11659     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11660                        DAG.getConstant(0, Op.getValueType()));
11661
11662   // CF and OF aren't always set the way we want. Determine which
11663   // of these we need.
11664   bool NeedCF = false;
11665   bool NeedOF = false;
11666   switch (X86CC) {
11667   default: break;
11668   case X86::COND_A: case X86::COND_AE:
11669   case X86::COND_B: case X86::COND_BE:
11670     NeedCF = true;
11671     break;
11672   case X86::COND_G: case X86::COND_GE:
11673   case X86::COND_L: case X86::COND_LE:
11674   case X86::COND_O: case X86::COND_NO: {
11675     // Check if we really need to set the
11676     // Overflow flag. If NoSignedWrap is present
11677     // that is not actually needed.
11678     switch (Op->getOpcode()) {
11679     case ISD::ADD:
11680     case ISD::SUB:
11681     case ISD::MUL:
11682     case ISD::SHL: {
11683       const BinaryWithFlagsSDNode *BinNode =
11684           cast<BinaryWithFlagsSDNode>(Op.getNode());
11685       if (BinNode->hasNoSignedWrap())
11686         break;
11687     }
11688     default:
11689       NeedOF = true;
11690       break;
11691     }
11692     break;
11693   }
11694   }
11695   // See if we can use the EFLAGS value from the operand instead of
11696   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
11697   // we prove that the arithmetic won't overflow, we can't use OF or CF.
11698   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
11699     // Emit a CMP with 0, which is the TEST pattern.
11700     //if (Op.getValueType() == MVT::i1)
11701     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
11702     //                     DAG.getConstant(0, MVT::i1));
11703     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11704                        DAG.getConstant(0, Op.getValueType()));
11705   }
11706   unsigned Opcode = 0;
11707   unsigned NumOperands = 0;
11708
11709   // Truncate operations may prevent the merge of the SETCC instruction
11710   // and the arithmetic instruction before it. Attempt to truncate the operands
11711   // of the arithmetic instruction and use a reduced bit-width instruction.
11712   bool NeedTruncation = false;
11713   SDValue ArithOp = Op;
11714   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
11715     SDValue Arith = Op->getOperand(0);
11716     // Both the trunc and the arithmetic op need to have one user each.
11717     if (Arith->hasOneUse())
11718       switch (Arith.getOpcode()) {
11719         default: break;
11720         case ISD::ADD:
11721         case ISD::SUB:
11722         case ISD::AND:
11723         case ISD::OR:
11724         case ISD::XOR: {
11725           NeedTruncation = true;
11726           ArithOp = Arith;
11727         }
11728       }
11729   }
11730
11731   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
11732   // which may be the result of a CAST.  We use the variable 'Op', which is the
11733   // non-casted variable when we check for possible users.
11734   switch (ArithOp.getOpcode()) {
11735   case ISD::ADD:
11736     // Due to an isel shortcoming, be conservative if this add is likely to be
11737     // selected as part of a load-modify-store instruction. When the root node
11738     // in a match is a store, isel doesn't know how to remap non-chain non-flag
11739     // uses of other nodes in the match, such as the ADD in this case. This
11740     // leads to the ADD being left around and reselected, with the result being
11741     // two adds in the output.  Alas, even if none our users are stores, that
11742     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
11743     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
11744     // climbing the DAG back to the root, and it doesn't seem to be worth the
11745     // effort.
11746     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11747          UE = Op.getNode()->use_end(); UI != UE; ++UI)
11748       if (UI->getOpcode() != ISD::CopyToReg &&
11749           UI->getOpcode() != ISD::SETCC &&
11750           UI->getOpcode() != ISD::STORE)
11751         goto default_case;
11752
11753     if (ConstantSDNode *C =
11754         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
11755       // An add of one will be selected as an INC.
11756       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
11757         Opcode = X86ISD::INC;
11758         NumOperands = 1;
11759         break;
11760       }
11761
11762       // An add of negative one (subtract of one) will be selected as a DEC.
11763       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
11764         Opcode = X86ISD::DEC;
11765         NumOperands = 1;
11766         break;
11767       }
11768     }
11769
11770     // Otherwise use a regular EFLAGS-setting add.
11771     Opcode = X86ISD::ADD;
11772     NumOperands = 2;
11773     break;
11774   case ISD::SHL:
11775   case ISD::SRL:
11776     // If we have a constant logical shift that's only used in a comparison
11777     // against zero turn it into an equivalent AND. This allows turning it into
11778     // a TEST instruction later.
11779     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
11780         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
11781       EVT VT = Op.getValueType();
11782       unsigned BitWidth = VT.getSizeInBits();
11783       unsigned ShAmt = Op->getConstantOperandVal(1);
11784       if (ShAmt >= BitWidth) // Avoid undefined shifts.
11785         break;
11786       APInt Mask = ArithOp.getOpcode() == ISD::SRL
11787                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
11788                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
11789       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
11790         break;
11791       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
11792                                 DAG.getConstant(Mask, VT));
11793       DAG.ReplaceAllUsesWith(Op, New);
11794       Op = New;
11795     }
11796     break;
11797
11798   case ISD::AND:
11799     // If the primary and result isn't used, don't bother using X86ISD::AND,
11800     // because a TEST instruction will be better.
11801     if (!hasNonFlagsUse(Op))
11802       break;
11803     // FALL THROUGH
11804   case ISD::SUB:
11805   case ISD::OR:
11806   case ISD::XOR:
11807     // Due to the ISEL shortcoming noted above, be conservative if this op is
11808     // likely to be selected as part of a load-modify-store instruction.
11809     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
11810            UE = Op.getNode()->use_end(); UI != UE; ++UI)
11811       if (UI->getOpcode() == ISD::STORE)
11812         goto default_case;
11813
11814     // Otherwise use a regular EFLAGS-setting instruction.
11815     switch (ArithOp.getOpcode()) {
11816     default: llvm_unreachable("unexpected operator!");
11817     case ISD::SUB: Opcode = X86ISD::SUB; break;
11818     case ISD::XOR: Opcode = X86ISD::XOR; break;
11819     case ISD::AND: Opcode = X86ISD::AND; break;
11820     case ISD::OR: {
11821       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
11822         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
11823         if (EFLAGS.getNode())
11824           return EFLAGS;
11825       }
11826       Opcode = X86ISD::OR;
11827       break;
11828     }
11829     }
11830
11831     NumOperands = 2;
11832     break;
11833   case X86ISD::ADD:
11834   case X86ISD::SUB:
11835   case X86ISD::INC:
11836   case X86ISD::DEC:
11837   case X86ISD::OR:
11838   case X86ISD::XOR:
11839   case X86ISD::AND:
11840     return SDValue(Op.getNode(), 1);
11841   default:
11842   default_case:
11843     break;
11844   }
11845
11846   // If we found that truncation is beneficial, perform the truncation and
11847   // update 'Op'.
11848   if (NeedTruncation) {
11849     EVT VT = Op.getValueType();
11850     SDValue WideVal = Op->getOperand(0);
11851     EVT WideVT = WideVal.getValueType();
11852     unsigned ConvertedOp = 0;
11853     // Use a target machine opcode to prevent further DAGCombine
11854     // optimizations that may separate the arithmetic operations
11855     // from the setcc node.
11856     switch (WideVal.getOpcode()) {
11857       default: break;
11858       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
11859       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
11860       case ISD::AND: ConvertedOp = X86ISD::AND; break;
11861       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
11862       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
11863     }
11864
11865     if (ConvertedOp) {
11866       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11867       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
11868         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
11869         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
11870         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
11871       }
11872     }
11873   }
11874
11875   if (Opcode == 0)
11876     // Emit a CMP with 0, which is the TEST pattern.
11877     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
11878                        DAG.getConstant(0, Op.getValueType()));
11879
11880   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
11881   SmallVector<SDValue, 4> Ops;
11882   for (unsigned i = 0; i != NumOperands; ++i)
11883     Ops.push_back(Op.getOperand(i));
11884
11885   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
11886   DAG.ReplaceAllUsesWith(Op, New);
11887   return SDValue(New.getNode(), 1);
11888 }
11889
11890 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
11891 /// equivalent.
11892 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
11893                                    SDLoc dl, SelectionDAG &DAG) const {
11894   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
11895     if (C->getAPIntValue() == 0)
11896       return EmitTest(Op0, X86CC, dl, DAG);
11897
11898      if (Op0.getValueType() == MVT::i1)
11899        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
11900   }
11901  
11902   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
11903        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
11904     // Do the comparison at i32 if it's smaller, besides the Atom case. 
11905     // This avoids subregister aliasing issues. Keep the smaller reference 
11906     // if we're optimizing for size, however, as that'll allow better folding 
11907     // of memory operations.
11908     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
11909         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
11910              AttributeSet::FunctionIndex, Attribute::MinSize) &&
11911         !Subtarget->isAtom()) {
11912       unsigned ExtendOp =
11913           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
11914       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
11915       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
11916     }
11917     // Use SUB instead of CMP to enable CSE between SUB and CMP.
11918     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
11919     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
11920                               Op0, Op1);
11921     return SDValue(Sub.getNode(), 1);
11922   }
11923   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
11924 }
11925
11926 /// Convert a comparison if required by the subtarget.
11927 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
11928                                                  SelectionDAG &DAG) const {
11929   // If the subtarget does not support the FUCOMI instruction, floating-point
11930   // comparisons have to be converted.
11931   if (Subtarget->hasCMov() ||
11932       Cmp.getOpcode() != X86ISD::CMP ||
11933       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
11934       !Cmp.getOperand(1).getValueType().isFloatingPoint())
11935     return Cmp;
11936
11937   // The instruction selector will select an FUCOM instruction instead of
11938   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
11939   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
11940   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
11941   SDLoc dl(Cmp);
11942   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
11943   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
11944   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
11945                             DAG.getConstant(8, MVT::i8));
11946   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
11947   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
11948 }
11949
11950 static bool isAllOnes(SDValue V) {
11951   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
11952   return C && C->isAllOnesValue();
11953 }
11954
11955 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
11956 /// if it's possible.
11957 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
11958                                      SDLoc dl, SelectionDAG &DAG) const {
11959   SDValue Op0 = And.getOperand(0);
11960   SDValue Op1 = And.getOperand(1);
11961   if (Op0.getOpcode() == ISD::TRUNCATE)
11962     Op0 = Op0.getOperand(0);
11963   if (Op1.getOpcode() == ISD::TRUNCATE)
11964     Op1 = Op1.getOperand(0);
11965
11966   SDValue LHS, RHS;
11967   if (Op1.getOpcode() == ISD::SHL)
11968     std::swap(Op0, Op1);
11969   if (Op0.getOpcode() == ISD::SHL) {
11970     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
11971       if (And00C->getZExtValue() == 1) {
11972         // If we looked past a truncate, check that it's only truncating away
11973         // known zeros.
11974         unsigned BitWidth = Op0.getValueSizeInBits();
11975         unsigned AndBitWidth = And.getValueSizeInBits();
11976         if (BitWidth > AndBitWidth) {
11977           APInt Zeros, Ones;
11978           DAG.computeKnownBits(Op0, Zeros, Ones);
11979           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
11980             return SDValue();
11981         }
11982         LHS = Op1;
11983         RHS = Op0.getOperand(1);
11984       }
11985   } else if (Op1.getOpcode() == ISD::Constant) {
11986     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
11987     uint64_t AndRHSVal = AndRHS->getZExtValue();
11988     SDValue AndLHS = Op0;
11989
11990     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
11991       LHS = AndLHS.getOperand(0);
11992       RHS = AndLHS.getOperand(1);
11993     }
11994
11995     // Use BT if the immediate can't be encoded in a TEST instruction.
11996     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
11997       LHS = AndLHS;
11998       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
11999     }
12000   }
12001
12002   if (LHS.getNode()) {
12003     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
12004     // instruction.  Since the shift amount is in-range-or-undefined, we know
12005     // that doing a bittest on the i32 value is ok.  We extend to i32 because
12006     // the encoding for the i16 version is larger than the i32 version.
12007     // Also promote i16 to i32 for performance / code size reason.
12008     if (LHS.getValueType() == MVT::i8 ||
12009         LHS.getValueType() == MVT::i16)
12010       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
12011
12012     // If the operand types disagree, extend the shift amount to match.  Since
12013     // BT ignores high bits (like shifts) we can use anyextend.
12014     if (LHS.getValueType() != RHS.getValueType())
12015       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
12016
12017     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
12018     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
12019     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12020                        DAG.getConstant(Cond, MVT::i8), BT);
12021   }
12022
12023   return SDValue();
12024 }
12025
12026 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
12027 /// mask CMPs.
12028 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
12029                               SDValue &Op1) {
12030   unsigned SSECC;
12031   bool Swap = false;
12032
12033   // SSE Condition code mapping:
12034   //  0 - EQ
12035   //  1 - LT
12036   //  2 - LE
12037   //  3 - UNORD
12038   //  4 - NEQ
12039   //  5 - NLT
12040   //  6 - NLE
12041   //  7 - ORD
12042   switch (SetCCOpcode) {
12043   default: llvm_unreachable("Unexpected SETCC condition");
12044   case ISD::SETOEQ:
12045   case ISD::SETEQ:  SSECC = 0; break;
12046   case ISD::SETOGT:
12047   case ISD::SETGT:  Swap = true; // Fallthrough
12048   case ISD::SETLT:
12049   case ISD::SETOLT: SSECC = 1; break;
12050   case ISD::SETOGE:
12051   case ISD::SETGE:  Swap = true; // Fallthrough
12052   case ISD::SETLE:
12053   case ISD::SETOLE: SSECC = 2; break;
12054   case ISD::SETUO:  SSECC = 3; break;
12055   case ISD::SETUNE:
12056   case ISD::SETNE:  SSECC = 4; break;
12057   case ISD::SETULE: Swap = true; // Fallthrough
12058   case ISD::SETUGE: SSECC = 5; break;
12059   case ISD::SETULT: Swap = true; // Fallthrough
12060   case ISD::SETUGT: SSECC = 6; break;
12061   case ISD::SETO:   SSECC = 7; break;
12062   case ISD::SETUEQ:
12063   case ISD::SETONE: SSECC = 8; break;
12064   }
12065   if (Swap)
12066     std::swap(Op0, Op1);
12067
12068   return SSECC;
12069 }
12070
12071 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
12072 // ones, and then concatenate the result back.
12073 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
12074   MVT VT = Op.getSimpleValueType();
12075
12076   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
12077          "Unsupported value type for operation");
12078
12079   unsigned NumElems = VT.getVectorNumElements();
12080   SDLoc dl(Op);
12081   SDValue CC = Op.getOperand(2);
12082
12083   // Extract the LHS vectors
12084   SDValue LHS = Op.getOperand(0);
12085   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
12086   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
12087
12088   // Extract the RHS vectors
12089   SDValue RHS = Op.getOperand(1);
12090   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
12091   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
12092
12093   // Issue the operation on the smaller types and concatenate the result back
12094   MVT EltVT = VT.getVectorElementType();
12095   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
12096   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
12097                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
12098                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
12099 }
12100
12101 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
12102                                      const X86Subtarget *Subtarget) {
12103   SDValue Op0 = Op.getOperand(0);
12104   SDValue Op1 = Op.getOperand(1);
12105   SDValue CC = Op.getOperand(2);
12106   MVT VT = Op.getSimpleValueType();
12107   SDLoc dl(Op);
12108
12109   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
12110          Op.getValueType().getScalarType() == MVT::i1 &&
12111          "Cannot set masked compare for this operation");
12112
12113   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12114   unsigned  Opc = 0;
12115   bool Unsigned = false;
12116   bool Swap = false;
12117   unsigned SSECC;
12118   switch (SetCCOpcode) {
12119   default: llvm_unreachable("Unexpected SETCC condition");
12120   case ISD::SETNE:  SSECC = 4; break;
12121   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
12122   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
12123   case ISD::SETLT:  Swap = true; //fall-through
12124   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
12125   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
12126   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
12127   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
12128   case ISD::SETULE: Unsigned = true; //fall-through
12129   case ISD::SETLE:  SSECC = 2; break;
12130   }
12131
12132   if (Swap)
12133     std::swap(Op0, Op1);
12134   if (Opc)
12135     return DAG.getNode(Opc, dl, VT, Op0, Op1);
12136   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
12137   return DAG.getNode(Opc, dl, VT, Op0, Op1,
12138                      DAG.getConstant(SSECC, MVT::i8));
12139 }
12140
12141 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
12142 /// operand \p Op1.  If non-trivial (for example because it's not constant)
12143 /// return an empty value.
12144 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
12145 {
12146   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
12147   if (!BV)
12148     return SDValue();
12149
12150   MVT VT = Op1.getSimpleValueType();
12151   MVT EVT = VT.getVectorElementType();
12152   unsigned n = VT.getVectorNumElements();
12153   SmallVector<SDValue, 8> ULTOp1;
12154
12155   for (unsigned i = 0; i < n; ++i) {
12156     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
12157     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
12158       return SDValue();
12159
12160     // Avoid underflow.
12161     APInt Val = Elt->getAPIntValue();
12162     if (Val == 0)
12163       return SDValue();
12164
12165     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
12166   }
12167
12168   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
12169 }
12170
12171 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
12172                            SelectionDAG &DAG) {
12173   SDValue Op0 = Op.getOperand(0);
12174   SDValue Op1 = Op.getOperand(1);
12175   SDValue CC = Op.getOperand(2);
12176   MVT VT = Op.getSimpleValueType();
12177   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
12178   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
12179   SDLoc dl(Op);
12180
12181   if (isFP) {
12182 #ifndef NDEBUG
12183     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
12184     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
12185 #endif
12186
12187     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
12188     unsigned Opc = X86ISD::CMPP;
12189     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
12190       assert(VT.getVectorNumElements() <= 16);
12191       Opc = X86ISD::CMPM;
12192     }
12193     // In the two special cases we can't handle, emit two comparisons.
12194     if (SSECC == 8) {
12195       unsigned CC0, CC1;
12196       unsigned CombineOpc;
12197       if (SetCCOpcode == ISD::SETUEQ) {
12198         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
12199       } else {
12200         assert(SetCCOpcode == ISD::SETONE);
12201         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
12202       }
12203
12204       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12205                                  DAG.getConstant(CC0, MVT::i8));
12206       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
12207                                  DAG.getConstant(CC1, MVT::i8));
12208       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
12209     }
12210     // Handle all other FP comparisons here.
12211     return DAG.getNode(Opc, dl, VT, Op0, Op1,
12212                        DAG.getConstant(SSECC, MVT::i8));
12213   }
12214
12215   // Break 256-bit integer vector compare into smaller ones.
12216   if (VT.is256BitVector() && !Subtarget->hasInt256())
12217     return Lower256IntVSETCC(Op, DAG);
12218
12219   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
12220   EVT OpVT = Op1.getValueType();
12221   if (Subtarget->hasAVX512()) {
12222     if (Op1.getValueType().is512BitVector() ||
12223         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
12224       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
12225
12226     // In AVX-512 architecture setcc returns mask with i1 elements,
12227     // But there is no compare instruction for i8 and i16 elements.
12228     // We are not talking about 512-bit operands in this case, these
12229     // types are illegal.
12230     if (MaskResult &&
12231         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
12232          OpVT.getVectorElementType().getSizeInBits() >= 8))
12233       return DAG.getNode(ISD::TRUNCATE, dl, VT,
12234                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
12235   }
12236
12237   // We are handling one of the integer comparisons here.  Since SSE only has
12238   // GT and EQ comparisons for integer, swapping operands and multiple
12239   // operations may be required for some comparisons.
12240   unsigned Opc;
12241   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
12242   bool Subus = false;
12243
12244   switch (SetCCOpcode) {
12245   default: llvm_unreachable("Unexpected SETCC condition");
12246   case ISD::SETNE:  Invert = true;
12247   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
12248   case ISD::SETLT:  Swap = true;
12249   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
12250   case ISD::SETGE:  Swap = true;
12251   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
12252                     Invert = true; break;
12253   case ISD::SETULT: Swap = true;
12254   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
12255                     FlipSigns = true; break;
12256   case ISD::SETUGE: Swap = true;
12257   case ISD::SETULE: Opc = X86ISD::PCMPGT;
12258                     FlipSigns = true; Invert = true; break;
12259   }
12260
12261   // Special case: Use min/max operations for SETULE/SETUGE
12262   MVT VET = VT.getVectorElementType();
12263   bool hasMinMax =
12264        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
12265     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
12266
12267   if (hasMinMax) {
12268     switch (SetCCOpcode) {
12269     default: break;
12270     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
12271     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
12272     }
12273
12274     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
12275   }
12276
12277   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
12278   if (!MinMax && hasSubus) {
12279     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
12280     // Op0 u<= Op1:
12281     //   t = psubus Op0, Op1
12282     //   pcmpeq t, <0..0>
12283     switch (SetCCOpcode) {
12284     default: break;
12285     case ISD::SETULT: {
12286       // If the comparison is against a constant we can turn this into a
12287       // setule.  With psubus, setule does not require a swap.  This is
12288       // beneficial because the constant in the register is no longer
12289       // destructed as the destination so it can be hoisted out of a loop.
12290       // Only do this pre-AVX since vpcmp* is no longer destructive.
12291       if (Subtarget->hasAVX())
12292         break;
12293       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
12294       if (ULEOp1.getNode()) {
12295         Op1 = ULEOp1;
12296         Subus = true; Invert = false; Swap = false;
12297       }
12298       break;
12299     }
12300     // Psubus is better than flip-sign because it requires no inversion.
12301     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
12302     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
12303     }
12304
12305     if (Subus) {
12306       Opc = X86ISD::SUBUS;
12307       FlipSigns = false;
12308     }
12309   }
12310
12311   if (Swap)
12312     std::swap(Op0, Op1);
12313
12314   // Check that the operation in question is available (most are plain SSE2,
12315   // but PCMPGTQ and PCMPEQQ have different requirements).
12316   if (VT == MVT::v2i64) {
12317     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
12318       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
12319
12320       // First cast everything to the right type.
12321       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12322       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12323
12324       // Since SSE has no unsigned integer comparisons, we need to flip the sign
12325       // bits of the inputs before performing those operations. The lower
12326       // compare is always unsigned.
12327       SDValue SB;
12328       if (FlipSigns) {
12329         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
12330       } else {
12331         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
12332         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
12333         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
12334                          Sign, Zero, Sign, Zero);
12335       }
12336       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
12337       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
12338
12339       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
12340       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
12341       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
12342
12343       // Create masks for only the low parts/high parts of the 64 bit integers.
12344       static const int MaskHi[] = { 1, 1, 3, 3 };
12345       static const int MaskLo[] = { 0, 0, 2, 2 };
12346       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
12347       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
12348       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
12349
12350       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
12351       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
12352
12353       if (Invert)
12354         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12355
12356       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12357     }
12358
12359     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
12360       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
12361       // pcmpeqd + pshufd + pand.
12362       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
12363
12364       // First cast everything to the right type.
12365       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
12366       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
12367
12368       // Do the compare.
12369       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
12370
12371       // Make sure the lower and upper halves are both all-ones.
12372       static const int Mask[] = { 1, 0, 3, 2 };
12373       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
12374       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
12375
12376       if (Invert)
12377         Result = DAG.getNOT(dl, Result, MVT::v4i32);
12378
12379       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
12380     }
12381   }
12382
12383   // Since SSE has no unsigned integer comparisons, we need to flip the sign
12384   // bits of the inputs before performing those operations.
12385   if (FlipSigns) {
12386     EVT EltVT = VT.getVectorElementType();
12387     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
12388     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
12389     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
12390   }
12391
12392   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
12393
12394   // If the logical-not of the result is required, perform that now.
12395   if (Invert)
12396     Result = DAG.getNOT(dl, Result, VT);
12397
12398   if (MinMax)
12399     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
12400
12401   if (Subus)
12402     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
12403                          getZeroVector(VT, Subtarget, DAG, dl));
12404
12405   return Result;
12406 }
12407
12408 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
12409
12410   MVT VT = Op.getSimpleValueType();
12411
12412   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
12413
12414   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
12415          && "SetCC type must be 8-bit or 1-bit integer");
12416   SDValue Op0 = Op.getOperand(0);
12417   SDValue Op1 = Op.getOperand(1);
12418   SDLoc dl(Op);
12419   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
12420
12421   // Optimize to BT if possible.
12422   // Lower (X & (1 << N)) == 0 to BT(X, N).
12423   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
12424   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
12425   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
12426       Op1.getOpcode() == ISD::Constant &&
12427       cast<ConstantSDNode>(Op1)->isNullValue() &&
12428       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12429     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
12430     if (NewSetCC.getNode())
12431       return NewSetCC;
12432   }
12433
12434   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
12435   // these.
12436   if (Op1.getOpcode() == ISD::Constant &&
12437       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
12438        cast<ConstantSDNode>(Op1)->isNullValue()) &&
12439       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12440
12441     // If the input is a setcc, then reuse the input setcc or use a new one with
12442     // the inverted condition.
12443     if (Op0.getOpcode() == X86ISD::SETCC) {
12444       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
12445       bool Invert = (CC == ISD::SETNE) ^
12446         cast<ConstantSDNode>(Op1)->isNullValue();
12447       if (!Invert)
12448         return Op0;
12449
12450       CCode = X86::GetOppositeBranchCondition(CCode);
12451       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12452                                   DAG.getConstant(CCode, MVT::i8),
12453                                   Op0.getOperand(1));
12454       if (VT == MVT::i1)
12455         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12456       return SetCC;
12457     }
12458   }
12459   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
12460       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
12461       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
12462
12463     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
12464     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
12465   }
12466
12467   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
12468   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
12469   if (X86CC == X86::COND_INVALID)
12470     return SDValue();
12471
12472   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
12473   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
12474   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12475                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
12476   if (VT == MVT::i1)
12477     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
12478   return SetCC;
12479 }
12480
12481 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
12482 static bool isX86LogicalCmp(SDValue Op) {
12483   unsigned Opc = Op.getNode()->getOpcode();
12484   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
12485       Opc == X86ISD::SAHF)
12486     return true;
12487   if (Op.getResNo() == 1 &&
12488       (Opc == X86ISD::ADD ||
12489        Opc == X86ISD::SUB ||
12490        Opc == X86ISD::ADC ||
12491        Opc == X86ISD::SBB ||
12492        Opc == X86ISD::SMUL ||
12493        Opc == X86ISD::UMUL ||
12494        Opc == X86ISD::INC ||
12495        Opc == X86ISD::DEC ||
12496        Opc == X86ISD::OR ||
12497        Opc == X86ISD::XOR ||
12498        Opc == X86ISD::AND))
12499     return true;
12500
12501   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
12502     return true;
12503
12504   return false;
12505 }
12506
12507 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
12508   if (V.getOpcode() != ISD::TRUNCATE)
12509     return false;
12510
12511   SDValue VOp0 = V.getOperand(0);
12512   unsigned InBits = VOp0.getValueSizeInBits();
12513   unsigned Bits = V.getValueSizeInBits();
12514   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
12515 }
12516
12517 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
12518   bool addTest = true;
12519   SDValue Cond  = Op.getOperand(0);
12520   SDValue Op1 = Op.getOperand(1);
12521   SDValue Op2 = Op.getOperand(2);
12522   SDLoc DL(Op);
12523   EVT VT = Op1.getValueType();
12524   SDValue CC;
12525
12526   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
12527   // are available. Otherwise fp cmovs get lowered into a less efficient branch
12528   // sequence later on.
12529   if (Cond.getOpcode() == ISD::SETCC &&
12530       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
12531        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
12532       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
12533     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
12534     int SSECC = translateX86FSETCC(
12535         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
12536
12537     if (SSECC != 8) {
12538       if (Subtarget->hasAVX512()) {
12539         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
12540                                   DAG.getConstant(SSECC, MVT::i8));
12541         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
12542       }
12543       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
12544                                 DAG.getConstant(SSECC, MVT::i8));
12545       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
12546       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
12547       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
12548     }
12549   }
12550
12551   if (Cond.getOpcode() == ISD::SETCC) {
12552     SDValue NewCond = LowerSETCC(Cond, DAG);
12553     if (NewCond.getNode())
12554       Cond = NewCond;
12555   }
12556
12557   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
12558   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
12559   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
12560   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
12561   if (Cond.getOpcode() == X86ISD::SETCC &&
12562       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
12563       isZero(Cond.getOperand(1).getOperand(1))) {
12564     SDValue Cmp = Cond.getOperand(1);
12565
12566     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
12567
12568     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
12569         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
12570       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
12571
12572       SDValue CmpOp0 = Cmp.getOperand(0);
12573       // Apply further optimizations for special cases
12574       // (select (x != 0), -1, 0) -> neg & sbb
12575       // (select (x == 0), 0, -1) -> neg & sbb
12576       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
12577         if (YC->isNullValue() &&
12578             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
12579           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
12580           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
12581                                     DAG.getConstant(0, CmpOp0.getValueType()),
12582                                     CmpOp0);
12583           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12584                                     DAG.getConstant(X86::COND_B, MVT::i8),
12585                                     SDValue(Neg.getNode(), 1));
12586           return Res;
12587         }
12588
12589       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
12590                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
12591       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
12592
12593       SDValue Res =   // Res = 0 or -1.
12594         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12595                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
12596
12597       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
12598         Res = DAG.getNOT(DL, Res, Res.getValueType());
12599
12600       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
12601       if (!N2C || !N2C->isNullValue())
12602         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
12603       return Res;
12604     }
12605   }
12606
12607   // Look past (and (setcc_carry (cmp ...)), 1).
12608   if (Cond.getOpcode() == ISD::AND &&
12609       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12610     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12611     if (C && C->getAPIntValue() == 1)
12612       Cond = Cond.getOperand(0);
12613   }
12614
12615   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12616   // setting operand in place of the X86ISD::SETCC.
12617   unsigned CondOpcode = Cond.getOpcode();
12618   if (CondOpcode == X86ISD::SETCC ||
12619       CondOpcode == X86ISD::SETCC_CARRY) {
12620     CC = Cond.getOperand(0);
12621
12622     SDValue Cmp = Cond.getOperand(1);
12623     unsigned Opc = Cmp.getOpcode();
12624     MVT VT = Op.getSimpleValueType();
12625
12626     bool IllegalFPCMov = false;
12627     if (VT.isFloatingPoint() && !VT.isVector() &&
12628         !isScalarFPTypeInSSEReg(VT))  // FPStack?
12629       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
12630
12631     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
12632         Opc == X86ISD::BT) { // FIXME
12633       Cond = Cmp;
12634       addTest = false;
12635     }
12636   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12637              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12638              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12639               Cond.getOperand(0).getValueType() != MVT::i8)) {
12640     SDValue LHS = Cond.getOperand(0);
12641     SDValue RHS = Cond.getOperand(1);
12642     unsigned X86Opcode;
12643     unsigned X86Cond;
12644     SDVTList VTs;
12645     switch (CondOpcode) {
12646     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12647     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12648     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12649     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12650     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12651     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12652     default: llvm_unreachable("unexpected overflowing operator");
12653     }
12654     if (CondOpcode == ISD::UMULO)
12655       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12656                           MVT::i32);
12657     else
12658       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12659
12660     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
12661
12662     if (CondOpcode == ISD::UMULO)
12663       Cond = X86Op.getValue(2);
12664     else
12665       Cond = X86Op.getValue(1);
12666
12667     CC = DAG.getConstant(X86Cond, MVT::i8);
12668     addTest = false;
12669   }
12670
12671   if (addTest) {
12672     // Look pass the truncate if the high bits are known zero.
12673     if (isTruncWithZeroHighBitsInput(Cond, DAG))
12674         Cond = Cond.getOperand(0);
12675
12676     // We know the result of AND is compared against zero. Try to match
12677     // it to BT.
12678     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
12679       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
12680       if (NewSetCC.getNode()) {
12681         CC = NewSetCC.getOperand(0);
12682         Cond = NewSetCC.getOperand(1);
12683         addTest = false;
12684       }
12685     }
12686   }
12687
12688   if (addTest) {
12689     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
12690     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
12691   }
12692
12693   // a <  b ? -1 :  0 -> RES = ~setcc_carry
12694   // a <  b ?  0 : -1 -> RES = setcc_carry
12695   // a >= b ? -1 :  0 -> RES = setcc_carry
12696   // a >= b ?  0 : -1 -> RES = ~setcc_carry
12697   if (Cond.getOpcode() == X86ISD::SUB) {
12698     Cond = ConvertCmpIfNecessary(Cond, DAG);
12699     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
12700
12701     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
12702         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
12703       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
12704                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
12705       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
12706         return DAG.getNOT(DL, Res, Res.getValueType());
12707       return Res;
12708     }
12709   }
12710
12711   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
12712   // widen the cmov and push the truncate through. This avoids introducing a new
12713   // branch during isel and doesn't add any extensions.
12714   if (Op.getValueType() == MVT::i8 &&
12715       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
12716     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
12717     if (T1.getValueType() == T2.getValueType() &&
12718         // Blacklist CopyFromReg to avoid partial register stalls.
12719         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
12720       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
12721       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
12722       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
12723     }
12724   }
12725
12726   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
12727   // condition is true.
12728   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
12729   SDValue Ops[] = { Op2, Op1, CC, Cond };
12730   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
12731 }
12732
12733 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
12734   MVT VT = Op->getSimpleValueType(0);
12735   SDValue In = Op->getOperand(0);
12736   MVT InVT = In.getSimpleValueType();
12737   SDLoc dl(Op);
12738
12739   unsigned int NumElts = VT.getVectorNumElements();
12740   if (NumElts != 8 && NumElts != 16)
12741     return SDValue();
12742
12743   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12744     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12745
12746   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12747   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12748
12749   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
12750   Constant *C = ConstantInt::get(*DAG.getContext(),
12751     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
12752
12753   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
12754   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
12755   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
12756                           MachinePointerInfo::getConstantPool(),
12757                           false, false, false, Alignment);
12758   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
12759   if (VT.is512BitVector())
12760     return Brcst;
12761   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
12762 }
12763
12764 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12765                                 SelectionDAG &DAG) {
12766   MVT VT = Op->getSimpleValueType(0);
12767   SDValue In = Op->getOperand(0);
12768   MVT InVT = In.getSimpleValueType();
12769   SDLoc dl(Op);
12770
12771   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
12772     return LowerSIGN_EXTEND_AVX512(Op, DAG);
12773
12774   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
12775       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
12776       (VT != MVT::v16i16 || InVT != MVT::v16i8))
12777     return SDValue();
12778
12779   if (Subtarget->hasInt256())
12780     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
12781
12782   // Optimize vectors in AVX mode
12783   // Sign extend  v8i16 to v8i32 and
12784   //              v4i32 to v4i64
12785   //
12786   // Divide input vector into two parts
12787   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
12788   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
12789   // concat the vectors to original VT
12790
12791   unsigned NumElems = InVT.getVectorNumElements();
12792   SDValue Undef = DAG.getUNDEF(InVT);
12793
12794   SmallVector<int,8> ShufMask1(NumElems, -1);
12795   for (unsigned i = 0; i != NumElems/2; ++i)
12796     ShufMask1[i] = i;
12797
12798   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
12799
12800   SmallVector<int,8> ShufMask2(NumElems, -1);
12801   for (unsigned i = 0; i != NumElems/2; ++i)
12802     ShufMask2[i] = i + NumElems/2;
12803
12804   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
12805
12806   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
12807                                 VT.getVectorNumElements()/2);
12808
12809   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
12810   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
12811
12812   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12813 }
12814
12815 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
12816 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
12817 // from the AND / OR.
12818 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
12819   Opc = Op.getOpcode();
12820   if (Opc != ISD::OR && Opc != ISD::AND)
12821     return false;
12822   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12823           Op.getOperand(0).hasOneUse() &&
12824           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
12825           Op.getOperand(1).hasOneUse());
12826 }
12827
12828 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
12829 // 1 and that the SETCC node has a single use.
12830 static bool isXor1OfSetCC(SDValue Op) {
12831   if (Op.getOpcode() != ISD::XOR)
12832     return false;
12833   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12834   if (N1C && N1C->getAPIntValue() == 1) {
12835     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
12836       Op.getOperand(0).hasOneUse();
12837   }
12838   return false;
12839 }
12840
12841 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
12842   bool addTest = true;
12843   SDValue Chain = Op.getOperand(0);
12844   SDValue Cond  = Op.getOperand(1);
12845   SDValue Dest  = Op.getOperand(2);
12846   SDLoc dl(Op);
12847   SDValue CC;
12848   bool Inverted = false;
12849
12850   if (Cond.getOpcode() == ISD::SETCC) {
12851     // Check for setcc([su]{add,sub,mul}o == 0).
12852     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
12853         isa<ConstantSDNode>(Cond.getOperand(1)) &&
12854         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
12855         Cond.getOperand(0).getResNo() == 1 &&
12856         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
12857          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
12858          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
12859          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
12860          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
12861          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
12862       Inverted = true;
12863       Cond = Cond.getOperand(0);
12864     } else {
12865       SDValue NewCond = LowerSETCC(Cond, DAG);
12866       if (NewCond.getNode())
12867         Cond = NewCond;
12868     }
12869   }
12870 #if 0
12871   // FIXME: LowerXALUO doesn't handle these!!
12872   else if (Cond.getOpcode() == X86ISD::ADD  ||
12873            Cond.getOpcode() == X86ISD::SUB  ||
12874            Cond.getOpcode() == X86ISD::SMUL ||
12875            Cond.getOpcode() == X86ISD::UMUL)
12876     Cond = LowerXALUO(Cond, DAG);
12877 #endif
12878
12879   // Look pass (and (setcc_carry (cmp ...)), 1).
12880   if (Cond.getOpcode() == ISD::AND &&
12881       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
12882     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
12883     if (C && C->getAPIntValue() == 1)
12884       Cond = Cond.getOperand(0);
12885   }
12886
12887   // If condition flag is set by a X86ISD::CMP, then use it as the condition
12888   // setting operand in place of the X86ISD::SETCC.
12889   unsigned CondOpcode = Cond.getOpcode();
12890   if (CondOpcode == X86ISD::SETCC ||
12891       CondOpcode == X86ISD::SETCC_CARRY) {
12892     CC = Cond.getOperand(0);
12893
12894     SDValue Cmp = Cond.getOperand(1);
12895     unsigned Opc = Cmp.getOpcode();
12896     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
12897     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
12898       Cond = Cmp;
12899       addTest = false;
12900     } else {
12901       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
12902       default: break;
12903       case X86::COND_O:
12904       case X86::COND_B:
12905         // These can only come from an arithmetic instruction with overflow,
12906         // e.g. SADDO, UADDO.
12907         Cond = Cond.getNode()->getOperand(1);
12908         addTest = false;
12909         break;
12910       }
12911     }
12912   }
12913   CondOpcode = Cond.getOpcode();
12914   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
12915       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
12916       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
12917        Cond.getOperand(0).getValueType() != MVT::i8)) {
12918     SDValue LHS = Cond.getOperand(0);
12919     SDValue RHS = Cond.getOperand(1);
12920     unsigned X86Opcode;
12921     unsigned X86Cond;
12922     SDVTList VTs;
12923     // Keep this in sync with LowerXALUO, otherwise we might create redundant
12924     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
12925     // X86ISD::INC).
12926     switch (CondOpcode) {
12927     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
12928     case ISD::SADDO:
12929       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12930         if (C->isOne()) {
12931           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
12932           break;
12933         }
12934       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
12935     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
12936     case ISD::SSUBO:
12937       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
12938         if (C->isOne()) {
12939           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
12940           break;
12941         }
12942       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
12943     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
12944     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
12945     default: llvm_unreachable("unexpected overflowing operator");
12946     }
12947     if (Inverted)
12948       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
12949     if (CondOpcode == ISD::UMULO)
12950       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
12951                           MVT::i32);
12952     else
12953       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
12954
12955     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
12956
12957     if (CondOpcode == ISD::UMULO)
12958       Cond = X86Op.getValue(2);
12959     else
12960       Cond = X86Op.getValue(1);
12961
12962     CC = DAG.getConstant(X86Cond, MVT::i8);
12963     addTest = false;
12964   } else {
12965     unsigned CondOpc;
12966     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
12967       SDValue Cmp = Cond.getOperand(0).getOperand(1);
12968       if (CondOpc == ISD::OR) {
12969         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
12970         // two branches instead of an explicit OR instruction with a
12971         // separate test.
12972         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12973             isX86LogicalCmp(Cmp)) {
12974           CC = Cond.getOperand(0).getOperand(0);
12975           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
12976                               Chain, Dest, CC, Cmp);
12977           CC = Cond.getOperand(1).getOperand(0);
12978           Cond = Cmp;
12979           addTest = false;
12980         }
12981       } else { // ISD::AND
12982         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
12983         // two branches instead of an explicit AND instruction with a
12984         // separate test. However, we only do this if this block doesn't
12985         // have a fall-through edge, because this requires an explicit
12986         // jmp when the condition is false.
12987         if (Cmp == Cond.getOperand(1).getOperand(1) &&
12988             isX86LogicalCmp(Cmp) &&
12989             Op.getNode()->hasOneUse()) {
12990           X86::CondCode CCode =
12991             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
12992           CCode = X86::GetOppositeBranchCondition(CCode);
12993           CC = DAG.getConstant(CCode, MVT::i8);
12994           SDNode *User = *Op.getNode()->use_begin();
12995           // Look for an unconditional branch following this conditional branch.
12996           // We need this because we need to reverse the successors in order
12997           // to implement FCMP_OEQ.
12998           if (User->getOpcode() == ISD::BR) {
12999             SDValue FalseBB = User->getOperand(1);
13000             SDNode *NewBR =
13001               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13002             assert(NewBR == User);
13003             (void)NewBR;
13004             Dest = FalseBB;
13005
13006             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13007                                 Chain, Dest, CC, Cmp);
13008             X86::CondCode CCode =
13009               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
13010             CCode = X86::GetOppositeBranchCondition(CCode);
13011             CC = DAG.getConstant(CCode, MVT::i8);
13012             Cond = Cmp;
13013             addTest = false;
13014           }
13015         }
13016       }
13017     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
13018       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
13019       // It should be transformed during dag combiner except when the condition
13020       // is set by a arithmetics with overflow node.
13021       X86::CondCode CCode =
13022         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
13023       CCode = X86::GetOppositeBranchCondition(CCode);
13024       CC = DAG.getConstant(CCode, MVT::i8);
13025       Cond = Cond.getOperand(0).getOperand(1);
13026       addTest = false;
13027     } else if (Cond.getOpcode() == ISD::SETCC &&
13028                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
13029       // For FCMP_OEQ, we can emit
13030       // two branches instead of an explicit AND instruction with a
13031       // separate test. However, we only do this if this block doesn't
13032       // have a fall-through edge, because this requires an explicit
13033       // jmp when the condition is false.
13034       if (Op.getNode()->hasOneUse()) {
13035         SDNode *User = *Op.getNode()->use_begin();
13036         // Look for an unconditional branch following this conditional branch.
13037         // We need this because we need to reverse the successors in order
13038         // to implement FCMP_OEQ.
13039         if (User->getOpcode() == ISD::BR) {
13040           SDValue FalseBB = User->getOperand(1);
13041           SDNode *NewBR =
13042             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13043           assert(NewBR == User);
13044           (void)NewBR;
13045           Dest = FalseBB;
13046
13047           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13048                                     Cond.getOperand(0), Cond.getOperand(1));
13049           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13050           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13051           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13052                               Chain, Dest, CC, Cmp);
13053           CC = DAG.getConstant(X86::COND_P, MVT::i8);
13054           Cond = Cmp;
13055           addTest = false;
13056         }
13057       }
13058     } else if (Cond.getOpcode() == ISD::SETCC &&
13059                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
13060       // For FCMP_UNE, we can emit
13061       // two branches instead of an explicit AND instruction with a
13062       // separate test. However, we only do this if this block doesn't
13063       // have a fall-through edge, because this requires an explicit
13064       // jmp when the condition is false.
13065       if (Op.getNode()->hasOneUse()) {
13066         SDNode *User = *Op.getNode()->use_begin();
13067         // Look for an unconditional branch following this conditional branch.
13068         // We need this because we need to reverse the successors in order
13069         // to implement FCMP_UNE.
13070         if (User->getOpcode() == ISD::BR) {
13071           SDValue FalseBB = User->getOperand(1);
13072           SDNode *NewBR =
13073             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
13074           assert(NewBR == User);
13075           (void)NewBR;
13076
13077           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
13078                                     Cond.getOperand(0), Cond.getOperand(1));
13079           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13080           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
13081           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13082                               Chain, Dest, CC, Cmp);
13083           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
13084           Cond = Cmp;
13085           addTest = false;
13086           Dest = FalseBB;
13087         }
13088       }
13089     }
13090   }
13091
13092   if (addTest) {
13093     // Look pass the truncate if the high bits are known zero.
13094     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13095         Cond = Cond.getOperand(0);
13096
13097     // We know the result of AND is compared against zero. Try to match
13098     // it to BT.
13099     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13100       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
13101       if (NewSetCC.getNode()) {
13102         CC = NewSetCC.getOperand(0);
13103         Cond = NewSetCC.getOperand(1);
13104         addTest = false;
13105       }
13106     }
13107   }
13108
13109   if (addTest) {
13110     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
13111     CC = DAG.getConstant(X86Cond, MVT::i8);
13112     Cond = EmitTest(Cond, X86Cond, dl, DAG);
13113   }
13114   Cond = ConvertCmpIfNecessary(Cond, DAG);
13115   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
13116                      Chain, Dest, CC, Cond);
13117 }
13118
13119 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
13120 // Calls to _alloca is needed to probe the stack when allocating more than 4k
13121 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
13122 // that the guard pages used by the OS virtual memory manager are allocated in
13123 // correct sequence.
13124 SDValue
13125 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
13126                                            SelectionDAG &DAG) const {
13127   MachineFunction &MF = DAG.getMachineFunction();
13128   bool SplitStack = MF.shouldSplitStack();
13129   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
13130                SplitStack;
13131   SDLoc dl(Op);
13132
13133   if (!Lower) {
13134     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13135     SDNode* Node = Op.getNode();
13136
13137     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
13138     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
13139         " not tell us which reg is the stack pointer!");
13140     EVT VT = Node->getValueType(0);
13141     SDValue Tmp1 = SDValue(Node, 0);
13142     SDValue Tmp2 = SDValue(Node, 1);
13143     SDValue Tmp3 = Node->getOperand(2);
13144     SDValue Chain = Tmp1.getOperand(0);
13145
13146     // Chain the dynamic stack allocation so that it doesn't modify the stack
13147     // pointer when other instructions are using the stack.
13148     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
13149         SDLoc(Node));
13150
13151     SDValue Size = Tmp2.getOperand(1);
13152     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
13153     Chain = SP.getValue(1);
13154     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
13155     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
13156     unsigned StackAlign = TFI.getStackAlignment();
13157     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
13158     if (Align > StackAlign)
13159       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
13160           DAG.getConstant(-(uint64_t)Align, VT));
13161     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
13162
13163     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
13164         DAG.getIntPtrConstant(0, true), SDValue(),
13165         SDLoc(Node));
13166
13167     SDValue Ops[2] = { Tmp1, Tmp2 };
13168     return DAG.getMergeValues(Ops, dl);
13169   }
13170
13171   // Get the inputs.
13172   SDValue Chain = Op.getOperand(0);
13173   SDValue Size  = Op.getOperand(1);
13174   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
13175   EVT VT = Op.getNode()->getValueType(0);
13176
13177   bool Is64Bit = Subtarget->is64Bit();
13178   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
13179
13180   if (SplitStack) {
13181     MachineRegisterInfo &MRI = MF.getRegInfo();
13182
13183     if (Is64Bit) {
13184       // The 64 bit implementation of segmented stacks needs to clobber both r10
13185       // r11. This makes it impossible to use it along with nested parameters.
13186       const Function *F = MF.getFunction();
13187
13188       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
13189            I != E; ++I)
13190         if (I->hasNestAttr())
13191           report_fatal_error("Cannot use segmented stacks with functions that "
13192                              "have nested arguments.");
13193     }
13194
13195     const TargetRegisterClass *AddrRegClass =
13196       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
13197     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
13198     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
13199     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
13200                                 DAG.getRegister(Vreg, SPTy));
13201     SDValue Ops1[2] = { Value, Chain };
13202     return DAG.getMergeValues(Ops1, dl);
13203   } else {
13204     SDValue Flag;
13205     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
13206
13207     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
13208     Flag = Chain.getValue(1);
13209     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
13210
13211     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
13212
13213     const X86RegisterInfo *RegInfo =
13214       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13215     unsigned SPReg = RegInfo->getStackRegister();
13216     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
13217     Chain = SP.getValue(1);
13218
13219     if (Align) {
13220       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
13221                        DAG.getConstant(-(uint64_t)Align, VT));
13222       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
13223     }
13224
13225     SDValue Ops1[2] = { SP, Chain };
13226     return DAG.getMergeValues(Ops1, dl);
13227   }
13228 }
13229
13230 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
13231   MachineFunction &MF = DAG.getMachineFunction();
13232   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
13233
13234   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13235   SDLoc DL(Op);
13236
13237   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
13238     // vastart just stores the address of the VarArgsFrameIndex slot into the
13239     // memory location argument.
13240     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13241                                    getPointerTy());
13242     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
13243                         MachinePointerInfo(SV), false, false, 0);
13244   }
13245
13246   // __va_list_tag:
13247   //   gp_offset         (0 - 6 * 8)
13248   //   fp_offset         (48 - 48 + 8 * 16)
13249   //   overflow_arg_area (point to parameters coming in memory).
13250   //   reg_save_area
13251   SmallVector<SDValue, 8> MemOps;
13252   SDValue FIN = Op.getOperand(1);
13253   // Store gp_offset
13254   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
13255                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
13256                                                MVT::i32),
13257                                FIN, MachinePointerInfo(SV), false, false, 0);
13258   MemOps.push_back(Store);
13259
13260   // Store fp_offset
13261   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13262                     FIN, DAG.getIntPtrConstant(4));
13263   Store = DAG.getStore(Op.getOperand(0), DL,
13264                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
13265                                        MVT::i32),
13266                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
13267   MemOps.push_back(Store);
13268
13269   // Store ptr to overflow_arg_area
13270   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13271                     FIN, DAG.getIntPtrConstant(4));
13272   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
13273                                     getPointerTy());
13274   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
13275                        MachinePointerInfo(SV, 8),
13276                        false, false, 0);
13277   MemOps.push_back(Store);
13278
13279   // Store ptr to reg_save_area.
13280   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
13281                     FIN, DAG.getIntPtrConstant(8));
13282   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
13283                                     getPointerTy());
13284   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
13285                        MachinePointerInfo(SV, 16), false, false, 0);
13286   MemOps.push_back(Store);
13287   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
13288 }
13289
13290 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
13291   assert(Subtarget->is64Bit() &&
13292          "LowerVAARG only handles 64-bit va_arg!");
13293   assert((Subtarget->isTargetLinux() ||
13294           Subtarget->isTargetDarwin()) &&
13295           "Unhandled target in LowerVAARG");
13296   assert(Op.getNode()->getNumOperands() == 4);
13297   SDValue Chain = Op.getOperand(0);
13298   SDValue SrcPtr = Op.getOperand(1);
13299   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
13300   unsigned Align = Op.getConstantOperandVal(3);
13301   SDLoc dl(Op);
13302
13303   EVT ArgVT = Op.getNode()->getValueType(0);
13304   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13305   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
13306   uint8_t ArgMode;
13307
13308   // Decide which area this value should be read from.
13309   // TODO: Implement the AMD64 ABI in its entirety. This simple
13310   // selection mechanism works only for the basic types.
13311   if (ArgVT == MVT::f80) {
13312     llvm_unreachable("va_arg for f80 not yet implemented");
13313   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
13314     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
13315   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
13316     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
13317   } else {
13318     llvm_unreachable("Unhandled argument type in LowerVAARG");
13319   }
13320
13321   if (ArgMode == 2) {
13322     // Sanity Check: Make sure using fp_offset makes sense.
13323     assert(!DAG.getTarget().Options.UseSoftFloat &&
13324            !(DAG.getMachineFunction()
13325                 .getFunction()->getAttributes()
13326                 .hasAttribute(AttributeSet::FunctionIndex,
13327                               Attribute::NoImplicitFloat)) &&
13328            Subtarget->hasSSE1());
13329   }
13330
13331   // Insert VAARG_64 node into the DAG
13332   // VAARG_64 returns two values: Variable Argument Address, Chain
13333   SmallVector<SDValue, 11> InstOps;
13334   InstOps.push_back(Chain);
13335   InstOps.push_back(SrcPtr);
13336   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
13337   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
13338   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
13339   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
13340   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
13341                                           VTs, InstOps, MVT::i64,
13342                                           MachinePointerInfo(SV),
13343                                           /*Align=*/0,
13344                                           /*Volatile=*/false,
13345                                           /*ReadMem=*/true,
13346                                           /*WriteMem=*/true);
13347   Chain = VAARG.getValue(1);
13348
13349   // Load the next argument and return it
13350   return DAG.getLoad(ArgVT, dl,
13351                      Chain,
13352                      VAARG,
13353                      MachinePointerInfo(),
13354                      false, false, false, 0);
13355 }
13356
13357 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
13358                            SelectionDAG &DAG) {
13359   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
13360   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
13361   SDValue Chain = Op.getOperand(0);
13362   SDValue DstPtr = Op.getOperand(1);
13363   SDValue SrcPtr = Op.getOperand(2);
13364   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
13365   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13366   SDLoc DL(Op);
13367
13368   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
13369                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
13370                        false,
13371                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
13372 }
13373
13374 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
13375 // amount is a constant. Takes immediate version of shift as input.
13376 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
13377                                           SDValue SrcOp, uint64_t ShiftAmt,
13378                                           SelectionDAG &DAG) {
13379   MVT ElementType = VT.getVectorElementType();
13380
13381   // Fold this packed shift into its first operand if ShiftAmt is 0.
13382   if (ShiftAmt == 0)
13383     return SrcOp;
13384
13385   // Check for ShiftAmt >= element width
13386   if (ShiftAmt >= ElementType.getSizeInBits()) {
13387     if (Opc == X86ISD::VSRAI)
13388       ShiftAmt = ElementType.getSizeInBits() - 1;
13389     else
13390       return DAG.getConstant(0, VT);
13391   }
13392
13393   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
13394          && "Unknown target vector shift-by-constant node");
13395
13396   // Fold this packed vector shift into a build vector if SrcOp is a
13397   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
13398   if (VT == SrcOp.getSimpleValueType() &&
13399       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
13400     SmallVector<SDValue, 8> Elts;
13401     unsigned NumElts = SrcOp->getNumOperands();
13402     ConstantSDNode *ND;
13403
13404     switch(Opc) {
13405     default: llvm_unreachable(nullptr);
13406     case X86ISD::VSHLI:
13407       for (unsigned i=0; i!=NumElts; ++i) {
13408         SDValue CurrentOp = SrcOp->getOperand(i);
13409         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13410           Elts.push_back(CurrentOp);
13411           continue;
13412         }
13413         ND = cast<ConstantSDNode>(CurrentOp);
13414         const APInt &C = ND->getAPIntValue();
13415         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
13416       }
13417       break;
13418     case X86ISD::VSRLI:
13419       for (unsigned i=0; i!=NumElts; ++i) {
13420         SDValue CurrentOp = SrcOp->getOperand(i);
13421         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13422           Elts.push_back(CurrentOp);
13423           continue;
13424         }
13425         ND = cast<ConstantSDNode>(CurrentOp);
13426         const APInt &C = ND->getAPIntValue();
13427         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
13428       }
13429       break;
13430     case X86ISD::VSRAI:
13431       for (unsigned i=0; i!=NumElts; ++i) {
13432         SDValue CurrentOp = SrcOp->getOperand(i);
13433         if (CurrentOp->getOpcode() == ISD::UNDEF) {
13434           Elts.push_back(CurrentOp);
13435           continue;
13436         }
13437         ND = cast<ConstantSDNode>(CurrentOp);
13438         const APInt &C = ND->getAPIntValue();
13439         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
13440       }
13441       break;
13442     }
13443
13444     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13445   }
13446
13447   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
13448 }
13449
13450 // getTargetVShiftNode - Handle vector element shifts where the shift amount
13451 // may or may not be a constant. Takes immediate version of shift as input.
13452 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
13453                                    SDValue SrcOp, SDValue ShAmt,
13454                                    SelectionDAG &DAG) {
13455   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
13456
13457   // Catch shift-by-constant.
13458   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
13459     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
13460                                       CShAmt->getZExtValue(), DAG);
13461
13462   // Change opcode to non-immediate version
13463   switch (Opc) {
13464     default: llvm_unreachable("Unknown target vector shift node");
13465     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
13466     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
13467     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
13468   }
13469
13470   // Need to build a vector containing shift amount
13471   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
13472   SDValue ShOps[4];
13473   ShOps[0] = ShAmt;
13474   ShOps[1] = DAG.getConstant(0, MVT::i32);
13475   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
13476   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
13477
13478   // The return type has to be a 128-bit type with the same element
13479   // type as the input type.
13480   MVT EltVT = VT.getVectorElementType();
13481   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
13482
13483   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
13484   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
13485 }
13486
13487 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
13488   SDLoc dl(Op);
13489   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13490   switch (IntNo) {
13491   default: return SDValue();    // Don't custom lower most intrinsics.
13492   // Comparison intrinsics.
13493   case Intrinsic::x86_sse_comieq_ss:
13494   case Intrinsic::x86_sse_comilt_ss:
13495   case Intrinsic::x86_sse_comile_ss:
13496   case Intrinsic::x86_sse_comigt_ss:
13497   case Intrinsic::x86_sse_comige_ss:
13498   case Intrinsic::x86_sse_comineq_ss:
13499   case Intrinsic::x86_sse_ucomieq_ss:
13500   case Intrinsic::x86_sse_ucomilt_ss:
13501   case Intrinsic::x86_sse_ucomile_ss:
13502   case Intrinsic::x86_sse_ucomigt_ss:
13503   case Intrinsic::x86_sse_ucomige_ss:
13504   case Intrinsic::x86_sse_ucomineq_ss:
13505   case Intrinsic::x86_sse2_comieq_sd:
13506   case Intrinsic::x86_sse2_comilt_sd:
13507   case Intrinsic::x86_sse2_comile_sd:
13508   case Intrinsic::x86_sse2_comigt_sd:
13509   case Intrinsic::x86_sse2_comige_sd:
13510   case Intrinsic::x86_sse2_comineq_sd:
13511   case Intrinsic::x86_sse2_ucomieq_sd:
13512   case Intrinsic::x86_sse2_ucomilt_sd:
13513   case Intrinsic::x86_sse2_ucomile_sd:
13514   case Intrinsic::x86_sse2_ucomigt_sd:
13515   case Intrinsic::x86_sse2_ucomige_sd:
13516   case Intrinsic::x86_sse2_ucomineq_sd: {
13517     unsigned Opc;
13518     ISD::CondCode CC;
13519     switch (IntNo) {
13520     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13521     case Intrinsic::x86_sse_comieq_ss:
13522     case Intrinsic::x86_sse2_comieq_sd:
13523       Opc = X86ISD::COMI;
13524       CC = ISD::SETEQ;
13525       break;
13526     case Intrinsic::x86_sse_comilt_ss:
13527     case Intrinsic::x86_sse2_comilt_sd:
13528       Opc = X86ISD::COMI;
13529       CC = ISD::SETLT;
13530       break;
13531     case Intrinsic::x86_sse_comile_ss:
13532     case Intrinsic::x86_sse2_comile_sd:
13533       Opc = X86ISD::COMI;
13534       CC = ISD::SETLE;
13535       break;
13536     case Intrinsic::x86_sse_comigt_ss:
13537     case Intrinsic::x86_sse2_comigt_sd:
13538       Opc = X86ISD::COMI;
13539       CC = ISD::SETGT;
13540       break;
13541     case Intrinsic::x86_sse_comige_ss:
13542     case Intrinsic::x86_sse2_comige_sd:
13543       Opc = X86ISD::COMI;
13544       CC = ISD::SETGE;
13545       break;
13546     case Intrinsic::x86_sse_comineq_ss:
13547     case Intrinsic::x86_sse2_comineq_sd:
13548       Opc = X86ISD::COMI;
13549       CC = ISD::SETNE;
13550       break;
13551     case Intrinsic::x86_sse_ucomieq_ss:
13552     case Intrinsic::x86_sse2_ucomieq_sd:
13553       Opc = X86ISD::UCOMI;
13554       CC = ISD::SETEQ;
13555       break;
13556     case Intrinsic::x86_sse_ucomilt_ss:
13557     case Intrinsic::x86_sse2_ucomilt_sd:
13558       Opc = X86ISD::UCOMI;
13559       CC = ISD::SETLT;
13560       break;
13561     case Intrinsic::x86_sse_ucomile_ss:
13562     case Intrinsic::x86_sse2_ucomile_sd:
13563       Opc = X86ISD::UCOMI;
13564       CC = ISD::SETLE;
13565       break;
13566     case Intrinsic::x86_sse_ucomigt_ss:
13567     case Intrinsic::x86_sse2_ucomigt_sd:
13568       Opc = X86ISD::UCOMI;
13569       CC = ISD::SETGT;
13570       break;
13571     case Intrinsic::x86_sse_ucomige_ss:
13572     case Intrinsic::x86_sse2_ucomige_sd:
13573       Opc = X86ISD::UCOMI;
13574       CC = ISD::SETGE;
13575       break;
13576     case Intrinsic::x86_sse_ucomineq_ss:
13577     case Intrinsic::x86_sse2_ucomineq_sd:
13578       Opc = X86ISD::UCOMI;
13579       CC = ISD::SETNE;
13580       break;
13581     }
13582
13583     SDValue LHS = Op.getOperand(1);
13584     SDValue RHS = Op.getOperand(2);
13585     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
13586     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
13587     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
13588     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13589                                 DAG.getConstant(X86CC, MVT::i8), Cond);
13590     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13591   }
13592
13593   // Arithmetic intrinsics.
13594   case Intrinsic::x86_sse2_pmulu_dq:
13595   case Intrinsic::x86_avx2_pmulu_dq:
13596     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
13597                        Op.getOperand(1), Op.getOperand(2));
13598
13599   case Intrinsic::x86_sse41_pmuldq:
13600   case Intrinsic::x86_avx2_pmul_dq:
13601     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
13602                        Op.getOperand(1), Op.getOperand(2));
13603
13604   case Intrinsic::x86_sse2_pmulhu_w:
13605   case Intrinsic::x86_avx2_pmulhu_w:
13606     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
13607                        Op.getOperand(1), Op.getOperand(2));
13608
13609   case Intrinsic::x86_sse2_pmulh_w:
13610   case Intrinsic::x86_avx2_pmulh_w:
13611     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
13612                        Op.getOperand(1), Op.getOperand(2));
13613
13614   // SSE2/AVX2 sub with unsigned saturation intrinsics
13615   case Intrinsic::x86_sse2_psubus_b:
13616   case Intrinsic::x86_sse2_psubus_w:
13617   case Intrinsic::x86_avx2_psubus_b:
13618   case Intrinsic::x86_avx2_psubus_w:
13619     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
13620                        Op.getOperand(1), Op.getOperand(2));
13621
13622   // SSE3/AVX horizontal add/sub intrinsics
13623   case Intrinsic::x86_sse3_hadd_ps:
13624   case Intrinsic::x86_sse3_hadd_pd:
13625   case Intrinsic::x86_avx_hadd_ps_256:
13626   case Intrinsic::x86_avx_hadd_pd_256:
13627   case Intrinsic::x86_sse3_hsub_ps:
13628   case Intrinsic::x86_sse3_hsub_pd:
13629   case Intrinsic::x86_avx_hsub_ps_256:
13630   case Intrinsic::x86_avx_hsub_pd_256:
13631   case Intrinsic::x86_ssse3_phadd_w_128:
13632   case Intrinsic::x86_ssse3_phadd_d_128:
13633   case Intrinsic::x86_avx2_phadd_w:
13634   case Intrinsic::x86_avx2_phadd_d:
13635   case Intrinsic::x86_ssse3_phsub_w_128:
13636   case Intrinsic::x86_ssse3_phsub_d_128:
13637   case Intrinsic::x86_avx2_phsub_w:
13638   case Intrinsic::x86_avx2_phsub_d: {
13639     unsigned Opcode;
13640     switch (IntNo) {
13641     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13642     case Intrinsic::x86_sse3_hadd_ps:
13643     case Intrinsic::x86_sse3_hadd_pd:
13644     case Intrinsic::x86_avx_hadd_ps_256:
13645     case Intrinsic::x86_avx_hadd_pd_256:
13646       Opcode = X86ISD::FHADD;
13647       break;
13648     case Intrinsic::x86_sse3_hsub_ps:
13649     case Intrinsic::x86_sse3_hsub_pd:
13650     case Intrinsic::x86_avx_hsub_ps_256:
13651     case Intrinsic::x86_avx_hsub_pd_256:
13652       Opcode = X86ISD::FHSUB;
13653       break;
13654     case Intrinsic::x86_ssse3_phadd_w_128:
13655     case Intrinsic::x86_ssse3_phadd_d_128:
13656     case Intrinsic::x86_avx2_phadd_w:
13657     case Intrinsic::x86_avx2_phadd_d:
13658       Opcode = X86ISD::HADD;
13659       break;
13660     case Intrinsic::x86_ssse3_phsub_w_128:
13661     case Intrinsic::x86_ssse3_phsub_d_128:
13662     case Intrinsic::x86_avx2_phsub_w:
13663     case Intrinsic::x86_avx2_phsub_d:
13664       Opcode = X86ISD::HSUB;
13665       break;
13666     }
13667     return DAG.getNode(Opcode, dl, Op.getValueType(),
13668                        Op.getOperand(1), Op.getOperand(2));
13669   }
13670
13671   // SSE2/SSE41/AVX2 integer max/min intrinsics.
13672   case Intrinsic::x86_sse2_pmaxu_b:
13673   case Intrinsic::x86_sse41_pmaxuw:
13674   case Intrinsic::x86_sse41_pmaxud:
13675   case Intrinsic::x86_avx2_pmaxu_b:
13676   case Intrinsic::x86_avx2_pmaxu_w:
13677   case Intrinsic::x86_avx2_pmaxu_d:
13678   case Intrinsic::x86_sse2_pminu_b:
13679   case Intrinsic::x86_sse41_pminuw:
13680   case Intrinsic::x86_sse41_pminud:
13681   case Intrinsic::x86_avx2_pminu_b:
13682   case Intrinsic::x86_avx2_pminu_w:
13683   case Intrinsic::x86_avx2_pminu_d:
13684   case Intrinsic::x86_sse41_pmaxsb:
13685   case Intrinsic::x86_sse2_pmaxs_w:
13686   case Intrinsic::x86_sse41_pmaxsd:
13687   case Intrinsic::x86_avx2_pmaxs_b:
13688   case Intrinsic::x86_avx2_pmaxs_w:
13689   case Intrinsic::x86_avx2_pmaxs_d:
13690   case Intrinsic::x86_sse41_pminsb:
13691   case Intrinsic::x86_sse2_pmins_w:
13692   case Intrinsic::x86_sse41_pminsd:
13693   case Intrinsic::x86_avx2_pmins_b:
13694   case Intrinsic::x86_avx2_pmins_w:
13695   case Intrinsic::x86_avx2_pmins_d: {
13696     unsigned Opcode;
13697     switch (IntNo) {
13698     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13699     case Intrinsic::x86_sse2_pmaxu_b:
13700     case Intrinsic::x86_sse41_pmaxuw:
13701     case Intrinsic::x86_sse41_pmaxud:
13702     case Intrinsic::x86_avx2_pmaxu_b:
13703     case Intrinsic::x86_avx2_pmaxu_w:
13704     case Intrinsic::x86_avx2_pmaxu_d:
13705       Opcode = X86ISD::UMAX;
13706       break;
13707     case Intrinsic::x86_sse2_pminu_b:
13708     case Intrinsic::x86_sse41_pminuw:
13709     case Intrinsic::x86_sse41_pminud:
13710     case Intrinsic::x86_avx2_pminu_b:
13711     case Intrinsic::x86_avx2_pminu_w:
13712     case Intrinsic::x86_avx2_pminu_d:
13713       Opcode = X86ISD::UMIN;
13714       break;
13715     case Intrinsic::x86_sse41_pmaxsb:
13716     case Intrinsic::x86_sse2_pmaxs_w:
13717     case Intrinsic::x86_sse41_pmaxsd:
13718     case Intrinsic::x86_avx2_pmaxs_b:
13719     case Intrinsic::x86_avx2_pmaxs_w:
13720     case Intrinsic::x86_avx2_pmaxs_d:
13721       Opcode = X86ISD::SMAX;
13722       break;
13723     case Intrinsic::x86_sse41_pminsb:
13724     case Intrinsic::x86_sse2_pmins_w:
13725     case Intrinsic::x86_sse41_pminsd:
13726     case Intrinsic::x86_avx2_pmins_b:
13727     case Intrinsic::x86_avx2_pmins_w:
13728     case Intrinsic::x86_avx2_pmins_d:
13729       Opcode = X86ISD::SMIN;
13730       break;
13731     }
13732     return DAG.getNode(Opcode, dl, Op.getValueType(),
13733                        Op.getOperand(1), Op.getOperand(2));
13734   }
13735
13736   // SSE/SSE2/AVX floating point max/min intrinsics.
13737   case Intrinsic::x86_sse_max_ps:
13738   case Intrinsic::x86_sse2_max_pd:
13739   case Intrinsic::x86_avx_max_ps_256:
13740   case Intrinsic::x86_avx_max_pd_256:
13741   case Intrinsic::x86_sse_min_ps:
13742   case Intrinsic::x86_sse2_min_pd:
13743   case Intrinsic::x86_avx_min_ps_256:
13744   case Intrinsic::x86_avx_min_pd_256: {
13745     unsigned Opcode;
13746     switch (IntNo) {
13747     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13748     case Intrinsic::x86_sse_max_ps:
13749     case Intrinsic::x86_sse2_max_pd:
13750     case Intrinsic::x86_avx_max_ps_256:
13751     case Intrinsic::x86_avx_max_pd_256:
13752       Opcode = X86ISD::FMAX;
13753       break;
13754     case Intrinsic::x86_sse_min_ps:
13755     case Intrinsic::x86_sse2_min_pd:
13756     case Intrinsic::x86_avx_min_ps_256:
13757     case Intrinsic::x86_avx_min_pd_256:
13758       Opcode = X86ISD::FMIN;
13759       break;
13760     }
13761     return DAG.getNode(Opcode, dl, Op.getValueType(),
13762                        Op.getOperand(1), Op.getOperand(2));
13763   }
13764
13765   // AVX2 variable shift intrinsics
13766   case Intrinsic::x86_avx2_psllv_d:
13767   case Intrinsic::x86_avx2_psllv_q:
13768   case Intrinsic::x86_avx2_psllv_d_256:
13769   case Intrinsic::x86_avx2_psllv_q_256:
13770   case Intrinsic::x86_avx2_psrlv_d:
13771   case Intrinsic::x86_avx2_psrlv_q:
13772   case Intrinsic::x86_avx2_psrlv_d_256:
13773   case Intrinsic::x86_avx2_psrlv_q_256:
13774   case Intrinsic::x86_avx2_psrav_d:
13775   case Intrinsic::x86_avx2_psrav_d_256: {
13776     unsigned Opcode;
13777     switch (IntNo) {
13778     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13779     case Intrinsic::x86_avx2_psllv_d:
13780     case Intrinsic::x86_avx2_psllv_q:
13781     case Intrinsic::x86_avx2_psllv_d_256:
13782     case Intrinsic::x86_avx2_psllv_q_256:
13783       Opcode = ISD::SHL;
13784       break;
13785     case Intrinsic::x86_avx2_psrlv_d:
13786     case Intrinsic::x86_avx2_psrlv_q:
13787     case Intrinsic::x86_avx2_psrlv_d_256:
13788     case Intrinsic::x86_avx2_psrlv_q_256:
13789       Opcode = ISD::SRL;
13790       break;
13791     case Intrinsic::x86_avx2_psrav_d:
13792     case Intrinsic::x86_avx2_psrav_d_256:
13793       Opcode = ISD::SRA;
13794       break;
13795     }
13796     return DAG.getNode(Opcode, dl, Op.getValueType(),
13797                        Op.getOperand(1), Op.getOperand(2));
13798   }
13799
13800   case Intrinsic::x86_sse2_packssdw_128:
13801   case Intrinsic::x86_sse2_packsswb_128:
13802   case Intrinsic::x86_avx2_packssdw:
13803   case Intrinsic::x86_avx2_packsswb:
13804     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
13805                        Op.getOperand(1), Op.getOperand(2));
13806
13807   case Intrinsic::x86_sse2_packuswb_128:
13808   case Intrinsic::x86_sse41_packusdw:
13809   case Intrinsic::x86_avx2_packuswb:
13810   case Intrinsic::x86_avx2_packusdw:
13811     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
13812                        Op.getOperand(1), Op.getOperand(2));
13813
13814   case Intrinsic::x86_ssse3_pshuf_b_128:
13815   case Intrinsic::x86_avx2_pshuf_b:
13816     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
13817                        Op.getOperand(1), Op.getOperand(2));
13818
13819   case Intrinsic::x86_sse2_pshuf_d:
13820     return DAG.getNode(X86ISD::PSHUFD, dl, Op.getValueType(),
13821                        Op.getOperand(1), Op.getOperand(2));
13822
13823   case Intrinsic::x86_sse2_pshufl_w:
13824     return DAG.getNode(X86ISD::PSHUFLW, dl, Op.getValueType(),
13825                        Op.getOperand(1), Op.getOperand(2));
13826
13827   case Intrinsic::x86_sse2_pshufh_w:
13828     return DAG.getNode(X86ISD::PSHUFHW, dl, Op.getValueType(),
13829                        Op.getOperand(1), Op.getOperand(2));
13830
13831   case Intrinsic::x86_ssse3_psign_b_128:
13832   case Intrinsic::x86_ssse3_psign_w_128:
13833   case Intrinsic::x86_ssse3_psign_d_128:
13834   case Intrinsic::x86_avx2_psign_b:
13835   case Intrinsic::x86_avx2_psign_w:
13836   case Intrinsic::x86_avx2_psign_d:
13837     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
13838                        Op.getOperand(1), Op.getOperand(2));
13839
13840   case Intrinsic::x86_sse41_insertps:
13841     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
13842                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13843
13844   case Intrinsic::x86_avx_vperm2f128_ps_256:
13845   case Intrinsic::x86_avx_vperm2f128_pd_256:
13846   case Intrinsic::x86_avx_vperm2f128_si_256:
13847   case Intrinsic::x86_avx2_vperm2i128:
13848     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
13849                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
13850
13851   case Intrinsic::x86_avx2_permd:
13852   case Intrinsic::x86_avx2_permps:
13853     // Operands intentionally swapped. Mask is last operand to intrinsic,
13854     // but second operand for node/instruction.
13855     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
13856                        Op.getOperand(2), Op.getOperand(1));
13857
13858   case Intrinsic::x86_sse_sqrt_ps:
13859   case Intrinsic::x86_sse2_sqrt_pd:
13860   case Intrinsic::x86_avx_sqrt_ps_256:
13861   case Intrinsic::x86_avx_sqrt_pd_256:
13862     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
13863
13864   // ptest and testp intrinsics. The intrinsic these come from are designed to
13865   // return an integer value, not just an instruction so lower it to the ptest
13866   // or testp pattern and a setcc for the result.
13867   case Intrinsic::x86_sse41_ptestz:
13868   case Intrinsic::x86_sse41_ptestc:
13869   case Intrinsic::x86_sse41_ptestnzc:
13870   case Intrinsic::x86_avx_ptestz_256:
13871   case Intrinsic::x86_avx_ptestc_256:
13872   case Intrinsic::x86_avx_ptestnzc_256:
13873   case Intrinsic::x86_avx_vtestz_ps:
13874   case Intrinsic::x86_avx_vtestc_ps:
13875   case Intrinsic::x86_avx_vtestnzc_ps:
13876   case Intrinsic::x86_avx_vtestz_pd:
13877   case Intrinsic::x86_avx_vtestc_pd:
13878   case Intrinsic::x86_avx_vtestnzc_pd:
13879   case Intrinsic::x86_avx_vtestz_ps_256:
13880   case Intrinsic::x86_avx_vtestc_ps_256:
13881   case Intrinsic::x86_avx_vtestnzc_ps_256:
13882   case Intrinsic::x86_avx_vtestz_pd_256:
13883   case Intrinsic::x86_avx_vtestc_pd_256:
13884   case Intrinsic::x86_avx_vtestnzc_pd_256: {
13885     bool IsTestPacked = false;
13886     unsigned X86CC;
13887     switch (IntNo) {
13888     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
13889     case Intrinsic::x86_avx_vtestz_ps:
13890     case Intrinsic::x86_avx_vtestz_pd:
13891     case Intrinsic::x86_avx_vtestz_ps_256:
13892     case Intrinsic::x86_avx_vtestz_pd_256:
13893       IsTestPacked = true; // Fallthrough
13894     case Intrinsic::x86_sse41_ptestz:
13895     case Intrinsic::x86_avx_ptestz_256:
13896       // ZF = 1
13897       X86CC = X86::COND_E;
13898       break;
13899     case Intrinsic::x86_avx_vtestc_ps:
13900     case Intrinsic::x86_avx_vtestc_pd:
13901     case Intrinsic::x86_avx_vtestc_ps_256:
13902     case Intrinsic::x86_avx_vtestc_pd_256:
13903       IsTestPacked = true; // Fallthrough
13904     case Intrinsic::x86_sse41_ptestc:
13905     case Intrinsic::x86_avx_ptestc_256:
13906       // CF = 1
13907       X86CC = X86::COND_B;
13908       break;
13909     case Intrinsic::x86_avx_vtestnzc_ps:
13910     case Intrinsic::x86_avx_vtestnzc_pd:
13911     case Intrinsic::x86_avx_vtestnzc_ps_256:
13912     case Intrinsic::x86_avx_vtestnzc_pd_256:
13913       IsTestPacked = true; // Fallthrough
13914     case Intrinsic::x86_sse41_ptestnzc:
13915     case Intrinsic::x86_avx_ptestnzc_256:
13916       // ZF and CF = 0
13917       X86CC = X86::COND_A;
13918       break;
13919     }
13920
13921     SDValue LHS = Op.getOperand(1);
13922     SDValue RHS = Op.getOperand(2);
13923     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
13924     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
13925     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13926     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
13927     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13928   }
13929   case Intrinsic::x86_avx512_kortestz_w:
13930   case Intrinsic::x86_avx512_kortestc_w: {
13931     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
13932     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
13933     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
13934     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
13935     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
13936     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
13937     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
13938   }
13939
13940   // SSE/AVX shift intrinsics
13941   case Intrinsic::x86_sse2_psll_w:
13942   case Intrinsic::x86_sse2_psll_d:
13943   case Intrinsic::x86_sse2_psll_q:
13944   case Intrinsic::x86_avx2_psll_w:
13945   case Intrinsic::x86_avx2_psll_d:
13946   case Intrinsic::x86_avx2_psll_q:
13947   case Intrinsic::x86_sse2_psrl_w:
13948   case Intrinsic::x86_sse2_psrl_d:
13949   case Intrinsic::x86_sse2_psrl_q:
13950   case Intrinsic::x86_avx2_psrl_w:
13951   case Intrinsic::x86_avx2_psrl_d:
13952   case Intrinsic::x86_avx2_psrl_q:
13953   case Intrinsic::x86_sse2_psra_w:
13954   case Intrinsic::x86_sse2_psra_d:
13955   case Intrinsic::x86_avx2_psra_w:
13956   case Intrinsic::x86_avx2_psra_d: {
13957     unsigned Opcode;
13958     switch (IntNo) {
13959     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
13960     case Intrinsic::x86_sse2_psll_w:
13961     case Intrinsic::x86_sse2_psll_d:
13962     case Intrinsic::x86_sse2_psll_q:
13963     case Intrinsic::x86_avx2_psll_w:
13964     case Intrinsic::x86_avx2_psll_d:
13965     case Intrinsic::x86_avx2_psll_q:
13966       Opcode = X86ISD::VSHL;
13967       break;
13968     case Intrinsic::x86_sse2_psrl_w:
13969     case Intrinsic::x86_sse2_psrl_d:
13970     case Intrinsic::x86_sse2_psrl_q:
13971     case Intrinsic::x86_avx2_psrl_w:
13972     case Intrinsic::x86_avx2_psrl_d:
13973     case Intrinsic::x86_avx2_psrl_q:
13974       Opcode = X86ISD::VSRL;
13975       break;
13976     case Intrinsic::x86_sse2_psra_w:
13977     case Intrinsic::x86_sse2_psra_d:
13978     case Intrinsic::x86_avx2_psra_w:
13979     case Intrinsic::x86_avx2_psra_d:
13980       Opcode = X86ISD::VSRA;
13981       break;
13982     }
13983     return DAG.getNode(Opcode, dl, Op.getValueType(),
13984                        Op.getOperand(1), Op.getOperand(2));
13985   }
13986
13987   // SSE/AVX immediate shift intrinsics
13988   case Intrinsic::x86_sse2_pslli_w:
13989   case Intrinsic::x86_sse2_pslli_d:
13990   case Intrinsic::x86_sse2_pslli_q:
13991   case Intrinsic::x86_avx2_pslli_w:
13992   case Intrinsic::x86_avx2_pslli_d:
13993   case Intrinsic::x86_avx2_pslli_q:
13994   case Intrinsic::x86_sse2_psrli_w:
13995   case Intrinsic::x86_sse2_psrli_d:
13996   case Intrinsic::x86_sse2_psrli_q:
13997   case Intrinsic::x86_avx2_psrli_w:
13998   case Intrinsic::x86_avx2_psrli_d:
13999   case Intrinsic::x86_avx2_psrli_q:
14000   case Intrinsic::x86_sse2_psrai_w:
14001   case Intrinsic::x86_sse2_psrai_d:
14002   case Intrinsic::x86_avx2_psrai_w:
14003   case Intrinsic::x86_avx2_psrai_d: {
14004     unsigned Opcode;
14005     switch (IntNo) {
14006     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14007     case Intrinsic::x86_sse2_pslli_w:
14008     case Intrinsic::x86_sse2_pslli_d:
14009     case Intrinsic::x86_sse2_pslli_q:
14010     case Intrinsic::x86_avx2_pslli_w:
14011     case Intrinsic::x86_avx2_pslli_d:
14012     case Intrinsic::x86_avx2_pslli_q:
14013       Opcode = X86ISD::VSHLI;
14014       break;
14015     case Intrinsic::x86_sse2_psrli_w:
14016     case Intrinsic::x86_sse2_psrli_d:
14017     case Intrinsic::x86_sse2_psrli_q:
14018     case Intrinsic::x86_avx2_psrli_w:
14019     case Intrinsic::x86_avx2_psrli_d:
14020     case Intrinsic::x86_avx2_psrli_q:
14021       Opcode = X86ISD::VSRLI;
14022       break;
14023     case Intrinsic::x86_sse2_psrai_w:
14024     case Intrinsic::x86_sse2_psrai_d:
14025     case Intrinsic::x86_avx2_psrai_w:
14026     case Intrinsic::x86_avx2_psrai_d:
14027       Opcode = X86ISD::VSRAI;
14028       break;
14029     }
14030     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
14031                                Op.getOperand(1), Op.getOperand(2), DAG);
14032   }
14033
14034   case Intrinsic::x86_sse42_pcmpistria128:
14035   case Intrinsic::x86_sse42_pcmpestria128:
14036   case Intrinsic::x86_sse42_pcmpistric128:
14037   case Intrinsic::x86_sse42_pcmpestric128:
14038   case Intrinsic::x86_sse42_pcmpistrio128:
14039   case Intrinsic::x86_sse42_pcmpestrio128:
14040   case Intrinsic::x86_sse42_pcmpistris128:
14041   case Intrinsic::x86_sse42_pcmpestris128:
14042   case Intrinsic::x86_sse42_pcmpistriz128:
14043   case Intrinsic::x86_sse42_pcmpestriz128: {
14044     unsigned Opcode;
14045     unsigned X86CC;
14046     switch (IntNo) {
14047     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14048     case Intrinsic::x86_sse42_pcmpistria128:
14049       Opcode = X86ISD::PCMPISTRI;
14050       X86CC = X86::COND_A;
14051       break;
14052     case Intrinsic::x86_sse42_pcmpestria128:
14053       Opcode = X86ISD::PCMPESTRI;
14054       X86CC = X86::COND_A;
14055       break;
14056     case Intrinsic::x86_sse42_pcmpistric128:
14057       Opcode = X86ISD::PCMPISTRI;
14058       X86CC = X86::COND_B;
14059       break;
14060     case Intrinsic::x86_sse42_pcmpestric128:
14061       Opcode = X86ISD::PCMPESTRI;
14062       X86CC = X86::COND_B;
14063       break;
14064     case Intrinsic::x86_sse42_pcmpistrio128:
14065       Opcode = X86ISD::PCMPISTRI;
14066       X86CC = X86::COND_O;
14067       break;
14068     case Intrinsic::x86_sse42_pcmpestrio128:
14069       Opcode = X86ISD::PCMPESTRI;
14070       X86CC = X86::COND_O;
14071       break;
14072     case Intrinsic::x86_sse42_pcmpistris128:
14073       Opcode = X86ISD::PCMPISTRI;
14074       X86CC = X86::COND_S;
14075       break;
14076     case Intrinsic::x86_sse42_pcmpestris128:
14077       Opcode = X86ISD::PCMPESTRI;
14078       X86CC = X86::COND_S;
14079       break;
14080     case Intrinsic::x86_sse42_pcmpistriz128:
14081       Opcode = X86ISD::PCMPISTRI;
14082       X86CC = X86::COND_E;
14083       break;
14084     case Intrinsic::x86_sse42_pcmpestriz128:
14085       Opcode = X86ISD::PCMPESTRI;
14086       X86CC = X86::COND_E;
14087       break;
14088     }
14089     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14090     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14091     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
14092     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14093                                 DAG.getConstant(X86CC, MVT::i8),
14094                                 SDValue(PCMP.getNode(), 1));
14095     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
14096   }
14097
14098   case Intrinsic::x86_sse42_pcmpistri128:
14099   case Intrinsic::x86_sse42_pcmpestri128: {
14100     unsigned Opcode;
14101     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
14102       Opcode = X86ISD::PCMPISTRI;
14103     else
14104       Opcode = X86ISD::PCMPESTRI;
14105
14106     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
14107     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
14108     return DAG.getNode(Opcode, dl, VTs, NewOps);
14109   }
14110   case Intrinsic::x86_fma_vfmadd_ps:
14111   case Intrinsic::x86_fma_vfmadd_pd:
14112   case Intrinsic::x86_fma_vfmsub_ps:
14113   case Intrinsic::x86_fma_vfmsub_pd:
14114   case Intrinsic::x86_fma_vfnmadd_ps:
14115   case Intrinsic::x86_fma_vfnmadd_pd:
14116   case Intrinsic::x86_fma_vfnmsub_ps:
14117   case Intrinsic::x86_fma_vfnmsub_pd:
14118   case Intrinsic::x86_fma_vfmaddsub_ps:
14119   case Intrinsic::x86_fma_vfmaddsub_pd:
14120   case Intrinsic::x86_fma_vfmsubadd_ps:
14121   case Intrinsic::x86_fma_vfmsubadd_pd:
14122   case Intrinsic::x86_fma_vfmadd_ps_256:
14123   case Intrinsic::x86_fma_vfmadd_pd_256:
14124   case Intrinsic::x86_fma_vfmsub_ps_256:
14125   case Intrinsic::x86_fma_vfmsub_pd_256:
14126   case Intrinsic::x86_fma_vfnmadd_ps_256:
14127   case Intrinsic::x86_fma_vfnmadd_pd_256:
14128   case Intrinsic::x86_fma_vfnmsub_ps_256:
14129   case Intrinsic::x86_fma_vfnmsub_pd_256:
14130   case Intrinsic::x86_fma_vfmaddsub_ps_256:
14131   case Intrinsic::x86_fma_vfmaddsub_pd_256:
14132   case Intrinsic::x86_fma_vfmsubadd_ps_256:
14133   case Intrinsic::x86_fma_vfmsubadd_pd_256:
14134   case Intrinsic::x86_fma_vfmadd_ps_512:
14135   case Intrinsic::x86_fma_vfmadd_pd_512:
14136   case Intrinsic::x86_fma_vfmsub_ps_512:
14137   case Intrinsic::x86_fma_vfmsub_pd_512:
14138   case Intrinsic::x86_fma_vfnmadd_ps_512:
14139   case Intrinsic::x86_fma_vfnmadd_pd_512:
14140   case Intrinsic::x86_fma_vfnmsub_ps_512:
14141   case Intrinsic::x86_fma_vfnmsub_pd_512:
14142   case Intrinsic::x86_fma_vfmaddsub_ps_512:
14143   case Intrinsic::x86_fma_vfmaddsub_pd_512:
14144   case Intrinsic::x86_fma_vfmsubadd_ps_512:
14145   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
14146     unsigned Opc;
14147     switch (IntNo) {
14148     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
14149     case Intrinsic::x86_fma_vfmadd_ps:
14150     case Intrinsic::x86_fma_vfmadd_pd:
14151     case Intrinsic::x86_fma_vfmadd_ps_256:
14152     case Intrinsic::x86_fma_vfmadd_pd_256:
14153     case Intrinsic::x86_fma_vfmadd_ps_512:
14154     case Intrinsic::x86_fma_vfmadd_pd_512:
14155       Opc = X86ISD::FMADD;
14156       break;
14157     case Intrinsic::x86_fma_vfmsub_ps:
14158     case Intrinsic::x86_fma_vfmsub_pd:
14159     case Intrinsic::x86_fma_vfmsub_ps_256:
14160     case Intrinsic::x86_fma_vfmsub_pd_256:
14161     case Intrinsic::x86_fma_vfmsub_ps_512:
14162     case Intrinsic::x86_fma_vfmsub_pd_512:
14163       Opc = X86ISD::FMSUB;
14164       break;
14165     case Intrinsic::x86_fma_vfnmadd_ps:
14166     case Intrinsic::x86_fma_vfnmadd_pd:
14167     case Intrinsic::x86_fma_vfnmadd_ps_256:
14168     case Intrinsic::x86_fma_vfnmadd_pd_256:
14169     case Intrinsic::x86_fma_vfnmadd_ps_512:
14170     case Intrinsic::x86_fma_vfnmadd_pd_512:
14171       Opc = X86ISD::FNMADD;
14172       break;
14173     case Intrinsic::x86_fma_vfnmsub_ps:
14174     case Intrinsic::x86_fma_vfnmsub_pd:
14175     case Intrinsic::x86_fma_vfnmsub_ps_256:
14176     case Intrinsic::x86_fma_vfnmsub_pd_256:
14177     case Intrinsic::x86_fma_vfnmsub_ps_512:
14178     case Intrinsic::x86_fma_vfnmsub_pd_512:
14179       Opc = X86ISD::FNMSUB;
14180       break;
14181     case Intrinsic::x86_fma_vfmaddsub_ps:
14182     case Intrinsic::x86_fma_vfmaddsub_pd:
14183     case Intrinsic::x86_fma_vfmaddsub_ps_256:
14184     case Intrinsic::x86_fma_vfmaddsub_pd_256:
14185     case Intrinsic::x86_fma_vfmaddsub_ps_512:
14186     case Intrinsic::x86_fma_vfmaddsub_pd_512:
14187       Opc = X86ISD::FMADDSUB;
14188       break;
14189     case Intrinsic::x86_fma_vfmsubadd_ps:
14190     case Intrinsic::x86_fma_vfmsubadd_pd:
14191     case Intrinsic::x86_fma_vfmsubadd_ps_256:
14192     case Intrinsic::x86_fma_vfmsubadd_pd_256:
14193     case Intrinsic::x86_fma_vfmsubadd_ps_512:
14194     case Intrinsic::x86_fma_vfmsubadd_pd_512:
14195       Opc = X86ISD::FMSUBADD;
14196       break;
14197     }
14198
14199     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
14200                        Op.getOperand(2), Op.getOperand(3));
14201   }
14202   }
14203 }
14204
14205 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14206                               SDValue Src, SDValue Mask, SDValue Base,
14207                               SDValue Index, SDValue ScaleOp, SDValue Chain,
14208                               const X86Subtarget * Subtarget) {
14209   SDLoc dl(Op);
14210   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14211   assert(C && "Invalid scale type");
14212   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14213   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14214                              Index.getSimpleValueType().getVectorNumElements());
14215   SDValue MaskInReg;
14216   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14217   if (MaskC)
14218     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14219   else
14220     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14221   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
14222   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14223   SDValue Segment = DAG.getRegister(0, MVT::i32);
14224   if (Src.getOpcode() == ISD::UNDEF)
14225     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
14226   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14227   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14228   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
14229   return DAG.getMergeValues(RetOps, dl);
14230 }
14231
14232 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14233                                SDValue Src, SDValue Mask, SDValue Base,
14234                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
14235   SDLoc dl(Op);
14236   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14237   assert(C && "Invalid scale type");
14238   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14239   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14240   SDValue Segment = DAG.getRegister(0, MVT::i32);
14241   EVT MaskVT = MVT::getVectorVT(MVT::i1,
14242                              Index.getSimpleValueType().getVectorNumElements());
14243   SDValue MaskInReg;
14244   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14245   if (MaskC)
14246     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14247   else
14248     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14249   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
14250   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
14251   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
14252   return SDValue(Res, 1);
14253 }
14254
14255 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
14256                                SDValue Mask, SDValue Base, SDValue Index,
14257                                SDValue ScaleOp, SDValue Chain) {
14258   SDLoc dl(Op);
14259   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
14260   assert(C && "Invalid scale type");
14261   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
14262   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
14263   SDValue Segment = DAG.getRegister(0, MVT::i32);
14264   EVT MaskVT =
14265     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
14266   SDValue MaskInReg;
14267   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
14268   if (MaskC)
14269     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
14270   else
14271     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
14272   //SDVTList VTs = DAG.getVTList(MVT::Other);
14273   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
14274   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
14275   return SDValue(Res, 0);
14276 }
14277
14278 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
14279 // read performance monitor counters (x86_rdpmc).
14280 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
14281                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14282                               SmallVectorImpl<SDValue> &Results) {
14283   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14284   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14285   SDValue LO, HI;
14286
14287   // The ECX register is used to select the index of the performance counter
14288   // to read.
14289   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
14290                                    N->getOperand(2));
14291   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
14292
14293   // Reads the content of a 64-bit performance counter and returns it in the
14294   // registers EDX:EAX.
14295   if (Subtarget->is64Bit()) {
14296     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14297     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14298                             LO.getValue(2));
14299   } else {
14300     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14301     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14302                             LO.getValue(2));
14303   }
14304   Chain = HI.getValue(1);
14305
14306   if (Subtarget->is64Bit()) {
14307     // The EAX register is loaded with the low-order 32 bits. The EDX register
14308     // is loaded with the supported high-order bits of the counter.
14309     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14310                               DAG.getConstant(32, MVT::i8));
14311     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14312     Results.push_back(Chain);
14313     return;
14314   }
14315
14316   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14317   SDValue Ops[] = { LO, HI };
14318   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14319   Results.push_back(Pair);
14320   Results.push_back(Chain);
14321 }
14322
14323 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
14324 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
14325 // also used to custom lower READCYCLECOUNTER nodes.
14326 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
14327                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
14328                               SmallVectorImpl<SDValue> &Results) {
14329   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14330   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
14331   SDValue LO, HI;
14332
14333   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
14334   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
14335   // and the EAX register is loaded with the low-order 32 bits.
14336   if (Subtarget->is64Bit()) {
14337     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
14338     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
14339                             LO.getValue(2));
14340   } else {
14341     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
14342     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
14343                             LO.getValue(2));
14344   }
14345   SDValue Chain = HI.getValue(1);
14346
14347   if (Opcode == X86ISD::RDTSCP_DAG) {
14348     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
14349
14350     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
14351     // the ECX register. Add 'ecx' explicitly to the chain.
14352     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
14353                                      HI.getValue(2));
14354     // Explicitly store the content of ECX at the location passed in input
14355     // to the 'rdtscp' intrinsic.
14356     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
14357                          MachinePointerInfo(), false, false, 0);
14358   }
14359
14360   if (Subtarget->is64Bit()) {
14361     // The EDX register is loaded with the high-order 32 bits of the MSR, and
14362     // the EAX register is loaded with the low-order 32 bits.
14363     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
14364                               DAG.getConstant(32, MVT::i8));
14365     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
14366     Results.push_back(Chain);
14367     return;
14368   }
14369
14370   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
14371   SDValue Ops[] = { LO, HI };
14372   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
14373   Results.push_back(Pair);
14374   Results.push_back(Chain);
14375 }
14376
14377 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
14378                                      SelectionDAG &DAG) {
14379   SmallVector<SDValue, 2> Results;
14380   SDLoc DL(Op);
14381   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
14382                           Results);
14383   return DAG.getMergeValues(Results, DL);
14384 }
14385
14386 enum IntrinsicType {
14387   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDPMC, RDTSC, XTEST
14388 };
14389
14390 struct IntrinsicData {
14391   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
14392     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
14393   IntrinsicType Type;
14394   unsigned      Opc0;
14395   unsigned      Opc1;
14396 };
14397
14398 std::map < unsigned, IntrinsicData> IntrMap;
14399 static void InitIntinsicsMap() {
14400   static bool Initialized = false;
14401   if (Initialized) 
14402     return;
14403   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14404                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14405   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
14406                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
14407   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
14408                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
14409   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
14410                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
14411   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
14412                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
14413   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
14414                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
14415   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
14416                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
14417   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
14418                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
14419   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
14420                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
14421
14422   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
14423                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
14424   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
14425                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
14426   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
14427                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
14428   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
14429                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
14430   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
14431                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
14432   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
14433                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
14434   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
14435                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
14436   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
14437                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
14438    
14439   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
14440                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
14441                                                         X86::VGATHERPF1QPSm)));
14442   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
14443                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
14444                                                         X86::VGATHERPF1QPDm)));
14445   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
14446                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
14447                                                         X86::VGATHERPF1DPDm)));
14448   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
14449                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
14450                                                         X86::VGATHERPF1DPSm)));
14451   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
14452                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
14453                                                         X86::VSCATTERPF1QPSm)));
14454   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
14455                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
14456                                                         X86::VSCATTERPF1QPDm)));
14457   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
14458                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
14459                                                         X86::VSCATTERPF1DPDm)));
14460   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
14461                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
14462                                                         X86::VSCATTERPF1DPSm)));
14463   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
14464                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14465   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
14466                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14467   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
14468                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
14469   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
14470                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14471   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
14472                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14473   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
14474                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
14475   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
14476                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
14477   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
14478                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
14479   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
14480                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
14481   IntrMap.insert(std::make_pair(Intrinsic::x86_rdpmc,
14482                                 IntrinsicData(RDPMC,  X86ISD::RDPMC_DAG, 0)));
14483   Initialized = true;
14484 }
14485
14486 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
14487                                       SelectionDAG &DAG) {
14488   InitIntinsicsMap();
14489   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
14490   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
14491   if (itr == IntrMap.end())
14492     return SDValue();
14493
14494   SDLoc dl(Op);
14495   IntrinsicData Intr = itr->second;
14496   switch(Intr.Type) {
14497   case RDSEED:
14498   case RDRAND: {
14499     // Emit the node with the right value type.
14500     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
14501     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
14502
14503     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
14504     // Otherwise return the value from Rand, which is always 0, casted to i32.
14505     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
14506                       DAG.getConstant(1, Op->getValueType(1)),
14507                       DAG.getConstant(X86::COND_B, MVT::i32),
14508                       SDValue(Result.getNode(), 1) };
14509     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
14510                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
14511                                   Ops);
14512
14513     // Return { result, isValid, chain }.
14514     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
14515                        SDValue(Result.getNode(), 2));
14516   }
14517   case GATHER: {
14518   //gather(v1, mask, index, base, scale);
14519     SDValue Chain = Op.getOperand(0);
14520     SDValue Src   = Op.getOperand(2);
14521     SDValue Base  = Op.getOperand(3);
14522     SDValue Index = Op.getOperand(4);
14523     SDValue Mask  = Op.getOperand(5);
14524     SDValue Scale = Op.getOperand(6);
14525     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
14526                           Subtarget);
14527   }
14528   case SCATTER: {
14529   //scatter(base, mask, index, v1, scale);
14530     SDValue Chain = Op.getOperand(0);
14531     SDValue Base  = Op.getOperand(2);
14532     SDValue Mask  = Op.getOperand(3);
14533     SDValue Index = Op.getOperand(4);
14534     SDValue Src   = Op.getOperand(5);
14535     SDValue Scale = Op.getOperand(6);
14536     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
14537   }
14538   case PREFETCH: {
14539     SDValue Hint = Op.getOperand(6);
14540     unsigned HintVal;
14541     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
14542         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
14543       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
14544     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
14545     SDValue Chain = Op.getOperand(0);
14546     SDValue Mask  = Op.getOperand(2);
14547     SDValue Index = Op.getOperand(3);
14548     SDValue Base  = Op.getOperand(4);
14549     SDValue Scale = Op.getOperand(5);
14550     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
14551   }
14552   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
14553   case RDTSC: {
14554     SmallVector<SDValue, 2> Results;
14555     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
14556     return DAG.getMergeValues(Results, dl);
14557   }
14558   // Read Performance Monitoring Counters.
14559   case RDPMC: {
14560     SmallVector<SDValue, 2> Results;
14561     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
14562     return DAG.getMergeValues(Results, dl);
14563   }
14564   // XTEST intrinsics.
14565   case XTEST: {
14566     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
14567     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
14568     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
14569                                 DAG.getConstant(X86::COND_NE, MVT::i8),
14570                                 InTrans);
14571     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
14572     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
14573                        Ret, SDValue(InTrans.getNode(), 1));
14574   }
14575   }
14576   llvm_unreachable("Unknown Intrinsic Type");
14577 }
14578
14579 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
14580                                            SelectionDAG &DAG) const {
14581   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14582   MFI->setReturnAddressIsTaken(true);
14583
14584   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
14585     return SDValue();
14586
14587   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14588   SDLoc dl(Op);
14589   EVT PtrVT = getPointerTy();
14590
14591   if (Depth > 0) {
14592     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
14593     const X86RegisterInfo *RegInfo =
14594       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14595     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
14596     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14597                        DAG.getNode(ISD::ADD, dl, PtrVT,
14598                                    FrameAddr, Offset),
14599                        MachinePointerInfo(), false, false, false, 0);
14600   }
14601
14602   // Just load the return address.
14603   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
14604   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
14605                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
14606 }
14607
14608 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
14609   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
14610   MFI->setFrameAddressIsTaken(true);
14611
14612   EVT VT = Op.getValueType();
14613   SDLoc dl(Op);  // FIXME probably not meaningful
14614   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
14615   const X86RegisterInfo *RegInfo =
14616     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14617   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14618   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
14619           (FrameReg == X86::EBP && VT == MVT::i32)) &&
14620          "Invalid Frame Register!");
14621   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
14622   while (Depth--)
14623     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
14624                             MachinePointerInfo(),
14625                             false, false, false, 0);
14626   return FrameAddr;
14627 }
14628
14629 // FIXME? Maybe this could be a TableGen attribute on some registers and
14630 // this table could be generated automatically from RegInfo.
14631 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
14632                                               EVT VT) const {
14633   unsigned Reg = StringSwitch<unsigned>(RegName)
14634                        .Case("esp", X86::ESP)
14635                        .Case("rsp", X86::RSP)
14636                        .Default(0);
14637   if (Reg)
14638     return Reg;
14639   report_fatal_error("Invalid register name global variable");
14640 }
14641
14642 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
14643                                                      SelectionDAG &DAG) const {
14644   const X86RegisterInfo *RegInfo =
14645     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14646   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
14647 }
14648
14649 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
14650   SDValue Chain     = Op.getOperand(0);
14651   SDValue Offset    = Op.getOperand(1);
14652   SDValue Handler   = Op.getOperand(2);
14653   SDLoc dl      (Op);
14654
14655   EVT PtrVT = getPointerTy();
14656   const X86RegisterInfo *RegInfo =
14657     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
14658   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
14659   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
14660           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
14661          "Invalid Frame Register!");
14662   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
14663   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
14664
14665   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
14666                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
14667   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
14668   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
14669                        false, false, 0);
14670   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
14671
14672   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
14673                      DAG.getRegister(StoreAddrReg, PtrVT));
14674 }
14675
14676 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
14677                                                SelectionDAG &DAG) const {
14678   SDLoc DL(Op);
14679   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
14680                      DAG.getVTList(MVT::i32, MVT::Other),
14681                      Op.getOperand(0), Op.getOperand(1));
14682 }
14683
14684 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
14685                                                 SelectionDAG &DAG) const {
14686   SDLoc DL(Op);
14687   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
14688                      Op.getOperand(0), Op.getOperand(1));
14689 }
14690
14691 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
14692   return Op.getOperand(0);
14693 }
14694
14695 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
14696                                                 SelectionDAG &DAG) const {
14697   SDValue Root = Op.getOperand(0);
14698   SDValue Trmp = Op.getOperand(1); // trampoline
14699   SDValue FPtr = Op.getOperand(2); // nested function
14700   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
14701   SDLoc dl (Op);
14702
14703   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14704   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
14705
14706   if (Subtarget->is64Bit()) {
14707     SDValue OutChains[6];
14708
14709     // Large code-model.
14710     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
14711     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
14712
14713     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
14714     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
14715
14716     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
14717
14718     // Load the pointer to the nested function into R11.
14719     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
14720     SDValue Addr = Trmp;
14721     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14722                                 Addr, MachinePointerInfo(TrmpAddr),
14723                                 false, false, 0);
14724
14725     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14726                        DAG.getConstant(2, MVT::i64));
14727     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
14728                                 MachinePointerInfo(TrmpAddr, 2),
14729                                 false, false, 2);
14730
14731     // Load the 'nest' parameter value into R10.
14732     // R10 is specified in X86CallingConv.td
14733     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
14734     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14735                        DAG.getConstant(10, MVT::i64));
14736     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14737                                 Addr, MachinePointerInfo(TrmpAddr, 10),
14738                                 false, false, 0);
14739
14740     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14741                        DAG.getConstant(12, MVT::i64));
14742     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
14743                                 MachinePointerInfo(TrmpAddr, 12),
14744                                 false, false, 2);
14745
14746     // Jump to the nested function.
14747     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
14748     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14749                        DAG.getConstant(20, MVT::i64));
14750     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
14751                                 Addr, MachinePointerInfo(TrmpAddr, 20),
14752                                 false, false, 0);
14753
14754     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
14755     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
14756                        DAG.getConstant(22, MVT::i64));
14757     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
14758                                 MachinePointerInfo(TrmpAddr, 22),
14759                                 false, false, 0);
14760
14761     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14762   } else {
14763     const Function *Func =
14764       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
14765     CallingConv::ID CC = Func->getCallingConv();
14766     unsigned NestReg;
14767
14768     switch (CC) {
14769     default:
14770       llvm_unreachable("Unsupported calling convention");
14771     case CallingConv::C:
14772     case CallingConv::X86_StdCall: {
14773       // Pass 'nest' parameter in ECX.
14774       // Must be kept in sync with X86CallingConv.td
14775       NestReg = X86::ECX;
14776
14777       // Check that ECX wasn't needed by an 'inreg' parameter.
14778       FunctionType *FTy = Func->getFunctionType();
14779       const AttributeSet &Attrs = Func->getAttributes();
14780
14781       if (!Attrs.isEmpty() && !Func->isVarArg()) {
14782         unsigned InRegCount = 0;
14783         unsigned Idx = 1;
14784
14785         for (FunctionType::param_iterator I = FTy->param_begin(),
14786              E = FTy->param_end(); I != E; ++I, ++Idx)
14787           if (Attrs.hasAttribute(Idx, Attribute::InReg))
14788             // FIXME: should only count parameters that are lowered to integers.
14789             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
14790
14791         if (InRegCount > 2) {
14792           report_fatal_error("Nest register in use - reduce number of inreg"
14793                              " parameters!");
14794         }
14795       }
14796       break;
14797     }
14798     case CallingConv::X86_FastCall:
14799     case CallingConv::X86_ThisCall:
14800     case CallingConv::Fast:
14801       // Pass 'nest' parameter in EAX.
14802       // Must be kept in sync with X86CallingConv.td
14803       NestReg = X86::EAX;
14804       break;
14805     }
14806
14807     SDValue OutChains[4];
14808     SDValue Addr, Disp;
14809
14810     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14811                        DAG.getConstant(10, MVT::i32));
14812     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
14813
14814     // This is storing the opcode for MOV32ri.
14815     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
14816     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
14817     OutChains[0] = DAG.getStore(Root, dl,
14818                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
14819                                 Trmp, MachinePointerInfo(TrmpAddr),
14820                                 false, false, 0);
14821
14822     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14823                        DAG.getConstant(1, MVT::i32));
14824     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
14825                                 MachinePointerInfo(TrmpAddr, 1),
14826                                 false, false, 1);
14827
14828     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
14829     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14830                        DAG.getConstant(5, MVT::i32));
14831     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
14832                                 MachinePointerInfo(TrmpAddr, 5),
14833                                 false, false, 1);
14834
14835     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
14836                        DAG.getConstant(6, MVT::i32));
14837     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
14838                                 MachinePointerInfo(TrmpAddr, 6),
14839                                 false, false, 1);
14840
14841     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
14842   }
14843 }
14844
14845 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
14846                                             SelectionDAG &DAG) const {
14847   /*
14848    The rounding mode is in bits 11:10 of FPSR, and has the following
14849    settings:
14850      00 Round to nearest
14851      01 Round to -inf
14852      10 Round to +inf
14853      11 Round to 0
14854
14855   FLT_ROUNDS, on the other hand, expects the following:
14856     -1 Undefined
14857      0 Round to 0
14858      1 Round to nearest
14859      2 Round to +inf
14860      3 Round to -inf
14861
14862   To perform the conversion, we do:
14863     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
14864   */
14865
14866   MachineFunction &MF = DAG.getMachineFunction();
14867   const TargetMachine &TM = MF.getTarget();
14868   const TargetFrameLowering &TFI = *TM.getFrameLowering();
14869   unsigned StackAlignment = TFI.getStackAlignment();
14870   MVT VT = Op.getSimpleValueType();
14871   SDLoc DL(Op);
14872
14873   // Save FP Control Word to stack slot
14874   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
14875   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
14876
14877   MachineMemOperand *MMO =
14878    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
14879                            MachineMemOperand::MOStore, 2, 2);
14880
14881   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
14882   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
14883                                           DAG.getVTList(MVT::Other),
14884                                           Ops, MVT::i16, MMO);
14885
14886   // Load FP Control Word from stack slot
14887   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
14888                             MachinePointerInfo(), false, false, false, 0);
14889
14890   // Transform as necessary
14891   SDValue CWD1 =
14892     DAG.getNode(ISD::SRL, DL, MVT::i16,
14893                 DAG.getNode(ISD::AND, DL, MVT::i16,
14894                             CWD, DAG.getConstant(0x800, MVT::i16)),
14895                 DAG.getConstant(11, MVT::i8));
14896   SDValue CWD2 =
14897     DAG.getNode(ISD::SRL, DL, MVT::i16,
14898                 DAG.getNode(ISD::AND, DL, MVT::i16,
14899                             CWD, DAG.getConstant(0x400, MVT::i16)),
14900                 DAG.getConstant(9, MVT::i8));
14901
14902   SDValue RetVal =
14903     DAG.getNode(ISD::AND, DL, MVT::i16,
14904                 DAG.getNode(ISD::ADD, DL, MVT::i16,
14905                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
14906                             DAG.getConstant(1, MVT::i16)),
14907                 DAG.getConstant(3, MVT::i16));
14908
14909   return DAG.getNode((VT.getSizeInBits() < 16 ?
14910                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
14911 }
14912
14913 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
14914   MVT VT = Op.getSimpleValueType();
14915   EVT OpVT = VT;
14916   unsigned NumBits = VT.getSizeInBits();
14917   SDLoc dl(Op);
14918
14919   Op = Op.getOperand(0);
14920   if (VT == MVT::i8) {
14921     // Zero extend to i32 since there is not an i8 bsr.
14922     OpVT = MVT::i32;
14923     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14924   }
14925
14926   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
14927   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14928   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14929
14930   // If src is zero (i.e. bsr sets ZF), returns NumBits.
14931   SDValue Ops[] = {
14932     Op,
14933     DAG.getConstant(NumBits+NumBits-1, OpVT),
14934     DAG.getConstant(X86::COND_E, MVT::i8),
14935     Op.getValue(1)
14936   };
14937   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
14938
14939   // Finally xor with NumBits-1.
14940   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14941
14942   if (VT == MVT::i8)
14943     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14944   return Op;
14945 }
14946
14947 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
14948   MVT VT = Op.getSimpleValueType();
14949   EVT OpVT = VT;
14950   unsigned NumBits = VT.getSizeInBits();
14951   SDLoc dl(Op);
14952
14953   Op = Op.getOperand(0);
14954   if (VT == MVT::i8) {
14955     // Zero extend to i32 since there is not an i8 bsr.
14956     OpVT = MVT::i32;
14957     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
14958   }
14959
14960   // Issue a bsr (scan bits in reverse).
14961   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
14962   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
14963
14964   // And xor with NumBits-1.
14965   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
14966
14967   if (VT == MVT::i8)
14968     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
14969   return Op;
14970 }
14971
14972 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
14973   MVT VT = Op.getSimpleValueType();
14974   unsigned NumBits = VT.getSizeInBits();
14975   SDLoc dl(Op);
14976   Op = Op.getOperand(0);
14977
14978   // Issue a bsf (scan bits forward) which also sets EFLAGS.
14979   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14980   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
14981
14982   // If src is zero (i.e. bsf sets ZF), returns NumBits.
14983   SDValue Ops[] = {
14984     Op,
14985     DAG.getConstant(NumBits, VT),
14986     DAG.getConstant(X86::COND_E, MVT::i8),
14987     Op.getValue(1)
14988   };
14989   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
14990 }
14991
14992 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
14993 // ones, and then concatenate the result back.
14994 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
14995   MVT VT = Op.getSimpleValueType();
14996
14997   assert(VT.is256BitVector() && VT.isInteger() &&
14998          "Unsupported value type for operation");
14999
15000   unsigned NumElems = VT.getVectorNumElements();
15001   SDLoc dl(Op);
15002
15003   // Extract the LHS vectors
15004   SDValue LHS = Op.getOperand(0);
15005   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15006   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15007
15008   // Extract the RHS vectors
15009   SDValue RHS = Op.getOperand(1);
15010   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
15011   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
15012
15013   MVT EltVT = VT.getVectorElementType();
15014   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15015
15016   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
15017                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
15018                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
15019 }
15020
15021 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
15022   assert(Op.getSimpleValueType().is256BitVector() &&
15023          Op.getSimpleValueType().isInteger() &&
15024          "Only handle AVX 256-bit vector integer operation");
15025   return Lower256IntArith(Op, DAG);
15026 }
15027
15028 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
15029   assert(Op.getSimpleValueType().is256BitVector() &&
15030          Op.getSimpleValueType().isInteger() &&
15031          "Only handle AVX 256-bit vector integer operation");
15032   return Lower256IntArith(Op, DAG);
15033 }
15034
15035 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
15036                         SelectionDAG &DAG) {
15037   SDLoc dl(Op);
15038   MVT VT = Op.getSimpleValueType();
15039
15040   // Decompose 256-bit ops into smaller 128-bit ops.
15041   if (VT.is256BitVector() && !Subtarget->hasInt256())
15042     return Lower256IntArith(Op, DAG);
15043
15044   SDValue A = Op.getOperand(0);
15045   SDValue B = Op.getOperand(1);
15046
15047   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
15048   if (VT == MVT::v4i32) {
15049     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
15050            "Should not custom lower when pmuldq is available!");
15051
15052     // Extract the odd parts.
15053     static const int UnpackMask[] = { 1, -1, 3, -1 };
15054     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
15055     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
15056
15057     // Multiply the even parts.
15058     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
15059     // Now multiply odd parts.
15060     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
15061
15062     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
15063     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
15064
15065     // Merge the two vectors back together with a shuffle. This expands into 2
15066     // shuffles.
15067     static const int ShufMask[] = { 0, 4, 2, 6 };
15068     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
15069   }
15070
15071   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
15072          "Only know how to lower V2I64/V4I64/V8I64 multiply");
15073
15074   //  Ahi = psrlqi(a, 32);
15075   //  Bhi = psrlqi(b, 32);
15076   //
15077   //  AloBlo = pmuludq(a, b);
15078   //  AloBhi = pmuludq(a, Bhi);
15079   //  AhiBlo = pmuludq(Ahi, b);
15080
15081   //  AloBhi = psllqi(AloBhi, 32);
15082   //  AhiBlo = psllqi(AhiBlo, 32);
15083   //  return AloBlo + AloBhi + AhiBlo;
15084
15085   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
15086   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
15087
15088   // Bit cast to 32-bit vectors for MULUDQ
15089   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
15090                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
15091   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
15092   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
15093   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
15094   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
15095
15096   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
15097   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
15098   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
15099
15100   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
15101   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
15102
15103   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
15104   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
15105 }
15106
15107 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
15108   assert(Subtarget->isTargetWin64() && "Unexpected target");
15109   EVT VT = Op.getValueType();
15110   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
15111          "Unexpected return type for lowering");
15112
15113   RTLIB::Libcall LC;
15114   bool isSigned;
15115   switch (Op->getOpcode()) {
15116   default: llvm_unreachable("Unexpected request for libcall!");
15117   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
15118   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
15119   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
15120   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
15121   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
15122   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
15123   }
15124
15125   SDLoc dl(Op);
15126   SDValue InChain = DAG.getEntryNode();
15127
15128   TargetLowering::ArgListTy Args;
15129   TargetLowering::ArgListEntry Entry;
15130   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
15131     EVT ArgVT = Op->getOperand(i).getValueType();
15132     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
15133            "Unexpected argument type for lowering");
15134     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
15135     Entry.Node = StackPtr;
15136     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
15137                            false, false, 16);
15138     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15139     Entry.Ty = PointerType::get(ArgTy,0);
15140     Entry.isSExt = false;
15141     Entry.isZExt = false;
15142     Args.push_back(Entry);
15143   }
15144
15145   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
15146                                          getPointerTy());
15147
15148   TargetLowering::CallLoweringInfo CLI(DAG);
15149   CLI.setDebugLoc(dl).setChain(InChain)
15150     .setCallee(getLibcallCallingConv(LC),
15151                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
15152                Callee, std::move(Args), 0)
15153     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
15154
15155   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
15156   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
15157 }
15158
15159 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
15160                              SelectionDAG &DAG) {
15161   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
15162   EVT VT = Op0.getValueType();
15163   SDLoc dl(Op);
15164
15165   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
15166          (VT == MVT::v8i32 && Subtarget->hasInt256()));
15167
15168   // Get the high parts.
15169   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
15170   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
15171   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
15172
15173   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
15174   // ints.
15175   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
15176   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
15177   unsigned Opcode =
15178       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
15179   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
15180                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
15181   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
15182                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
15183
15184   // Shuffle it back into the right order.
15185   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
15186   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
15187   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
15188   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
15189
15190   // If we have a signed multiply but no PMULDQ fix up the high parts of a
15191   // unsigned multiply.
15192   if (IsSigned && !Subtarget->hasSSE41()) {
15193     SDValue ShAmt =
15194         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
15195     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
15196                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
15197     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
15198                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
15199
15200     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
15201     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
15202   }
15203
15204   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
15205 }
15206
15207 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
15208                                          const X86Subtarget *Subtarget) {
15209   MVT VT = Op.getSimpleValueType();
15210   SDLoc dl(Op);
15211   SDValue R = Op.getOperand(0);
15212   SDValue Amt = Op.getOperand(1);
15213
15214   // Optimize shl/srl/sra with constant shift amount.
15215   if (isSplatVector(Amt.getNode())) {
15216     SDValue SclrAmt = Amt->getOperand(0);
15217     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
15218       uint64_t ShiftAmt = C->getZExtValue();
15219
15220       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
15221           (Subtarget->hasInt256() &&
15222            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15223           (Subtarget->hasAVX512() &&
15224            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15225         if (Op.getOpcode() == ISD::SHL)
15226           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15227                                             DAG);
15228         if (Op.getOpcode() == ISD::SRL)
15229           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15230                                             DAG);
15231         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
15232           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15233                                             DAG);
15234       }
15235
15236       if (VT == MVT::v16i8) {
15237         if (Op.getOpcode() == ISD::SHL) {
15238           // Make a large shift.
15239           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15240                                                    MVT::v8i16, R, ShiftAmt,
15241                                                    DAG);
15242           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15243           // Zero out the rightmost bits.
15244           SmallVector<SDValue, 16> V(16,
15245                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15246                                                      MVT::i8));
15247           return DAG.getNode(ISD::AND, dl, VT, SHL,
15248                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15249         }
15250         if (Op.getOpcode() == ISD::SRL) {
15251           // Make a large shift.
15252           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15253                                                    MVT::v8i16, R, ShiftAmt,
15254                                                    DAG);
15255           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15256           // Zero out the leftmost bits.
15257           SmallVector<SDValue, 16> V(16,
15258                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15259                                                      MVT::i8));
15260           return DAG.getNode(ISD::AND, dl, VT, SRL,
15261                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15262         }
15263         if (Op.getOpcode() == ISD::SRA) {
15264           if (ShiftAmt == 7) {
15265             // R s>> 7  ===  R s< 0
15266             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15267             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15268           }
15269
15270           // R s>> a === ((R u>> a) ^ m) - m
15271           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15272           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
15273                                                          MVT::i8));
15274           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15275           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15276           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15277           return Res;
15278         }
15279         llvm_unreachable("Unknown shift opcode.");
15280       }
15281
15282       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
15283         if (Op.getOpcode() == ISD::SHL) {
15284           // Make a large shift.
15285           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
15286                                                    MVT::v16i16, R, ShiftAmt,
15287                                                    DAG);
15288           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
15289           // Zero out the rightmost bits.
15290           SmallVector<SDValue, 32> V(32,
15291                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
15292                                                      MVT::i8));
15293           return DAG.getNode(ISD::AND, dl, VT, SHL,
15294                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15295         }
15296         if (Op.getOpcode() == ISD::SRL) {
15297           // Make a large shift.
15298           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
15299                                                    MVT::v16i16, R, ShiftAmt,
15300                                                    DAG);
15301           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
15302           // Zero out the leftmost bits.
15303           SmallVector<SDValue, 32> V(32,
15304                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
15305                                                      MVT::i8));
15306           return DAG.getNode(ISD::AND, dl, VT, SRL,
15307                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
15308         }
15309         if (Op.getOpcode() == ISD::SRA) {
15310           if (ShiftAmt == 7) {
15311             // R s>> 7  ===  R s< 0
15312             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
15313             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
15314           }
15315
15316           // R s>> a === ((R u>> a) ^ m) - m
15317           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
15318           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
15319                                                          MVT::i8));
15320           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
15321           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
15322           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
15323           return Res;
15324         }
15325         llvm_unreachable("Unknown shift opcode.");
15326       }
15327     }
15328   }
15329
15330   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15331   if (!Subtarget->is64Bit() &&
15332       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
15333       Amt.getOpcode() == ISD::BITCAST &&
15334       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15335     Amt = Amt.getOperand(0);
15336     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15337                      VT.getVectorNumElements();
15338     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
15339     uint64_t ShiftAmt = 0;
15340     for (unsigned i = 0; i != Ratio; ++i) {
15341       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
15342       if (!C)
15343         return SDValue();
15344       // 6 == Log2(64)
15345       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
15346     }
15347     // Check remaining shift amounts.
15348     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15349       uint64_t ShAmt = 0;
15350       for (unsigned j = 0; j != Ratio; ++j) {
15351         ConstantSDNode *C =
15352           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
15353         if (!C)
15354           return SDValue();
15355         // 6 == Log2(64)
15356         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
15357       }
15358       if (ShAmt != ShiftAmt)
15359         return SDValue();
15360     }
15361     switch (Op.getOpcode()) {
15362     default:
15363       llvm_unreachable("Unknown shift opcode!");
15364     case ISD::SHL:
15365       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
15366                                         DAG);
15367     case ISD::SRL:
15368       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
15369                                         DAG);
15370     case ISD::SRA:
15371       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
15372                                         DAG);
15373     }
15374   }
15375
15376   return SDValue();
15377 }
15378
15379 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
15380                                         const X86Subtarget* Subtarget) {
15381   MVT VT = Op.getSimpleValueType();
15382   SDLoc dl(Op);
15383   SDValue R = Op.getOperand(0);
15384   SDValue Amt = Op.getOperand(1);
15385
15386   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
15387       VT == MVT::v4i32 || VT == MVT::v8i16 ||
15388       (Subtarget->hasInt256() &&
15389        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
15390         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
15391        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
15392     SDValue BaseShAmt;
15393     EVT EltVT = VT.getVectorElementType();
15394
15395     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15396       unsigned NumElts = VT.getVectorNumElements();
15397       unsigned i, j;
15398       for (i = 0; i != NumElts; ++i) {
15399         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
15400           continue;
15401         break;
15402       }
15403       for (j = i; j != NumElts; ++j) {
15404         SDValue Arg = Amt.getOperand(j);
15405         if (Arg.getOpcode() == ISD::UNDEF) continue;
15406         if (Arg != Amt.getOperand(i))
15407           break;
15408       }
15409       if (i != NumElts && j == NumElts)
15410         BaseShAmt = Amt.getOperand(i);
15411     } else {
15412       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
15413         Amt = Amt.getOperand(0);
15414       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
15415                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
15416         SDValue InVec = Amt.getOperand(0);
15417         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
15418           unsigned NumElts = InVec.getValueType().getVectorNumElements();
15419           unsigned i = 0;
15420           for (; i != NumElts; ++i) {
15421             SDValue Arg = InVec.getOperand(i);
15422             if (Arg.getOpcode() == ISD::UNDEF) continue;
15423             BaseShAmt = Arg;
15424             break;
15425           }
15426         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
15427            if (ConstantSDNode *C =
15428                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
15429              unsigned SplatIdx =
15430                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
15431              if (C->getZExtValue() == SplatIdx)
15432                BaseShAmt = InVec.getOperand(1);
15433            }
15434         }
15435         if (!BaseShAmt.getNode())
15436           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
15437                                   DAG.getIntPtrConstant(0));
15438       }
15439     }
15440
15441     if (BaseShAmt.getNode()) {
15442       if (EltVT.bitsGT(MVT::i32))
15443         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
15444       else if (EltVT.bitsLT(MVT::i32))
15445         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
15446
15447       switch (Op.getOpcode()) {
15448       default:
15449         llvm_unreachable("Unknown shift opcode!");
15450       case ISD::SHL:
15451         switch (VT.SimpleTy) {
15452         default: return SDValue();
15453         case MVT::v2i64:
15454         case MVT::v4i32:
15455         case MVT::v8i16:
15456         case MVT::v4i64:
15457         case MVT::v8i32:
15458         case MVT::v16i16:
15459         case MVT::v16i32:
15460         case MVT::v8i64:
15461           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
15462         }
15463       case ISD::SRA:
15464         switch (VT.SimpleTy) {
15465         default: return SDValue();
15466         case MVT::v4i32:
15467         case MVT::v8i16:
15468         case MVT::v8i32:
15469         case MVT::v16i16:
15470         case MVT::v16i32:
15471         case MVT::v8i64:
15472           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
15473         }
15474       case ISD::SRL:
15475         switch (VT.SimpleTy) {
15476         default: return SDValue();
15477         case MVT::v2i64:
15478         case MVT::v4i32:
15479         case MVT::v8i16:
15480         case MVT::v4i64:
15481         case MVT::v8i32:
15482         case MVT::v16i16:
15483         case MVT::v16i32:
15484         case MVT::v8i64:
15485           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
15486         }
15487       }
15488     }
15489   }
15490
15491   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
15492   if (!Subtarget->is64Bit() &&
15493       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
15494       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
15495       Amt.getOpcode() == ISD::BITCAST &&
15496       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
15497     Amt = Amt.getOperand(0);
15498     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
15499                      VT.getVectorNumElements();
15500     std::vector<SDValue> Vals(Ratio);
15501     for (unsigned i = 0; i != Ratio; ++i)
15502       Vals[i] = Amt.getOperand(i);
15503     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
15504       for (unsigned j = 0; j != Ratio; ++j)
15505         if (Vals[j] != Amt.getOperand(i + j))
15506           return SDValue();
15507     }
15508     switch (Op.getOpcode()) {
15509     default:
15510       llvm_unreachable("Unknown shift opcode!");
15511     case ISD::SHL:
15512       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
15513     case ISD::SRL:
15514       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
15515     case ISD::SRA:
15516       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
15517     }
15518   }
15519
15520   return SDValue();
15521 }
15522
15523 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
15524                           SelectionDAG &DAG) {
15525   MVT VT = Op.getSimpleValueType();
15526   SDLoc dl(Op);
15527   SDValue R = Op.getOperand(0);
15528   SDValue Amt = Op.getOperand(1);
15529   SDValue V;
15530
15531   assert(VT.isVector() && "Custom lowering only for vector shifts!");
15532   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
15533
15534   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
15535   if (V.getNode())
15536     return V;
15537
15538   V = LowerScalarVariableShift(Op, DAG, Subtarget);
15539   if (V.getNode())
15540       return V;
15541
15542   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
15543     return Op;
15544   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
15545   if (Subtarget->hasInt256()) {
15546     if (Op.getOpcode() == ISD::SRL &&
15547         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15548          VT == MVT::v4i64 || VT == MVT::v8i32))
15549       return Op;
15550     if (Op.getOpcode() == ISD::SHL &&
15551         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
15552          VT == MVT::v4i64 || VT == MVT::v8i32))
15553       return Op;
15554     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
15555       return Op;
15556   }
15557
15558   // If possible, lower this packed shift into a vector multiply instead of
15559   // expanding it into a sequence of scalar shifts.
15560   // Do this only if the vector shift count is a constant build_vector.
15561   if (Op.getOpcode() == ISD::SHL && 
15562       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
15563        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
15564       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15565     SmallVector<SDValue, 8> Elts;
15566     EVT SVT = VT.getScalarType();
15567     unsigned SVTBits = SVT.getSizeInBits();
15568     const APInt &One = APInt(SVTBits, 1);
15569     unsigned NumElems = VT.getVectorNumElements();
15570
15571     for (unsigned i=0; i !=NumElems; ++i) {
15572       SDValue Op = Amt->getOperand(i);
15573       if (Op->getOpcode() == ISD::UNDEF) {
15574         Elts.push_back(Op);
15575         continue;
15576       }
15577
15578       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
15579       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
15580       uint64_t ShAmt = C.getZExtValue();
15581       if (ShAmt >= SVTBits) {
15582         Elts.push_back(DAG.getUNDEF(SVT));
15583         continue;
15584       }
15585       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
15586     }
15587     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15588     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
15589   }
15590
15591   // Lower SHL with variable shift amount.
15592   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
15593     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
15594
15595     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
15596     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
15597     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
15598     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
15599   }
15600
15601   // If possible, lower this shift as a sequence of two shifts by
15602   // constant plus a MOVSS/MOVSD instead of scalarizing it.
15603   // Example:
15604   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
15605   //
15606   // Could be rewritten as:
15607   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
15608   //
15609   // The advantage is that the two shifts from the example would be
15610   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
15611   // the vector shift into four scalar shifts plus four pairs of vector
15612   // insert/extract.
15613   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
15614       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
15615     unsigned TargetOpcode = X86ISD::MOVSS;
15616     bool CanBeSimplified;
15617     // The splat value for the first packed shift (the 'X' from the example).
15618     SDValue Amt1 = Amt->getOperand(0);
15619     // The splat value for the second packed shift (the 'Y' from the example).
15620     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
15621                                         Amt->getOperand(2);
15622
15623     // See if it is possible to replace this node with a sequence of
15624     // two shifts followed by a MOVSS/MOVSD
15625     if (VT == MVT::v4i32) {
15626       // Check if it is legal to use a MOVSS.
15627       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
15628                         Amt2 == Amt->getOperand(3);
15629       if (!CanBeSimplified) {
15630         // Otherwise, check if we can still simplify this node using a MOVSD.
15631         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
15632                           Amt->getOperand(2) == Amt->getOperand(3);
15633         TargetOpcode = X86ISD::MOVSD;
15634         Amt2 = Amt->getOperand(2);
15635       }
15636     } else {
15637       // Do similar checks for the case where the machine value type
15638       // is MVT::v8i16.
15639       CanBeSimplified = Amt1 == Amt->getOperand(1);
15640       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
15641         CanBeSimplified = Amt2 == Amt->getOperand(i);
15642
15643       if (!CanBeSimplified) {
15644         TargetOpcode = X86ISD::MOVSD;
15645         CanBeSimplified = true;
15646         Amt2 = Amt->getOperand(4);
15647         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
15648           CanBeSimplified = Amt1 == Amt->getOperand(i);
15649         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
15650           CanBeSimplified = Amt2 == Amt->getOperand(j);
15651       }
15652     }
15653     
15654     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
15655         isa<ConstantSDNode>(Amt2)) {
15656       // Replace this node with two shifts followed by a MOVSS/MOVSD.
15657       EVT CastVT = MVT::v4i32;
15658       SDValue Splat1 = 
15659         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
15660       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
15661       SDValue Splat2 = 
15662         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
15663       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
15664       if (TargetOpcode == X86ISD::MOVSD)
15665         CastVT = MVT::v2i64;
15666       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
15667       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
15668       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
15669                                             BitCast1, DAG);
15670       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
15671     }
15672   }
15673
15674   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
15675     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
15676
15677     // a = a << 5;
15678     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
15679     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
15680
15681     // Turn 'a' into a mask suitable for VSELECT
15682     SDValue VSelM = DAG.getConstant(0x80, VT);
15683     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15684     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15685
15686     SDValue CM1 = DAG.getConstant(0x0f, VT);
15687     SDValue CM2 = DAG.getConstant(0x3f, VT);
15688
15689     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
15690     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
15691     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
15692     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15693     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15694
15695     // a += a
15696     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15697     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15698     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15699
15700     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
15701     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
15702     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
15703     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
15704     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
15705
15706     // a += a
15707     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
15708     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
15709     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
15710
15711     // return VSELECT(r, r+r, a);
15712     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
15713                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
15714     return R;
15715   }
15716
15717   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
15718   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
15719   // solution better.
15720   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
15721     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
15722     unsigned ExtOpc =
15723         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
15724     R = DAG.getNode(ExtOpc, dl, NewVT, R);
15725     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
15726     return DAG.getNode(ISD::TRUNCATE, dl, VT,
15727                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
15728     }
15729
15730   // Decompose 256-bit shifts into smaller 128-bit shifts.
15731   if (VT.is256BitVector()) {
15732     unsigned NumElems = VT.getVectorNumElements();
15733     MVT EltVT = VT.getVectorElementType();
15734     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15735
15736     // Extract the two vectors
15737     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
15738     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
15739
15740     // Recreate the shift amount vectors
15741     SDValue Amt1, Amt2;
15742     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
15743       // Constant shift amount
15744       SmallVector<SDValue, 4> Amt1Csts;
15745       SmallVector<SDValue, 4> Amt2Csts;
15746       for (unsigned i = 0; i != NumElems/2; ++i)
15747         Amt1Csts.push_back(Amt->getOperand(i));
15748       for (unsigned i = NumElems/2; i != NumElems; ++i)
15749         Amt2Csts.push_back(Amt->getOperand(i));
15750
15751       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
15752       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
15753     } else {
15754       // Variable shift amount
15755       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
15756       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
15757     }
15758
15759     // Issue new vector shifts for the smaller types
15760     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
15761     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
15762
15763     // Concatenate the result back
15764     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
15765   }
15766
15767   return SDValue();
15768 }
15769
15770 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
15771   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
15772   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
15773   // looks for this combo and may remove the "setcc" instruction if the "setcc"
15774   // has only one use.
15775   SDNode *N = Op.getNode();
15776   SDValue LHS = N->getOperand(0);
15777   SDValue RHS = N->getOperand(1);
15778   unsigned BaseOp = 0;
15779   unsigned Cond = 0;
15780   SDLoc DL(Op);
15781   switch (Op.getOpcode()) {
15782   default: llvm_unreachable("Unknown ovf instruction!");
15783   case ISD::SADDO:
15784     // A subtract of one will be selected as a INC. Note that INC doesn't
15785     // set CF, so we can't do this for UADDO.
15786     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15787       if (C->isOne()) {
15788         BaseOp = X86ISD::INC;
15789         Cond = X86::COND_O;
15790         break;
15791       }
15792     BaseOp = X86ISD::ADD;
15793     Cond = X86::COND_O;
15794     break;
15795   case ISD::UADDO:
15796     BaseOp = X86ISD::ADD;
15797     Cond = X86::COND_B;
15798     break;
15799   case ISD::SSUBO:
15800     // A subtract of one will be selected as a DEC. Note that DEC doesn't
15801     // set CF, so we can't do this for USUBO.
15802     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
15803       if (C->isOne()) {
15804         BaseOp = X86ISD::DEC;
15805         Cond = X86::COND_O;
15806         break;
15807       }
15808     BaseOp = X86ISD::SUB;
15809     Cond = X86::COND_O;
15810     break;
15811   case ISD::USUBO:
15812     BaseOp = X86ISD::SUB;
15813     Cond = X86::COND_B;
15814     break;
15815   case ISD::SMULO:
15816     BaseOp = X86ISD::SMUL;
15817     Cond = X86::COND_O;
15818     break;
15819   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
15820     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
15821                                  MVT::i32);
15822     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
15823
15824     SDValue SetCC =
15825       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
15826                   DAG.getConstant(X86::COND_O, MVT::i32),
15827                   SDValue(Sum.getNode(), 2));
15828
15829     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15830   }
15831   }
15832
15833   // Also sets EFLAGS.
15834   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
15835   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
15836
15837   SDValue SetCC =
15838     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
15839                 DAG.getConstant(Cond, MVT::i32),
15840                 SDValue(Sum.getNode(), 1));
15841
15842   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
15843 }
15844
15845 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
15846                                                   SelectionDAG &DAG) const {
15847   SDLoc dl(Op);
15848   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
15849   MVT VT = Op.getSimpleValueType();
15850
15851   if (!Subtarget->hasSSE2() || !VT.isVector())
15852     return SDValue();
15853
15854   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
15855                       ExtraVT.getScalarType().getSizeInBits();
15856
15857   switch (VT.SimpleTy) {
15858     default: return SDValue();
15859     case MVT::v8i32:
15860     case MVT::v16i16:
15861       if (!Subtarget->hasFp256())
15862         return SDValue();
15863       if (!Subtarget->hasInt256()) {
15864         // needs to be split
15865         unsigned NumElems = VT.getVectorNumElements();
15866
15867         // Extract the LHS vectors
15868         SDValue LHS = Op.getOperand(0);
15869         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
15870         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
15871
15872         MVT EltVT = VT.getVectorElementType();
15873         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
15874
15875         EVT ExtraEltVT = ExtraVT.getVectorElementType();
15876         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
15877         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
15878                                    ExtraNumElems/2);
15879         SDValue Extra = DAG.getValueType(ExtraVT);
15880
15881         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
15882         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
15883
15884         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
15885       }
15886       // fall through
15887     case MVT::v4i32:
15888     case MVT::v8i16: {
15889       SDValue Op0 = Op.getOperand(0);
15890       SDValue Op00 = Op0.getOperand(0);
15891       SDValue Tmp1;
15892       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
15893       if (Op0.getOpcode() == ISD::BITCAST &&
15894           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
15895         // (sext (vzext x)) -> (vsext x)
15896         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
15897         if (Tmp1.getNode()) {
15898           EVT ExtraEltVT = ExtraVT.getVectorElementType();
15899           // This folding is only valid when the in-reg type is a vector of i8,
15900           // i16, or i32.
15901           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
15902               ExtraEltVT == MVT::i32) {
15903             SDValue Tmp1Op0 = Tmp1.getOperand(0);
15904             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
15905                    "This optimization is invalid without a VZEXT.");
15906             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
15907           }
15908           Op0 = Tmp1;
15909         }
15910       }
15911
15912       // If the above didn't work, then just use Shift-Left + Shift-Right.
15913       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
15914                                         DAG);
15915       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
15916                                         DAG);
15917     }
15918   }
15919 }
15920
15921 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
15922                                  SelectionDAG &DAG) {
15923   SDLoc dl(Op);
15924   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
15925     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
15926   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
15927     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
15928
15929   // The only fence that needs an instruction is a sequentially-consistent
15930   // cross-thread fence.
15931   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
15932     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
15933     // no-sse2). There isn't any reason to disable it if the target processor
15934     // supports it.
15935     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
15936       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
15937
15938     SDValue Chain = Op.getOperand(0);
15939     SDValue Zero = DAG.getConstant(0, MVT::i32);
15940     SDValue Ops[] = {
15941       DAG.getRegister(X86::ESP, MVT::i32), // Base
15942       DAG.getTargetConstant(1, MVT::i8),   // Scale
15943       DAG.getRegister(0, MVT::i32),        // Index
15944       DAG.getTargetConstant(0, MVT::i32),  // Disp
15945       DAG.getRegister(0, MVT::i32),        // Segment.
15946       Zero,
15947       Chain
15948     };
15949     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
15950     return SDValue(Res, 0);
15951   }
15952
15953   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
15954   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
15955 }
15956
15957 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
15958                              SelectionDAG &DAG) {
15959   MVT T = Op.getSimpleValueType();
15960   SDLoc DL(Op);
15961   unsigned Reg = 0;
15962   unsigned size = 0;
15963   switch(T.SimpleTy) {
15964   default: llvm_unreachable("Invalid value type!");
15965   case MVT::i8:  Reg = X86::AL;  size = 1; break;
15966   case MVT::i16: Reg = X86::AX;  size = 2; break;
15967   case MVT::i32: Reg = X86::EAX; size = 4; break;
15968   case MVT::i64:
15969     assert(Subtarget->is64Bit() && "Node not type legal!");
15970     Reg = X86::RAX; size = 8;
15971     break;
15972   }
15973   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
15974                                   Op.getOperand(2), SDValue());
15975   SDValue Ops[] = { cpIn.getValue(0),
15976                     Op.getOperand(1),
15977                     Op.getOperand(3),
15978                     DAG.getTargetConstant(size, MVT::i8),
15979                     cpIn.getValue(1) };
15980   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15981   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
15982   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
15983                                            Ops, T, MMO);
15984
15985   SDValue cpOut =
15986     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
15987   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
15988                                       MVT::i32, cpOut.getValue(2));
15989   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
15990                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15991
15992   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
15993   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
15994   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
15995   return SDValue();
15996 }
15997
15998 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
15999                             SelectionDAG &DAG) {
16000   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
16001   MVT DstVT = Op.getSimpleValueType();
16002
16003   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
16004     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16005     if (DstVT != MVT::f64)
16006       // This conversion needs to be expanded.
16007       return SDValue();
16008
16009     SDValue InVec = Op->getOperand(0);
16010     SDLoc dl(Op);
16011     unsigned NumElts = SrcVT.getVectorNumElements();
16012     EVT SVT = SrcVT.getVectorElementType();
16013
16014     // Widen the vector in input in the case of MVT::v2i32.
16015     // Example: from MVT::v2i32 to MVT::v4i32.
16016     SmallVector<SDValue, 16> Elts;
16017     for (unsigned i = 0, e = NumElts; i != e; ++i)
16018       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
16019                                  DAG.getIntPtrConstant(i)));
16020
16021     // Explicitly mark the extra elements as Undef.
16022     SDValue Undef = DAG.getUNDEF(SVT);
16023     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
16024       Elts.push_back(Undef);
16025
16026     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16027     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
16028     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
16029     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
16030                        DAG.getIntPtrConstant(0));
16031   }
16032
16033   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
16034          Subtarget->hasMMX() && "Unexpected custom BITCAST");
16035   assert((DstVT == MVT::i64 ||
16036           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
16037          "Unexpected custom BITCAST");
16038   // i64 <=> MMX conversions are Legal.
16039   if (SrcVT==MVT::i64 && DstVT.isVector())
16040     return Op;
16041   if (DstVT==MVT::i64 && SrcVT.isVector())
16042     return Op;
16043   // MMX <=> MMX conversions are Legal.
16044   if (SrcVT.isVector() && DstVT.isVector())
16045     return Op;
16046   // All other conversions need to be expanded.
16047   return SDValue();
16048 }
16049
16050 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
16051   SDNode *Node = Op.getNode();
16052   SDLoc dl(Node);
16053   EVT T = Node->getValueType(0);
16054   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
16055                               DAG.getConstant(0, T), Node->getOperand(2));
16056   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
16057                        cast<AtomicSDNode>(Node)->getMemoryVT(),
16058                        Node->getOperand(0),
16059                        Node->getOperand(1), negOp,
16060                        cast<AtomicSDNode>(Node)->getMemOperand(),
16061                        cast<AtomicSDNode>(Node)->getOrdering(),
16062                        cast<AtomicSDNode>(Node)->getSynchScope());
16063 }
16064
16065 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
16066   SDNode *Node = Op.getNode();
16067   SDLoc dl(Node);
16068   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16069
16070   // Convert seq_cst store -> xchg
16071   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
16072   // FIXME: On 32-bit, store -> fist or movq would be more efficient
16073   //        (The only way to get a 16-byte store is cmpxchg16b)
16074   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
16075   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
16076       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
16077     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
16078                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
16079                                  Node->getOperand(0),
16080                                  Node->getOperand(1), Node->getOperand(2),
16081                                  cast<AtomicSDNode>(Node)->getMemOperand(),
16082                                  cast<AtomicSDNode>(Node)->getOrdering(),
16083                                  cast<AtomicSDNode>(Node)->getSynchScope());
16084     return Swap.getValue(1);
16085   }
16086   // Other atomic stores have a simple pattern.
16087   return Op;
16088 }
16089
16090 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
16091   EVT VT = Op.getNode()->getSimpleValueType(0);
16092
16093   // Let legalize expand this if it isn't a legal type yet.
16094   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
16095     return SDValue();
16096
16097   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16098
16099   unsigned Opc;
16100   bool ExtraOp = false;
16101   switch (Op.getOpcode()) {
16102   default: llvm_unreachable("Invalid code");
16103   case ISD::ADDC: Opc = X86ISD::ADD; break;
16104   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
16105   case ISD::SUBC: Opc = X86ISD::SUB; break;
16106   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
16107   }
16108
16109   if (!ExtraOp)
16110     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16111                        Op.getOperand(1));
16112   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
16113                      Op.getOperand(1), Op.getOperand(2));
16114 }
16115
16116 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
16117                             SelectionDAG &DAG) {
16118   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
16119
16120   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
16121   // which returns the values as { float, float } (in XMM0) or
16122   // { double, double } (which is returned in XMM0, XMM1).
16123   SDLoc dl(Op);
16124   SDValue Arg = Op.getOperand(0);
16125   EVT ArgVT = Arg.getValueType();
16126   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16127
16128   TargetLowering::ArgListTy Args;
16129   TargetLowering::ArgListEntry Entry;
16130
16131   Entry.Node = Arg;
16132   Entry.Ty = ArgTy;
16133   Entry.isSExt = false;
16134   Entry.isZExt = false;
16135   Args.push_back(Entry);
16136
16137   bool isF64 = ArgVT == MVT::f64;
16138   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
16139   // the small struct {f32, f32} is returned in (eax, edx). For f64,
16140   // the results are returned via SRet in memory.
16141   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
16142   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16143   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
16144
16145   Type *RetTy = isF64
16146     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
16147     : (Type*)VectorType::get(ArgTy, 4);
16148
16149   TargetLowering::CallLoweringInfo CLI(DAG);
16150   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
16151     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
16152
16153   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
16154
16155   if (isF64)
16156     // Returned in xmm0 and xmm1.
16157     return CallResult.first;
16158
16159   // Returned in bits 0:31 and 32:64 xmm0.
16160   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16161                                CallResult.first, DAG.getIntPtrConstant(0));
16162   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
16163                                CallResult.first, DAG.getIntPtrConstant(1));
16164   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
16165   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
16166 }
16167
16168 /// LowerOperation - Provide custom lowering hooks for some operations.
16169 ///
16170 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
16171   switch (Op.getOpcode()) {
16172   default: llvm_unreachable("Should not custom lower this!");
16173   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
16174   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
16175   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
16176     return LowerCMP_SWAP(Op, Subtarget, DAG);
16177   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
16178   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
16179   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
16180   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
16181   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
16182   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
16183   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
16184   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
16185   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
16186   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
16187   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
16188   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
16189   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
16190   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
16191   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
16192   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
16193   case ISD::SHL_PARTS:
16194   case ISD::SRA_PARTS:
16195   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
16196   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
16197   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
16198   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
16199   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
16200   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
16201   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
16202   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
16203   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
16204   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
16205   case ISD::FABS:               return LowerFABS(Op, DAG);
16206   case ISD::FNEG:               return LowerFNEG(Op, DAG);
16207   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
16208   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
16209   case ISD::SETCC:              return LowerSETCC(Op, DAG);
16210   case ISD::SELECT:             return LowerSELECT(Op, DAG);
16211   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
16212   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
16213   case ISD::VASTART:            return LowerVASTART(Op, DAG);
16214   case ISD::VAARG:              return LowerVAARG(Op, DAG);
16215   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
16216   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
16217   case ISD::INTRINSIC_VOID:
16218   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
16219   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
16220   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
16221   case ISD::FRAME_TO_ARGS_OFFSET:
16222                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
16223   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
16224   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
16225   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
16226   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
16227   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
16228   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
16229   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
16230   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
16231   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
16232   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
16233   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
16234   case ISD::UMUL_LOHI:
16235   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
16236   case ISD::SRA:
16237   case ISD::SRL:
16238   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
16239   case ISD::SADDO:
16240   case ISD::UADDO:
16241   case ISD::SSUBO:
16242   case ISD::USUBO:
16243   case ISD::SMULO:
16244   case ISD::UMULO:              return LowerXALUO(Op, DAG);
16245   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
16246   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
16247   case ISD::ADDC:
16248   case ISD::ADDE:
16249   case ISD::SUBC:
16250   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
16251   case ISD::ADD:                return LowerADD(Op, DAG);
16252   case ISD::SUB:                return LowerSUB(Op, DAG);
16253   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
16254   }
16255 }
16256
16257 static void ReplaceATOMIC_LOAD(SDNode *Node,
16258                                SmallVectorImpl<SDValue> &Results,
16259                                SelectionDAG &DAG) {
16260   SDLoc dl(Node);
16261   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
16262
16263   // Convert wide load -> cmpxchg8b/cmpxchg16b
16264   // FIXME: On 32-bit, load -> fild or movq would be more efficient
16265   //        (The only way to get a 16-byte load is cmpxchg16b)
16266   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
16267   SDValue Zero = DAG.getConstant(0, VT);
16268   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
16269   SDValue Swap =
16270       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
16271                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
16272                            cast<AtomicSDNode>(Node)->getMemOperand(),
16273                            cast<AtomicSDNode>(Node)->getOrdering(),
16274                            cast<AtomicSDNode>(Node)->getOrdering(),
16275                            cast<AtomicSDNode>(Node)->getSynchScope());
16276   Results.push_back(Swap.getValue(0));
16277   Results.push_back(Swap.getValue(2));
16278 }
16279
16280 /// ReplaceNodeResults - Replace a node with an illegal result type
16281 /// with a new node built out of custom code.
16282 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
16283                                            SmallVectorImpl<SDValue>&Results,
16284                                            SelectionDAG &DAG) const {
16285   SDLoc dl(N);
16286   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16287   switch (N->getOpcode()) {
16288   default:
16289     llvm_unreachable("Do not know how to custom type legalize this operation!");
16290   case ISD::SIGN_EXTEND_INREG:
16291   case ISD::ADDC:
16292   case ISD::ADDE:
16293   case ISD::SUBC:
16294   case ISD::SUBE:
16295     // We don't want to expand or promote these.
16296     return;
16297   case ISD::SDIV:
16298   case ISD::UDIV:
16299   case ISD::SREM:
16300   case ISD::UREM:
16301   case ISD::SDIVREM:
16302   case ISD::UDIVREM: {
16303     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
16304     Results.push_back(V);
16305     return;
16306   }
16307   case ISD::FP_TO_SINT:
16308   case ISD::FP_TO_UINT: {
16309     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
16310
16311     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
16312       return;
16313
16314     std::pair<SDValue,SDValue> Vals =
16315         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
16316     SDValue FIST = Vals.first, StackSlot = Vals.second;
16317     if (FIST.getNode()) {
16318       EVT VT = N->getValueType(0);
16319       // Return a load from the stack slot.
16320       if (StackSlot.getNode())
16321         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
16322                                       MachinePointerInfo(),
16323                                       false, false, false, 0));
16324       else
16325         Results.push_back(FIST);
16326     }
16327     return;
16328   }
16329   case ISD::UINT_TO_FP: {
16330     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16331     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
16332         N->getValueType(0) != MVT::v2f32)
16333       return;
16334     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
16335                                  N->getOperand(0));
16336     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
16337                                      MVT::f64);
16338     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
16339     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
16340                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
16341     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
16342     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
16343     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
16344     return;
16345   }
16346   case ISD::FP_ROUND: {
16347     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
16348         return;
16349     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
16350     Results.push_back(V);
16351     return;
16352   }
16353   case ISD::INTRINSIC_W_CHAIN: {
16354     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
16355     switch (IntNo) {
16356     default : llvm_unreachable("Do not know how to custom type "
16357                                "legalize this intrinsic operation!");
16358     case Intrinsic::x86_rdtsc:
16359       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16360                                      Results);
16361     case Intrinsic::x86_rdtscp:
16362       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
16363                                      Results);
16364     case Intrinsic::x86_rdpmc:
16365       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
16366     }
16367   }
16368   case ISD::READCYCLECOUNTER: {
16369     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
16370                                    Results);
16371   }
16372   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
16373     EVT T = N->getValueType(0);
16374     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
16375     bool Regs64bit = T == MVT::i128;
16376     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
16377     SDValue cpInL, cpInH;
16378     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16379                         DAG.getConstant(0, HalfT));
16380     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
16381                         DAG.getConstant(1, HalfT));
16382     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
16383                              Regs64bit ? X86::RAX : X86::EAX,
16384                              cpInL, SDValue());
16385     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
16386                              Regs64bit ? X86::RDX : X86::EDX,
16387                              cpInH, cpInL.getValue(1));
16388     SDValue swapInL, swapInH;
16389     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16390                           DAG.getConstant(0, HalfT));
16391     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
16392                           DAG.getConstant(1, HalfT));
16393     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
16394                                Regs64bit ? X86::RBX : X86::EBX,
16395                                swapInL, cpInH.getValue(1));
16396     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
16397                                Regs64bit ? X86::RCX : X86::ECX,
16398                                swapInH, swapInL.getValue(1));
16399     SDValue Ops[] = { swapInH.getValue(0),
16400                       N->getOperand(1),
16401                       swapInH.getValue(1) };
16402     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16403     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
16404     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
16405                                   X86ISD::LCMPXCHG8_DAG;
16406     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
16407     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
16408                                         Regs64bit ? X86::RAX : X86::EAX,
16409                                         HalfT, Result.getValue(1));
16410     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
16411                                         Regs64bit ? X86::RDX : X86::EDX,
16412                                         HalfT, cpOutL.getValue(2));
16413     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
16414
16415     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
16416                                         MVT::i32, cpOutH.getValue(2));
16417     SDValue Success =
16418         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16419                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
16420     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
16421
16422     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
16423     Results.push_back(Success);
16424     Results.push_back(EFLAGS.getValue(1));
16425     return;
16426   }
16427   case ISD::ATOMIC_SWAP:
16428   case ISD::ATOMIC_LOAD_ADD:
16429   case ISD::ATOMIC_LOAD_SUB:
16430   case ISD::ATOMIC_LOAD_AND:
16431   case ISD::ATOMIC_LOAD_OR:
16432   case ISD::ATOMIC_LOAD_XOR:
16433   case ISD::ATOMIC_LOAD_NAND:
16434   case ISD::ATOMIC_LOAD_MIN:
16435   case ISD::ATOMIC_LOAD_MAX:
16436   case ISD::ATOMIC_LOAD_UMIN:
16437   case ISD::ATOMIC_LOAD_UMAX:
16438     // Delegate to generic TypeLegalization. Situations we can really handle
16439     // should have already been dealt with by X86AtomicExpand.cpp.
16440     break;
16441   case ISD::ATOMIC_LOAD: {
16442     ReplaceATOMIC_LOAD(N, Results, DAG);
16443     return;
16444   }
16445   case ISD::BITCAST: {
16446     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
16447     EVT DstVT = N->getValueType(0);
16448     EVT SrcVT = N->getOperand(0)->getValueType(0);
16449
16450     if (SrcVT != MVT::f64 ||
16451         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
16452       return;
16453
16454     unsigned NumElts = DstVT.getVectorNumElements();
16455     EVT SVT = DstVT.getVectorElementType();
16456     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
16457     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
16458                                    MVT::v2f64, N->getOperand(0));
16459     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
16460
16461     if (ExperimentalVectorWideningLegalization) {
16462       // If we are legalizing vectors by widening, we already have the desired
16463       // legal vector type, just return it.
16464       Results.push_back(ToVecInt);
16465       return;
16466     }
16467
16468     SmallVector<SDValue, 8> Elts;
16469     for (unsigned i = 0, e = NumElts; i != e; ++i)
16470       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
16471                                    ToVecInt, DAG.getIntPtrConstant(i)));
16472
16473     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
16474   }
16475   }
16476 }
16477
16478 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
16479   switch (Opcode) {
16480   default: return nullptr;
16481   case X86ISD::BSF:                return "X86ISD::BSF";
16482   case X86ISD::BSR:                return "X86ISD::BSR";
16483   case X86ISD::SHLD:               return "X86ISD::SHLD";
16484   case X86ISD::SHRD:               return "X86ISD::SHRD";
16485   case X86ISD::FAND:               return "X86ISD::FAND";
16486   case X86ISD::FANDN:              return "X86ISD::FANDN";
16487   case X86ISD::FOR:                return "X86ISD::FOR";
16488   case X86ISD::FXOR:               return "X86ISD::FXOR";
16489   case X86ISD::FSRL:               return "X86ISD::FSRL";
16490   case X86ISD::FILD:               return "X86ISD::FILD";
16491   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
16492   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
16493   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
16494   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
16495   case X86ISD::FLD:                return "X86ISD::FLD";
16496   case X86ISD::FST:                return "X86ISD::FST";
16497   case X86ISD::CALL:               return "X86ISD::CALL";
16498   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
16499   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
16500   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
16501   case X86ISD::BT:                 return "X86ISD::BT";
16502   case X86ISD::CMP:                return "X86ISD::CMP";
16503   case X86ISD::COMI:               return "X86ISD::COMI";
16504   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
16505   case X86ISD::CMPM:               return "X86ISD::CMPM";
16506   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
16507   case X86ISD::SETCC:              return "X86ISD::SETCC";
16508   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
16509   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
16510   case X86ISD::CMOV:               return "X86ISD::CMOV";
16511   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
16512   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
16513   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
16514   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
16515   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
16516   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
16517   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
16518   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
16519   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
16520   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
16521   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
16522   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
16523   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
16524   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
16525   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
16526   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
16527   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
16528   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
16529   case X86ISD::HADD:               return "X86ISD::HADD";
16530   case X86ISD::HSUB:               return "X86ISD::HSUB";
16531   case X86ISD::FHADD:              return "X86ISD::FHADD";
16532   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
16533   case X86ISD::UMAX:               return "X86ISD::UMAX";
16534   case X86ISD::UMIN:               return "X86ISD::UMIN";
16535   case X86ISD::SMAX:               return "X86ISD::SMAX";
16536   case X86ISD::SMIN:               return "X86ISD::SMIN";
16537   case X86ISD::FMAX:               return "X86ISD::FMAX";
16538   case X86ISD::FMIN:               return "X86ISD::FMIN";
16539   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
16540   case X86ISD::FMINC:              return "X86ISD::FMINC";
16541   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
16542   case X86ISD::FRCP:               return "X86ISD::FRCP";
16543   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
16544   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
16545   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
16546   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
16547   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
16548   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
16549   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
16550   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
16551   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
16552   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
16553   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
16554   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
16555   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
16556   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
16557   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
16558   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
16559   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
16560   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
16561   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
16562   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
16563   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
16564   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
16565   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
16566   case X86ISD::VSHL:               return "X86ISD::VSHL";
16567   case X86ISD::VSRL:               return "X86ISD::VSRL";
16568   case X86ISD::VSRA:               return "X86ISD::VSRA";
16569   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
16570   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
16571   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
16572   case X86ISD::CMPP:               return "X86ISD::CMPP";
16573   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
16574   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
16575   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
16576   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
16577   case X86ISD::ADD:                return "X86ISD::ADD";
16578   case X86ISD::SUB:                return "X86ISD::SUB";
16579   case X86ISD::ADC:                return "X86ISD::ADC";
16580   case X86ISD::SBB:                return "X86ISD::SBB";
16581   case X86ISD::SMUL:               return "X86ISD::SMUL";
16582   case X86ISD::UMUL:               return "X86ISD::UMUL";
16583   case X86ISD::INC:                return "X86ISD::INC";
16584   case X86ISD::DEC:                return "X86ISD::DEC";
16585   case X86ISD::OR:                 return "X86ISD::OR";
16586   case X86ISD::XOR:                return "X86ISD::XOR";
16587   case X86ISD::AND:                return "X86ISD::AND";
16588   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
16589   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
16590   case X86ISD::PTEST:              return "X86ISD::PTEST";
16591   case X86ISD::TESTP:              return "X86ISD::TESTP";
16592   case X86ISD::TESTM:              return "X86ISD::TESTM";
16593   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
16594   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
16595   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
16596   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
16597   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
16598   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
16599   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
16600   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
16601   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
16602   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
16603   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
16604   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
16605   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
16606   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
16607   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
16608   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
16609   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
16610   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
16611   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
16612   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
16613   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
16614   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
16615   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
16616   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
16617   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
16618   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
16619   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
16620   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
16621   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
16622   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
16623   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
16624   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
16625   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
16626   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
16627   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
16628   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
16629   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
16630   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
16631   case X86ISD::SAHF:               return "X86ISD::SAHF";
16632   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
16633   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
16634   case X86ISD::FMADD:              return "X86ISD::FMADD";
16635   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
16636   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
16637   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
16638   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
16639   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
16640   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
16641   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
16642   case X86ISD::XTEST:              return "X86ISD::XTEST";
16643   }
16644 }
16645
16646 // isLegalAddressingMode - Return true if the addressing mode represented
16647 // by AM is legal for this target, for a load/store of the specified type.
16648 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
16649                                               Type *Ty) const {
16650   // X86 supports extremely general addressing modes.
16651   CodeModel::Model M = getTargetMachine().getCodeModel();
16652   Reloc::Model R = getTargetMachine().getRelocationModel();
16653
16654   // X86 allows a sign-extended 32-bit immediate field as a displacement.
16655   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
16656     return false;
16657
16658   if (AM.BaseGV) {
16659     unsigned GVFlags =
16660       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
16661
16662     // If a reference to this global requires an extra load, we can't fold it.
16663     if (isGlobalStubReference(GVFlags))
16664       return false;
16665
16666     // If BaseGV requires a register for the PIC base, we cannot also have a
16667     // BaseReg specified.
16668     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
16669       return false;
16670
16671     // If lower 4G is not available, then we must use rip-relative addressing.
16672     if ((M != CodeModel::Small || R != Reloc::Static) &&
16673         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
16674       return false;
16675   }
16676
16677   switch (AM.Scale) {
16678   case 0:
16679   case 1:
16680   case 2:
16681   case 4:
16682   case 8:
16683     // These scales always work.
16684     break;
16685   case 3:
16686   case 5:
16687   case 9:
16688     // These scales are formed with basereg+scalereg.  Only accept if there is
16689     // no basereg yet.
16690     if (AM.HasBaseReg)
16691       return false;
16692     break;
16693   default:  // Other stuff never works.
16694     return false;
16695   }
16696
16697   return true;
16698 }
16699
16700 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
16701   unsigned Bits = Ty->getScalarSizeInBits();
16702
16703   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
16704   // particularly cheaper than those without.
16705   if (Bits == 8)
16706     return false;
16707
16708   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
16709   // variable shifts just as cheap as scalar ones.
16710   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
16711     return false;
16712
16713   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
16714   // fully general vector.
16715   return true;
16716 }
16717
16718 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
16719   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16720     return false;
16721   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
16722   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
16723   return NumBits1 > NumBits2;
16724 }
16725
16726 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
16727   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
16728     return false;
16729
16730   if (!isTypeLegal(EVT::getEVT(Ty1)))
16731     return false;
16732
16733   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
16734
16735   // Assuming the caller doesn't have a zeroext or signext return parameter,
16736   // truncation all the way down to i1 is valid.
16737   return true;
16738 }
16739
16740 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
16741   return isInt<32>(Imm);
16742 }
16743
16744 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
16745   // Can also use sub to handle negated immediates.
16746   return isInt<32>(Imm);
16747 }
16748
16749 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
16750   if (!VT1.isInteger() || !VT2.isInteger())
16751     return false;
16752   unsigned NumBits1 = VT1.getSizeInBits();
16753   unsigned NumBits2 = VT2.getSizeInBits();
16754   return NumBits1 > NumBits2;
16755 }
16756
16757 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
16758   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16759   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
16760 }
16761
16762 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
16763   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
16764   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
16765 }
16766
16767 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
16768   EVT VT1 = Val.getValueType();
16769   if (isZExtFree(VT1, VT2))
16770     return true;
16771
16772   if (Val.getOpcode() != ISD::LOAD)
16773     return false;
16774
16775   if (!VT1.isSimple() || !VT1.isInteger() ||
16776       !VT2.isSimple() || !VT2.isInteger())
16777     return false;
16778
16779   switch (VT1.getSimpleVT().SimpleTy) {
16780   default: break;
16781   case MVT::i8:
16782   case MVT::i16:
16783   case MVT::i32:
16784     // X86 has 8, 16, and 32-bit zero-extending loads.
16785     return true;
16786   }
16787
16788   return false;
16789 }
16790
16791 bool
16792 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
16793   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
16794     return false;
16795
16796   VT = VT.getScalarType();
16797
16798   if (!VT.isSimple())
16799     return false;
16800
16801   switch (VT.getSimpleVT().SimpleTy) {
16802   case MVT::f32:
16803   case MVT::f64:
16804     return true;
16805   default:
16806     break;
16807   }
16808
16809   return false;
16810 }
16811
16812 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
16813   // i16 instructions are longer (0x66 prefix) and potentially slower.
16814   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
16815 }
16816
16817 /// isShuffleMaskLegal - Targets can use this to indicate that they only
16818 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
16819 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
16820 /// are assumed to be legal.
16821 bool
16822 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
16823                                       EVT VT) const {
16824   if (!VT.isSimple())
16825     return false;
16826
16827   MVT SVT = VT.getSimpleVT();
16828
16829   // Very little shuffling can be done for 64-bit vectors right now.
16830   if (VT.getSizeInBits() == 64)
16831     return false;
16832
16833   // If this is a single-input shuffle with no 128 bit lane crossings we can
16834   // lower it into pshufb.
16835   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
16836       (SVT.is256BitVector() && Subtarget->hasInt256())) {
16837     bool isLegal = true;
16838     for (unsigned I = 0, E = M.size(); I != E; ++I) {
16839       if (M[I] >= (int)SVT.getVectorNumElements() ||
16840           ShuffleCrosses128bitLane(SVT, I, M[I])) {
16841         isLegal = false;
16842         break;
16843       }
16844     }
16845     if (isLegal)
16846       return true;
16847   }
16848
16849   // FIXME: blends, shifts.
16850   return (SVT.getVectorNumElements() == 2 ||
16851           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
16852           isMOVLMask(M, SVT) ||
16853           isSHUFPMask(M, SVT) ||
16854           isPSHUFDMask(M, SVT) ||
16855           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
16856           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
16857           isPALIGNRMask(M, SVT, Subtarget) ||
16858           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
16859           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
16860           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16861           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
16862           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
16863 }
16864
16865 bool
16866 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
16867                                           EVT VT) const {
16868   if (!VT.isSimple())
16869     return false;
16870
16871   MVT SVT = VT.getSimpleVT();
16872   unsigned NumElts = SVT.getVectorNumElements();
16873   // FIXME: This collection of masks seems suspect.
16874   if (NumElts == 2)
16875     return true;
16876   if (NumElts == 4 && SVT.is128BitVector()) {
16877     return (isMOVLMask(Mask, SVT)  ||
16878             isCommutedMOVLMask(Mask, SVT, true) ||
16879             isSHUFPMask(Mask, SVT) ||
16880             isSHUFPMask(Mask, SVT, /* Commuted */ true));
16881   }
16882   return false;
16883 }
16884
16885 //===----------------------------------------------------------------------===//
16886 //                           X86 Scheduler Hooks
16887 //===----------------------------------------------------------------------===//
16888
16889 /// Utility function to emit xbegin specifying the start of an RTM region.
16890 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
16891                                      const TargetInstrInfo *TII) {
16892   DebugLoc DL = MI->getDebugLoc();
16893
16894   const BasicBlock *BB = MBB->getBasicBlock();
16895   MachineFunction::iterator I = MBB;
16896   ++I;
16897
16898   // For the v = xbegin(), we generate
16899   //
16900   // thisMBB:
16901   //  xbegin sinkMBB
16902   //
16903   // mainMBB:
16904   //  eax = -1
16905   //
16906   // sinkMBB:
16907   //  v = eax
16908
16909   MachineBasicBlock *thisMBB = MBB;
16910   MachineFunction *MF = MBB->getParent();
16911   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16912   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16913   MF->insert(I, mainMBB);
16914   MF->insert(I, sinkMBB);
16915
16916   // Transfer the remainder of BB and its successor edges to sinkMBB.
16917   sinkMBB->splice(sinkMBB->begin(), MBB,
16918                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16919   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16920
16921   // thisMBB:
16922   //  xbegin sinkMBB
16923   //  # fallthrough to mainMBB
16924   //  # abortion to sinkMBB
16925   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
16926   thisMBB->addSuccessor(mainMBB);
16927   thisMBB->addSuccessor(sinkMBB);
16928
16929   // mainMBB:
16930   //  EAX = -1
16931   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
16932   mainMBB->addSuccessor(sinkMBB);
16933
16934   // sinkMBB:
16935   // EAX is live into the sinkMBB
16936   sinkMBB->addLiveIn(X86::EAX);
16937   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16938           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16939     .addReg(X86::EAX);
16940
16941   MI->eraseFromParent();
16942   return sinkMBB;
16943 }
16944
16945 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16946 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16947 // in the .td file.
16948 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16949                                        const TargetInstrInfo *TII) {
16950   unsigned Opc;
16951   switch (MI->getOpcode()) {
16952   default: llvm_unreachable("illegal opcode!");
16953   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16954   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16955   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16956   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16957   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16958   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16959   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16960   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16961   }
16962
16963   DebugLoc dl = MI->getDebugLoc();
16964   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16965
16966   unsigned NumArgs = MI->getNumOperands();
16967   for (unsigned i = 1; i < NumArgs; ++i) {
16968     MachineOperand &Op = MI->getOperand(i);
16969     if (!(Op.isReg() && Op.isImplicit()))
16970       MIB.addOperand(Op);
16971   }
16972   if (MI->hasOneMemOperand())
16973     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16974
16975   BuildMI(*BB, MI, dl,
16976     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16977     .addReg(X86::XMM0);
16978
16979   MI->eraseFromParent();
16980   return BB;
16981 }
16982
16983 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16984 // defs in an instruction pattern
16985 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16986                                        const TargetInstrInfo *TII) {
16987   unsigned Opc;
16988   switch (MI->getOpcode()) {
16989   default: llvm_unreachable("illegal opcode!");
16990   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16991   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16992   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16993   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16994   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16995   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16996   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16997   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16998   }
16999
17000   DebugLoc dl = MI->getDebugLoc();
17001   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
17002
17003   unsigned NumArgs = MI->getNumOperands(); // remove the results
17004   for (unsigned i = 1; i < NumArgs; ++i) {
17005     MachineOperand &Op = MI->getOperand(i);
17006     if (!(Op.isReg() && Op.isImplicit()))
17007       MIB.addOperand(Op);
17008   }
17009   if (MI->hasOneMemOperand())
17010     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
17011
17012   BuildMI(*BB, MI, dl,
17013     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
17014     .addReg(X86::ECX);
17015
17016   MI->eraseFromParent();
17017   return BB;
17018 }
17019
17020 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
17021                                        const TargetInstrInfo *TII,
17022                                        const X86Subtarget* Subtarget) {
17023   DebugLoc dl = MI->getDebugLoc();
17024
17025   // Address into RAX/EAX, other two args into ECX, EDX.
17026   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
17027   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
17028   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
17029   for (int i = 0; i < X86::AddrNumOperands; ++i)
17030     MIB.addOperand(MI->getOperand(i));
17031
17032   unsigned ValOps = X86::AddrNumOperands;
17033   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
17034     .addReg(MI->getOperand(ValOps).getReg());
17035   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
17036     .addReg(MI->getOperand(ValOps+1).getReg());
17037
17038   // The instruction doesn't actually take any operands though.
17039   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
17040
17041   MI->eraseFromParent(); // The pseudo is gone now.
17042   return BB;
17043 }
17044
17045 MachineBasicBlock *
17046 X86TargetLowering::EmitVAARG64WithCustomInserter(
17047                    MachineInstr *MI,
17048                    MachineBasicBlock *MBB) const {
17049   // Emit va_arg instruction on X86-64.
17050
17051   // Operands to this pseudo-instruction:
17052   // 0  ) Output        : destination address (reg)
17053   // 1-5) Input         : va_list address (addr, i64mem)
17054   // 6  ) ArgSize       : Size (in bytes) of vararg type
17055   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
17056   // 8  ) Align         : Alignment of type
17057   // 9  ) EFLAGS (implicit-def)
17058
17059   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
17060   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
17061
17062   unsigned DestReg = MI->getOperand(0).getReg();
17063   MachineOperand &Base = MI->getOperand(1);
17064   MachineOperand &Scale = MI->getOperand(2);
17065   MachineOperand &Index = MI->getOperand(3);
17066   MachineOperand &Disp = MI->getOperand(4);
17067   MachineOperand &Segment = MI->getOperand(5);
17068   unsigned ArgSize = MI->getOperand(6).getImm();
17069   unsigned ArgMode = MI->getOperand(7).getImm();
17070   unsigned Align = MI->getOperand(8).getImm();
17071
17072   // Memory Reference
17073   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
17074   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17075   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17076
17077   // Machine Information
17078   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17079   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
17080   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
17081   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
17082   DebugLoc DL = MI->getDebugLoc();
17083
17084   // struct va_list {
17085   //   i32   gp_offset
17086   //   i32   fp_offset
17087   //   i64   overflow_area (address)
17088   //   i64   reg_save_area (address)
17089   // }
17090   // sizeof(va_list) = 24
17091   // alignment(va_list) = 8
17092
17093   unsigned TotalNumIntRegs = 6;
17094   unsigned TotalNumXMMRegs = 8;
17095   bool UseGPOffset = (ArgMode == 1);
17096   bool UseFPOffset = (ArgMode == 2);
17097   unsigned MaxOffset = TotalNumIntRegs * 8 +
17098                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
17099
17100   /* Align ArgSize to a multiple of 8 */
17101   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
17102   bool NeedsAlign = (Align > 8);
17103
17104   MachineBasicBlock *thisMBB = MBB;
17105   MachineBasicBlock *overflowMBB;
17106   MachineBasicBlock *offsetMBB;
17107   MachineBasicBlock *endMBB;
17108
17109   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
17110   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
17111   unsigned OffsetReg = 0;
17112
17113   if (!UseGPOffset && !UseFPOffset) {
17114     // If we only pull from the overflow region, we don't create a branch.
17115     // We don't need to alter control flow.
17116     OffsetDestReg = 0; // unused
17117     OverflowDestReg = DestReg;
17118
17119     offsetMBB = nullptr;
17120     overflowMBB = thisMBB;
17121     endMBB = thisMBB;
17122   } else {
17123     // First emit code to check if gp_offset (or fp_offset) is below the bound.
17124     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
17125     // If not, pull from overflow_area. (branch to overflowMBB)
17126     //
17127     //       thisMBB
17128     //         |     .
17129     //         |        .
17130     //     offsetMBB   overflowMBB
17131     //         |        .
17132     //         |     .
17133     //        endMBB
17134
17135     // Registers for the PHI in endMBB
17136     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
17137     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
17138
17139     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17140     MachineFunction *MF = MBB->getParent();
17141     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17142     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17143     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17144
17145     MachineFunction::iterator MBBIter = MBB;
17146     ++MBBIter;
17147
17148     // Insert the new basic blocks
17149     MF->insert(MBBIter, offsetMBB);
17150     MF->insert(MBBIter, overflowMBB);
17151     MF->insert(MBBIter, endMBB);
17152
17153     // Transfer the remainder of MBB and its successor edges to endMBB.
17154     endMBB->splice(endMBB->begin(), thisMBB,
17155                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
17156     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
17157
17158     // Make offsetMBB and overflowMBB successors of thisMBB
17159     thisMBB->addSuccessor(offsetMBB);
17160     thisMBB->addSuccessor(overflowMBB);
17161
17162     // endMBB is a successor of both offsetMBB and overflowMBB
17163     offsetMBB->addSuccessor(endMBB);
17164     overflowMBB->addSuccessor(endMBB);
17165
17166     // Load the offset value into a register
17167     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17168     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
17169       .addOperand(Base)
17170       .addOperand(Scale)
17171       .addOperand(Index)
17172       .addDisp(Disp, UseFPOffset ? 4 : 0)
17173       .addOperand(Segment)
17174       .setMemRefs(MMOBegin, MMOEnd);
17175
17176     // Check if there is enough room left to pull this argument.
17177     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
17178       .addReg(OffsetReg)
17179       .addImm(MaxOffset + 8 - ArgSizeA8);
17180
17181     // Branch to "overflowMBB" if offset >= max
17182     // Fall through to "offsetMBB" otherwise
17183     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
17184       .addMBB(overflowMBB);
17185   }
17186
17187   // In offsetMBB, emit code to use the reg_save_area.
17188   if (offsetMBB) {
17189     assert(OffsetReg != 0);
17190
17191     // Read the reg_save_area address.
17192     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
17193     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
17194       .addOperand(Base)
17195       .addOperand(Scale)
17196       .addOperand(Index)
17197       .addDisp(Disp, 16)
17198       .addOperand(Segment)
17199       .setMemRefs(MMOBegin, MMOEnd);
17200
17201     // Zero-extend the offset
17202     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
17203       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
17204         .addImm(0)
17205         .addReg(OffsetReg)
17206         .addImm(X86::sub_32bit);
17207
17208     // Add the offset to the reg_save_area to get the final address.
17209     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
17210       .addReg(OffsetReg64)
17211       .addReg(RegSaveReg);
17212
17213     // Compute the offset for the next argument
17214     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
17215     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
17216       .addReg(OffsetReg)
17217       .addImm(UseFPOffset ? 16 : 8);
17218
17219     // Store it back into the va_list.
17220     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
17221       .addOperand(Base)
17222       .addOperand(Scale)
17223       .addOperand(Index)
17224       .addDisp(Disp, UseFPOffset ? 4 : 0)
17225       .addOperand(Segment)
17226       .addReg(NextOffsetReg)
17227       .setMemRefs(MMOBegin, MMOEnd);
17228
17229     // Jump to endMBB
17230     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
17231       .addMBB(endMBB);
17232   }
17233
17234   //
17235   // Emit code to use overflow area
17236   //
17237
17238   // Load the overflow_area address into a register.
17239   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
17240   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
17241     .addOperand(Base)
17242     .addOperand(Scale)
17243     .addOperand(Index)
17244     .addDisp(Disp, 8)
17245     .addOperand(Segment)
17246     .setMemRefs(MMOBegin, MMOEnd);
17247
17248   // If we need to align it, do so. Otherwise, just copy the address
17249   // to OverflowDestReg.
17250   if (NeedsAlign) {
17251     // Align the overflow address
17252     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
17253     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
17254
17255     // aligned_addr = (addr + (align-1)) & ~(align-1)
17256     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
17257       .addReg(OverflowAddrReg)
17258       .addImm(Align-1);
17259
17260     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
17261       .addReg(TmpReg)
17262       .addImm(~(uint64_t)(Align-1));
17263   } else {
17264     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
17265       .addReg(OverflowAddrReg);
17266   }
17267
17268   // Compute the next overflow address after this argument.
17269   // (the overflow address should be kept 8-byte aligned)
17270   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
17271   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
17272     .addReg(OverflowDestReg)
17273     .addImm(ArgSizeA8);
17274
17275   // Store the new overflow address.
17276   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
17277     .addOperand(Base)
17278     .addOperand(Scale)
17279     .addOperand(Index)
17280     .addDisp(Disp, 8)
17281     .addOperand(Segment)
17282     .addReg(NextAddrReg)
17283     .setMemRefs(MMOBegin, MMOEnd);
17284
17285   // If we branched, emit the PHI to the front of endMBB.
17286   if (offsetMBB) {
17287     BuildMI(*endMBB, endMBB->begin(), DL,
17288             TII->get(X86::PHI), DestReg)
17289       .addReg(OffsetDestReg).addMBB(offsetMBB)
17290       .addReg(OverflowDestReg).addMBB(overflowMBB);
17291   }
17292
17293   // Erase the pseudo instruction
17294   MI->eraseFromParent();
17295
17296   return endMBB;
17297 }
17298
17299 MachineBasicBlock *
17300 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
17301                                                  MachineInstr *MI,
17302                                                  MachineBasicBlock *MBB) const {
17303   // Emit code to save XMM registers to the stack. The ABI says that the
17304   // number of registers to save is given in %al, so it's theoretically
17305   // possible to do an indirect jump trick to avoid saving all of them,
17306   // however this code takes a simpler approach and just executes all
17307   // of the stores if %al is non-zero. It's less code, and it's probably
17308   // easier on the hardware branch predictor, and stores aren't all that
17309   // expensive anyway.
17310
17311   // Create the new basic blocks. One block contains all the XMM stores,
17312   // and one block is the final destination regardless of whether any
17313   // stores were performed.
17314   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
17315   MachineFunction *F = MBB->getParent();
17316   MachineFunction::iterator MBBIter = MBB;
17317   ++MBBIter;
17318   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
17319   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
17320   F->insert(MBBIter, XMMSaveMBB);
17321   F->insert(MBBIter, EndMBB);
17322
17323   // Transfer the remainder of MBB and its successor edges to EndMBB.
17324   EndMBB->splice(EndMBB->begin(), MBB,
17325                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17326   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
17327
17328   // The original block will now fall through to the XMM save block.
17329   MBB->addSuccessor(XMMSaveMBB);
17330   // The XMMSaveMBB will fall through to the end block.
17331   XMMSaveMBB->addSuccessor(EndMBB);
17332
17333   // Now add the instructions.
17334   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
17335   DebugLoc DL = MI->getDebugLoc();
17336
17337   unsigned CountReg = MI->getOperand(0).getReg();
17338   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
17339   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
17340
17341   if (!Subtarget->isTargetWin64()) {
17342     // If %al is 0, branch around the XMM save block.
17343     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
17344     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
17345     MBB->addSuccessor(EndMBB);
17346   }
17347
17348   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
17349   // that was just emitted, but clearly shouldn't be "saved".
17350   assert((MI->getNumOperands() <= 3 ||
17351           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
17352           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
17353          && "Expected last argument to be EFLAGS");
17354   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
17355   // In the XMM save block, save all the XMM argument registers.
17356   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
17357     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
17358     MachineMemOperand *MMO =
17359       F->getMachineMemOperand(
17360           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
17361         MachineMemOperand::MOStore,
17362         /*Size=*/16, /*Align=*/16);
17363     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
17364       .addFrameIndex(RegSaveFrameIndex)
17365       .addImm(/*Scale=*/1)
17366       .addReg(/*IndexReg=*/0)
17367       .addImm(/*Disp=*/Offset)
17368       .addReg(/*Segment=*/0)
17369       .addReg(MI->getOperand(i).getReg())
17370       .addMemOperand(MMO);
17371   }
17372
17373   MI->eraseFromParent();   // The pseudo instruction is gone now.
17374
17375   return EndMBB;
17376 }
17377
17378 // The EFLAGS operand of SelectItr might be missing a kill marker
17379 // because there were multiple uses of EFLAGS, and ISel didn't know
17380 // which to mark. Figure out whether SelectItr should have had a
17381 // kill marker, and set it if it should. Returns the correct kill
17382 // marker value.
17383 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
17384                                      MachineBasicBlock* BB,
17385                                      const TargetRegisterInfo* TRI) {
17386   // Scan forward through BB for a use/def of EFLAGS.
17387   MachineBasicBlock::iterator miI(std::next(SelectItr));
17388   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
17389     const MachineInstr& mi = *miI;
17390     if (mi.readsRegister(X86::EFLAGS))
17391       return false;
17392     if (mi.definesRegister(X86::EFLAGS))
17393       break; // Should have kill-flag - update below.
17394   }
17395
17396   // If we hit the end of the block, check whether EFLAGS is live into a
17397   // successor.
17398   if (miI == BB->end()) {
17399     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
17400                                           sEnd = BB->succ_end();
17401          sItr != sEnd; ++sItr) {
17402       MachineBasicBlock* succ = *sItr;
17403       if (succ->isLiveIn(X86::EFLAGS))
17404         return false;
17405     }
17406   }
17407
17408   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
17409   // out. SelectMI should have a kill flag on EFLAGS.
17410   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
17411   return true;
17412 }
17413
17414 MachineBasicBlock *
17415 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
17416                                      MachineBasicBlock *BB) const {
17417   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17418   DebugLoc DL = MI->getDebugLoc();
17419
17420   // To "insert" a SELECT_CC instruction, we actually have to insert the
17421   // diamond control-flow pattern.  The incoming instruction knows the
17422   // destination vreg to set, the condition code register to branch on, the
17423   // true/false values to select between, and a branch opcode to use.
17424   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17425   MachineFunction::iterator It = BB;
17426   ++It;
17427
17428   //  thisMBB:
17429   //  ...
17430   //   TrueVal = ...
17431   //   cmpTY ccX, r1, r2
17432   //   bCC copy1MBB
17433   //   fallthrough --> copy0MBB
17434   MachineBasicBlock *thisMBB = BB;
17435   MachineFunction *F = BB->getParent();
17436   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
17437   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
17438   F->insert(It, copy0MBB);
17439   F->insert(It, sinkMBB);
17440
17441   // If the EFLAGS register isn't dead in the terminator, then claim that it's
17442   // live into the sink and copy blocks.
17443   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
17444   if (!MI->killsRegister(X86::EFLAGS) &&
17445       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
17446     copy0MBB->addLiveIn(X86::EFLAGS);
17447     sinkMBB->addLiveIn(X86::EFLAGS);
17448   }
17449
17450   // Transfer the remainder of BB and its successor edges to sinkMBB.
17451   sinkMBB->splice(sinkMBB->begin(), BB,
17452                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
17453   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
17454
17455   // Add the true and fallthrough blocks as its successors.
17456   BB->addSuccessor(copy0MBB);
17457   BB->addSuccessor(sinkMBB);
17458
17459   // Create the conditional branch instruction.
17460   unsigned Opc =
17461     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
17462   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
17463
17464   //  copy0MBB:
17465   //   %FalseValue = ...
17466   //   # fallthrough to sinkMBB
17467   copy0MBB->addSuccessor(sinkMBB);
17468
17469   //  sinkMBB:
17470   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
17471   //  ...
17472   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17473           TII->get(X86::PHI), MI->getOperand(0).getReg())
17474     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
17475     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
17476
17477   MI->eraseFromParent();   // The pseudo instruction is gone now.
17478   return sinkMBB;
17479 }
17480
17481 MachineBasicBlock *
17482 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
17483                                         bool Is64Bit) const {
17484   MachineFunction *MF = BB->getParent();
17485   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17486   DebugLoc DL = MI->getDebugLoc();
17487   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17488
17489   assert(MF->shouldSplitStack());
17490
17491   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17492   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17493
17494   // BB:
17495   //  ... [Till the alloca]
17496   // If stacklet is not large enough, jump to mallocMBB
17497   //
17498   // bumpMBB:
17499   //  Allocate by subtracting from RSP
17500   //  Jump to continueMBB
17501   //
17502   // mallocMBB:
17503   //  Allocate by call to runtime
17504   //
17505   // continueMBB:
17506   //  ...
17507   //  [rest of original BB]
17508   //
17509
17510   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17511   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17512   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17513
17514   MachineRegisterInfo &MRI = MF->getRegInfo();
17515   const TargetRegisterClass *AddrRegClass =
17516     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17517
17518   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17519     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17520     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17521     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17522     sizeVReg = MI->getOperand(1).getReg(),
17523     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17524
17525   MachineFunction::iterator MBBIter = BB;
17526   ++MBBIter;
17527
17528   MF->insert(MBBIter, bumpMBB);
17529   MF->insert(MBBIter, mallocMBB);
17530   MF->insert(MBBIter, continueMBB);
17531
17532   continueMBB->splice(continueMBB->begin(), BB,
17533                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17534   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17535
17536   // Add code to the main basic block to check if the stack limit has been hit,
17537   // and if so, jump to mallocMBB otherwise to bumpMBB.
17538   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17539   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17540     .addReg(tmpSPVReg).addReg(sizeVReg);
17541   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17542     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17543     .addReg(SPLimitVReg);
17544   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17545
17546   // bumpMBB simply decreases the stack pointer, since we know the current
17547   // stacklet has enough space.
17548   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17549     .addReg(SPLimitVReg);
17550   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17551     .addReg(SPLimitVReg);
17552   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17553
17554   // Calls into a routine in libgcc to allocate more space from the heap.
17555   const uint32_t *RegMask =
17556     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17557   if (Is64Bit) {
17558     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17559       .addReg(sizeVReg);
17560     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17561       .addExternalSymbol("__morestack_allocate_stack_space")
17562       .addRegMask(RegMask)
17563       .addReg(X86::RDI, RegState::Implicit)
17564       .addReg(X86::RAX, RegState::ImplicitDefine);
17565   } else {
17566     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17567       .addImm(12);
17568     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17569     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17570       .addExternalSymbol("__morestack_allocate_stack_space")
17571       .addRegMask(RegMask)
17572       .addReg(X86::EAX, RegState::ImplicitDefine);
17573   }
17574
17575   if (!Is64Bit)
17576     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17577       .addImm(16);
17578
17579   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17580     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17581   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17582
17583   // Set up the CFG correctly.
17584   BB->addSuccessor(bumpMBB);
17585   BB->addSuccessor(mallocMBB);
17586   mallocMBB->addSuccessor(continueMBB);
17587   bumpMBB->addSuccessor(continueMBB);
17588
17589   // Take care of the PHI nodes.
17590   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17591           MI->getOperand(0).getReg())
17592     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17593     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17594
17595   // Delete the original pseudo instruction.
17596   MI->eraseFromParent();
17597
17598   // And we're done.
17599   return continueMBB;
17600 }
17601
17602 MachineBasicBlock *
17603 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17604                                         MachineBasicBlock *BB) const {
17605   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17606   DebugLoc DL = MI->getDebugLoc();
17607
17608   assert(!Subtarget->isTargetMacho());
17609
17610   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17611   // non-trivial part is impdef of ESP.
17612
17613   if (Subtarget->isTargetWin64()) {
17614     if (Subtarget->isTargetCygMing()) {
17615       // ___chkstk(Mingw64):
17616       // Clobbers R10, R11, RAX and EFLAGS.
17617       // Updates RSP.
17618       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17619         .addExternalSymbol("___chkstk")
17620         .addReg(X86::RAX, RegState::Implicit)
17621         .addReg(X86::RSP, RegState::Implicit)
17622         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17623         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17624         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17625     } else {
17626       // __chkstk(MSVCRT): does not update stack pointer.
17627       // Clobbers R10, R11 and EFLAGS.
17628       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17629         .addExternalSymbol("__chkstk")
17630         .addReg(X86::RAX, RegState::Implicit)
17631         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17632       // RAX has the offset to be subtracted from RSP.
17633       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17634         .addReg(X86::RSP)
17635         .addReg(X86::RAX);
17636     }
17637   } else {
17638     const char *StackProbeSymbol =
17639       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17640
17641     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17642       .addExternalSymbol(StackProbeSymbol)
17643       .addReg(X86::EAX, RegState::Implicit)
17644       .addReg(X86::ESP, RegState::Implicit)
17645       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17646       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17647       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17648   }
17649
17650   MI->eraseFromParent();   // The pseudo instruction is gone now.
17651   return BB;
17652 }
17653
17654 MachineBasicBlock *
17655 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17656                                       MachineBasicBlock *BB) const {
17657   // This is pretty easy.  We're taking the value that we received from
17658   // our load from the relocation, sticking it in either RDI (x86-64)
17659   // or EAX and doing an indirect call.  The return value will then
17660   // be in the normal return register.
17661   MachineFunction *F = BB->getParent();
17662   const X86InstrInfo *TII
17663     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17664   DebugLoc DL = MI->getDebugLoc();
17665
17666   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17667   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17668
17669   // Get a register mask for the lowered call.
17670   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17671   // proper register mask.
17672   const uint32_t *RegMask =
17673     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17674   if (Subtarget->is64Bit()) {
17675     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17676                                       TII->get(X86::MOV64rm), X86::RDI)
17677     .addReg(X86::RIP)
17678     .addImm(0).addReg(0)
17679     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17680                       MI->getOperand(3).getTargetFlags())
17681     .addReg(0);
17682     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17683     addDirectMem(MIB, X86::RDI);
17684     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17685   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17686     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17687                                       TII->get(X86::MOV32rm), X86::EAX)
17688     .addReg(0)
17689     .addImm(0).addReg(0)
17690     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17691                       MI->getOperand(3).getTargetFlags())
17692     .addReg(0);
17693     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17694     addDirectMem(MIB, X86::EAX);
17695     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17696   } else {
17697     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17698                                       TII->get(X86::MOV32rm), X86::EAX)
17699     .addReg(TII->getGlobalBaseReg(F))
17700     .addImm(0).addReg(0)
17701     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17702                       MI->getOperand(3).getTargetFlags())
17703     .addReg(0);
17704     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17705     addDirectMem(MIB, X86::EAX);
17706     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17707   }
17708
17709   MI->eraseFromParent(); // The pseudo instruction is gone now.
17710   return BB;
17711 }
17712
17713 MachineBasicBlock *
17714 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17715                                     MachineBasicBlock *MBB) const {
17716   DebugLoc DL = MI->getDebugLoc();
17717   MachineFunction *MF = MBB->getParent();
17718   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17719   MachineRegisterInfo &MRI = MF->getRegInfo();
17720
17721   const BasicBlock *BB = MBB->getBasicBlock();
17722   MachineFunction::iterator I = MBB;
17723   ++I;
17724
17725   // Memory Reference
17726   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17727   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17728
17729   unsigned DstReg;
17730   unsigned MemOpndSlot = 0;
17731
17732   unsigned CurOp = 0;
17733
17734   DstReg = MI->getOperand(CurOp++).getReg();
17735   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17736   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17737   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17738   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17739
17740   MemOpndSlot = CurOp;
17741
17742   MVT PVT = getPointerTy();
17743   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17744          "Invalid Pointer Size!");
17745
17746   // For v = setjmp(buf), we generate
17747   //
17748   // thisMBB:
17749   //  buf[LabelOffset] = restoreMBB
17750   //  SjLjSetup restoreMBB
17751   //
17752   // mainMBB:
17753   //  v_main = 0
17754   //
17755   // sinkMBB:
17756   //  v = phi(main, restore)
17757   //
17758   // restoreMBB:
17759   //  v_restore = 1
17760
17761   MachineBasicBlock *thisMBB = MBB;
17762   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17763   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17764   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17765   MF->insert(I, mainMBB);
17766   MF->insert(I, sinkMBB);
17767   MF->push_back(restoreMBB);
17768
17769   MachineInstrBuilder MIB;
17770
17771   // Transfer the remainder of BB and its successor edges to sinkMBB.
17772   sinkMBB->splice(sinkMBB->begin(), MBB,
17773                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17774   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17775
17776   // thisMBB:
17777   unsigned PtrStoreOpc = 0;
17778   unsigned LabelReg = 0;
17779   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17780   Reloc::Model RM = MF->getTarget().getRelocationModel();
17781   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17782                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17783
17784   // Prepare IP either in reg or imm.
17785   if (!UseImmLabel) {
17786     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17787     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17788     LabelReg = MRI.createVirtualRegister(PtrRC);
17789     if (Subtarget->is64Bit()) {
17790       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17791               .addReg(X86::RIP)
17792               .addImm(0)
17793               .addReg(0)
17794               .addMBB(restoreMBB)
17795               .addReg(0);
17796     } else {
17797       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17798       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17799               .addReg(XII->getGlobalBaseReg(MF))
17800               .addImm(0)
17801               .addReg(0)
17802               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17803               .addReg(0);
17804     }
17805   } else
17806     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17807   // Store IP
17808   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17809   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17810     if (i == X86::AddrDisp)
17811       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17812     else
17813       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17814   }
17815   if (!UseImmLabel)
17816     MIB.addReg(LabelReg);
17817   else
17818     MIB.addMBB(restoreMBB);
17819   MIB.setMemRefs(MMOBegin, MMOEnd);
17820   // Setup
17821   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17822           .addMBB(restoreMBB);
17823
17824   const X86RegisterInfo *RegInfo =
17825     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17826   MIB.addRegMask(RegInfo->getNoPreservedMask());
17827   thisMBB->addSuccessor(mainMBB);
17828   thisMBB->addSuccessor(restoreMBB);
17829
17830   // mainMBB:
17831   //  EAX = 0
17832   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17833   mainMBB->addSuccessor(sinkMBB);
17834
17835   // sinkMBB:
17836   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17837           TII->get(X86::PHI), DstReg)
17838     .addReg(mainDstReg).addMBB(mainMBB)
17839     .addReg(restoreDstReg).addMBB(restoreMBB);
17840
17841   // restoreMBB:
17842   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17843   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17844   restoreMBB->addSuccessor(sinkMBB);
17845
17846   MI->eraseFromParent();
17847   return sinkMBB;
17848 }
17849
17850 MachineBasicBlock *
17851 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17852                                      MachineBasicBlock *MBB) const {
17853   DebugLoc DL = MI->getDebugLoc();
17854   MachineFunction *MF = MBB->getParent();
17855   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17856   MachineRegisterInfo &MRI = MF->getRegInfo();
17857
17858   // Memory Reference
17859   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17860   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17861
17862   MVT PVT = getPointerTy();
17863   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17864          "Invalid Pointer Size!");
17865
17866   const TargetRegisterClass *RC =
17867     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17868   unsigned Tmp = MRI.createVirtualRegister(RC);
17869   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17870   const X86RegisterInfo *RegInfo =
17871     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17872   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17873   unsigned SP = RegInfo->getStackRegister();
17874
17875   MachineInstrBuilder MIB;
17876
17877   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17878   const int64_t SPOffset = 2 * PVT.getStoreSize();
17879
17880   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17881   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17882
17883   // Reload FP
17884   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17885   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17886     MIB.addOperand(MI->getOperand(i));
17887   MIB.setMemRefs(MMOBegin, MMOEnd);
17888   // Reload IP
17889   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17890   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17891     if (i == X86::AddrDisp)
17892       MIB.addDisp(MI->getOperand(i), LabelOffset);
17893     else
17894       MIB.addOperand(MI->getOperand(i));
17895   }
17896   MIB.setMemRefs(MMOBegin, MMOEnd);
17897   // Reload SP
17898   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17899   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17900     if (i == X86::AddrDisp)
17901       MIB.addDisp(MI->getOperand(i), SPOffset);
17902     else
17903       MIB.addOperand(MI->getOperand(i));
17904   }
17905   MIB.setMemRefs(MMOBegin, MMOEnd);
17906   // Jump
17907   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17908
17909   MI->eraseFromParent();
17910   return MBB;
17911 }
17912
17913 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17914 // accumulator loops. Writing back to the accumulator allows the coalescer
17915 // to remove extra copies in the loop.   
17916 MachineBasicBlock *
17917 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17918                                  MachineBasicBlock *MBB) const {
17919   MachineOperand &AddendOp = MI->getOperand(3);
17920
17921   // Bail out early if the addend isn't a register - we can't switch these.
17922   if (!AddendOp.isReg())
17923     return MBB;
17924
17925   MachineFunction &MF = *MBB->getParent();
17926   MachineRegisterInfo &MRI = MF.getRegInfo();
17927
17928   // Check whether the addend is defined by a PHI:
17929   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17930   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17931   if (!AddendDef.isPHI())
17932     return MBB;
17933
17934   // Look for the following pattern:
17935   // loop:
17936   //   %addend = phi [%entry, 0], [%loop, %result]
17937   //   ...
17938   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17939
17940   // Replace with:
17941   //   loop:
17942   //   %addend = phi [%entry, 0], [%loop, %result]
17943   //   ...
17944   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17945
17946   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17947     assert(AddendDef.getOperand(i).isReg());
17948     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17949     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17950     if (&PHISrcInst == MI) {
17951       // Found a matching instruction.
17952       unsigned NewFMAOpc = 0;
17953       switch (MI->getOpcode()) {
17954         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17955         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17956         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17957         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17958         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17959         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17960         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17961         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17962         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17963         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17964         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17965         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17966         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17967         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17968         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17969         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17970         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17971         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17972         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17973         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17974         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17975         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17976         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17977         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17978         default: llvm_unreachable("Unrecognized FMA variant.");
17979       }
17980
17981       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17982       MachineInstrBuilder MIB =
17983         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17984         .addOperand(MI->getOperand(0))
17985         .addOperand(MI->getOperand(3))
17986         .addOperand(MI->getOperand(2))
17987         .addOperand(MI->getOperand(1));
17988       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17989       MI->eraseFromParent();
17990     }
17991   }
17992
17993   return MBB;
17994 }
17995
17996 MachineBasicBlock *
17997 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17998                                                MachineBasicBlock *BB) const {
17999   switch (MI->getOpcode()) {
18000   default: llvm_unreachable("Unexpected instr type to insert");
18001   case X86::TAILJMPd64:
18002   case X86::TAILJMPr64:
18003   case X86::TAILJMPm64:
18004     llvm_unreachable("TAILJMP64 would not be touched here.");
18005   case X86::TCRETURNdi64:
18006   case X86::TCRETURNri64:
18007   case X86::TCRETURNmi64:
18008     return BB;
18009   case X86::WIN_ALLOCA:
18010     return EmitLoweredWinAlloca(MI, BB);
18011   case X86::SEG_ALLOCA_32:
18012     return EmitLoweredSegAlloca(MI, BB, false);
18013   case X86::SEG_ALLOCA_64:
18014     return EmitLoweredSegAlloca(MI, BB, true);
18015   case X86::TLSCall_32:
18016   case X86::TLSCall_64:
18017     return EmitLoweredTLSCall(MI, BB);
18018   case X86::CMOV_GR8:
18019   case X86::CMOV_FR32:
18020   case X86::CMOV_FR64:
18021   case X86::CMOV_V4F32:
18022   case X86::CMOV_V2F64:
18023   case X86::CMOV_V2I64:
18024   case X86::CMOV_V8F32:
18025   case X86::CMOV_V4F64:
18026   case X86::CMOV_V4I64:
18027   case X86::CMOV_V16F32:
18028   case X86::CMOV_V8F64:
18029   case X86::CMOV_V8I64:
18030   case X86::CMOV_GR16:
18031   case X86::CMOV_GR32:
18032   case X86::CMOV_RFP32:
18033   case X86::CMOV_RFP64:
18034   case X86::CMOV_RFP80:
18035     return EmitLoweredSelect(MI, BB);
18036
18037   case X86::FP32_TO_INT16_IN_MEM:
18038   case X86::FP32_TO_INT32_IN_MEM:
18039   case X86::FP32_TO_INT64_IN_MEM:
18040   case X86::FP64_TO_INT16_IN_MEM:
18041   case X86::FP64_TO_INT32_IN_MEM:
18042   case X86::FP64_TO_INT64_IN_MEM:
18043   case X86::FP80_TO_INT16_IN_MEM:
18044   case X86::FP80_TO_INT32_IN_MEM:
18045   case X86::FP80_TO_INT64_IN_MEM: {
18046     MachineFunction *F = BB->getParent();
18047     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
18048     DebugLoc DL = MI->getDebugLoc();
18049
18050     // Change the floating point control register to use "round towards zero"
18051     // mode when truncating to an integer value.
18052     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
18053     addFrameReference(BuildMI(*BB, MI, DL,
18054                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
18055
18056     // Load the old value of the high byte of the control word...
18057     unsigned OldCW =
18058       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
18059     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
18060                       CWFrameIdx);
18061
18062     // Set the high part to be round to zero...
18063     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
18064       .addImm(0xC7F);
18065
18066     // Reload the modified control word now...
18067     addFrameReference(BuildMI(*BB, MI, DL,
18068                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18069
18070     // Restore the memory image of control word to original value
18071     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
18072       .addReg(OldCW);
18073
18074     // Get the X86 opcode to use.
18075     unsigned Opc;
18076     switch (MI->getOpcode()) {
18077     default: llvm_unreachable("illegal opcode!");
18078     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
18079     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
18080     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
18081     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
18082     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
18083     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
18084     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
18085     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
18086     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
18087     }
18088
18089     X86AddressMode AM;
18090     MachineOperand &Op = MI->getOperand(0);
18091     if (Op.isReg()) {
18092       AM.BaseType = X86AddressMode::RegBase;
18093       AM.Base.Reg = Op.getReg();
18094     } else {
18095       AM.BaseType = X86AddressMode::FrameIndexBase;
18096       AM.Base.FrameIndex = Op.getIndex();
18097     }
18098     Op = MI->getOperand(1);
18099     if (Op.isImm())
18100       AM.Scale = Op.getImm();
18101     Op = MI->getOperand(2);
18102     if (Op.isImm())
18103       AM.IndexReg = Op.getImm();
18104     Op = MI->getOperand(3);
18105     if (Op.isGlobal()) {
18106       AM.GV = Op.getGlobal();
18107     } else {
18108       AM.Disp = Op.getImm();
18109     }
18110     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
18111                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
18112
18113     // Reload the original control word now.
18114     addFrameReference(BuildMI(*BB, MI, DL,
18115                               TII->get(X86::FLDCW16m)), CWFrameIdx);
18116
18117     MI->eraseFromParent();   // The pseudo instruction is gone now.
18118     return BB;
18119   }
18120     // String/text processing lowering.
18121   case X86::PCMPISTRM128REG:
18122   case X86::VPCMPISTRM128REG:
18123   case X86::PCMPISTRM128MEM:
18124   case X86::VPCMPISTRM128MEM:
18125   case X86::PCMPESTRM128REG:
18126   case X86::VPCMPESTRM128REG:
18127   case X86::PCMPESTRM128MEM:
18128   case X86::VPCMPESTRM128MEM:
18129     assert(Subtarget->hasSSE42() &&
18130            "Target must have SSE4.2 or AVX features enabled");
18131     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18132
18133   // String/text processing lowering.
18134   case X86::PCMPISTRIREG:
18135   case X86::VPCMPISTRIREG:
18136   case X86::PCMPISTRIMEM:
18137   case X86::VPCMPISTRIMEM:
18138   case X86::PCMPESTRIREG:
18139   case X86::VPCMPESTRIREG:
18140   case X86::PCMPESTRIMEM:
18141   case X86::VPCMPESTRIMEM:
18142     assert(Subtarget->hasSSE42() &&
18143            "Target must have SSE4.2 or AVX features enabled");
18144     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18145
18146   // Thread synchronization.
18147   case X86::MONITOR:
18148     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
18149
18150   // xbegin
18151   case X86::XBEGIN:
18152     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
18153
18154   case X86::VASTART_SAVE_XMM_REGS:
18155     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
18156
18157   case X86::VAARG_64:
18158     return EmitVAARG64WithCustomInserter(MI, BB);
18159
18160   case X86::EH_SjLj_SetJmp32:
18161   case X86::EH_SjLj_SetJmp64:
18162     return emitEHSjLjSetJmp(MI, BB);
18163
18164   case X86::EH_SjLj_LongJmp32:
18165   case X86::EH_SjLj_LongJmp64:
18166     return emitEHSjLjLongJmp(MI, BB);
18167
18168   case TargetOpcode::STACKMAP:
18169   case TargetOpcode::PATCHPOINT:
18170     return emitPatchPoint(MI, BB);
18171
18172   case X86::VFMADDPDr213r:
18173   case X86::VFMADDPSr213r:
18174   case X86::VFMADDSDr213r:
18175   case X86::VFMADDSSr213r:
18176   case X86::VFMSUBPDr213r:
18177   case X86::VFMSUBPSr213r:
18178   case X86::VFMSUBSDr213r:
18179   case X86::VFMSUBSSr213r:
18180   case X86::VFNMADDPDr213r:
18181   case X86::VFNMADDPSr213r:
18182   case X86::VFNMADDSDr213r:
18183   case X86::VFNMADDSSr213r:
18184   case X86::VFNMSUBPDr213r:
18185   case X86::VFNMSUBPSr213r:
18186   case X86::VFNMSUBSDr213r:
18187   case X86::VFNMSUBSSr213r:
18188   case X86::VFMADDPDr213rY:
18189   case X86::VFMADDPSr213rY:
18190   case X86::VFMSUBPDr213rY:
18191   case X86::VFMSUBPSr213rY:
18192   case X86::VFNMADDPDr213rY:
18193   case X86::VFNMADDPSr213rY:
18194   case X86::VFNMSUBPDr213rY:
18195   case X86::VFNMSUBPSr213rY:
18196     return emitFMA3Instr(MI, BB);
18197   }
18198 }
18199
18200 //===----------------------------------------------------------------------===//
18201 //                           X86 Optimization Hooks
18202 //===----------------------------------------------------------------------===//
18203
18204 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
18205                                                       APInt &KnownZero,
18206                                                       APInt &KnownOne,
18207                                                       const SelectionDAG &DAG,
18208                                                       unsigned Depth) const {
18209   unsigned BitWidth = KnownZero.getBitWidth();
18210   unsigned Opc = Op.getOpcode();
18211   assert((Opc >= ISD::BUILTIN_OP_END ||
18212           Opc == ISD::INTRINSIC_WO_CHAIN ||
18213           Opc == ISD::INTRINSIC_W_CHAIN ||
18214           Opc == ISD::INTRINSIC_VOID) &&
18215          "Should use MaskedValueIsZero if you don't know whether Op"
18216          " is a target node!");
18217
18218   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
18219   switch (Opc) {
18220   default: break;
18221   case X86ISD::ADD:
18222   case X86ISD::SUB:
18223   case X86ISD::ADC:
18224   case X86ISD::SBB:
18225   case X86ISD::SMUL:
18226   case X86ISD::UMUL:
18227   case X86ISD::INC:
18228   case X86ISD::DEC:
18229   case X86ISD::OR:
18230   case X86ISD::XOR:
18231   case X86ISD::AND:
18232     // These nodes' second result is a boolean.
18233     if (Op.getResNo() == 0)
18234       break;
18235     // Fallthrough
18236   case X86ISD::SETCC:
18237     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
18238     break;
18239   case ISD::INTRINSIC_WO_CHAIN: {
18240     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
18241     unsigned NumLoBits = 0;
18242     switch (IntId) {
18243     default: break;
18244     case Intrinsic::x86_sse_movmsk_ps:
18245     case Intrinsic::x86_avx_movmsk_ps_256:
18246     case Intrinsic::x86_sse2_movmsk_pd:
18247     case Intrinsic::x86_avx_movmsk_pd_256:
18248     case Intrinsic::x86_mmx_pmovmskb:
18249     case Intrinsic::x86_sse2_pmovmskb_128:
18250     case Intrinsic::x86_avx2_pmovmskb: {
18251       // High bits of movmskp{s|d}, pmovmskb are known zero.
18252       switch (IntId) {
18253         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
18254         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
18255         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
18256         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
18257         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
18258         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
18259         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
18260         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
18261       }
18262       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
18263       break;
18264     }
18265     }
18266     break;
18267   }
18268   }
18269 }
18270
18271 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
18272   SDValue Op,
18273   const SelectionDAG &,
18274   unsigned Depth) const {
18275   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
18276   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
18277     return Op.getValueType().getScalarType().getSizeInBits();
18278
18279   // Fallback case.
18280   return 1;
18281 }
18282
18283 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
18284 /// node is a GlobalAddress + offset.
18285 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
18286                                        const GlobalValue* &GA,
18287                                        int64_t &Offset) const {
18288   if (N->getOpcode() == X86ISD::Wrapper) {
18289     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
18290       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
18291       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
18292       return true;
18293     }
18294   }
18295   return TargetLowering::isGAPlusOffset(N, GA, Offset);
18296 }
18297
18298 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
18299 /// same as extracting the high 128-bit part of 256-bit vector and then
18300 /// inserting the result into the low part of a new 256-bit vector
18301 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
18302   EVT VT = SVOp->getValueType(0);
18303   unsigned NumElems = VT.getVectorNumElements();
18304
18305   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18306   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
18307     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18308         SVOp->getMaskElt(j) >= 0)
18309       return false;
18310
18311   return true;
18312 }
18313
18314 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
18315 /// same as extracting the low 128-bit part of 256-bit vector and then
18316 /// inserting the result into the high part of a new 256-bit vector
18317 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
18318   EVT VT = SVOp->getValueType(0);
18319   unsigned NumElems = VT.getVectorNumElements();
18320
18321   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18322   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
18323     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
18324         SVOp->getMaskElt(j) >= 0)
18325       return false;
18326
18327   return true;
18328 }
18329
18330 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
18331 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
18332                                         TargetLowering::DAGCombinerInfo &DCI,
18333                                         const X86Subtarget* Subtarget) {
18334   SDLoc dl(N);
18335   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18336   SDValue V1 = SVOp->getOperand(0);
18337   SDValue V2 = SVOp->getOperand(1);
18338   EVT VT = SVOp->getValueType(0);
18339   unsigned NumElems = VT.getVectorNumElements();
18340
18341   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
18342       V2.getOpcode() == ISD::CONCAT_VECTORS) {
18343     //
18344     //                   0,0,0,...
18345     //                      |
18346     //    V      UNDEF    BUILD_VECTOR    UNDEF
18347     //     \      /           \           /
18348     //  CONCAT_VECTOR         CONCAT_VECTOR
18349     //         \                  /
18350     //          \                /
18351     //          RESULT: V + zero extended
18352     //
18353     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
18354         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
18355         V1.getOperand(1).getOpcode() != ISD::UNDEF)
18356       return SDValue();
18357
18358     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
18359       return SDValue();
18360
18361     // To match the shuffle mask, the first half of the mask should
18362     // be exactly the first vector, and all the rest a splat with the
18363     // first element of the second one.
18364     for (unsigned i = 0; i != NumElems/2; ++i)
18365       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
18366           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
18367         return SDValue();
18368
18369     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
18370     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
18371       if (Ld->hasNUsesOfValue(1, 0)) {
18372         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
18373         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
18374         SDValue ResNode =
18375           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
18376                                   Ld->getMemoryVT(),
18377                                   Ld->getPointerInfo(),
18378                                   Ld->getAlignment(),
18379                                   false/*isVolatile*/, true/*ReadMem*/,
18380                                   false/*WriteMem*/);
18381
18382         // Make sure the newly-created LOAD is in the same position as Ld in
18383         // terms of dependency. We create a TokenFactor for Ld and ResNode,
18384         // and update uses of Ld's output chain to use the TokenFactor.
18385         if (Ld->hasAnyUseOfValue(1)) {
18386           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
18387                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
18388           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
18389           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
18390                                  SDValue(ResNode.getNode(), 1));
18391         }
18392
18393         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
18394       }
18395     }
18396
18397     // Emit a zeroed vector and insert the desired subvector on its
18398     // first half.
18399     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
18400     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
18401     return DCI.CombineTo(N, InsV);
18402   }
18403
18404   //===--------------------------------------------------------------------===//
18405   // Combine some shuffles into subvector extracts and inserts:
18406   //
18407
18408   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
18409   if (isShuffleHigh128VectorInsertLow(SVOp)) {
18410     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
18411     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
18412     return DCI.CombineTo(N, InsV);
18413   }
18414
18415   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
18416   if (isShuffleLow128VectorInsertHigh(SVOp)) {
18417     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
18418     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
18419     return DCI.CombineTo(N, InsV);
18420   }
18421
18422   return SDValue();
18423 }
18424
18425 /// \brief Get the PSHUF-style mask from PSHUF node.
18426 ///
18427 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
18428 /// PSHUF-style masks that can be reused with such instructions.
18429 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
18430   SmallVector<int, 4> Mask;
18431   bool IsUnary;
18432   bool HaveMask = getTargetShuffleMask(N.getNode(), N.getSimpleValueType(), Mask, IsUnary);
18433   (void)HaveMask;
18434   assert(HaveMask);
18435
18436   switch (N.getOpcode()) {
18437   case X86ISD::PSHUFD:
18438     return Mask;
18439   case X86ISD::PSHUFLW:
18440     Mask.resize(4);
18441     return Mask;
18442   case X86ISD::PSHUFHW:
18443     Mask.erase(Mask.begin(), Mask.begin() + 4);
18444     for (int &M : Mask)
18445       M -= 4;
18446     return Mask;
18447   default:
18448     llvm_unreachable("No valid shuffle instruction found!");
18449   }
18450 }
18451
18452 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
18453 ///
18454 /// We walk up the chain and look for a combinable shuffle, skipping over
18455 /// shuffles that we could hoist this shuffle's transformation past without
18456 /// altering anything.
18457 static bool combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
18458                                          SelectionDAG &DAG,
18459                                          TargetLowering::DAGCombinerInfo &DCI) {
18460   assert(N.getOpcode() == X86ISD::PSHUFD &&
18461          "Called with something other than an x86 128-bit half shuffle!");
18462   SDLoc DL(N);
18463
18464   // Walk up a single-use chain looking for a combinable shuffle.
18465   SDValue V = N.getOperand(0);
18466   for (; V.hasOneUse(); V = V.getOperand(0)) {
18467     switch (V.getOpcode()) {
18468     default:
18469       return false; // Nothing combined!
18470
18471     case ISD::BITCAST:
18472       // Skip bitcasts as we always know the type for the target specific
18473       // instructions.
18474       continue;
18475
18476     case X86ISD::PSHUFD:
18477       // Found another dword shuffle.
18478       break;
18479
18480     case X86ISD::PSHUFLW:
18481       // Check that the low words (being shuffled) are the identity in the
18482       // dword shuffle, and the high words are self-contained.
18483       if (Mask[0] != 0 || Mask[1] != 1 ||
18484           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
18485         return false;
18486
18487       continue;
18488
18489     case X86ISD::PSHUFHW:
18490       // Check that the high words (being shuffled) are the identity in the
18491       // dword shuffle, and the low words are self-contained.
18492       if (Mask[2] != 2 || Mask[3] != 3 ||
18493           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
18494         return false;
18495
18496       continue;
18497     }
18498     // Break out of the loop if we break out of the switch.
18499     break;
18500   }
18501
18502   if (!V.hasOneUse())
18503     // We fell out of the loop without finding a viable combining instruction.
18504     return false;
18505
18506   // Record the old value to use in RAUW-ing.
18507   SDValue Old = V;
18508
18509   // Merge this node's mask and our incoming mask.
18510   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18511   for (int &M : Mask)
18512     M = VMask[M];
18513   V = DAG.getNode(X86ISD::PSHUFD, DL, V.getValueType(), V.getOperand(0),
18514                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18515
18516   // It is possible that one of the combinable shuffles was completely absorbed
18517   // by the other, just replace it and revisit all users in that case.
18518   if (Old.getNode() == V.getNode()) {
18519     DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo=*/true);
18520     return true;
18521   }
18522
18523   // Replace N with its operand as we're going to combine that shuffle away.
18524   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18525
18526   // Replace the combinable shuffle with the combined one, updating all users
18527   // so that we re-evaluate the chain here.
18528   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18529   return true;
18530 }
18531
18532 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
18533 ///
18534 /// We walk up the chain, skipping shuffles of the other half and looking
18535 /// through shuffles which switch halves trying to find a shuffle of the same
18536 /// pair of dwords.
18537 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
18538                                         SelectionDAG &DAG,
18539                                         TargetLowering::DAGCombinerInfo &DCI) {
18540   assert(
18541       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
18542       "Called with something other than an x86 128-bit half shuffle!");
18543   SDLoc DL(N);
18544   unsigned CombineOpcode = N.getOpcode();
18545
18546   // Walk up a single-use chain looking for a combinable shuffle.
18547   SDValue V = N.getOperand(0);
18548   for (; V.hasOneUse(); V = V.getOperand(0)) {
18549     switch (V.getOpcode()) {
18550     default:
18551       return false; // Nothing combined!
18552
18553     case ISD::BITCAST:
18554       // Skip bitcasts as we always know the type for the target specific
18555       // instructions.
18556       continue;
18557
18558     case X86ISD::PSHUFLW:
18559     case X86ISD::PSHUFHW:
18560       if (V.getOpcode() == CombineOpcode)
18561         break;
18562
18563       // Other-half shuffles are no-ops.
18564       continue;
18565
18566     case X86ISD::PSHUFD: {
18567       // We can only handle pshufd if the half we are combining either stays in
18568       // its half, or switches to the other half. Bail if one of these isn't
18569       // true.
18570       SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18571       int DOffset = CombineOpcode == X86ISD::PSHUFLW ? 0 : 2;
18572       if (!((VMask[DOffset + 0] < 2 && VMask[DOffset + 1] < 2) ||
18573             (VMask[DOffset + 0] >= 2 && VMask[DOffset + 1] >= 2)))
18574         return false;
18575
18576       // Map the mask through the pshufd and keep walking up the chain.
18577       for (int i = 0; i < 4; ++i)
18578         Mask[i] = 2 * (VMask[DOffset + Mask[i] / 2] % 2) + Mask[i] % 2;
18579
18580       // Switch halves if the pshufd does.
18581       CombineOpcode =
18582           VMask[DOffset + Mask[0] / 2] < 2 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
18583       continue;
18584     }
18585     }
18586     // Break out of the loop if we break out of the switch.
18587     break;
18588   }
18589
18590   if (!V.hasOneUse())
18591     // We fell out of the loop without finding a viable combining instruction.
18592     return false;
18593
18594   // Record the old value to use in RAUW-ing.
18595   SDValue Old = V;
18596
18597   // Merge this node's mask and our incoming mask (adjusted to account for all
18598   // the pshufd instructions encountered).
18599   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
18600   for (int &M : Mask)
18601     M = VMask[M];
18602   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
18603                   getV4X86ShuffleImm8ForMask(Mask, DAG));
18604
18605   // Replace N with its operand as we're going to combine that shuffle away.
18606   DAG.ReplaceAllUsesWith(N, N.getOperand(0));
18607
18608   // Replace the combinable shuffle with the combined one, updating all users
18609   // so that we re-evaluate the chain here.
18610   DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
18611   return true;
18612 }
18613
18614 /// \brief Try to combine x86 target specific shuffles.
18615 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
18616                                            TargetLowering::DAGCombinerInfo &DCI,
18617                                            const X86Subtarget *Subtarget) {
18618   SDLoc DL(N);
18619   MVT VT = N.getSimpleValueType();
18620   SmallVector<int, 4> Mask;
18621
18622   switch (N.getOpcode()) {
18623   case X86ISD::PSHUFD:
18624   case X86ISD::PSHUFLW:
18625   case X86ISD::PSHUFHW:
18626     Mask = getPSHUFShuffleMask(N);
18627     assert(Mask.size() == 4);
18628     break;
18629   default:
18630     return SDValue();
18631   }
18632
18633   // Nuke no-op shuffles that show up after combining.
18634   if (isNoopShuffleMask(Mask))
18635     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
18636
18637   // Look for simplifications involving one or two shuffle instructions.
18638   SDValue V = N.getOperand(0);
18639   switch (N.getOpcode()) {
18640   default:
18641     break;
18642   case X86ISD::PSHUFLW:
18643   case X86ISD::PSHUFHW:
18644     assert(VT == MVT::v8i16);
18645     (void)VT;
18646
18647     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
18648       return SDValue(); // We combined away this shuffle, so we're done.
18649
18650     // See if this reduces to a PSHUFD which is no more expensive and can
18651     // combine with more operations.
18652     if (Mask[0] % 2 == 0 && Mask[2] % 2 == 0 &&
18653         areAdjacentMasksSequential(Mask)) {
18654       int DMask[] = {-1, -1, -1, -1};
18655       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
18656       DMask[DOffset + 0] = DOffset + Mask[0] / 2;
18657       DMask[DOffset + 1] = DOffset + Mask[2] / 2;
18658       V = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, V);
18659       DCI.AddToWorklist(V.getNode());
18660       V = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V,
18661                       getV4X86ShuffleImm8ForMask(DMask, DAG));
18662       DCI.AddToWorklist(V.getNode());
18663       return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, V);
18664     }
18665
18666     break;
18667
18668   case X86ISD::PSHUFD:
18669     if (combineRedundantDWordShuffle(N, Mask, DAG, DCI))
18670       return SDValue(); // We combined away this shuffle.
18671
18672     break;
18673   }
18674
18675   return SDValue();
18676 }
18677
18678 /// PerformShuffleCombine - Performs several different shuffle combines.
18679 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
18680                                      TargetLowering::DAGCombinerInfo &DCI,
18681                                      const X86Subtarget *Subtarget) {
18682   SDLoc dl(N);
18683   SDValue N0 = N->getOperand(0);
18684   SDValue N1 = N->getOperand(1);
18685   EVT VT = N->getValueType(0);
18686
18687   // Canonicalize shuffles that perform 'addsub' on packed float vectors
18688   // according to the rule:
18689   //  (shuffle (FADD A, B), (FSUB A, B), Mask) ->
18690   //  (shuffle (FSUB A, -B), (FADD A, -B), Mask)
18691   //
18692   // Where 'Mask' is:
18693   //  <0,5,2,7>             -- for v4f32 and v4f64 shuffles;
18694   //  <0,3>                 -- for v2f64 shuffles;
18695   //  <0,9,2,11,4,13,6,15>  -- for v8f32 shuffles.
18696   //
18697   // This helps pattern-matching more SSE3/AVX ADDSUB instructions
18698   // during ISel stage.
18699   if (N->getOpcode() == ISD::VECTOR_SHUFFLE &&
18700       ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
18701        (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
18702       N0->getOpcode() == ISD::FADD && N1->getOpcode() == ISD::FSUB &&
18703       // Operands to the FADD and FSUB must be the same.
18704       ((N0->getOperand(0) == N1->getOperand(0) &&
18705         N0->getOperand(1) == N1->getOperand(1)) ||
18706        // FADD is commutable. See if by commuting the operands of the FADD
18707        // we would still be able to match the operands of the FSUB dag node.
18708        (N0->getOperand(1) == N1->getOperand(0) &&
18709         N0->getOperand(0) == N1->getOperand(1))) &&
18710       N0->getOperand(0)->getOpcode() != ISD::UNDEF &&
18711       N0->getOperand(1)->getOpcode() != ISD::UNDEF) {
18712     
18713     ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
18714     unsigned NumElts = VT.getVectorNumElements();
18715     ArrayRef<int> Mask = SV->getMask();
18716     bool CanFold = true;
18717
18718     for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i)
18719       CanFold = Mask[i] == (int)((i & 1) ? i + NumElts : i);
18720
18721     if (CanFold) {
18722       SDValue Op0 = N1->getOperand(0);
18723       SDValue Op1 = DAG.getNode(ISD::FNEG, dl, VT, N1->getOperand(1));
18724       SDValue Sub = DAG.getNode(ISD::FSUB, dl, VT, Op0, Op1);
18725       SDValue Add = DAG.getNode(ISD::FADD, dl, VT, Op0, Op1);
18726       return DAG.getVectorShuffle(VT, dl, Sub, Add, Mask);
18727     }
18728   }
18729
18730   // Don't create instructions with illegal types after legalize types has run.
18731   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18732   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18733     return SDValue();
18734
18735   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18736   if (Subtarget->hasFp256() && VT.is256BitVector() &&
18737       N->getOpcode() == ISD::VECTOR_SHUFFLE)
18738     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18739
18740   // During Type Legalization, when promoting illegal vector types,
18741   // the backend might introduce new shuffle dag nodes and bitcasts.
18742   //
18743   // This code performs the following transformation:
18744   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18745   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18746   //
18747   // We do this only if both the bitcast and the BINOP dag nodes have
18748   // one use. Also, perform this transformation only if the new binary
18749   // operation is legal. This is to avoid introducing dag nodes that
18750   // potentially need to be further expanded (or custom lowered) into a
18751   // less optimal sequence of dag nodes.
18752   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18753       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18754       N0.getOpcode() == ISD::BITCAST) {
18755     SDValue BC0 = N0.getOperand(0);
18756     EVT SVT = BC0.getValueType();
18757     unsigned Opcode = BC0.getOpcode();
18758     unsigned NumElts = VT.getVectorNumElements();
18759     
18760     if (BC0.hasOneUse() && SVT.isVector() &&
18761         SVT.getVectorNumElements() * 2 == NumElts &&
18762         TLI.isOperationLegal(Opcode, VT)) {
18763       bool CanFold = false;
18764       switch (Opcode) {
18765       default : break;
18766       case ISD::ADD :
18767       case ISD::FADD :
18768       case ISD::SUB :
18769       case ISD::FSUB :
18770       case ISD::MUL :
18771       case ISD::FMUL :
18772         CanFold = true;
18773       }
18774
18775       unsigned SVTNumElts = SVT.getVectorNumElements();
18776       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18777       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18778         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18779       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18780         CanFold = SVOp->getMaskElt(i) < 0;
18781
18782       if (CanFold) {
18783         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18784         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18785         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18786         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18787       }
18788     }
18789   }
18790
18791   // Only handle 128 wide vector from here on.
18792   if (!VT.is128BitVector())
18793     return SDValue();
18794
18795   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18796   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18797   // consecutive, non-overlapping, and in the right order.
18798   SmallVector<SDValue, 16> Elts;
18799   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18800     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18801
18802   SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18803   if (LD.getNode())
18804     return LD;
18805
18806   if (isTargetShuffle(N->getOpcode())) {
18807     SDValue Shuffle =
18808         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
18809     if (Shuffle.getNode())
18810       return Shuffle;
18811   }
18812
18813   return SDValue();
18814 }
18815
18816 /// PerformTruncateCombine - Converts truncate operation to
18817 /// a sequence of vector shuffle operations.
18818 /// It is possible when we truncate 256-bit vector to 128-bit vector
18819 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18820                                       TargetLowering::DAGCombinerInfo &DCI,
18821                                       const X86Subtarget *Subtarget)  {
18822   return SDValue();
18823 }
18824
18825 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18826 /// specific shuffle of a load can be folded into a single element load.
18827 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18828 /// shuffles have been customed lowered so we need to handle those here.
18829 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18830                                          TargetLowering::DAGCombinerInfo &DCI) {
18831   if (DCI.isBeforeLegalizeOps())
18832     return SDValue();
18833
18834   SDValue InVec = N->getOperand(0);
18835   SDValue EltNo = N->getOperand(1);
18836
18837   if (!isa<ConstantSDNode>(EltNo))
18838     return SDValue();
18839
18840   EVT VT = InVec.getValueType();
18841
18842   bool HasShuffleIntoBitcast = false;
18843   if (InVec.getOpcode() == ISD::BITCAST) {
18844     // Don't duplicate a load with other uses.
18845     if (!InVec.hasOneUse())
18846       return SDValue();
18847     EVT BCVT = InVec.getOperand(0).getValueType();
18848     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18849       return SDValue();
18850     InVec = InVec.getOperand(0);
18851     HasShuffleIntoBitcast = true;
18852   }
18853
18854   if (!isTargetShuffle(InVec.getOpcode()))
18855     return SDValue();
18856
18857   // Don't duplicate a load with other uses.
18858   if (!InVec.hasOneUse())
18859     return SDValue();
18860
18861   SmallVector<int, 16> ShuffleMask;
18862   bool UnaryShuffle;
18863   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18864                             UnaryShuffle))
18865     return SDValue();
18866
18867   // Select the input vector, guarding against out of range extract vector.
18868   unsigned NumElems = VT.getVectorNumElements();
18869   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18870   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18871   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18872                                          : InVec.getOperand(1);
18873
18874   // If inputs to shuffle are the same for both ops, then allow 2 uses
18875   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18876
18877   if (LdNode.getOpcode() == ISD::BITCAST) {
18878     // Don't duplicate a load with other uses.
18879     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18880       return SDValue();
18881
18882     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18883     LdNode = LdNode.getOperand(0);
18884   }
18885
18886   if (!ISD::isNormalLoad(LdNode.getNode()))
18887     return SDValue();
18888
18889   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18890
18891   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18892     return SDValue();
18893
18894   if (HasShuffleIntoBitcast) {
18895     // If there's a bitcast before the shuffle, check if the load type and
18896     // alignment is valid.
18897     unsigned Align = LN0->getAlignment();
18898     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18899     unsigned NewAlign = TLI.getDataLayout()->
18900       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18901
18902     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18903       return SDValue();
18904   }
18905
18906   // All checks match so transform back to vector_shuffle so that DAG combiner
18907   // can finish the job
18908   SDLoc dl(N);
18909
18910   // Create shuffle node taking into account the case that its a unary shuffle
18911   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18912   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18913                                  InVec.getOperand(0), Shuffle,
18914                                  &ShuffleMask[0]);
18915   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18916   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18917                      EltNo);
18918 }
18919
18920 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18921 /// generation and convert it from being a bunch of shuffles and extracts
18922 /// to a simple store and scalar loads to extract the elements.
18923 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18924                                          TargetLowering::DAGCombinerInfo &DCI) {
18925   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18926   if (NewOp.getNode())
18927     return NewOp;
18928
18929   SDValue InputVector = N->getOperand(0);
18930
18931   // Detect whether we are trying to convert from mmx to i32 and the bitcast
18932   // from mmx to v2i32 has a single usage.
18933   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18934       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18935       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18936     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18937                        N->getValueType(0),
18938                        InputVector.getNode()->getOperand(0));
18939
18940   // Only operate on vectors of 4 elements, where the alternative shuffling
18941   // gets to be more expensive.
18942   if (InputVector.getValueType() != MVT::v4i32)
18943     return SDValue();
18944
18945   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18946   // single use which is a sign-extend or zero-extend, and all elements are
18947   // used.
18948   SmallVector<SDNode *, 4> Uses;
18949   unsigned ExtractedElements = 0;
18950   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18951        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18952     if (UI.getUse().getResNo() != InputVector.getResNo())
18953       return SDValue();
18954
18955     SDNode *Extract = *UI;
18956     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18957       return SDValue();
18958
18959     if (Extract->getValueType(0) != MVT::i32)
18960       return SDValue();
18961     if (!Extract->hasOneUse())
18962       return SDValue();
18963     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18964         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18965       return SDValue();
18966     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18967       return SDValue();
18968
18969     // Record which element was extracted.
18970     ExtractedElements |=
18971       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18972
18973     Uses.push_back(Extract);
18974   }
18975
18976   // If not all the elements were used, this may not be worthwhile.
18977   if (ExtractedElements != 15)
18978     return SDValue();
18979
18980   // Ok, we've now decided to do the transformation.
18981   SDLoc dl(InputVector);
18982
18983   // Store the value to a temporary stack slot.
18984   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18985   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18986                             MachinePointerInfo(), false, false, 0);
18987
18988   // Replace each use (extract) with a load of the appropriate element.
18989   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18990        UE = Uses.end(); UI != UE; ++UI) {
18991     SDNode *Extract = *UI;
18992
18993     // cOMpute the element's address.
18994     SDValue Idx = Extract->getOperand(1);
18995     unsigned EltSize =
18996         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18997     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18998     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18999     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
19000
19001     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
19002                                      StackPtr, OffsetVal);
19003
19004     // Load the scalar.
19005     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
19006                                      ScalarAddr, MachinePointerInfo(),
19007                                      false, false, false, 0);
19008
19009     // Replace the exact with the load.
19010     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
19011   }
19012
19013   // The replacement was made in place; don't return anything.
19014   return SDValue();
19015 }
19016
19017 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
19018 static std::pair<unsigned, bool>
19019 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
19020                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
19021   if (!VT.isVector())
19022     return std::make_pair(0, false);
19023
19024   bool NeedSplit = false;
19025   switch (VT.getSimpleVT().SimpleTy) {
19026   default: return std::make_pair(0, false);
19027   case MVT::v32i8:
19028   case MVT::v16i16:
19029   case MVT::v8i32:
19030     if (!Subtarget->hasAVX2())
19031       NeedSplit = true;
19032     if (!Subtarget->hasAVX())
19033       return std::make_pair(0, false);
19034     break;
19035   case MVT::v16i8:
19036   case MVT::v8i16:
19037   case MVT::v4i32:
19038     if (!Subtarget->hasSSE2())
19039       return std::make_pair(0, false);
19040   }
19041
19042   // SSE2 has only a small subset of the operations.
19043   bool hasUnsigned = Subtarget->hasSSE41() ||
19044                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
19045   bool hasSigned = Subtarget->hasSSE41() ||
19046                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
19047
19048   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19049
19050   unsigned Opc = 0;
19051   // Check for x CC y ? x : y.
19052   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19053       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19054     switch (CC) {
19055     default: break;
19056     case ISD::SETULT:
19057     case ISD::SETULE:
19058       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19059     case ISD::SETUGT:
19060     case ISD::SETUGE:
19061       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19062     case ISD::SETLT:
19063     case ISD::SETLE:
19064       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19065     case ISD::SETGT:
19066     case ISD::SETGE:
19067       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19068     }
19069   // Check for x CC y ? y : x -- a min/max with reversed arms.
19070   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19071              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19072     switch (CC) {
19073     default: break;
19074     case ISD::SETULT:
19075     case ISD::SETULE:
19076       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
19077     case ISD::SETUGT:
19078     case ISD::SETUGE:
19079       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
19080     case ISD::SETLT:
19081     case ISD::SETLE:
19082       Opc = hasSigned ? X86ISD::SMAX : 0; break;
19083     case ISD::SETGT:
19084     case ISD::SETGE:
19085       Opc = hasSigned ? X86ISD::SMIN : 0; break;
19086     }
19087   }
19088
19089   return std::make_pair(Opc, NeedSplit);
19090 }
19091
19092 static SDValue
19093 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
19094                                       const X86Subtarget *Subtarget) {
19095   SDLoc dl(N);
19096   SDValue Cond = N->getOperand(0);
19097   SDValue LHS = N->getOperand(1);
19098   SDValue RHS = N->getOperand(2);
19099
19100   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
19101     SDValue CondSrc = Cond->getOperand(0);
19102     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
19103       Cond = CondSrc->getOperand(0);
19104   }
19105
19106   MVT VT = N->getSimpleValueType(0);
19107   MVT EltVT = VT.getVectorElementType();
19108   unsigned NumElems = VT.getVectorNumElements();
19109   // There is no blend with immediate in AVX-512.
19110   if (VT.is512BitVector())
19111     return SDValue();
19112
19113   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
19114     return SDValue();
19115   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
19116     return SDValue();
19117
19118   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
19119     return SDValue();
19120
19121   unsigned MaskValue = 0;
19122   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
19123     return SDValue();
19124
19125   SmallVector<int, 8> ShuffleMask(NumElems, -1);
19126   for (unsigned i = 0; i < NumElems; ++i) {
19127     // Be sure we emit undef where we can.
19128     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
19129       ShuffleMask[i] = -1;
19130     else
19131       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
19132   }
19133
19134   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
19135 }
19136
19137 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
19138 /// nodes.
19139 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
19140                                     TargetLowering::DAGCombinerInfo &DCI,
19141                                     const X86Subtarget *Subtarget) {
19142   SDLoc DL(N);
19143   SDValue Cond = N->getOperand(0);
19144   // Get the LHS/RHS of the select.
19145   SDValue LHS = N->getOperand(1);
19146   SDValue RHS = N->getOperand(2);
19147   EVT VT = LHS.getValueType();
19148   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19149
19150   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
19151   // instructions match the semantics of the common C idiom x<y?x:y but not
19152   // x<=y?x:y, because of how they handle negative zero (which can be
19153   // ignored in unsafe-math mode).
19154   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
19155       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
19156       (Subtarget->hasSSE2() ||
19157        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
19158     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19159
19160     unsigned Opcode = 0;
19161     // Check for x CC y ? x : y.
19162     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19163         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19164       switch (CC) {
19165       default: break;
19166       case ISD::SETULT:
19167         // Converting this to a min would handle NaNs incorrectly, and swapping
19168         // the operands would cause it to handle comparisons between positive
19169         // and negative zero incorrectly.
19170         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19171           if (!DAG.getTarget().Options.UnsafeFPMath &&
19172               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19173             break;
19174           std::swap(LHS, RHS);
19175         }
19176         Opcode = X86ISD::FMIN;
19177         break;
19178       case ISD::SETOLE:
19179         // Converting this to a min would handle comparisons between positive
19180         // and negative zero incorrectly.
19181         if (!DAG.getTarget().Options.UnsafeFPMath &&
19182             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19183           break;
19184         Opcode = X86ISD::FMIN;
19185         break;
19186       case ISD::SETULE:
19187         // Converting this to a min would handle both negative zeros and NaNs
19188         // incorrectly, but we can swap the operands to fix both.
19189         std::swap(LHS, RHS);
19190       case ISD::SETOLT:
19191       case ISD::SETLT:
19192       case ISD::SETLE:
19193         Opcode = X86ISD::FMIN;
19194         break;
19195
19196       case ISD::SETOGE:
19197         // Converting this to a max would handle comparisons between positive
19198         // and negative zero incorrectly.
19199         if (!DAG.getTarget().Options.UnsafeFPMath &&
19200             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
19201           break;
19202         Opcode = X86ISD::FMAX;
19203         break;
19204       case ISD::SETUGT:
19205         // Converting this to a max would handle NaNs incorrectly, and swapping
19206         // the operands would cause it to handle comparisons between positive
19207         // and negative zero incorrectly.
19208         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
19209           if (!DAG.getTarget().Options.UnsafeFPMath &&
19210               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
19211             break;
19212           std::swap(LHS, RHS);
19213         }
19214         Opcode = X86ISD::FMAX;
19215         break;
19216       case ISD::SETUGE:
19217         // Converting this to a max would handle both negative zeros and NaNs
19218         // incorrectly, but we can swap the operands to fix both.
19219         std::swap(LHS, RHS);
19220       case ISD::SETOGT:
19221       case ISD::SETGT:
19222       case ISD::SETGE:
19223         Opcode = X86ISD::FMAX;
19224         break;
19225       }
19226     // Check for x CC y ? y : x -- a min/max with reversed arms.
19227     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
19228                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
19229       switch (CC) {
19230       default: break;
19231       case ISD::SETOGE:
19232         // Converting this to a min would handle comparisons between positive
19233         // and negative zero incorrectly, and swapping the operands would
19234         // cause it to handle NaNs incorrectly.
19235         if (!DAG.getTarget().Options.UnsafeFPMath &&
19236             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
19237           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19238             break;
19239           std::swap(LHS, RHS);
19240         }
19241         Opcode = X86ISD::FMIN;
19242         break;
19243       case ISD::SETUGT:
19244         // Converting this to a min would handle NaNs incorrectly.
19245         if (!DAG.getTarget().Options.UnsafeFPMath &&
19246             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
19247           break;
19248         Opcode = X86ISD::FMIN;
19249         break;
19250       case ISD::SETUGE:
19251         // Converting this to a min would handle both negative zeros and NaNs
19252         // incorrectly, but we can swap the operands to fix both.
19253         std::swap(LHS, RHS);
19254       case ISD::SETOGT:
19255       case ISD::SETGT:
19256       case ISD::SETGE:
19257         Opcode = X86ISD::FMIN;
19258         break;
19259
19260       case ISD::SETULT:
19261         // Converting this to a max would handle NaNs incorrectly.
19262         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19263           break;
19264         Opcode = X86ISD::FMAX;
19265         break;
19266       case ISD::SETOLE:
19267         // Converting this to a max would handle comparisons between positive
19268         // and negative zero incorrectly, and swapping the operands would
19269         // cause it to handle NaNs incorrectly.
19270         if (!DAG.getTarget().Options.UnsafeFPMath &&
19271             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
19272           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
19273             break;
19274           std::swap(LHS, RHS);
19275         }
19276         Opcode = X86ISD::FMAX;
19277         break;
19278       case ISD::SETULE:
19279         // Converting this to a max would handle both negative zeros and NaNs
19280         // incorrectly, but we can swap the operands to fix both.
19281         std::swap(LHS, RHS);
19282       case ISD::SETOLT:
19283       case ISD::SETLT:
19284       case ISD::SETLE:
19285         Opcode = X86ISD::FMAX;
19286         break;
19287       }
19288     }
19289
19290     if (Opcode)
19291       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
19292   }
19293
19294   EVT CondVT = Cond.getValueType();
19295   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
19296       CondVT.getVectorElementType() == MVT::i1) {
19297     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
19298     // lowering on AVX-512. In this case we convert it to
19299     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
19300     // The same situation for all 128 and 256-bit vectors of i8 and i16
19301     EVT OpVT = LHS.getValueType();
19302     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
19303         (OpVT.getVectorElementType() == MVT::i8 ||
19304          OpVT.getVectorElementType() == MVT::i16)) {
19305       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
19306       DCI.AddToWorklist(Cond.getNode());
19307       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
19308     }
19309   }
19310   // If this is a select between two integer constants, try to do some
19311   // optimizations.
19312   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
19313     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
19314       // Don't do this for crazy integer types.
19315       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
19316         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
19317         // so that TrueC (the true value) is larger than FalseC.
19318         bool NeedsCondInvert = false;
19319
19320         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
19321             // Efficiently invertible.
19322             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
19323              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
19324               isa<ConstantSDNode>(Cond.getOperand(1))))) {
19325           NeedsCondInvert = true;
19326           std::swap(TrueC, FalseC);
19327         }
19328
19329         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
19330         if (FalseC->getAPIntValue() == 0 &&
19331             TrueC->getAPIntValue().isPowerOf2()) {
19332           if (NeedsCondInvert) // Invert the condition if needed.
19333             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19334                                DAG.getConstant(1, Cond.getValueType()));
19335
19336           // Zero extend the condition if needed.
19337           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
19338
19339           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19340           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
19341                              DAG.getConstant(ShAmt, MVT::i8));
19342         }
19343
19344         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
19345         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19346           if (NeedsCondInvert) // Invert the condition if needed.
19347             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19348                                DAG.getConstant(1, Cond.getValueType()));
19349
19350           // Zero extend the condition if needed.
19351           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19352                              FalseC->getValueType(0), Cond);
19353           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19354                              SDValue(FalseC, 0));
19355         }
19356
19357         // Optimize cases that will turn into an LEA instruction.  This requires
19358         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19359         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19360           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19361           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19362
19363           bool isFastMultiplier = false;
19364           if (Diff < 10) {
19365             switch ((unsigned char)Diff) {
19366               default: break;
19367               case 1:  // result = add base, cond
19368               case 2:  // result = lea base(    , cond*2)
19369               case 3:  // result = lea base(cond, cond*2)
19370               case 4:  // result = lea base(    , cond*4)
19371               case 5:  // result = lea base(cond, cond*4)
19372               case 8:  // result = lea base(    , cond*8)
19373               case 9:  // result = lea base(cond, cond*8)
19374                 isFastMultiplier = true;
19375                 break;
19376             }
19377           }
19378
19379           if (isFastMultiplier) {
19380             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19381             if (NeedsCondInvert) // Invert the condition if needed.
19382               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
19383                                  DAG.getConstant(1, Cond.getValueType()));
19384
19385             // Zero extend the condition if needed.
19386             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19387                                Cond);
19388             // Scale the condition by the difference.
19389             if (Diff != 1)
19390               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19391                                  DAG.getConstant(Diff, Cond.getValueType()));
19392
19393             // Add the base if non-zero.
19394             if (FalseC->getAPIntValue() != 0)
19395               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19396                                  SDValue(FalseC, 0));
19397             return Cond;
19398           }
19399         }
19400       }
19401   }
19402
19403   // Canonicalize max and min:
19404   // (x > y) ? x : y -> (x >= y) ? x : y
19405   // (x < y) ? x : y -> (x <= y) ? x : y
19406   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
19407   // the need for an extra compare
19408   // against zero. e.g.
19409   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
19410   // subl   %esi, %edi
19411   // testl  %edi, %edi
19412   // movl   $0, %eax
19413   // cmovgl %edi, %eax
19414   // =>
19415   // xorl   %eax, %eax
19416   // subl   %esi, $edi
19417   // cmovsl %eax, %edi
19418   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
19419       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
19420       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
19421     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19422     switch (CC) {
19423     default: break;
19424     case ISD::SETLT:
19425     case ISD::SETGT: {
19426       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
19427       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
19428                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
19429       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
19430     }
19431     }
19432   }
19433
19434   // Early exit check
19435   if (!TLI.isTypeLegal(VT))
19436     return SDValue();
19437
19438   // Match VSELECTs into subs with unsigned saturation.
19439   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19440       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
19441       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
19442        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
19443     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
19444
19445     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
19446     // left side invert the predicate to simplify logic below.
19447     SDValue Other;
19448     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
19449       Other = RHS;
19450       CC = ISD::getSetCCInverse(CC, true);
19451     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
19452       Other = LHS;
19453     }
19454
19455     if (Other.getNode() && Other->getNumOperands() == 2 &&
19456         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
19457       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
19458       SDValue CondRHS = Cond->getOperand(1);
19459
19460       // Look for a general sub with unsigned saturation first.
19461       // x >= y ? x-y : 0 --> subus x, y
19462       // x >  y ? x-y : 0 --> subus x, y
19463       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
19464           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
19465         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19466
19467       // If the RHS is a constant we have to reverse the const canonicalization.
19468       // x > C-1 ? x+-C : 0 --> subus x, C
19469       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
19470           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
19471         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
19472         if (CondRHS.getConstantOperandVal(0) == -A-1)
19473           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
19474                              DAG.getConstant(-A, VT));
19475       }
19476
19477       // Another special case: If C was a sign bit, the sub has been
19478       // canonicalized into a xor.
19479       // FIXME: Would it be better to use computeKnownBits to determine whether
19480       //        it's safe to decanonicalize the xor?
19481       // x s< 0 ? x^C : 0 --> subus x, C
19482       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
19483           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
19484           isSplatVector(OpRHS.getNode())) {
19485         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
19486         if (A.isSignBit())
19487           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
19488       }
19489     }
19490   }
19491
19492   // Try to match a min/max vector operation.
19493   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
19494     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
19495     unsigned Opc = ret.first;
19496     bool NeedSplit = ret.second;
19497
19498     if (Opc && NeedSplit) {
19499       unsigned NumElems = VT.getVectorNumElements();
19500       // Extract the LHS vectors
19501       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
19502       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
19503
19504       // Extract the RHS vectors
19505       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
19506       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
19507
19508       // Create min/max for each subvector
19509       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
19510       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
19511
19512       // Merge the result
19513       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
19514     } else if (Opc)
19515       return DAG.getNode(Opc, DL, VT, LHS, RHS);
19516   }
19517
19518   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
19519   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
19520       // Check if SETCC has already been promoted
19521       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
19522       // Check that condition value type matches vselect operand type
19523       CondVT == VT) { 
19524
19525     assert(Cond.getValueType().isVector() &&
19526            "vector select expects a vector selector!");
19527
19528     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
19529     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
19530
19531     if (!TValIsAllOnes && !FValIsAllZeros) {
19532       // Try invert the condition if true value is not all 1s and false value
19533       // is not all 0s.
19534       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
19535       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
19536
19537       if (TValIsAllZeros || FValIsAllOnes) {
19538         SDValue CC = Cond.getOperand(2);
19539         ISD::CondCode NewCC =
19540           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
19541                                Cond.getOperand(0).getValueType().isInteger());
19542         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
19543         std::swap(LHS, RHS);
19544         TValIsAllOnes = FValIsAllOnes;
19545         FValIsAllZeros = TValIsAllZeros;
19546       }
19547     }
19548
19549     if (TValIsAllOnes || FValIsAllZeros) {
19550       SDValue Ret;
19551
19552       if (TValIsAllOnes && FValIsAllZeros)
19553         Ret = Cond;
19554       else if (TValIsAllOnes)
19555         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
19556                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
19557       else if (FValIsAllZeros)
19558         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
19559                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
19560
19561       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
19562     }
19563   }
19564
19565   // Try to fold this VSELECT into a MOVSS/MOVSD
19566   if (N->getOpcode() == ISD::VSELECT &&
19567       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
19568     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
19569         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
19570       bool CanFold = false;
19571       unsigned NumElems = Cond.getNumOperands();
19572       SDValue A = LHS;
19573       SDValue B = RHS;
19574       
19575       if (isZero(Cond.getOperand(0))) {
19576         CanFold = true;
19577
19578         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
19579         // fold (vselect <0,-1> -> (movsd A, B)
19580         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19581           CanFold = isAllOnes(Cond.getOperand(i));
19582       } else if (isAllOnes(Cond.getOperand(0))) {
19583         CanFold = true;
19584         std::swap(A, B);
19585
19586         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
19587         // fold (vselect <-1,0> -> (movsd B, A)
19588         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
19589           CanFold = isZero(Cond.getOperand(i));
19590       }
19591
19592       if (CanFold) {
19593         if (VT == MVT::v4i32 || VT == MVT::v4f32)
19594           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
19595         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
19596       }
19597
19598       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
19599         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
19600         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
19601         //                             (v2i64 (bitcast B)))))
19602         //
19603         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
19604         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
19605         //                             (v2f64 (bitcast B)))))
19606         //
19607         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
19608         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
19609         //                             (v2i64 (bitcast A)))))
19610         //
19611         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
19612         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
19613         //                             (v2f64 (bitcast A)))))
19614
19615         CanFold = (isZero(Cond.getOperand(0)) &&
19616                    isZero(Cond.getOperand(1)) &&
19617                    isAllOnes(Cond.getOperand(2)) &&
19618                    isAllOnes(Cond.getOperand(3)));
19619
19620         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
19621             isAllOnes(Cond.getOperand(1)) &&
19622             isZero(Cond.getOperand(2)) &&
19623             isZero(Cond.getOperand(3))) {
19624           CanFold = true;
19625           std::swap(LHS, RHS);
19626         }
19627
19628         if (CanFold) {
19629           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
19630           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
19631           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
19632           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
19633                                                 NewB, DAG);
19634           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
19635         }
19636       }
19637     }
19638   }
19639
19640   // If we know that this node is legal then we know that it is going to be
19641   // matched by one of the SSE/AVX BLEND instructions. These instructions only
19642   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
19643   // to simplify previous instructions.
19644   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
19645       !DCI.isBeforeLegalize() &&
19646       // We explicitly check against v8i16 and v16i16 because, although
19647       // they're marked as Custom, they might only be legal when Cond is a
19648       // build_vector of constants. This will be taken care in a later
19649       // condition.
19650       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
19651        VT != MVT::v8i16)) {
19652     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
19653
19654     // Don't optimize vector selects that map to mask-registers.
19655     if (BitWidth == 1)
19656       return SDValue();
19657
19658     // Check all uses of that condition operand to check whether it will be
19659     // consumed by non-BLEND instructions, which may depend on all bits are set
19660     // properly.
19661     for (SDNode::use_iterator I = Cond->use_begin(),
19662                               E = Cond->use_end(); I != E; ++I)
19663       if (I->getOpcode() != ISD::VSELECT)
19664         // TODO: Add other opcodes eventually lowered into BLEND.
19665         return SDValue();
19666
19667     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
19668     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
19669
19670     APInt KnownZero, KnownOne;
19671     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
19672                                           DCI.isBeforeLegalizeOps());
19673     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
19674         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
19675       DCI.CommitTargetLoweringOpt(TLO);
19676   }
19677
19678   // We should generate an X86ISD::BLENDI from a vselect if its argument
19679   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
19680   // constants. This specific pattern gets generated when we split a
19681   // selector for a 512 bit vector in a machine without AVX512 (but with
19682   // 256-bit vectors), during legalization:
19683   //
19684   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
19685   //
19686   // Iff we find this pattern and the build_vectors are built from
19687   // constants, we translate the vselect into a shuffle_vector that we
19688   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
19689   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
19690     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
19691     if (Shuffle.getNode())
19692       return Shuffle;
19693   }
19694
19695   return SDValue();
19696 }
19697
19698 // Check whether a boolean test is testing a boolean value generated by
19699 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
19700 // code.
19701 //
19702 // Simplify the following patterns:
19703 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
19704 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
19705 // to (Op EFLAGS Cond)
19706 //
19707 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
19708 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
19709 // to (Op EFLAGS !Cond)
19710 //
19711 // where Op could be BRCOND or CMOV.
19712 //
19713 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
19714   // Quit if not CMP and SUB with its value result used.
19715   if (Cmp.getOpcode() != X86ISD::CMP &&
19716       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
19717       return SDValue();
19718
19719   // Quit if not used as a boolean value.
19720   if (CC != X86::COND_E && CC != X86::COND_NE)
19721     return SDValue();
19722
19723   // Check CMP operands. One of them should be 0 or 1 and the other should be
19724   // an SetCC or extended from it.
19725   SDValue Op1 = Cmp.getOperand(0);
19726   SDValue Op2 = Cmp.getOperand(1);
19727
19728   SDValue SetCC;
19729   const ConstantSDNode* C = nullptr;
19730   bool needOppositeCond = (CC == X86::COND_E);
19731   bool checkAgainstTrue = false; // Is it a comparison against 1?
19732
19733   if ((C = dyn_cast<ConstantSDNode>(Op1)))
19734     SetCC = Op2;
19735   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19736     SetCC = Op1;
19737   else // Quit if all operands are not constants.
19738     return SDValue();
19739
19740   if (C->getZExtValue() == 1) {
19741     needOppositeCond = !needOppositeCond;
19742     checkAgainstTrue = true;
19743   } else if (C->getZExtValue() != 0)
19744     // Quit if the constant is neither 0 or 1.
19745     return SDValue();
19746
19747   bool truncatedToBoolWithAnd = false;
19748   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19749   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19750          SetCC.getOpcode() == ISD::TRUNCATE ||
19751          SetCC.getOpcode() == ISD::AND) {
19752     if (SetCC.getOpcode() == ISD::AND) {
19753       int OpIdx = -1;
19754       ConstantSDNode *CS;
19755       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19756           CS->getZExtValue() == 1)
19757         OpIdx = 1;
19758       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19759           CS->getZExtValue() == 1)
19760         OpIdx = 0;
19761       if (OpIdx == -1)
19762         break;
19763       SetCC = SetCC.getOperand(OpIdx);
19764       truncatedToBoolWithAnd = true;
19765     } else
19766       SetCC = SetCC.getOperand(0);
19767   }
19768
19769   switch (SetCC.getOpcode()) {
19770   case X86ISD::SETCC_CARRY:
19771     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19772     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19773     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19774     // truncated to i1 using 'and'.
19775     if (checkAgainstTrue && !truncatedToBoolWithAnd)
19776       break;
19777     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19778            "Invalid use of SETCC_CARRY!");
19779     // FALL THROUGH
19780   case X86ISD::SETCC:
19781     // Set the condition code or opposite one if necessary.
19782     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19783     if (needOppositeCond)
19784       CC = X86::GetOppositeBranchCondition(CC);
19785     return SetCC.getOperand(1);
19786   case X86ISD::CMOV: {
19787     // Check whether false/true value has canonical one, i.e. 0 or 1.
19788     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19789     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19790     // Quit if true value is not a constant.
19791     if (!TVal)
19792       return SDValue();
19793     // Quit if false value is not a constant.
19794     if (!FVal) {
19795       SDValue Op = SetCC.getOperand(0);
19796       // Skip 'zext' or 'trunc' node.
19797       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19798           Op.getOpcode() == ISD::TRUNCATE)
19799         Op = Op.getOperand(0);
19800       // A special case for rdrand/rdseed, where 0 is set if false cond is
19801       // found.
19802       if ((Op.getOpcode() != X86ISD::RDRAND &&
19803            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19804         return SDValue();
19805     }
19806     // Quit if false value is not the constant 0 or 1.
19807     bool FValIsFalse = true;
19808     if (FVal && FVal->getZExtValue() != 0) {
19809       if (FVal->getZExtValue() != 1)
19810         return SDValue();
19811       // If FVal is 1, opposite cond is needed.
19812       needOppositeCond = !needOppositeCond;
19813       FValIsFalse = false;
19814     }
19815     // Quit if TVal is not the constant opposite of FVal.
19816     if (FValIsFalse && TVal->getZExtValue() != 1)
19817       return SDValue();
19818     if (!FValIsFalse && TVal->getZExtValue() != 0)
19819       return SDValue();
19820     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19821     if (needOppositeCond)
19822       CC = X86::GetOppositeBranchCondition(CC);
19823     return SetCC.getOperand(3);
19824   }
19825   }
19826
19827   return SDValue();
19828 }
19829
19830 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19831 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19832                                   TargetLowering::DAGCombinerInfo &DCI,
19833                                   const X86Subtarget *Subtarget) {
19834   SDLoc DL(N);
19835
19836   // If the flag operand isn't dead, don't touch this CMOV.
19837   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19838     return SDValue();
19839
19840   SDValue FalseOp = N->getOperand(0);
19841   SDValue TrueOp = N->getOperand(1);
19842   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19843   SDValue Cond = N->getOperand(3);
19844
19845   if (CC == X86::COND_E || CC == X86::COND_NE) {
19846     switch (Cond.getOpcode()) {
19847     default: break;
19848     case X86ISD::BSR:
19849     case X86ISD::BSF:
19850       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19851       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19852         return (CC == X86::COND_E) ? FalseOp : TrueOp;
19853     }
19854   }
19855
19856   SDValue Flags;
19857
19858   Flags = checkBoolTestSetCCCombine(Cond, CC);
19859   if (Flags.getNode() &&
19860       // Extra check as FCMOV only supports a subset of X86 cond.
19861       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19862     SDValue Ops[] = { FalseOp, TrueOp,
19863                       DAG.getConstant(CC, MVT::i8), Flags };
19864     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19865   }
19866
19867   // If this is a select between two integer constants, try to do some
19868   // optimizations.  Note that the operands are ordered the opposite of SELECT
19869   // operands.
19870   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19871     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19872       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19873       // larger than FalseC (the false value).
19874       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19875         CC = X86::GetOppositeBranchCondition(CC);
19876         std::swap(TrueC, FalseC);
19877         std::swap(TrueOp, FalseOp);
19878       }
19879
19880       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19881       // This is efficient for any integer data type (including i8/i16) and
19882       // shift amount.
19883       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19884         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19885                            DAG.getConstant(CC, MVT::i8), Cond);
19886
19887         // Zero extend the condition if needed.
19888         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19889
19890         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19891         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19892                            DAG.getConstant(ShAmt, MVT::i8));
19893         if (N->getNumValues() == 2)  // Dead flag value?
19894           return DCI.CombineTo(N, Cond, SDValue());
19895         return Cond;
19896       }
19897
19898       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
19899       // for any integer data type, including i8/i16.
19900       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19901         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19902                            DAG.getConstant(CC, MVT::i8), Cond);
19903
19904         // Zero extend the condition if needed.
19905         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19906                            FalseC->getValueType(0), Cond);
19907         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19908                            SDValue(FalseC, 0));
19909
19910         if (N->getNumValues() == 2)  // Dead flag value?
19911           return DCI.CombineTo(N, Cond, SDValue());
19912         return Cond;
19913       }
19914
19915       // Optimize cases that will turn into an LEA instruction.  This requires
19916       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19917       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19918         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19919         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19920
19921         bool isFastMultiplier = false;
19922         if (Diff < 10) {
19923           switch ((unsigned char)Diff) {
19924           default: break;
19925           case 1:  // result = add base, cond
19926           case 2:  // result = lea base(    , cond*2)
19927           case 3:  // result = lea base(cond, cond*2)
19928           case 4:  // result = lea base(    , cond*4)
19929           case 5:  // result = lea base(cond, cond*4)
19930           case 8:  // result = lea base(    , cond*8)
19931           case 9:  // result = lea base(cond, cond*8)
19932             isFastMultiplier = true;
19933             break;
19934           }
19935         }
19936
19937         if (isFastMultiplier) {
19938           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19939           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19940                              DAG.getConstant(CC, MVT::i8), Cond);
19941           // Zero extend the condition if needed.
19942           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19943                              Cond);
19944           // Scale the condition by the difference.
19945           if (Diff != 1)
19946             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19947                                DAG.getConstant(Diff, Cond.getValueType()));
19948
19949           // Add the base if non-zero.
19950           if (FalseC->getAPIntValue() != 0)
19951             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19952                                SDValue(FalseC, 0));
19953           if (N->getNumValues() == 2)  // Dead flag value?
19954             return DCI.CombineTo(N, Cond, SDValue());
19955           return Cond;
19956         }
19957       }
19958     }
19959   }
19960
19961   // Handle these cases:
19962   //   (select (x != c), e, c) -> select (x != c), e, x),
19963   //   (select (x == c), c, e) -> select (x == c), x, e)
19964   // where the c is an integer constant, and the "select" is the combination
19965   // of CMOV and CMP.
19966   //
19967   // The rationale for this change is that the conditional-move from a constant
19968   // needs two instructions, however, conditional-move from a register needs
19969   // only one instruction.
19970   //
19971   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19972   //  some instruction-combining opportunities. This opt needs to be
19973   //  postponed as late as possible.
19974   //
19975   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19976     // the DCI.xxxx conditions are provided to postpone the optimization as
19977     // late as possible.
19978
19979     ConstantSDNode *CmpAgainst = nullptr;
19980     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19981         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19982         !isa<ConstantSDNode>(Cond.getOperand(0))) {
19983
19984       if (CC == X86::COND_NE &&
19985           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19986         CC = X86::GetOppositeBranchCondition(CC);
19987         std::swap(TrueOp, FalseOp);
19988       }
19989
19990       if (CC == X86::COND_E &&
19991           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19992         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19993                           DAG.getConstant(CC, MVT::i8), Cond };
19994         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19995       }
19996     }
19997   }
19998
19999   return SDValue();
20000 }
20001
20002 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
20003                                                 const X86Subtarget *Subtarget) {
20004   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
20005   switch (IntNo) {
20006   default: return SDValue();
20007   // SSE/AVX/AVX2 blend intrinsics.
20008   case Intrinsic::x86_avx2_pblendvb:
20009   case Intrinsic::x86_avx2_pblendw:
20010   case Intrinsic::x86_avx2_pblendd_128:
20011   case Intrinsic::x86_avx2_pblendd_256:
20012     // Don't try to simplify this intrinsic if we don't have AVX2.
20013     if (!Subtarget->hasAVX2())
20014       return SDValue();
20015     // FALL-THROUGH
20016   case Intrinsic::x86_avx_blend_pd_256:
20017   case Intrinsic::x86_avx_blend_ps_256:
20018   case Intrinsic::x86_avx_blendv_pd_256:
20019   case Intrinsic::x86_avx_blendv_ps_256:
20020     // Don't try to simplify this intrinsic if we don't have AVX.
20021     if (!Subtarget->hasAVX())
20022       return SDValue();
20023     // FALL-THROUGH
20024   case Intrinsic::x86_sse41_pblendw:
20025   case Intrinsic::x86_sse41_blendpd:
20026   case Intrinsic::x86_sse41_blendps:
20027   case Intrinsic::x86_sse41_blendvps:
20028   case Intrinsic::x86_sse41_blendvpd:
20029   case Intrinsic::x86_sse41_pblendvb: {
20030     SDValue Op0 = N->getOperand(1);
20031     SDValue Op1 = N->getOperand(2);
20032     SDValue Mask = N->getOperand(3);
20033
20034     // Don't try to simplify this intrinsic if we don't have SSE4.1.
20035     if (!Subtarget->hasSSE41())
20036       return SDValue();
20037
20038     // fold (blend A, A, Mask) -> A
20039     if (Op0 == Op1)
20040       return Op0;
20041     // fold (blend A, B, allZeros) -> A
20042     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
20043       return Op0;
20044     // fold (blend A, B, allOnes) -> B
20045     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
20046       return Op1;
20047     
20048     // Simplify the case where the mask is a constant i32 value.
20049     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
20050       if (C->isNullValue())
20051         return Op0;
20052       if (C->isAllOnesValue())
20053         return Op1;
20054     }
20055
20056     return SDValue();
20057   }
20058
20059   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
20060   case Intrinsic::x86_sse2_psrai_w:
20061   case Intrinsic::x86_sse2_psrai_d:
20062   case Intrinsic::x86_avx2_psrai_w:
20063   case Intrinsic::x86_avx2_psrai_d:
20064   case Intrinsic::x86_sse2_psra_w:
20065   case Intrinsic::x86_sse2_psra_d:
20066   case Intrinsic::x86_avx2_psra_w:
20067   case Intrinsic::x86_avx2_psra_d: {
20068     SDValue Op0 = N->getOperand(1);
20069     SDValue Op1 = N->getOperand(2);
20070     EVT VT = Op0.getValueType();
20071     assert(VT.isVector() && "Expected a vector type!");
20072
20073     if (isa<BuildVectorSDNode>(Op1))
20074       Op1 = Op1.getOperand(0);
20075
20076     if (!isa<ConstantSDNode>(Op1))
20077       return SDValue();
20078
20079     EVT SVT = VT.getVectorElementType();
20080     unsigned SVTBits = SVT.getSizeInBits();
20081
20082     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
20083     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
20084     uint64_t ShAmt = C.getZExtValue();
20085
20086     // Don't try to convert this shift into a ISD::SRA if the shift
20087     // count is bigger than or equal to the element size.
20088     if (ShAmt >= SVTBits)
20089       return SDValue();
20090
20091     // Trivial case: if the shift count is zero, then fold this
20092     // into the first operand.
20093     if (ShAmt == 0)
20094       return Op0;
20095
20096     // Replace this packed shift intrinsic with a target independent
20097     // shift dag node.
20098     SDValue Splat = DAG.getConstant(C, VT);
20099     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
20100   }
20101   }
20102 }
20103
20104 /// PerformMulCombine - Optimize a single multiply with constant into two
20105 /// in order to implement it with two cheaper instructions, e.g.
20106 /// LEA + SHL, LEA + LEA.
20107 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
20108                                  TargetLowering::DAGCombinerInfo &DCI) {
20109   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
20110     return SDValue();
20111
20112   EVT VT = N->getValueType(0);
20113   if (VT != MVT::i64)
20114     return SDValue();
20115
20116   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
20117   if (!C)
20118     return SDValue();
20119   uint64_t MulAmt = C->getZExtValue();
20120   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
20121     return SDValue();
20122
20123   uint64_t MulAmt1 = 0;
20124   uint64_t MulAmt2 = 0;
20125   if ((MulAmt % 9) == 0) {
20126     MulAmt1 = 9;
20127     MulAmt2 = MulAmt / 9;
20128   } else if ((MulAmt % 5) == 0) {
20129     MulAmt1 = 5;
20130     MulAmt2 = MulAmt / 5;
20131   } else if ((MulAmt % 3) == 0) {
20132     MulAmt1 = 3;
20133     MulAmt2 = MulAmt / 3;
20134   }
20135   if (MulAmt2 &&
20136       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
20137     SDLoc DL(N);
20138
20139     if (isPowerOf2_64(MulAmt2) &&
20140         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
20141       // If second multiplifer is pow2, issue it first. We want the multiply by
20142       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
20143       // is an add.
20144       std::swap(MulAmt1, MulAmt2);
20145
20146     SDValue NewMul;
20147     if (isPowerOf2_64(MulAmt1))
20148       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
20149                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
20150     else
20151       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
20152                            DAG.getConstant(MulAmt1, VT));
20153
20154     if (isPowerOf2_64(MulAmt2))
20155       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
20156                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
20157     else
20158       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
20159                            DAG.getConstant(MulAmt2, VT));
20160
20161     // Do not add new nodes to DAG combiner worklist.
20162     DCI.CombineTo(N, NewMul, false);
20163   }
20164   return SDValue();
20165 }
20166
20167 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
20168   SDValue N0 = N->getOperand(0);
20169   SDValue N1 = N->getOperand(1);
20170   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
20171   EVT VT = N0.getValueType();
20172
20173   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
20174   // since the result of setcc_c is all zero's or all ones.
20175   if (VT.isInteger() && !VT.isVector() &&
20176       N1C && N0.getOpcode() == ISD::AND &&
20177       N0.getOperand(1).getOpcode() == ISD::Constant) {
20178     SDValue N00 = N0.getOperand(0);
20179     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
20180         ((N00.getOpcode() == ISD::ANY_EXTEND ||
20181           N00.getOpcode() == ISD::ZERO_EXTEND) &&
20182          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
20183       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
20184       APInt ShAmt = N1C->getAPIntValue();
20185       Mask = Mask.shl(ShAmt);
20186       if (Mask != 0)
20187         return DAG.getNode(ISD::AND, SDLoc(N), VT,
20188                            N00, DAG.getConstant(Mask, VT));
20189     }
20190   }
20191
20192   // Hardware support for vector shifts is sparse which makes us scalarize the
20193   // vector operations in many cases. Also, on sandybridge ADD is faster than
20194   // shl.
20195   // (shl V, 1) -> add V,V
20196   if (isSplatVector(N1.getNode())) {
20197     assert(N0.getValueType().isVector() && "Invalid vector shift type");
20198     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
20199     // We shift all of the values by one. In many cases we do not have
20200     // hardware support for this operation. This is better expressed as an ADD
20201     // of two values.
20202     if (N1C && (1 == N1C->getZExtValue())) {
20203       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
20204     }
20205   }
20206
20207   return SDValue();
20208 }
20209
20210 /// \brief Returns a vector of 0s if the node in input is a vector logical
20211 /// shift by a constant amount which is known to be bigger than or equal
20212 /// to the vector element size in bits.
20213 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
20214                                       const X86Subtarget *Subtarget) {
20215   EVT VT = N->getValueType(0);
20216
20217   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
20218       (!Subtarget->hasInt256() ||
20219        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
20220     return SDValue();
20221
20222   SDValue Amt = N->getOperand(1);
20223   SDLoc DL(N);
20224   if (isSplatVector(Amt.getNode())) {
20225     SDValue SclrAmt = Amt->getOperand(0);
20226     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
20227       APInt ShiftAmt = C->getAPIntValue();
20228       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
20229
20230       // SSE2/AVX2 logical shifts always return a vector of 0s
20231       // if the shift amount is bigger than or equal to
20232       // the element size. The constant shift amount will be
20233       // encoded as a 8-bit immediate.
20234       if (ShiftAmt.trunc(8).uge(MaxAmount))
20235         return getZeroVector(VT, Subtarget, DAG, DL);
20236     }
20237   }
20238
20239   return SDValue();
20240 }
20241
20242 /// PerformShiftCombine - Combine shifts.
20243 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
20244                                    TargetLowering::DAGCombinerInfo &DCI,
20245                                    const X86Subtarget *Subtarget) {
20246   if (N->getOpcode() == ISD::SHL) {
20247     SDValue V = PerformSHLCombine(N, DAG);
20248     if (V.getNode()) return V;
20249   }
20250
20251   if (N->getOpcode() != ISD::SRA) {
20252     // Try to fold this logical shift into a zero vector.
20253     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
20254     if (V.getNode()) return V;
20255   }
20256
20257   return SDValue();
20258 }
20259
20260 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
20261 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
20262 // and friends.  Likewise for OR -> CMPNEQSS.
20263 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
20264                             TargetLowering::DAGCombinerInfo &DCI,
20265                             const X86Subtarget *Subtarget) {
20266   unsigned opcode;
20267
20268   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
20269   // we're requiring SSE2 for both.
20270   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
20271     SDValue N0 = N->getOperand(0);
20272     SDValue N1 = N->getOperand(1);
20273     SDValue CMP0 = N0->getOperand(1);
20274     SDValue CMP1 = N1->getOperand(1);
20275     SDLoc DL(N);
20276
20277     // The SETCCs should both refer to the same CMP.
20278     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
20279       return SDValue();
20280
20281     SDValue CMP00 = CMP0->getOperand(0);
20282     SDValue CMP01 = CMP0->getOperand(1);
20283     EVT     VT    = CMP00.getValueType();
20284
20285     if (VT == MVT::f32 || VT == MVT::f64) {
20286       bool ExpectingFlags = false;
20287       // Check for any users that want flags:
20288       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
20289            !ExpectingFlags && UI != UE; ++UI)
20290         switch (UI->getOpcode()) {
20291         default:
20292         case ISD::BR_CC:
20293         case ISD::BRCOND:
20294         case ISD::SELECT:
20295           ExpectingFlags = true;
20296           break;
20297         case ISD::CopyToReg:
20298         case ISD::SIGN_EXTEND:
20299         case ISD::ZERO_EXTEND:
20300         case ISD::ANY_EXTEND:
20301           break;
20302         }
20303
20304       if (!ExpectingFlags) {
20305         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
20306         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
20307
20308         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
20309           X86::CondCode tmp = cc0;
20310           cc0 = cc1;
20311           cc1 = tmp;
20312         }
20313
20314         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
20315             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
20316           // FIXME: need symbolic constants for these magic numbers.
20317           // See X86ATTInstPrinter.cpp:printSSECC().
20318           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
20319           if (Subtarget->hasAVX512()) {
20320             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
20321                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
20322             if (N->getValueType(0) != MVT::i1)
20323               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
20324                                  FSetCC);
20325             return FSetCC;
20326           }
20327           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
20328                                               CMP00.getValueType(), CMP00, CMP01,
20329                                               DAG.getConstant(x86cc, MVT::i8));
20330
20331           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
20332           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
20333
20334           if (is64BitFP && !Subtarget->is64Bit()) {
20335             // On a 32-bit target, we cannot bitcast the 64-bit float to a
20336             // 64-bit integer, since that's not a legal type. Since
20337             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
20338             // bits, but can do this little dance to extract the lowest 32 bits
20339             // and work with those going forward.
20340             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
20341                                            OnesOrZeroesF);
20342             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
20343                                            Vector64);
20344             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
20345                                         Vector32, DAG.getIntPtrConstant(0));
20346             IntVT = MVT::i32;
20347           }
20348
20349           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
20350           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
20351                                       DAG.getConstant(1, IntVT));
20352           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
20353           return OneBitOfTruth;
20354         }
20355       }
20356     }
20357   }
20358   return SDValue();
20359 }
20360
20361 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
20362 /// so it can be folded inside ANDNP.
20363 static bool CanFoldXORWithAllOnes(const SDNode *N) {
20364   EVT VT = N->getValueType(0);
20365
20366   // Match direct AllOnes for 128 and 256-bit vectors
20367   if (ISD::isBuildVectorAllOnes(N))
20368     return true;
20369
20370   // Look through a bit convert.
20371   if (N->getOpcode() == ISD::BITCAST)
20372     N = N->getOperand(0).getNode();
20373
20374   // Sometimes the operand may come from a insert_subvector building a 256-bit
20375   // allones vector
20376   if (VT.is256BitVector() &&
20377       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
20378     SDValue V1 = N->getOperand(0);
20379     SDValue V2 = N->getOperand(1);
20380
20381     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
20382         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
20383         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
20384         ISD::isBuildVectorAllOnes(V2.getNode()))
20385       return true;
20386   }
20387
20388   return false;
20389 }
20390
20391 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
20392 // register. In most cases we actually compare or select YMM-sized registers
20393 // and mixing the two types creates horrible code. This method optimizes
20394 // some of the transition sequences.
20395 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
20396                                  TargetLowering::DAGCombinerInfo &DCI,
20397                                  const X86Subtarget *Subtarget) {
20398   EVT VT = N->getValueType(0);
20399   if (!VT.is256BitVector())
20400     return SDValue();
20401
20402   assert((N->getOpcode() == ISD::ANY_EXTEND ||
20403           N->getOpcode() == ISD::ZERO_EXTEND ||
20404           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
20405
20406   SDValue Narrow = N->getOperand(0);
20407   EVT NarrowVT = Narrow->getValueType(0);
20408   if (!NarrowVT.is128BitVector())
20409     return SDValue();
20410
20411   if (Narrow->getOpcode() != ISD::XOR &&
20412       Narrow->getOpcode() != ISD::AND &&
20413       Narrow->getOpcode() != ISD::OR)
20414     return SDValue();
20415
20416   SDValue N0  = Narrow->getOperand(0);
20417   SDValue N1  = Narrow->getOperand(1);
20418   SDLoc DL(Narrow);
20419
20420   // The Left side has to be a trunc.
20421   if (N0.getOpcode() != ISD::TRUNCATE)
20422     return SDValue();
20423
20424   // The type of the truncated inputs.
20425   EVT WideVT = N0->getOperand(0)->getValueType(0);
20426   if (WideVT != VT)
20427     return SDValue();
20428
20429   // The right side has to be a 'trunc' or a constant vector.
20430   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
20431   bool RHSConst = (isSplatVector(N1.getNode()) &&
20432                    isa<ConstantSDNode>(N1->getOperand(0)));
20433   if (!RHSTrunc && !RHSConst)
20434     return SDValue();
20435
20436   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20437
20438   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
20439     return SDValue();
20440
20441   // Set N0 and N1 to hold the inputs to the new wide operation.
20442   N0 = N0->getOperand(0);
20443   if (RHSConst) {
20444     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
20445                      N1->getOperand(0));
20446     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
20447     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
20448   } else if (RHSTrunc) {
20449     N1 = N1->getOperand(0);
20450   }
20451
20452   // Generate the wide operation.
20453   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
20454   unsigned Opcode = N->getOpcode();
20455   switch (Opcode) {
20456   case ISD::ANY_EXTEND:
20457     return Op;
20458   case ISD::ZERO_EXTEND: {
20459     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
20460     APInt Mask = APInt::getAllOnesValue(InBits);
20461     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
20462     return DAG.getNode(ISD::AND, DL, VT,
20463                        Op, DAG.getConstant(Mask, VT));
20464   }
20465   case ISD::SIGN_EXTEND:
20466     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
20467                        Op, DAG.getValueType(NarrowVT));
20468   default:
20469     llvm_unreachable("Unexpected opcode");
20470   }
20471 }
20472
20473 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
20474                                  TargetLowering::DAGCombinerInfo &DCI,
20475                                  const X86Subtarget *Subtarget) {
20476   EVT VT = N->getValueType(0);
20477   if (DCI.isBeforeLegalizeOps())
20478     return SDValue();
20479
20480   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20481   if (R.getNode())
20482     return R;
20483
20484   // Create BEXTR instructions
20485   // BEXTR is ((X >> imm) & (2**size-1))
20486   if (VT == MVT::i32 || VT == MVT::i64) {
20487     SDValue N0 = N->getOperand(0);
20488     SDValue N1 = N->getOperand(1);
20489     SDLoc DL(N);
20490
20491     // Check for BEXTR.
20492     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
20493         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
20494       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
20495       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20496       if (MaskNode && ShiftNode) {
20497         uint64_t Mask = MaskNode->getZExtValue();
20498         uint64_t Shift = ShiftNode->getZExtValue();
20499         if (isMask_64(Mask)) {
20500           uint64_t MaskSize = CountPopulation_64(Mask);
20501           if (Shift + MaskSize <= VT.getSizeInBits())
20502             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
20503                                DAG.getConstant(Shift | (MaskSize << 8), VT));
20504         }
20505       }
20506     } // BEXTR
20507
20508     return SDValue();
20509   }
20510
20511   // Want to form ANDNP nodes:
20512   // 1) In the hopes of then easily combining them with OR and AND nodes
20513   //    to form PBLEND/PSIGN.
20514   // 2) To match ANDN packed intrinsics
20515   if (VT != MVT::v2i64 && VT != MVT::v4i64)
20516     return SDValue();
20517
20518   SDValue N0 = N->getOperand(0);
20519   SDValue N1 = N->getOperand(1);
20520   SDLoc DL(N);
20521
20522   // Check LHS for vnot
20523   if (N0.getOpcode() == ISD::XOR &&
20524       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
20525       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
20526     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
20527
20528   // Check RHS for vnot
20529   if (N1.getOpcode() == ISD::XOR &&
20530       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
20531       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
20532     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
20533
20534   return SDValue();
20535 }
20536
20537 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
20538                                 TargetLowering::DAGCombinerInfo &DCI,
20539                                 const X86Subtarget *Subtarget) {
20540   if (DCI.isBeforeLegalizeOps())
20541     return SDValue();
20542
20543   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
20544   if (R.getNode())
20545     return R;
20546
20547   SDValue N0 = N->getOperand(0);
20548   SDValue N1 = N->getOperand(1);
20549   EVT VT = N->getValueType(0);
20550
20551   // look for psign/blend
20552   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
20553     if (!Subtarget->hasSSSE3() ||
20554         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
20555       return SDValue();
20556
20557     // Canonicalize pandn to RHS
20558     if (N0.getOpcode() == X86ISD::ANDNP)
20559       std::swap(N0, N1);
20560     // or (and (m, y), (pandn m, x))
20561     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
20562       SDValue Mask = N1.getOperand(0);
20563       SDValue X    = N1.getOperand(1);
20564       SDValue Y;
20565       if (N0.getOperand(0) == Mask)
20566         Y = N0.getOperand(1);
20567       if (N0.getOperand(1) == Mask)
20568         Y = N0.getOperand(0);
20569
20570       // Check to see if the mask appeared in both the AND and ANDNP and
20571       if (!Y.getNode())
20572         return SDValue();
20573
20574       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
20575       // Look through mask bitcast.
20576       if (Mask.getOpcode() == ISD::BITCAST)
20577         Mask = Mask.getOperand(0);
20578       if (X.getOpcode() == ISD::BITCAST)
20579         X = X.getOperand(0);
20580       if (Y.getOpcode() == ISD::BITCAST)
20581         Y = Y.getOperand(0);
20582
20583       EVT MaskVT = Mask.getValueType();
20584
20585       // Validate that the Mask operand is a vector sra node.
20586       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
20587       // there is no psrai.b
20588       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
20589       unsigned SraAmt = ~0;
20590       if (Mask.getOpcode() == ISD::SRA) {
20591         SDValue Amt = Mask.getOperand(1);
20592         if (isSplatVector(Amt.getNode())) {
20593           SDValue SclrAmt = Amt->getOperand(0);
20594           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
20595             SraAmt = C->getZExtValue();
20596         }
20597       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
20598         SDValue SraC = Mask.getOperand(1);
20599         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
20600       }
20601       if ((SraAmt + 1) != EltBits)
20602         return SDValue();
20603
20604       SDLoc DL(N);
20605
20606       // Now we know we at least have a plendvb with the mask val.  See if
20607       // we can form a psignb/w/d.
20608       // psign = x.type == y.type == mask.type && y = sub(0, x);
20609       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
20610           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
20611           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
20612         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
20613                "Unsupported VT for PSIGN");
20614         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
20615         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20616       }
20617       // PBLENDVB only available on SSE 4.1
20618       if (!Subtarget->hasSSE41())
20619         return SDValue();
20620
20621       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
20622
20623       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
20624       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
20625       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
20626       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
20627       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
20628     }
20629   }
20630
20631   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
20632     return SDValue();
20633
20634   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
20635   MachineFunction &MF = DAG.getMachineFunction();
20636   bool OptForSize = MF.getFunction()->getAttributes().
20637     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
20638
20639   // SHLD/SHRD instructions have lower register pressure, but on some
20640   // platforms they have higher latency than the equivalent
20641   // series of shifts/or that would otherwise be generated.
20642   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
20643   // have higher latencies and we are not optimizing for size.
20644   if (!OptForSize && Subtarget->isSHLDSlow())
20645     return SDValue();
20646
20647   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
20648     std::swap(N0, N1);
20649   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
20650     return SDValue();
20651   if (!N0.hasOneUse() || !N1.hasOneUse())
20652     return SDValue();
20653
20654   SDValue ShAmt0 = N0.getOperand(1);
20655   if (ShAmt0.getValueType() != MVT::i8)
20656     return SDValue();
20657   SDValue ShAmt1 = N1.getOperand(1);
20658   if (ShAmt1.getValueType() != MVT::i8)
20659     return SDValue();
20660   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
20661     ShAmt0 = ShAmt0.getOperand(0);
20662   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
20663     ShAmt1 = ShAmt1.getOperand(0);
20664
20665   SDLoc DL(N);
20666   unsigned Opc = X86ISD::SHLD;
20667   SDValue Op0 = N0.getOperand(0);
20668   SDValue Op1 = N1.getOperand(0);
20669   if (ShAmt0.getOpcode() == ISD::SUB) {
20670     Opc = X86ISD::SHRD;
20671     std::swap(Op0, Op1);
20672     std::swap(ShAmt0, ShAmt1);
20673   }
20674
20675   unsigned Bits = VT.getSizeInBits();
20676   if (ShAmt1.getOpcode() == ISD::SUB) {
20677     SDValue Sum = ShAmt1.getOperand(0);
20678     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
20679       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
20680       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
20681         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
20682       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
20683         return DAG.getNode(Opc, DL, VT,
20684                            Op0, Op1,
20685                            DAG.getNode(ISD::TRUNCATE, DL,
20686                                        MVT::i8, ShAmt0));
20687     }
20688   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
20689     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
20690     if (ShAmt0C &&
20691         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
20692       return DAG.getNode(Opc, DL, VT,
20693                          N0.getOperand(0), N1.getOperand(0),
20694                          DAG.getNode(ISD::TRUNCATE, DL,
20695                                        MVT::i8, ShAmt0));
20696   }
20697
20698   return SDValue();
20699 }
20700
20701 // Generate NEG and CMOV for integer abs.
20702 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
20703   EVT VT = N->getValueType(0);
20704
20705   // Since X86 does not have CMOV for 8-bit integer, we don't convert
20706   // 8-bit integer abs to NEG and CMOV.
20707   if (VT.isInteger() && VT.getSizeInBits() == 8)
20708     return SDValue();
20709
20710   SDValue N0 = N->getOperand(0);
20711   SDValue N1 = N->getOperand(1);
20712   SDLoc DL(N);
20713
20714   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
20715   // and change it to SUB and CMOV.
20716   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
20717       N0.getOpcode() == ISD::ADD &&
20718       N0.getOperand(1) == N1 &&
20719       N1.getOpcode() == ISD::SRA &&
20720       N1.getOperand(0) == N0.getOperand(0))
20721     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
20722       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
20723         // Generate SUB & CMOV.
20724         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
20725                                   DAG.getConstant(0, VT), N0.getOperand(0));
20726
20727         SDValue Ops[] = { N0.getOperand(0), Neg,
20728                           DAG.getConstant(X86::COND_GE, MVT::i8),
20729                           SDValue(Neg.getNode(), 1) };
20730         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
20731       }
20732   return SDValue();
20733 }
20734
20735 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20736 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20737                                  TargetLowering::DAGCombinerInfo &DCI,
20738                                  const X86Subtarget *Subtarget) {
20739   if (DCI.isBeforeLegalizeOps())
20740     return SDValue();
20741
20742   if (Subtarget->hasCMov()) {
20743     SDValue RV = performIntegerAbsCombine(N, DAG);
20744     if (RV.getNode())
20745       return RV;
20746   }
20747
20748   return SDValue();
20749 }
20750
20751 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20752 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20753                                   TargetLowering::DAGCombinerInfo &DCI,
20754                                   const X86Subtarget *Subtarget) {
20755   LoadSDNode *Ld = cast<LoadSDNode>(N);
20756   EVT RegVT = Ld->getValueType(0);
20757   EVT MemVT = Ld->getMemoryVT();
20758   SDLoc dl(Ld);
20759   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20760   unsigned RegSz = RegVT.getSizeInBits();
20761
20762   // On Sandybridge unaligned 256bit loads are inefficient.
20763   ISD::LoadExtType Ext = Ld->getExtensionType();
20764   unsigned Alignment = Ld->getAlignment();
20765   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20766   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20767       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20768     unsigned NumElems = RegVT.getVectorNumElements();
20769     if (NumElems < 2)
20770       return SDValue();
20771
20772     SDValue Ptr = Ld->getBasePtr();
20773     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20774
20775     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20776                                   NumElems/2);
20777     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20778                                 Ld->getPointerInfo(), Ld->isVolatile(),
20779                                 Ld->isNonTemporal(), Ld->isInvariant(),
20780                                 Alignment);
20781     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20782     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20783                                 Ld->getPointerInfo(), Ld->isVolatile(),
20784                                 Ld->isNonTemporal(), Ld->isInvariant(),
20785                                 std::min(16U, Alignment));
20786     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20787                              Load1.getValue(1),
20788                              Load2.getValue(1));
20789
20790     SDValue NewVec = DAG.getUNDEF(RegVT);
20791     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20792     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20793     return DCI.CombineTo(N, NewVec, TF, true);
20794   }
20795
20796   // If this is a vector EXT Load then attempt to optimize it using a
20797   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20798   // expansion is still better than scalar code.
20799   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20800   // emit a shuffle and a arithmetic shift.
20801   // TODO: It is possible to support ZExt by zeroing the undef values
20802   // during the shuffle phase or after the shuffle.
20803   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20804       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20805     assert(MemVT != RegVT && "Cannot extend to the same type");
20806     assert(MemVT.isVector() && "Must load a vector from memory");
20807
20808     unsigned NumElems = RegVT.getVectorNumElements();
20809     unsigned MemSz = MemVT.getSizeInBits();
20810     assert(RegSz > MemSz && "Register size must be greater than the mem size");
20811
20812     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20813       return SDValue();
20814
20815     // All sizes must be a power of two.
20816     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20817       return SDValue();
20818
20819     // Attempt to load the original value using scalar loads.
20820     // Find the largest scalar type that divides the total loaded size.
20821     MVT SclrLoadTy = MVT::i8;
20822     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20823          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20824       MVT Tp = (MVT::SimpleValueType)tp;
20825       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20826         SclrLoadTy = Tp;
20827       }
20828     }
20829
20830     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20831     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20832         (64 <= MemSz))
20833       SclrLoadTy = MVT::f64;
20834
20835     // Calculate the number of scalar loads that we need to perform
20836     // in order to load our vector from memory.
20837     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20838     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20839       return SDValue();
20840
20841     unsigned loadRegZize = RegSz;
20842     if (Ext == ISD::SEXTLOAD && RegSz == 256)
20843       loadRegZize /= 2;
20844
20845     // Represent our vector as a sequence of elements which are the
20846     // largest scalar that we can load.
20847     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20848       loadRegZize/SclrLoadTy.getSizeInBits());
20849
20850     // Represent the data using the same element type that is stored in
20851     // memory. In practice, we ''widen'' MemVT.
20852     EVT WideVecVT =
20853           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20854                        loadRegZize/MemVT.getScalarType().getSizeInBits());
20855
20856     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20857       "Invalid vector type");
20858
20859     // We can't shuffle using an illegal type.
20860     if (!TLI.isTypeLegal(WideVecVT))
20861       return SDValue();
20862
20863     SmallVector<SDValue, 8> Chains;
20864     SDValue Ptr = Ld->getBasePtr();
20865     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20866                                         TLI.getPointerTy());
20867     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20868
20869     for (unsigned i = 0; i < NumLoads; ++i) {
20870       // Perform a single load.
20871       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20872                                        Ptr, Ld->getPointerInfo(),
20873                                        Ld->isVolatile(), Ld->isNonTemporal(),
20874                                        Ld->isInvariant(), Ld->getAlignment());
20875       Chains.push_back(ScalarLoad.getValue(1));
20876       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20877       // another round of DAGCombining.
20878       if (i == 0)
20879         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20880       else
20881         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20882                           ScalarLoad, DAG.getIntPtrConstant(i));
20883
20884       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20885     }
20886
20887     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20888
20889     // Bitcast the loaded value to a vector of the original element type, in
20890     // the size of the target vector type.
20891     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20892     unsigned SizeRatio = RegSz/MemSz;
20893
20894     if (Ext == ISD::SEXTLOAD) {
20895       // If we have SSE4.1 we can directly emit a VSEXT node.
20896       if (Subtarget->hasSSE41()) {
20897         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20898         return DCI.CombineTo(N, Sext, TF, true);
20899       }
20900
20901       // Otherwise we'll shuffle the small elements in the high bits of the
20902       // larger type and perform an arithmetic shift. If the shift is not legal
20903       // it's better to scalarize.
20904       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20905         return SDValue();
20906
20907       // Redistribute the loaded elements into the different locations.
20908       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20909       for (unsigned i = 0; i != NumElems; ++i)
20910         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20911
20912       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20913                                            DAG.getUNDEF(WideVecVT),
20914                                            &ShuffleVec[0]);
20915
20916       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20917
20918       // Build the arithmetic shift.
20919       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20920                      MemVT.getVectorElementType().getSizeInBits();
20921       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20922                           DAG.getConstant(Amt, RegVT));
20923
20924       return DCI.CombineTo(N, Shuff, TF, true);
20925     }
20926
20927     // Redistribute the loaded elements into the different locations.
20928     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20929     for (unsigned i = 0; i != NumElems; ++i)
20930       ShuffleVec[i*SizeRatio] = i;
20931
20932     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20933                                          DAG.getUNDEF(WideVecVT),
20934                                          &ShuffleVec[0]);
20935
20936     // Bitcast to the requested type.
20937     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20938     // Replace the original load with the new sequence
20939     // and return the new chain.
20940     return DCI.CombineTo(N, Shuff, TF, true);
20941   }
20942
20943   return SDValue();
20944 }
20945
20946 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20947 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20948                                    const X86Subtarget *Subtarget) {
20949   StoreSDNode *St = cast<StoreSDNode>(N);
20950   EVT VT = St->getValue().getValueType();
20951   EVT StVT = St->getMemoryVT();
20952   SDLoc dl(St);
20953   SDValue StoredVal = St->getOperand(1);
20954   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20955
20956   // If we are saving a concatenation of two XMM registers, perform two stores.
20957   // On Sandy Bridge, 256-bit memory operations are executed by two
20958   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20959   // memory  operation.
20960   unsigned Alignment = St->getAlignment();
20961   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20962   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20963       StVT == VT && !IsAligned) {
20964     unsigned NumElems = VT.getVectorNumElements();
20965     if (NumElems < 2)
20966       return SDValue();
20967
20968     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20969     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20970
20971     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20972     SDValue Ptr0 = St->getBasePtr();
20973     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20974
20975     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20976                                 St->getPointerInfo(), St->isVolatile(),
20977                                 St->isNonTemporal(), Alignment);
20978     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20979                                 St->getPointerInfo(), St->isVolatile(),
20980                                 St->isNonTemporal(),
20981                                 std::min(16U, Alignment));
20982     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20983   }
20984
20985   // Optimize trunc store (of multiple scalars) to shuffle and store.
20986   // First, pack all of the elements in one place. Next, store to memory
20987   // in fewer chunks.
20988   if (St->isTruncatingStore() && VT.isVector()) {
20989     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20990     unsigned NumElems = VT.getVectorNumElements();
20991     assert(StVT != VT && "Cannot truncate to the same type");
20992     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20993     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20994
20995     // From, To sizes and ElemCount must be pow of two
20996     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20997     // We are going to use the original vector elt for storing.
20998     // Accumulated smaller vector elements must be a multiple of the store size.
20999     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
21000
21001     unsigned SizeRatio  = FromSz / ToSz;
21002
21003     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
21004
21005     // Create a type on which we perform the shuffle
21006     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
21007             StVT.getScalarType(), NumElems*SizeRatio);
21008
21009     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
21010
21011     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
21012     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
21013     for (unsigned i = 0; i != NumElems; ++i)
21014       ShuffleVec[i] = i * SizeRatio;
21015
21016     // Can't shuffle using an illegal type.
21017     if (!TLI.isTypeLegal(WideVecVT))
21018       return SDValue();
21019
21020     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
21021                                          DAG.getUNDEF(WideVecVT),
21022                                          &ShuffleVec[0]);
21023     // At this point all of the data is stored at the bottom of the
21024     // register. We now need to save it to mem.
21025
21026     // Find the largest store unit
21027     MVT StoreType = MVT::i8;
21028     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
21029          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
21030       MVT Tp = (MVT::SimpleValueType)tp;
21031       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
21032         StoreType = Tp;
21033     }
21034
21035     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
21036     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
21037         (64 <= NumElems * ToSz))
21038       StoreType = MVT::f64;
21039
21040     // Bitcast the original vector into a vector of store-size units
21041     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
21042             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
21043     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
21044     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
21045     SmallVector<SDValue, 8> Chains;
21046     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
21047                                         TLI.getPointerTy());
21048     SDValue Ptr = St->getBasePtr();
21049
21050     // Perform one or more big stores into memory.
21051     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
21052       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
21053                                    StoreType, ShuffWide,
21054                                    DAG.getIntPtrConstant(i));
21055       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
21056                                 St->getPointerInfo(), St->isVolatile(),
21057                                 St->isNonTemporal(), St->getAlignment());
21058       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
21059       Chains.push_back(Ch);
21060     }
21061
21062     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
21063   }
21064
21065   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
21066   // the FP state in cases where an emms may be missing.
21067   // A preferable solution to the general problem is to figure out the right
21068   // places to insert EMMS.  This qualifies as a quick hack.
21069
21070   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
21071   if (VT.getSizeInBits() != 64)
21072     return SDValue();
21073
21074   const Function *F = DAG.getMachineFunction().getFunction();
21075   bool NoImplicitFloatOps = F->getAttributes().
21076     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
21077   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
21078                      && Subtarget->hasSSE2();
21079   if ((VT.isVector() ||
21080        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
21081       isa<LoadSDNode>(St->getValue()) &&
21082       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
21083       St->getChain().hasOneUse() && !St->isVolatile()) {
21084     SDNode* LdVal = St->getValue().getNode();
21085     LoadSDNode *Ld = nullptr;
21086     int TokenFactorIndex = -1;
21087     SmallVector<SDValue, 8> Ops;
21088     SDNode* ChainVal = St->getChain().getNode();
21089     // Must be a store of a load.  We currently handle two cases:  the load
21090     // is a direct child, and it's under an intervening TokenFactor.  It is
21091     // possible to dig deeper under nested TokenFactors.
21092     if (ChainVal == LdVal)
21093       Ld = cast<LoadSDNode>(St->getChain());
21094     else if (St->getValue().hasOneUse() &&
21095              ChainVal->getOpcode() == ISD::TokenFactor) {
21096       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
21097         if (ChainVal->getOperand(i).getNode() == LdVal) {
21098           TokenFactorIndex = i;
21099           Ld = cast<LoadSDNode>(St->getValue());
21100         } else
21101           Ops.push_back(ChainVal->getOperand(i));
21102       }
21103     }
21104
21105     if (!Ld || !ISD::isNormalLoad(Ld))
21106       return SDValue();
21107
21108     // If this is not the MMX case, i.e. we are just turning i64 load/store
21109     // into f64 load/store, avoid the transformation if there are multiple
21110     // uses of the loaded value.
21111     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
21112       return SDValue();
21113
21114     SDLoc LdDL(Ld);
21115     SDLoc StDL(N);
21116     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
21117     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
21118     // pair instead.
21119     if (Subtarget->is64Bit() || F64IsLegal) {
21120       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
21121       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
21122                                   Ld->getPointerInfo(), Ld->isVolatile(),
21123                                   Ld->isNonTemporal(), Ld->isInvariant(),
21124                                   Ld->getAlignment());
21125       SDValue NewChain = NewLd.getValue(1);
21126       if (TokenFactorIndex != -1) {
21127         Ops.push_back(NewChain);
21128         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21129       }
21130       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
21131                           St->getPointerInfo(),
21132                           St->isVolatile(), St->isNonTemporal(),
21133                           St->getAlignment());
21134     }
21135
21136     // Otherwise, lower to two pairs of 32-bit loads / stores.
21137     SDValue LoAddr = Ld->getBasePtr();
21138     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
21139                                  DAG.getConstant(4, MVT::i32));
21140
21141     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
21142                                Ld->getPointerInfo(),
21143                                Ld->isVolatile(), Ld->isNonTemporal(),
21144                                Ld->isInvariant(), Ld->getAlignment());
21145     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
21146                                Ld->getPointerInfo().getWithOffset(4),
21147                                Ld->isVolatile(), Ld->isNonTemporal(),
21148                                Ld->isInvariant(),
21149                                MinAlign(Ld->getAlignment(), 4));
21150
21151     SDValue NewChain = LoLd.getValue(1);
21152     if (TokenFactorIndex != -1) {
21153       Ops.push_back(LoLd);
21154       Ops.push_back(HiLd);
21155       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
21156     }
21157
21158     LoAddr = St->getBasePtr();
21159     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
21160                          DAG.getConstant(4, MVT::i32));
21161
21162     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
21163                                 St->getPointerInfo(),
21164                                 St->isVolatile(), St->isNonTemporal(),
21165                                 St->getAlignment());
21166     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
21167                                 St->getPointerInfo().getWithOffset(4),
21168                                 St->isVolatile(),
21169                                 St->isNonTemporal(),
21170                                 MinAlign(St->getAlignment(), 4));
21171     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
21172   }
21173   return SDValue();
21174 }
21175
21176 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
21177 /// and return the operands for the horizontal operation in LHS and RHS.  A
21178 /// horizontal operation performs the binary operation on successive elements
21179 /// of its first operand, then on successive elements of its second operand,
21180 /// returning the resulting values in a vector.  For example, if
21181 ///   A = < float a0, float a1, float a2, float a3 >
21182 /// and
21183 ///   B = < float b0, float b1, float b2, float b3 >
21184 /// then the result of doing a horizontal operation on A and B is
21185 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
21186 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
21187 /// A horizontal-op B, for some already available A and B, and if so then LHS is
21188 /// set to A, RHS to B, and the routine returns 'true'.
21189 /// Note that the binary operation should have the property that if one of the
21190 /// operands is UNDEF then the result is UNDEF.
21191 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
21192   // Look for the following pattern: if
21193   //   A = < float a0, float a1, float a2, float a3 >
21194   //   B = < float b0, float b1, float b2, float b3 >
21195   // and
21196   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
21197   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
21198   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
21199   // which is A horizontal-op B.
21200
21201   // At least one of the operands should be a vector shuffle.
21202   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
21203       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
21204     return false;
21205
21206   MVT VT = LHS.getSimpleValueType();
21207
21208   assert((VT.is128BitVector() || VT.is256BitVector()) &&
21209          "Unsupported vector type for horizontal add/sub");
21210
21211   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
21212   // operate independently on 128-bit lanes.
21213   unsigned NumElts = VT.getVectorNumElements();
21214   unsigned NumLanes = VT.getSizeInBits()/128;
21215   unsigned NumLaneElts = NumElts / NumLanes;
21216   assert((NumLaneElts % 2 == 0) &&
21217          "Vector type should have an even number of elements in each lane");
21218   unsigned HalfLaneElts = NumLaneElts/2;
21219
21220   // View LHS in the form
21221   //   LHS = VECTOR_SHUFFLE A, B, LMask
21222   // If LHS is not a shuffle then pretend it is the shuffle
21223   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
21224   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
21225   // type VT.
21226   SDValue A, B;
21227   SmallVector<int, 16> LMask(NumElts);
21228   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21229     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
21230       A = LHS.getOperand(0);
21231     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
21232       B = LHS.getOperand(1);
21233     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
21234     std::copy(Mask.begin(), Mask.end(), LMask.begin());
21235   } else {
21236     if (LHS.getOpcode() != ISD::UNDEF)
21237       A = LHS;
21238     for (unsigned i = 0; i != NumElts; ++i)
21239       LMask[i] = i;
21240   }
21241
21242   // Likewise, view RHS in the form
21243   //   RHS = VECTOR_SHUFFLE C, D, RMask
21244   SDValue C, D;
21245   SmallVector<int, 16> RMask(NumElts);
21246   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
21247     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
21248       C = RHS.getOperand(0);
21249     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
21250       D = RHS.getOperand(1);
21251     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
21252     std::copy(Mask.begin(), Mask.end(), RMask.begin());
21253   } else {
21254     if (RHS.getOpcode() != ISD::UNDEF)
21255       C = RHS;
21256     for (unsigned i = 0; i != NumElts; ++i)
21257       RMask[i] = i;
21258   }
21259
21260   // Check that the shuffles are both shuffling the same vectors.
21261   if (!(A == C && B == D) && !(A == D && B == C))
21262     return false;
21263
21264   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
21265   if (!A.getNode() && !B.getNode())
21266     return false;
21267
21268   // If A and B occur in reverse order in RHS, then "swap" them (which means
21269   // rewriting the mask).
21270   if (A != C)
21271     CommuteVectorShuffleMask(RMask, NumElts);
21272
21273   // At this point LHS and RHS are equivalent to
21274   //   LHS = VECTOR_SHUFFLE A, B, LMask
21275   //   RHS = VECTOR_SHUFFLE A, B, RMask
21276   // Check that the masks correspond to performing a horizontal operation.
21277   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
21278     for (unsigned i = 0; i != NumLaneElts; ++i) {
21279       int LIdx = LMask[i+l], RIdx = RMask[i+l];
21280
21281       // Ignore any UNDEF components.
21282       if (LIdx < 0 || RIdx < 0 ||
21283           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
21284           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
21285         continue;
21286
21287       // Check that successive elements are being operated on.  If not, this is
21288       // not a horizontal operation.
21289       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
21290       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
21291       if (!(LIdx == Index && RIdx == Index + 1) &&
21292           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
21293         return false;
21294     }
21295   }
21296
21297   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
21298   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
21299   return true;
21300 }
21301
21302 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
21303 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
21304                                   const X86Subtarget *Subtarget) {
21305   EVT VT = N->getValueType(0);
21306   SDValue LHS = N->getOperand(0);
21307   SDValue RHS = N->getOperand(1);
21308
21309   // Try to synthesize horizontal adds from adds of shuffles.
21310   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21311        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21312       isHorizontalBinOp(LHS, RHS, true))
21313     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
21314   return SDValue();
21315 }
21316
21317 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
21318 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
21319                                   const X86Subtarget *Subtarget) {
21320   EVT VT = N->getValueType(0);
21321   SDValue LHS = N->getOperand(0);
21322   SDValue RHS = N->getOperand(1);
21323
21324   // Try to synthesize horizontal subs from subs of shuffles.
21325   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
21326        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
21327       isHorizontalBinOp(LHS, RHS, false))
21328     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
21329   return SDValue();
21330 }
21331
21332 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
21333 /// X86ISD::FXOR nodes.
21334 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
21335   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
21336   // F[X]OR(0.0, x) -> x
21337   // F[X]OR(x, 0.0) -> x
21338   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21339     if (C->getValueAPF().isPosZero())
21340       return N->getOperand(1);
21341   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21342     if (C->getValueAPF().isPosZero())
21343       return N->getOperand(0);
21344   return SDValue();
21345 }
21346
21347 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
21348 /// X86ISD::FMAX nodes.
21349 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
21350   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
21351
21352   // Only perform optimizations if UnsafeMath is used.
21353   if (!DAG.getTarget().Options.UnsafeFPMath)
21354     return SDValue();
21355
21356   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
21357   // into FMINC and FMAXC, which are Commutative operations.
21358   unsigned NewOp = 0;
21359   switch (N->getOpcode()) {
21360     default: llvm_unreachable("unknown opcode");
21361     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
21362     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
21363   }
21364
21365   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
21366                      N->getOperand(0), N->getOperand(1));
21367 }
21368
21369 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
21370 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
21371   // FAND(0.0, x) -> 0.0
21372   // FAND(x, 0.0) -> 0.0
21373   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21374     if (C->getValueAPF().isPosZero())
21375       return N->getOperand(0);
21376   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21377     if (C->getValueAPF().isPosZero())
21378       return N->getOperand(1);
21379   return SDValue();
21380 }
21381
21382 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
21383 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
21384   // FANDN(x, 0.0) -> 0.0
21385   // FANDN(0.0, x) -> x
21386   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
21387     if (C->getValueAPF().isPosZero())
21388       return N->getOperand(1);
21389   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
21390     if (C->getValueAPF().isPosZero())
21391       return N->getOperand(1);
21392   return SDValue();
21393 }
21394
21395 static SDValue PerformBTCombine(SDNode *N,
21396                                 SelectionDAG &DAG,
21397                                 TargetLowering::DAGCombinerInfo &DCI) {
21398   // BT ignores high bits in the bit index operand.
21399   SDValue Op1 = N->getOperand(1);
21400   if (Op1.hasOneUse()) {
21401     unsigned BitWidth = Op1.getValueSizeInBits();
21402     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
21403     APInt KnownZero, KnownOne;
21404     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
21405                                           !DCI.isBeforeLegalizeOps());
21406     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21407     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
21408         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
21409       DCI.CommitTargetLoweringOpt(TLO);
21410   }
21411   return SDValue();
21412 }
21413
21414 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
21415   SDValue Op = N->getOperand(0);
21416   if (Op.getOpcode() == ISD::BITCAST)
21417     Op = Op.getOperand(0);
21418   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
21419   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
21420       VT.getVectorElementType().getSizeInBits() ==
21421       OpVT.getVectorElementType().getSizeInBits()) {
21422     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
21423   }
21424   return SDValue();
21425 }
21426
21427 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
21428                                                const X86Subtarget *Subtarget) {
21429   EVT VT = N->getValueType(0);
21430   if (!VT.isVector())
21431     return SDValue();
21432
21433   SDValue N0 = N->getOperand(0);
21434   SDValue N1 = N->getOperand(1);
21435   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
21436   SDLoc dl(N);
21437
21438   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
21439   // both SSE and AVX2 since there is no sign-extended shift right
21440   // operation on a vector with 64-bit elements.
21441   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
21442   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
21443   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
21444       N0.getOpcode() == ISD::SIGN_EXTEND)) {
21445     SDValue N00 = N0.getOperand(0);
21446
21447     // EXTLOAD has a better solution on AVX2,
21448     // it may be replaced with X86ISD::VSEXT node.
21449     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
21450       if (!ISD::isNormalLoad(N00.getNode()))
21451         return SDValue();
21452
21453     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
21454         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
21455                                   N00, N1);
21456       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
21457     }
21458   }
21459   return SDValue();
21460 }
21461
21462 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
21463                                   TargetLowering::DAGCombinerInfo &DCI,
21464                                   const X86Subtarget *Subtarget) {
21465   if (!DCI.isBeforeLegalizeOps())
21466     return SDValue();
21467
21468   if (!Subtarget->hasFp256())
21469     return SDValue();
21470
21471   EVT VT = N->getValueType(0);
21472   if (VT.isVector() && VT.getSizeInBits() == 256) {
21473     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21474     if (R.getNode())
21475       return R;
21476   }
21477
21478   return SDValue();
21479 }
21480
21481 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
21482                                  const X86Subtarget* Subtarget) {
21483   SDLoc dl(N);
21484   EVT VT = N->getValueType(0);
21485
21486   // Let legalize expand this if it isn't a legal type yet.
21487   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
21488     return SDValue();
21489
21490   EVT ScalarVT = VT.getScalarType();
21491   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
21492       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
21493     return SDValue();
21494
21495   SDValue A = N->getOperand(0);
21496   SDValue B = N->getOperand(1);
21497   SDValue C = N->getOperand(2);
21498
21499   bool NegA = (A.getOpcode() == ISD::FNEG);
21500   bool NegB = (B.getOpcode() == ISD::FNEG);
21501   bool NegC = (C.getOpcode() == ISD::FNEG);
21502
21503   // Negative multiplication when NegA xor NegB
21504   bool NegMul = (NegA != NegB);
21505   if (NegA)
21506     A = A.getOperand(0);
21507   if (NegB)
21508     B = B.getOperand(0);
21509   if (NegC)
21510     C = C.getOperand(0);
21511
21512   unsigned Opcode;
21513   if (!NegMul)
21514     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
21515   else
21516     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
21517
21518   return DAG.getNode(Opcode, dl, VT, A, B, C);
21519 }
21520
21521 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
21522                                   TargetLowering::DAGCombinerInfo &DCI,
21523                                   const X86Subtarget *Subtarget) {
21524   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
21525   //           (and (i32 x86isd::setcc_carry), 1)
21526   // This eliminates the zext. This transformation is necessary because
21527   // ISD::SETCC is always legalized to i8.
21528   SDLoc dl(N);
21529   SDValue N0 = N->getOperand(0);
21530   EVT VT = N->getValueType(0);
21531
21532   if (N0.getOpcode() == ISD::AND &&
21533       N0.hasOneUse() &&
21534       N0.getOperand(0).hasOneUse()) {
21535     SDValue N00 = N0.getOperand(0);
21536     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21537       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
21538       if (!C || C->getZExtValue() != 1)
21539         return SDValue();
21540       return DAG.getNode(ISD::AND, dl, VT,
21541                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21542                                      N00.getOperand(0), N00.getOperand(1)),
21543                          DAG.getConstant(1, VT));
21544     }
21545   }
21546
21547   if (N0.getOpcode() == ISD::TRUNCATE &&
21548       N0.hasOneUse() &&
21549       N0.getOperand(0).hasOneUse()) {
21550     SDValue N00 = N0.getOperand(0);
21551     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
21552       return DAG.getNode(ISD::AND, dl, VT,
21553                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
21554                                      N00.getOperand(0), N00.getOperand(1)),
21555                          DAG.getConstant(1, VT));
21556     }
21557   }
21558   if (VT.is256BitVector()) {
21559     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
21560     if (R.getNode())
21561       return R;
21562   }
21563
21564   return SDValue();
21565 }
21566
21567 // Optimize x == -y --> x+y == 0
21568 //          x != -y --> x+y != 0
21569 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
21570                                       const X86Subtarget* Subtarget) {
21571   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
21572   SDValue LHS = N->getOperand(0);
21573   SDValue RHS = N->getOperand(1);
21574   EVT VT = N->getValueType(0);
21575   SDLoc DL(N);
21576
21577   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
21578     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
21579       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
21580         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21581                                    LHS.getValueType(), RHS, LHS.getOperand(1));
21582         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21583                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21584       }
21585   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
21586     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
21587       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
21588         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
21589                                    RHS.getValueType(), LHS, RHS.getOperand(1));
21590         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
21591                             addV, DAG.getConstant(0, addV.getValueType()), CC);
21592       }
21593
21594   if (VT.getScalarType() == MVT::i1) {
21595     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
21596       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21597     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
21598     if (!IsSEXT0 && !IsVZero0)
21599       return SDValue();
21600     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
21601       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
21602     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
21603
21604     if (!IsSEXT1 && !IsVZero1)
21605       return SDValue();
21606
21607     if (IsSEXT0 && IsVZero1) {
21608       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
21609       if (CC == ISD::SETEQ)
21610         return DAG.getNOT(DL, LHS.getOperand(0), VT);
21611       return LHS.getOperand(0);
21612     }
21613     if (IsSEXT1 && IsVZero0) {
21614       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
21615       if (CC == ISD::SETEQ)
21616         return DAG.getNOT(DL, RHS.getOperand(0), VT);
21617       return RHS.getOperand(0);
21618     }
21619   }
21620
21621   return SDValue();
21622 }
21623
21624 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
21625                                       const X86Subtarget *Subtarget) {
21626   SDLoc dl(N);
21627   MVT VT = N->getOperand(1)->getSimpleValueType(0);
21628   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
21629          "X86insertps is only defined for v4x32");
21630
21631   SDValue Ld = N->getOperand(1);
21632   if (MayFoldLoad(Ld)) {
21633     // Extract the countS bits from the immediate so we can get the proper
21634     // address when narrowing the vector load to a specific element.
21635     // When the second source op is a memory address, interps doesn't use
21636     // countS and just gets an f32 from that address.
21637     unsigned DestIndex =
21638         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
21639     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
21640   } else
21641     return SDValue();
21642
21643   // Create this as a scalar to vector to match the instruction pattern.
21644   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
21645   // countS bits are ignored when loading from memory on insertps, which
21646   // means we don't need to explicitly set them to 0.
21647   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
21648                      LoadScalarToVector, N->getOperand(2));
21649 }
21650
21651 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
21652 // as "sbb reg,reg", since it can be extended without zext and produces
21653 // an all-ones bit which is more useful than 0/1 in some cases.
21654 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
21655                                MVT VT) {
21656   if (VT == MVT::i8)
21657     return DAG.getNode(ISD::AND, DL, VT,
21658                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21659                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
21660                        DAG.getConstant(1, VT));
21661   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
21662   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
21663                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
21664                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
21665 }
21666
21667 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
21668 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
21669                                    TargetLowering::DAGCombinerInfo &DCI,
21670                                    const X86Subtarget *Subtarget) {
21671   SDLoc DL(N);
21672   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
21673   SDValue EFLAGS = N->getOperand(1);
21674
21675   if (CC == X86::COND_A) {
21676     // Try to convert COND_A into COND_B in an attempt to facilitate
21677     // materializing "setb reg".
21678     //
21679     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
21680     // cannot take an immediate as its first operand.
21681     //
21682     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
21683         EFLAGS.getValueType().isInteger() &&
21684         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
21685       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
21686                                    EFLAGS.getNode()->getVTList(),
21687                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
21688       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
21689       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
21690     }
21691   }
21692
21693   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
21694   // a zext and produces an all-ones bit which is more useful than 0/1 in some
21695   // cases.
21696   if (CC == X86::COND_B)
21697     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
21698
21699   SDValue Flags;
21700
21701   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21702   if (Flags.getNode()) {
21703     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21704     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
21705   }
21706
21707   return SDValue();
21708 }
21709
21710 // Optimize branch condition evaluation.
21711 //
21712 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
21713                                     TargetLowering::DAGCombinerInfo &DCI,
21714                                     const X86Subtarget *Subtarget) {
21715   SDLoc DL(N);
21716   SDValue Chain = N->getOperand(0);
21717   SDValue Dest = N->getOperand(1);
21718   SDValue EFLAGS = N->getOperand(3);
21719   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
21720
21721   SDValue Flags;
21722
21723   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
21724   if (Flags.getNode()) {
21725     SDValue Cond = DAG.getConstant(CC, MVT::i8);
21726     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
21727                        Flags);
21728   }
21729
21730   return SDValue();
21731 }
21732
21733 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
21734                                         const X86TargetLowering *XTLI) {
21735   SDValue Op0 = N->getOperand(0);
21736   EVT InVT = Op0->getValueType(0);
21737
21738   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21739   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21740     SDLoc dl(N);
21741     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21742     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21743     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21744   }
21745
21746   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21747   // a 32-bit target where SSE doesn't support i64->FP operations.
21748   if (Op0.getOpcode() == ISD::LOAD) {
21749     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21750     EVT VT = Ld->getValueType(0);
21751     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21752         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21753         !XTLI->getSubtarget()->is64Bit() &&
21754         VT == MVT::i64) {
21755       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21756                                           Ld->getChain(), Op0, DAG);
21757       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21758       return FILDChain;
21759     }
21760   }
21761   return SDValue();
21762 }
21763
21764 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21765 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21766                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21767   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21768   // the result is either zero or one (depending on the input carry bit).
21769   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21770   if (X86::isZeroNode(N->getOperand(0)) &&
21771       X86::isZeroNode(N->getOperand(1)) &&
21772       // We don't have a good way to replace an EFLAGS use, so only do this when
21773       // dead right now.
21774       SDValue(N, 1).use_empty()) {
21775     SDLoc DL(N);
21776     EVT VT = N->getValueType(0);
21777     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21778     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21779                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21780                                            DAG.getConstant(X86::COND_B,MVT::i8),
21781                                            N->getOperand(2)),
21782                                DAG.getConstant(1, VT));
21783     return DCI.CombineTo(N, Res1, CarryOut);
21784   }
21785
21786   return SDValue();
21787 }
21788
21789 // fold (add Y, (sete  X, 0)) -> adc  0, Y
21790 //      (add Y, (setne X, 0)) -> sbb -1, Y
21791 //      (sub (sete  X, 0), Y) -> sbb  0, Y
21792 //      (sub (setne X, 0), Y) -> adc -1, Y
21793 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21794   SDLoc DL(N);
21795
21796   // Look through ZExts.
21797   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21798   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21799     return SDValue();
21800
21801   SDValue SetCC = Ext.getOperand(0);
21802   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21803     return SDValue();
21804
21805   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21806   if (CC != X86::COND_E && CC != X86::COND_NE)
21807     return SDValue();
21808
21809   SDValue Cmp = SetCC.getOperand(1);
21810   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21811       !X86::isZeroNode(Cmp.getOperand(1)) ||
21812       !Cmp.getOperand(0).getValueType().isInteger())
21813     return SDValue();
21814
21815   SDValue CmpOp0 = Cmp.getOperand(0);
21816   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21817                                DAG.getConstant(1, CmpOp0.getValueType()));
21818
21819   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21820   if (CC == X86::COND_NE)
21821     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21822                        DL, OtherVal.getValueType(), OtherVal,
21823                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21824   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21825                      DL, OtherVal.getValueType(), OtherVal,
21826                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21827 }
21828
21829 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21830 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21831                                  const X86Subtarget *Subtarget) {
21832   EVT VT = N->getValueType(0);
21833   SDValue Op0 = N->getOperand(0);
21834   SDValue Op1 = N->getOperand(1);
21835
21836   // Try to synthesize horizontal adds from adds of shuffles.
21837   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21838        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21839       isHorizontalBinOp(Op0, Op1, true))
21840     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21841
21842   return OptimizeConditionalInDecrement(N, DAG);
21843 }
21844
21845 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21846                                  const X86Subtarget *Subtarget) {
21847   SDValue Op0 = N->getOperand(0);
21848   SDValue Op1 = N->getOperand(1);
21849
21850   // X86 can't encode an immediate LHS of a sub. See if we can push the
21851   // negation into a preceding instruction.
21852   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21853     // If the RHS of the sub is a XOR with one use and a constant, invert the
21854     // immediate. Then add one to the LHS of the sub so we can turn
21855     // X-Y -> X+~Y+1, saving one register.
21856     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21857         isa<ConstantSDNode>(Op1.getOperand(1))) {
21858       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21859       EVT VT = Op0.getValueType();
21860       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21861                                    Op1.getOperand(0),
21862                                    DAG.getConstant(~XorC, VT));
21863       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21864                          DAG.getConstant(C->getAPIntValue()+1, VT));
21865     }
21866   }
21867
21868   // Try to synthesize horizontal adds from adds of shuffles.
21869   EVT VT = N->getValueType(0);
21870   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21871        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21872       isHorizontalBinOp(Op0, Op1, true))
21873     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21874
21875   return OptimizeConditionalInDecrement(N, DAG);
21876 }
21877
21878 /// performVZEXTCombine - Performs build vector combines
21879 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21880                                         TargetLowering::DAGCombinerInfo &DCI,
21881                                         const X86Subtarget *Subtarget) {
21882   // (vzext (bitcast (vzext (x)) -> (vzext x)
21883   SDValue In = N->getOperand(0);
21884   while (In.getOpcode() == ISD::BITCAST)
21885     In = In.getOperand(0);
21886
21887   if (In.getOpcode() != X86ISD::VZEXT)
21888     return SDValue();
21889
21890   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21891                      In.getOperand(0));
21892 }
21893
21894 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21895                                              DAGCombinerInfo &DCI) const {
21896   SelectionDAG &DAG = DCI.DAG;
21897   switch (N->getOpcode()) {
21898   default: break;
21899   case ISD::EXTRACT_VECTOR_ELT:
21900     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21901   case ISD::VSELECT:
21902   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21903   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21904   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
21905   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
21906   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
21907   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
21908   case ISD::SHL:
21909   case ISD::SRA:
21910   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
21911   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
21912   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
21913   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
21914   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
21915   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
21916   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
21917   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
21918   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
21919   case X86ISD::FXOR:
21920   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
21921   case X86ISD::FMIN:
21922   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
21923   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
21924   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
21925   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
21926   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
21927   case ISD::ANY_EXTEND:
21928   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
21929   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
21930   case ISD::SIGN_EXTEND_INREG:
21931     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21932   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21933   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
21934   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21935   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21936   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
21937   case X86ISD::SHUFP:       // Handle all target specific shuffles
21938   case X86ISD::PALIGNR:
21939   case X86ISD::UNPCKH:
21940   case X86ISD::UNPCKL:
21941   case X86ISD::MOVHLPS:
21942   case X86ISD::MOVLHPS:
21943   case X86ISD::PSHUFD:
21944   case X86ISD::PSHUFHW:
21945   case X86ISD::PSHUFLW:
21946   case X86ISD::MOVSS:
21947   case X86ISD::MOVSD:
21948   case X86ISD::VPERMILP:
21949   case X86ISD::VPERM2X128:
21950   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21951   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
21952   case ISD::INTRINSIC_WO_CHAIN:
21953     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21954   case X86ISD::INSERTPS:
21955     return PerformINSERTPSCombine(N, DAG, Subtarget);
21956   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21957   }
21958
21959   return SDValue();
21960 }
21961
21962 /// isTypeDesirableForOp - Return true if the target has native support for
21963 /// the specified value type and it is 'desirable' to use the type for the
21964 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21965 /// instruction encodings are longer and some i16 instructions are slow.
21966 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21967   if (!isTypeLegal(VT))
21968     return false;
21969   if (VT != MVT::i16)
21970     return true;
21971
21972   switch (Opc) {
21973   default:
21974     return true;
21975   case ISD::LOAD:
21976   case ISD::SIGN_EXTEND:
21977   case ISD::ZERO_EXTEND:
21978   case ISD::ANY_EXTEND:
21979   case ISD::SHL:
21980   case ISD::SRL:
21981   case ISD::SUB:
21982   case ISD::ADD:
21983   case ISD::MUL:
21984   case ISD::AND:
21985   case ISD::OR:
21986   case ISD::XOR:
21987     return false;
21988   }
21989 }
21990
21991 /// IsDesirableToPromoteOp - This method query the target whether it is
21992 /// beneficial for dag combiner to promote the specified node. If true, it
21993 /// should return the desired promotion type by reference.
21994 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21995   EVT VT = Op.getValueType();
21996   if (VT != MVT::i16)
21997     return false;
21998
21999   bool Promote = false;
22000   bool Commute = false;
22001   switch (Op.getOpcode()) {
22002   default: break;
22003   case ISD::LOAD: {
22004     LoadSDNode *LD = cast<LoadSDNode>(Op);
22005     // If the non-extending load has a single use and it's not live out, then it
22006     // might be folded.
22007     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
22008                                                      Op.hasOneUse()*/) {
22009       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
22010              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
22011         // The only case where we'd want to promote LOAD (rather then it being
22012         // promoted as an operand is when it's only use is liveout.
22013         if (UI->getOpcode() != ISD::CopyToReg)
22014           return false;
22015       }
22016     }
22017     Promote = true;
22018     break;
22019   }
22020   case ISD::SIGN_EXTEND:
22021   case ISD::ZERO_EXTEND:
22022   case ISD::ANY_EXTEND:
22023     Promote = true;
22024     break;
22025   case ISD::SHL:
22026   case ISD::SRL: {
22027     SDValue N0 = Op.getOperand(0);
22028     // Look out for (store (shl (load), x)).
22029     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
22030       return false;
22031     Promote = true;
22032     break;
22033   }
22034   case ISD::ADD:
22035   case ISD::MUL:
22036   case ISD::AND:
22037   case ISD::OR:
22038   case ISD::XOR:
22039     Commute = true;
22040     // fallthrough
22041   case ISD::SUB: {
22042     SDValue N0 = Op.getOperand(0);
22043     SDValue N1 = Op.getOperand(1);
22044     if (!Commute && MayFoldLoad(N1))
22045       return false;
22046     // Avoid disabling potential load folding opportunities.
22047     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
22048       return false;
22049     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
22050       return false;
22051     Promote = true;
22052   }
22053   }
22054
22055   PVT = MVT::i32;
22056   return Promote;
22057 }
22058
22059 //===----------------------------------------------------------------------===//
22060 //                           X86 Inline Assembly Support
22061 //===----------------------------------------------------------------------===//
22062
22063 namespace {
22064   // Helper to match a string separated by whitespace.
22065   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
22066     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
22067
22068     for (unsigned i = 0, e = args.size(); i != e; ++i) {
22069       StringRef piece(*args[i]);
22070       if (!s.startswith(piece)) // Check if the piece matches.
22071         return false;
22072
22073       s = s.substr(piece.size());
22074       StringRef::size_type pos = s.find_first_not_of(" \t");
22075       if (pos == 0) // We matched a prefix.
22076         return false;
22077
22078       s = s.substr(pos);
22079     }
22080
22081     return s.empty();
22082   }
22083   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
22084 }
22085
22086 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
22087
22088   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
22089     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
22090         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
22091         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
22092
22093       if (AsmPieces.size() == 3)
22094         return true;
22095       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
22096         return true;
22097     }
22098   }
22099   return false;
22100 }
22101
22102 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
22103   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
22104
22105   std::string AsmStr = IA->getAsmString();
22106
22107   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
22108   if (!Ty || Ty->getBitWidth() % 16 != 0)
22109     return false;
22110
22111   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
22112   SmallVector<StringRef, 4> AsmPieces;
22113   SplitString(AsmStr, AsmPieces, ";\n");
22114
22115   switch (AsmPieces.size()) {
22116   default: return false;
22117   case 1:
22118     // FIXME: this should verify that we are targeting a 486 or better.  If not,
22119     // we will turn this bswap into something that will be lowered to logical
22120     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
22121     // lower so don't worry about this.
22122     // bswap $0
22123     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
22124         matchAsm(AsmPieces[0], "bswapl", "$0") ||
22125         matchAsm(AsmPieces[0], "bswapq", "$0") ||
22126         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
22127         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
22128         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
22129       // No need to check constraints, nothing other than the equivalent of
22130       // "=r,0" would be valid here.
22131       return IntrinsicLowering::LowerToByteSwap(CI);
22132     }
22133
22134     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
22135     if (CI->getType()->isIntegerTy(16) &&
22136         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22137         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
22138          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
22139       AsmPieces.clear();
22140       const std::string &ConstraintsStr = IA->getConstraintString();
22141       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22142       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22143       if (clobbersFlagRegisters(AsmPieces))
22144         return IntrinsicLowering::LowerToByteSwap(CI);
22145     }
22146     break;
22147   case 3:
22148     if (CI->getType()->isIntegerTy(32) &&
22149         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
22150         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
22151         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
22152         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
22153       AsmPieces.clear();
22154       const std::string &ConstraintsStr = IA->getConstraintString();
22155       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
22156       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
22157       if (clobbersFlagRegisters(AsmPieces))
22158         return IntrinsicLowering::LowerToByteSwap(CI);
22159     }
22160
22161     if (CI->getType()->isIntegerTy(64)) {
22162       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
22163       if (Constraints.size() >= 2 &&
22164           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
22165           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
22166         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
22167         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
22168             matchAsm(AsmPieces[1], "bswap", "%edx") &&
22169             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
22170           return IntrinsicLowering::LowerToByteSwap(CI);
22171       }
22172     }
22173     break;
22174   }
22175   return false;
22176 }
22177
22178 /// getConstraintType - Given a constraint letter, return the type of
22179 /// constraint it is for this target.
22180 X86TargetLowering::ConstraintType
22181 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
22182   if (Constraint.size() == 1) {
22183     switch (Constraint[0]) {
22184     case 'R':
22185     case 'q':
22186     case 'Q':
22187     case 'f':
22188     case 't':
22189     case 'u':
22190     case 'y':
22191     case 'x':
22192     case 'Y':
22193     case 'l':
22194       return C_RegisterClass;
22195     case 'a':
22196     case 'b':
22197     case 'c':
22198     case 'd':
22199     case 'S':
22200     case 'D':
22201     case 'A':
22202       return C_Register;
22203     case 'I':
22204     case 'J':
22205     case 'K':
22206     case 'L':
22207     case 'M':
22208     case 'N':
22209     case 'G':
22210     case 'C':
22211     case 'e':
22212     case 'Z':
22213       return C_Other;
22214     default:
22215       break;
22216     }
22217   }
22218   return TargetLowering::getConstraintType(Constraint);
22219 }
22220
22221 /// Examine constraint type and operand type and determine a weight value.
22222 /// This object must already have been set up with the operand type
22223 /// and the current alternative constraint selected.
22224 TargetLowering::ConstraintWeight
22225   X86TargetLowering::getSingleConstraintMatchWeight(
22226     AsmOperandInfo &info, const char *constraint) const {
22227   ConstraintWeight weight = CW_Invalid;
22228   Value *CallOperandVal = info.CallOperandVal;
22229     // If we don't have a value, we can't do a match,
22230     // but allow it at the lowest weight.
22231   if (!CallOperandVal)
22232     return CW_Default;
22233   Type *type = CallOperandVal->getType();
22234   // Look at the constraint type.
22235   switch (*constraint) {
22236   default:
22237     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
22238   case 'R':
22239   case 'q':
22240   case 'Q':
22241   case 'a':
22242   case 'b':
22243   case 'c':
22244   case 'd':
22245   case 'S':
22246   case 'D':
22247   case 'A':
22248     if (CallOperandVal->getType()->isIntegerTy())
22249       weight = CW_SpecificReg;
22250     break;
22251   case 'f':
22252   case 't':
22253   case 'u':
22254     if (type->isFloatingPointTy())
22255       weight = CW_SpecificReg;
22256     break;
22257   case 'y':
22258     if (type->isX86_MMXTy() && Subtarget->hasMMX())
22259       weight = CW_SpecificReg;
22260     break;
22261   case 'x':
22262   case 'Y':
22263     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
22264         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
22265       weight = CW_Register;
22266     break;
22267   case 'I':
22268     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
22269       if (C->getZExtValue() <= 31)
22270         weight = CW_Constant;
22271     }
22272     break;
22273   case 'J':
22274     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22275       if (C->getZExtValue() <= 63)
22276         weight = CW_Constant;
22277     }
22278     break;
22279   case 'K':
22280     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22281       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
22282         weight = CW_Constant;
22283     }
22284     break;
22285   case 'L':
22286     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22287       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
22288         weight = CW_Constant;
22289     }
22290     break;
22291   case 'M':
22292     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22293       if (C->getZExtValue() <= 3)
22294         weight = CW_Constant;
22295     }
22296     break;
22297   case 'N':
22298     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22299       if (C->getZExtValue() <= 0xff)
22300         weight = CW_Constant;
22301     }
22302     break;
22303   case 'G':
22304   case 'C':
22305     if (dyn_cast<ConstantFP>(CallOperandVal)) {
22306       weight = CW_Constant;
22307     }
22308     break;
22309   case 'e':
22310     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22311       if ((C->getSExtValue() >= -0x80000000LL) &&
22312           (C->getSExtValue() <= 0x7fffffffLL))
22313         weight = CW_Constant;
22314     }
22315     break;
22316   case 'Z':
22317     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
22318       if (C->getZExtValue() <= 0xffffffff)
22319         weight = CW_Constant;
22320     }
22321     break;
22322   }
22323   return weight;
22324 }
22325
22326 /// LowerXConstraint - try to replace an X constraint, which matches anything,
22327 /// with another that has more specific requirements based on the type of the
22328 /// corresponding operand.
22329 const char *X86TargetLowering::
22330 LowerXConstraint(EVT ConstraintVT) const {
22331   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
22332   // 'f' like normal targets.
22333   if (ConstraintVT.isFloatingPoint()) {
22334     if (Subtarget->hasSSE2())
22335       return "Y";
22336     if (Subtarget->hasSSE1())
22337       return "x";
22338   }
22339
22340   return TargetLowering::LowerXConstraint(ConstraintVT);
22341 }
22342
22343 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
22344 /// vector.  If it is invalid, don't add anything to Ops.
22345 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
22346                                                      std::string &Constraint,
22347                                                      std::vector<SDValue>&Ops,
22348                                                      SelectionDAG &DAG) const {
22349   SDValue Result;
22350
22351   // Only support length 1 constraints for now.
22352   if (Constraint.length() > 1) return;
22353
22354   char ConstraintLetter = Constraint[0];
22355   switch (ConstraintLetter) {
22356   default: break;
22357   case 'I':
22358     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22359       if (C->getZExtValue() <= 31) {
22360         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22361         break;
22362       }
22363     }
22364     return;
22365   case 'J':
22366     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22367       if (C->getZExtValue() <= 63) {
22368         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22369         break;
22370       }
22371     }
22372     return;
22373   case 'K':
22374     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22375       if (isInt<8>(C->getSExtValue())) {
22376         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22377         break;
22378       }
22379     }
22380     return;
22381   case 'N':
22382     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22383       if (C->getZExtValue() <= 255) {
22384         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22385         break;
22386       }
22387     }
22388     return;
22389   case 'e': {
22390     // 32-bit signed value
22391     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22392       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22393                                            C->getSExtValue())) {
22394         // Widen to 64 bits here to get it sign extended.
22395         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
22396         break;
22397       }
22398     // FIXME gcc accepts some relocatable values here too, but only in certain
22399     // memory models; it's complicated.
22400     }
22401     return;
22402   }
22403   case 'Z': {
22404     // 32-bit unsigned value
22405     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
22406       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
22407                                            C->getZExtValue())) {
22408         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
22409         break;
22410       }
22411     }
22412     // FIXME gcc accepts some relocatable values here too, but only in certain
22413     // memory models; it's complicated.
22414     return;
22415   }
22416   case 'i': {
22417     // Literal immediates are always ok.
22418     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
22419       // Widen to 64 bits here to get it sign extended.
22420       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
22421       break;
22422     }
22423
22424     // In any sort of PIC mode addresses need to be computed at runtime by
22425     // adding in a register or some sort of table lookup.  These can't
22426     // be used as immediates.
22427     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
22428       return;
22429
22430     // If we are in non-pic codegen mode, we allow the address of a global (with
22431     // an optional displacement) to be used with 'i'.
22432     GlobalAddressSDNode *GA = nullptr;
22433     int64_t Offset = 0;
22434
22435     // Match either (GA), (GA+C), (GA+C1+C2), etc.
22436     while (1) {
22437       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
22438         Offset += GA->getOffset();
22439         break;
22440       } else if (Op.getOpcode() == ISD::ADD) {
22441         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22442           Offset += C->getZExtValue();
22443           Op = Op.getOperand(0);
22444           continue;
22445         }
22446       } else if (Op.getOpcode() == ISD::SUB) {
22447         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
22448           Offset += -C->getZExtValue();
22449           Op = Op.getOperand(0);
22450           continue;
22451         }
22452       }
22453
22454       // Otherwise, this isn't something we can handle, reject it.
22455       return;
22456     }
22457
22458     const GlobalValue *GV = GA->getGlobal();
22459     // If we require an extra load to get this address, as in PIC mode, we
22460     // can't accept it.
22461     if (isGlobalStubReference(
22462             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
22463       return;
22464
22465     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
22466                                         GA->getValueType(0), Offset);
22467     break;
22468   }
22469   }
22470
22471   if (Result.getNode()) {
22472     Ops.push_back(Result);
22473     return;
22474   }
22475   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
22476 }
22477
22478 std::pair<unsigned, const TargetRegisterClass*>
22479 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
22480                                                 MVT VT) const {
22481   // First, see if this is a constraint that directly corresponds to an LLVM
22482   // register class.
22483   if (Constraint.size() == 1) {
22484     // GCC Constraint Letters
22485     switch (Constraint[0]) {
22486     default: break;
22487       // TODO: Slight differences here in allocation order and leaving
22488       // RIP in the class. Do they matter any more here than they do
22489       // in the normal allocation?
22490     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
22491       if (Subtarget->is64Bit()) {
22492         if (VT == MVT::i32 || VT == MVT::f32)
22493           return std::make_pair(0U, &X86::GR32RegClass);
22494         if (VT == MVT::i16)
22495           return std::make_pair(0U, &X86::GR16RegClass);
22496         if (VT == MVT::i8 || VT == MVT::i1)
22497           return std::make_pair(0U, &X86::GR8RegClass);
22498         if (VT == MVT::i64 || VT == MVT::f64)
22499           return std::make_pair(0U, &X86::GR64RegClass);
22500         break;
22501       }
22502       // 32-bit fallthrough
22503     case 'Q':   // Q_REGS
22504       if (VT == MVT::i32 || VT == MVT::f32)
22505         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
22506       if (VT == MVT::i16)
22507         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
22508       if (VT == MVT::i8 || VT == MVT::i1)
22509         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
22510       if (VT == MVT::i64)
22511         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
22512       break;
22513     case 'r':   // GENERAL_REGS
22514     case 'l':   // INDEX_REGS
22515       if (VT == MVT::i8 || VT == MVT::i1)
22516         return std::make_pair(0U, &X86::GR8RegClass);
22517       if (VT == MVT::i16)
22518         return std::make_pair(0U, &X86::GR16RegClass);
22519       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
22520         return std::make_pair(0U, &X86::GR32RegClass);
22521       return std::make_pair(0U, &X86::GR64RegClass);
22522     case 'R':   // LEGACY_REGS
22523       if (VT == MVT::i8 || VT == MVT::i1)
22524         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
22525       if (VT == MVT::i16)
22526         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
22527       if (VT == MVT::i32 || !Subtarget->is64Bit())
22528         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
22529       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
22530     case 'f':  // FP Stack registers.
22531       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
22532       // value to the correct fpstack register class.
22533       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
22534         return std::make_pair(0U, &X86::RFP32RegClass);
22535       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
22536         return std::make_pair(0U, &X86::RFP64RegClass);
22537       return std::make_pair(0U, &X86::RFP80RegClass);
22538     case 'y':   // MMX_REGS if MMX allowed.
22539       if (!Subtarget->hasMMX()) break;
22540       return std::make_pair(0U, &X86::VR64RegClass);
22541     case 'Y':   // SSE_REGS if SSE2 allowed
22542       if (!Subtarget->hasSSE2()) break;
22543       // FALL THROUGH.
22544     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
22545       if (!Subtarget->hasSSE1()) break;
22546
22547       switch (VT.SimpleTy) {
22548       default: break;
22549       // Scalar SSE types.
22550       case MVT::f32:
22551       case MVT::i32:
22552         return std::make_pair(0U, &X86::FR32RegClass);
22553       case MVT::f64:
22554       case MVT::i64:
22555         return std::make_pair(0U, &X86::FR64RegClass);
22556       // Vector types.
22557       case MVT::v16i8:
22558       case MVT::v8i16:
22559       case MVT::v4i32:
22560       case MVT::v2i64:
22561       case MVT::v4f32:
22562       case MVT::v2f64:
22563         return std::make_pair(0U, &X86::VR128RegClass);
22564       // AVX types.
22565       case MVT::v32i8:
22566       case MVT::v16i16:
22567       case MVT::v8i32:
22568       case MVT::v4i64:
22569       case MVT::v8f32:
22570       case MVT::v4f64:
22571         return std::make_pair(0U, &X86::VR256RegClass);
22572       case MVT::v8f64:
22573       case MVT::v16f32:
22574       case MVT::v16i32:
22575       case MVT::v8i64:
22576         return std::make_pair(0U, &X86::VR512RegClass);
22577       }
22578       break;
22579     }
22580   }
22581
22582   // Use the default implementation in TargetLowering to convert the register
22583   // constraint into a member of a register class.
22584   std::pair<unsigned, const TargetRegisterClass*> Res;
22585   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
22586
22587   // Not found as a standard register?
22588   if (!Res.second) {
22589     // Map st(0) -> st(7) -> ST0
22590     if (Constraint.size() == 7 && Constraint[0] == '{' &&
22591         tolower(Constraint[1]) == 's' &&
22592         tolower(Constraint[2]) == 't' &&
22593         Constraint[3] == '(' &&
22594         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
22595         Constraint[5] == ')' &&
22596         Constraint[6] == '}') {
22597
22598       Res.first = X86::ST0+Constraint[4]-'0';
22599       Res.second = &X86::RFP80RegClass;
22600       return Res;
22601     }
22602
22603     // GCC allows "st(0)" to be called just plain "st".
22604     if (StringRef("{st}").equals_lower(Constraint)) {
22605       Res.first = X86::ST0;
22606       Res.second = &X86::RFP80RegClass;
22607       return Res;
22608     }
22609
22610     // flags -> EFLAGS
22611     if (StringRef("{flags}").equals_lower(Constraint)) {
22612       Res.first = X86::EFLAGS;
22613       Res.second = &X86::CCRRegClass;
22614       return Res;
22615     }
22616
22617     // 'A' means EAX + EDX.
22618     if (Constraint == "A") {
22619       Res.first = X86::EAX;
22620       Res.second = &X86::GR32_ADRegClass;
22621       return Res;
22622     }
22623     return Res;
22624   }
22625
22626   // Otherwise, check to see if this is a register class of the wrong value
22627   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
22628   // turn into {ax},{dx}.
22629   if (Res.second->hasType(VT))
22630     return Res;   // Correct type already, nothing to do.
22631
22632   // All of the single-register GCC register classes map their values onto
22633   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
22634   // really want an 8-bit or 32-bit register, map to the appropriate register
22635   // class and return the appropriate register.
22636   if (Res.second == &X86::GR16RegClass) {
22637     if (VT == MVT::i8 || VT == MVT::i1) {
22638       unsigned DestReg = 0;
22639       switch (Res.first) {
22640       default: break;
22641       case X86::AX: DestReg = X86::AL; break;
22642       case X86::DX: DestReg = X86::DL; break;
22643       case X86::CX: DestReg = X86::CL; break;
22644       case X86::BX: DestReg = X86::BL; break;
22645       }
22646       if (DestReg) {
22647         Res.first = DestReg;
22648         Res.second = &X86::GR8RegClass;
22649       }
22650     } else if (VT == MVT::i32 || VT == MVT::f32) {
22651       unsigned DestReg = 0;
22652       switch (Res.first) {
22653       default: break;
22654       case X86::AX: DestReg = X86::EAX; break;
22655       case X86::DX: DestReg = X86::EDX; break;
22656       case X86::CX: DestReg = X86::ECX; break;
22657       case X86::BX: DestReg = X86::EBX; break;
22658       case X86::SI: DestReg = X86::ESI; break;
22659       case X86::DI: DestReg = X86::EDI; break;
22660       case X86::BP: DestReg = X86::EBP; break;
22661       case X86::SP: DestReg = X86::ESP; break;
22662       }
22663       if (DestReg) {
22664         Res.first = DestReg;
22665         Res.second = &X86::GR32RegClass;
22666       }
22667     } else if (VT == MVT::i64 || VT == MVT::f64) {
22668       unsigned DestReg = 0;
22669       switch (Res.first) {
22670       default: break;
22671       case X86::AX: DestReg = X86::RAX; break;
22672       case X86::DX: DestReg = X86::RDX; break;
22673       case X86::CX: DestReg = X86::RCX; break;
22674       case X86::BX: DestReg = X86::RBX; break;
22675       case X86::SI: DestReg = X86::RSI; break;
22676       case X86::DI: DestReg = X86::RDI; break;
22677       case X86::BP: DestReg = X86::RBP; break;
22678       case X86::SP: DestReg = X86::RSP; break;
22679       }
22680       if (DestReg) {
22681         Res.first = DestReg;
22682         Res.second = &X86::GR64RegClass;
22683       }
22684     }
22685   } else if (Res.second == &X86::FR32RegClass ||
22686              Res.second == &X86::FR64RegClass ||
22687              Res.second == &X86::VR128RegClass ||
22688              Res.second == &X86::VR256RegClass ||
22689              Res.second == &X86::FR32XRegClass ||
22690              Res.second == &X86::FR64XRegClass ||
22691              Res.second == &X86::VR128XRegClass ||
22692              Res.second == &X86::VR256XRegClass ||
22693              Res.second == &X86::VR512RegClass) {
22694     // Handle references to XMM physical registers that got mapped into the
22695     // wrong class.  This can happen with constraints like {xmm0} where the
22696     // target independent register mapper will just pick the first match it can
22697     // find, ignoring the required type.
22698
22699     if (VT == MVT::f32 || VT == MVT::i32)
22700       Res.second = &X86::FR32RegClass;
22701     else if (VT == MVT::f64 || VT == MVT::i64)
22702       Res.second = &X86::FR64RegClass;
22703     else if (X86::VR128RegClass.hasType(VT))
22704       Res.second = &X86::VR128RegClass;
22705     else if (X86::VR256RegClass.hasType(VT))
22706       Res.second = &X86::VR256RegClass;
22707     else if (X86::VR512RegClass.hasType(VT))
22708       Res.second = &X86::VR512RegClass;
22709   }
22710
22711   return Res;
22712 }
22713
22714 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
22715                                             Type *Ty) const {
22716   // Scaling factors are not free at all.
22717   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
22718   // will take 2 allocations in the out of order engine instead of 1
22719   // for plain addressing mode, i.e. inst (reg1).
22720   // E.g.,
22721   // vaddps (%rsi,%drx), %ymm0, %ymm1
22722   // Requires two allocations (one for the load, one for the computation)
22723   // whereas:
22724   // vaddps (%rsi), %ymm0, %ymm1
22725   // Requires just 1 allocation, i.e., freeing allocations for other operations
22726   // and having less micro operations to execute.
22727   //
22728   // For some X86 architectures, this is even worse because for instance for
22729   // stores, the complex addressing mode forces the instruction to use the
22730   // "load" ports instead of the dedicated "store" port.
22731   // E.g., on Haswell:
22732   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
22733   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
22734   if (isLegalAddressingMode(AM, Ty))
22735     // Scale represents reg2 * scale, thus account for 1
22736     // as soon as we use a second register.
22737     return AM.Scale != 0;
22738   return -1;
22739 }
22740
22741 bool X86TargetLowering::isTargetFTOL() const {
22742   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22743 }