Re-apply r211399, "Generate native unwind info on Win64" with a fix to ignore SEH...
[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/Debug.h"
48 #include "llvm/Support/ErrorHandling.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Target/TargetOptions.h"
51 #include <bitset>
52 #include <cctype>
53 using namespace llvm;
54
55 #define DEBUG_TYPE "x86-isel"
56
57 STATISTIC(NumTailCalls, "Number of tail calls");
58
59 // Forward declarations.
60 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
61                        SDValue V2);
62
63 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
64                                 SelectionDAG &DAG, SDLoc dl,
65                                 unsigned vectorWidth) {
66   assert((vectorWidth == 128 || vectorWidth == 256) &&
67          "Unsupported vector width");
68   EVT VT = Vec.getValueType();
69   EVT ElVT = VT.getVectorElementType();
70   unsigned Factor = VT.getSizeInBits()/vectorWidth;
71   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
72                                   VT.getVectorNumElements()/Factor);
73
74   // Extract from UNDEF is UNDEF.
75   if (Vec.getOpcode() == ISD::UNDEF)
76     return DAG.getUNDEF(ResultVT);
77
78   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
79   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
80
81   // This is the index of the first element of the vectorWidth-bit chunk
82   // we want.
83   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
84                                * ElemsPerChunk);
85
86   // If the input is a buildvector just emit a smaller one.
87   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
88     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
89                        makeArrayRef(Vec->op_begin()+NormalizedIdxVal,
90                                     ElemsPerChunk));
91
92   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
93   SDValue Result = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec,
94                                VecIdx);
95
96   return Result;
97
98 }
99 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
100 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
101 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
102 /// instructions or a simple subregister reference. Idx is an index in the
103 /// 128 bits we want.  It need not be aligned to a 128-bit bounday.  That makes
104 /// lowering EXTRACT_VECTOR_ELT operations easier.
105 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
106                                    SelectionDAG &DAG, SDLoc dl) {
107   assert((Vec.getValueType().is256BitVector() ||
108           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
109   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
110 }
111
112 /// Generate a DAG to grab 256-bits from a 512-bit vector.
113 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
114                                    SelectionDAG &DAG, SDLoc dl) {
115   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
116   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
117 }
118
119 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
120                                unsigned IdxVal, SelectionDAG &DAG,
121                                SDLoc dl, unsigned vectorWidth) {
122   assert((vectorWidth == 128 || vectorWidth == 256) &&
123          "Unsupported vector width");
124   // Inserting UNDEF is Result
125   if (Vec.getOpcode() == ISD::UNDEF)
126     return Result;
127   EVT VT = Vec.getValueType();
128   EVT ElVT = VT.getVectorElementType();
129   EVT ResultVT = Result.getValueType();
130
131   // Insert the relevant vectorWidth bits.
132   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
133
134   // This is the index of the first element of the vectorWidth-bit chunk
135   // we want.
136   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
137                                * ElemsPerChunk);
138
139   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal);
140   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec,
141                      VecIdx);
142 }
143 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
144 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
145 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
146 /// simple superregister reference.  Idx is an index in the 128 bits
147 /// we want.  It need not be aligned to a 128-bit bounday.  That makes
148 /// lowering INSERT_VECTOR_ELT operations easier.
149 static SDValue Insert128BitVector(SDValue Result, SDValue Vec,
150                                   unsigned IdxVal, SelectionDAG &DAG,
151                                   SDLoc dl) {
152   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
153   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
154 }
155
156 static SDValue Insert256BitVector(SDValue Result, SDValue Vec,
157                                   unsigned IdxVal, SelectionDAG &DAG,
158                                   SDLoc dl) {
159   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
160   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
161 }
162
163 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
164 /// instructions. This is used because creating CONCAT_VECTOR nodes of
165 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
166 /// large BUILD_VECTORS.
167 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
168                                    unsigned NumElems, SelectionDAG &DAG,
169                                    SDLoc dl) {
170   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
171   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
172 }
173
174 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
175                                    unsigned NumElems, SelectionDAG &DAG,
176                                    SDLoc dl) {
177   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
178   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
179 }
180
181 static TargetLoweringObjectFile *createTLOF(const Triple &TT) {
182   if (TT.isOSBinFormatMachO()) {
183     if (TT.getArch() == Triple::x86_64)
184       return new X86_64MachoTargetObjectFile();
185     return new TargetLoweringObjectFileMachO();
186   }
187
188   if (TT.isOSLinux())
189     return new X86LinuxTargetObjectFile();
190   if (TT.isOSBinFormatELF())
191     return new TargetLoweringObjectFileELF();
192   if (TT.isKnownWindowsMSVCEnvironment())
193     return new X86WindowsTargetObjectFile();
194   if (TT.isOSBinFormatCOFF())
195     return new TargetLoweringObjectFileCOFF();
196   llvm_unreachable("unknown subtarget type");
197 }
198
199 // FIXME: This should stop caching the target machine as soon as
200 // we can remove resetOperationActions et al.
201 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
202   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
203   Subtarget = &TM.getSubtarget<X86Subtarget>();
204   X86ScalarSSEf64 = Subtarget->hasSSE2();
205   X86ScalarSSEf32 = Subtarget->hasSSE1();
206   TD = getDataLayout();
207
208   resetOperationActions();
209 }
210
211 void X86TargetLowering::resetOperationActions() {
212   const TargetMachine &TM = getTargetMachine();
213   static bool FirstTimeThrough = true;
214
215   // If none of the target options have changed, then we don't need to reset the
216   // operation actions.
217   if (!FirstTimeThrough && TO == TM.Options) return;
218
219   if (!FirstTimeThrough) {
220     // Reinitialize the actions.
221     initActions();
222     FirstTimeThrough = false;
223   }
224
225   TO = TM.Options;
226
227   // Set up the TargetLowering object.
228   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
229
230   // X86 is weird, it always uses i8 for shift amounts and setcc results.
231   setBooleanContents(ZeroOrOneBooleanContent);
232   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
233   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
234
235   // For 64-bit since we have so many registers use the ILP scheduler, for
236   // 32-bit code use the register pressure specific scheduling.
237   // For Atom, always use ILP scheduling.
238   if (Subtarget->isAtom())
239     setSchedulingPreference(Sched::ILP);
240   else if (Subtarget->is64Bit())
241     setSchedulingPreference(Sched::ILP);
242   else
243     setSchedulingPreference(Sched::RegPressure);
244   const X86RegisterInfo *RegInfo =
245     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
246   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
247
248   // Bypass expensive divides on Atom when compiling with O2
249   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
250     addBypassSlowDiv(32, 8);
251     if (Subtarget->is64Bit())
252       addBypassSlowDiv(64, 16);
253   }
254
255   if (Subtarget->isTargetKnownWindowsMSVC()) {
256     // Setup Windows compiler runtime calls.
257     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
258     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
259     setLibcallName(RTLIB::SREM_I64, "_allrem");
260     setLibcallName(RTLIB::UREM_I64, "_aullrem");
261     setLibcallName(RTLIB::MUL_I64, "_allmul");
262     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
265     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
266     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
267
268     // The _ftol2 runtime function has an unusual calling conv, which
269     // is modeled by a special pseudo-instruction.
270     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
272     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
273     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
274   }
275
276   if (Subtarget->isTargetDarwin()) {
277     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
278     setUseUnderscoreSetJmp(false);
279     setUseUnderscoreLongJmp(false);
280   } else if (Subtarget->isTargetWindowsGNU()) {
281     // MS runtime is weird: it exports _setjmp, but longjmp!
282     setUseUnderscoreSetJmp(true);
283     setUseUnderscoreLongJmp(false);
284   } else {
285     setUseUnderscoreSetJmp(true);
286     setUseUnderscoreLongJmp(true);
287   }
288
289   // Set up the register classes.
290   addRegisterClass(MVT::i8, &X86::GR8RegClass);
291   addRegisterClass(MVT::i16, &X86::GR16RegClass);
292   addRegisterClass(MVT::i32, &X86::GR32RegClass);
293   if (Subtarget->is64Bit())
294     addRegisterClass(MVT::i64, &X86::GR64RegClass);
295
296   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
297
298   // We don't accept any truncstore of integer registers.
299   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
300   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
303   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
304   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
305
306   // SETOEQ and SETUNE require checking two conditions.
307   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
308   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
309   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
311   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
312   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
313
314   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
315   // operation.
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
317   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
318   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
319
320   if (Subtarget->is64Bit()) {
321     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
322     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
323   } else if (!TM.Options.UseSoftFloat) {
324     // We have an algorithm for SSE2->double, and we turn this into a
325     // 64-bit FILD followed by conditional FADD for other targets.
326     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
327     // We have an algorithm for SSE2, and we turn this into a 64-bit
328     // FILD for other targets.
329     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
330   }
331
332   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
333   // this operation.
334   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
335   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
336
337   if (!TM.Options.UseSoftFloat) {
338     // SSE has no i16 to fp conversion, only i32
339     if (X86ScalarSSEf32) {
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
341       // f32 and f64 cases are Legal, f80 case is not
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
343     } else {
344       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
345       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
346     }
347   } else {
348     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
349     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
350   }
351
352   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
353   // are Legal, f80 is custom lowered.
354   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
355   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
356
357   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
358   // this operation.
359   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
360   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
361
362   if (X86ScalarSSEf32) {
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
364     // f32 and f64 cases are Legal, f80 case is not
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
366   } else {
367     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
368     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
369   }
370
371   // Handle FP_TO_UINT by promoting the destination to a larger signed
372   // conversion.
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
374   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
375   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
376
377   if (Subtarget->is64Bit()) {
378     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
379     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
380   } else if (!TM.Options.UseSoftFloat) {
381     // Since AVX is a superset of SSE3, only check for SSE here.
382     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
383       // Expand FP_TO_UINT into a select.
384       // FIXME: We would like to use a Custom expander here eventually to do
385       // the optimal thing for SSE vs. the default expansion in the legalizer.
386       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
387     else
388       // With SSE3 we can use fisttpll to convert to a signed i64; without
389       // SSE, we're stuck with a fistpll.
390       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
391   }
392
393   if (isTargetFTOL()) {
394     // Use the _ftol2 runtime function, which has a pseudo-instruction
395     // to handle its weird calling convention.
396     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
397   }
398
399   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
400   if (!X86ScalarSSEf64) {
401     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
402     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
403     if (Subtarget->is64Bit()) {
404       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
405       // Without SSE, i64->f64 goes through memory.
406       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
407     }
408   }
409
410   // Scalar integer divide and remainder are lowered to use operations that
411   // produce two results, to match the available instructions. This exposes
412   // the two-result form to trivial CSE, which is able to combine x/y and x%y
413   // into a single instruction.
414   //
415   // Scalar integer multiply-high is also lowered to use two-result
416   // operations, to match the available instructions. However, plain multiply
417   // (low) operations are left as Legal, as there are single-result
418   // instructions for this in x86. Using the two-result multiply instructions
419   // when both high and low results are needed must be arranged by dagcombine.
420   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
421     MVT VT = IntVTs[i];
422     setOperationAction(ISD::MULHS, VT, Expand);
423     setOperationAction(ISD::MULHU, VT, Expand);
424     setOperationAction(ISD::SDIV, VT, Expand);
425     setOperationAction(ISD::UDIV, VT, Expand);
426     setOperationAction(ISD::SREM, VT, Expand);
427     setOperationAction(ISD::UREM, VT, Expand);
428
429     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
430     setOperationAction(ISD::ADDC, VT, Custom);
431     setOperationAction(ISD::ADDE, VT, Custom);
432     setOperationAction(ISD::SUBC, VT, Custom);
433     setOperationAction(ISD::SUBE, VT, Custom);
434   }
435
436   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
437   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
438   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
440   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
443   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
444   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
445   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
446   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
447   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
448   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
449   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
450   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
451   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
452   if (Subtarget->is64Bit())
453     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
454   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
455   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
456   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
457   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
458   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
459   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
460   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
461   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
462
463   // Promote the i8 variants and force them on up to i32 which has a shorter
464   // encoding.
465   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
466   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
467   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
468   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
469   if (Subtarget->hasBMI()) {
470     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
471     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
472     if (Subtarget->is64Bit())
473       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
474   } else {
475     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
476     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
477     if (Subtarget->is64Bit())
478       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
479   }
480
481   if (Subtarget->hasLZCNT()) {
482     // When promoting the i8 variants, force them to i32 for a shorter
483     // encoding.
484     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
485     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
486     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
487     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
490     if (Subtarget->is64Bit())
491       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
492   } else {
493     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
494     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
495     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
496     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
497     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
498     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
499     if (Subtarget->is64Bit()) {
500       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
501       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
502     }
503   }
504
505   if (Subtarget->hasPOPCNT()) {
506     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
507   } else {
508     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
509     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
510     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
511     if (Subtarget->is64Bit())
512       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
513   }
514
515   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
516
517   if (!Subtarget->hasMOVBE())
518     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
519
520   // These should be promoted to a larger select which is supported.
521   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
522   // X86 wants to expand cmov itself.
523   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
524   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
525   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
526   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
527   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
528   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
529   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
530   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
531   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
532   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
533   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
534   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
535   if (Subtarget->is64Bit()) {
536     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
537     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
538   }
539   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
540   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
541   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
542   // support continuation, user-level threading, and etc.. As a result, no
543   // other SjLj exception interfaces are implemented and please don't build
544   // your own exception handling based on them.
545   // LLVM/Clang supports zero-cost DWARF exception handling.
546   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
547   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
548
549   // Darwin ABI issue.
550   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
551   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
552   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
553   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
554   if (Subtarget->is64Bit())
555     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
556   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
557   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
558   if (Subtarget->is64Bit()) {
559     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
560     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
561     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
562     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
563     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
564   }
565   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
566   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
567   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
568   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
569   if (Subtarget->is64Bit()) {
570     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
571     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
572     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
573   }
574
575   if (Subtarget->hasSSE1())
576     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
577
578   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
579
580   // Expand certain atomics
581   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
582     MVT VT = IntVTs[i];
583     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
585     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
586   }
587
588   if (!Subtarget->is64Bit()) {
589     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
593     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
594     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
595     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
596     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
597     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
598     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
599     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
600     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
601   }
602
603   if (Subtarget->hasCmpxchg16b()) {
604     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
605   }
606
607   // FIXME - use subtarget debug flags
608   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
609       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
610     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
611   }
612
613   if (Subtarget->is64Bit()) {
614     setExceptionPointerRegister(X86::RAX);
615     setExceptionSelectorRegister(X86::RDX);
616   } else {
617     setExceptionPointerRegister(X86::EAX);
618     setExceptionSelectorRegister(X86::EDX);
619   }
620   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
621   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
622
623   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
624   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
625
626   setOperationAction(ISD::TRAP, MVT::Other, Legal);
627   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
628
629   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
630   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
631   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
632   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
633     // TargetInfo::X86_64ABIBuiltinVaList
634     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
635     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
636   } else {
637     // TargetInfo::CharPtrBuiltinVaList
638     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
639     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
640   }
641
642   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
643   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
644
645   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
646                      MVT::i64 : MVT::i32, Custom);
647
648   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
649     // f32 and f64 use SSE.
650     // Set up the FP register classes.
651     addRegisterClass(MVT::f32, &X86::FR32RegClass);
652     addRegisterClass(MVT::f64, &X86::FR64RegClass);
653
654     // Use ANDPD to simulate FABS.
655     setOperationAction(ISD::FABS , MVT::f64, Custom);
656     setOperationAction(ISD::FABS , MVT::f32, Custom);
657
658     // Use XORP to simulate FNEG.
659     setOperationAction(ISD::FNEG , MVT::f64, Custom);
660     setOperationAction(ISD::FNEG , MVT::f32, Custom);
661
662     // Use ANDPD and ORPD to simulate FCOPYSIGN.
663     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
664     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
665
666     // Lower this to FGETSIGNx86 plus an AND.
667     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
668     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
669
670     // We don't support sin/cos/fmod
671     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
672     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
673     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
674     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
675     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
676     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
677
678     // Expand FP immediates into loads from the stack, except for the special
679     // cases we handle.
680     addLegalFPImmediate(APFloat(+0.0)); // xorpd
681     addLegalFPImmediate(APFloat(+0.0f)); // xorps
682   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
683     // Use SSE for f32, x87 for f64.
684     // Set up the FP register classes.
685     addRegisterClass(MVT::f32, &X86::FR32RegClass);
686     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
687
688     // Use ANDPS to simulate FABS.
689     setOperationAction(ISD::FABS , MVT::f32, Custom);
690
691     // Use XORP to simulate FNEG.
692     setOperationAction(ISD::FNEG , MVT::f32, Custom);
693
694     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
695
696     // Use ANDPS and ORPS to simulate FCOPYSIGN.
697     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
698     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
699
700     // We don't support sin/cos/fmod
701     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
702     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
703     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
704
705     // Special cases we handle for FP constants.
706     addLegalFPImmediate(APFloat(+0.0f)); // xorps
707     addLegalFPImmediate(APFloat(+0.0)); // FLD0
708     addLegalFPImmediate(APFloat(+1.0)); // FLD1
709     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
710     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
711
712     if (!TM.Options.UnsafeFPMath) {
713       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
714       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
715       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
716     }
717   } else if (!TM.Options.UseSoftFloat) {
718     // f32 and f64 in x87.
719     // Set up the FP register classes.
720     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
721     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
722
723     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
724     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
725     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
726     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
727
728     if (!TM.Options.UnsafeFPMath) {
729       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
730       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
731       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
732       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
733       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
735     }
736     addLegalFPImmediate(APFloat(+0.0)); // FLD0
737     addLegalFPImmediate(APFloat(+1.0)); // FLD1
738     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
739     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
740     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
741     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
742     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
743     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
744   }
745
746   // We don't support FMA.
747   setOperationAction(ISD::FMA, MVT::f64, Expand);
748   setOperationAction(ISD::FMA, MVT::f32, Expand);
749
750   // Long double always uses X87.
751   if (!TM.Options.UseSoftFloat) {
752     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
753     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
754     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
755     {
756       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
757       addLegalFPImmediate(TmpFlt);  // FLD0
758       TmpFlt.changeSign();
759       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
760
761       bool ignored;
762       APFloat TmpFlt2(+1.0);
763       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
764                       &ignored);
765       addLegalFPImmediate(TmpFlt2);  // FLD1
766       TmpFlt2.changeSign();
767       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
768     }
769
770     if (!TM.Options.UnsafeFPMath) {
771       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
772       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
773       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
774     }
775
776     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
777     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
778     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
779     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
780     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
781     setOperationAction(ISD::FMA, MVT::f80, Expand);
782   }
783
784   // Always use a library call for pow.
785   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
786   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
787   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
788
789   setOperationAction(ISD::FLOG, MVT::f80, Expand);
790   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
791   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
792   setOperationAction(ISD::FEXP, MVT::f80, Expand);
793   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
794
795   // First set operation action for all vector types to either promote
796   // (for widening) or expand (for scalarization). Then we will selectively
797   // turn on ones that can be effectively codegen'd.
798   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
799            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
800     MVT VT = (MVT::SimpleValueType)i;
801     setOperationAction(ISD::ADD , VT, Expand);
802     setOperationAction(ISD::SUB , VT, Expand);
803     setOperationAction(ISD::FADD, VT, Expand);
804     setOperationAction(ISD::FNEG, VT, Expand);
805     setOperationAction(ISD::FSUB, VT, Expand);
806     setOperationAction(ISD::MUL , VT, Expand);
807     setOperationAction(ISD::FMUL, VT, Expand);
808     setOperationAction(ISD::SDIV, VT, Expand);
809     setOperationAction(ISD::UDIV, VT, Expand);
810     setOperationAction(ISD::FDIV, VT, Expand);
811     setOperationAction(ISD::SREM, VT, Expand);
812     setOperationAction(ISD::UREM, VT, Expand);
813     setOperationAction(ISD::LOAD, VT, Expand);
814     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
815     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
816     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
817     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
818     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
819     setOperationAction(ISD::FABS, VT, Expand);
820     setOperationAction(ISD::FSIN, VT, Expand);
821     setOperationAction(ISD::FSINCOS, VT, Expand);
822     setOperationAction(ISD::FCOS, VT, Expand);
823     setOperationAction(ISD::FSINCOS, VT, Expand);
824     setOperationAction(ISD::FREM, VT, Expand);
825     setOperationAction(ISD::FMA,  VT, Expand);
826     setOperationAction(ISD::FPOWI, VT, Expand);
827     setOperationAction(ISD::FSQRT, VT, Expand);
828     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
829     setOperationAction(ISD::FFLOOR, VT, Expand);
830     setOperationAction(ISD::FCEIL, VT, Expand);
831     setOperationAction(ISD::FTRUNC, VT, Expand);
832     setOperationAction(ISD::FRINT, VT, Expand);
833     setOperationAction(ISD::FNEARBYINT, VT, Expand);
834     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
835     setOperationAction(ISD::MULHS, VT, Expand);
836     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
837     setOperationAction(ISD::MULHU, VT, Expand);
838     setOperationAction(ISD::SDIVREM, VT, Expand);
839     setOperationAction(ISD::UDIVREM, VT, Expand);
840     setOperationAction(ISD::FPOW, VT, Expand);
841     setOperationAction(ISD::CTPOP, VT, Expand);
842     setOperationAction(ISD::CTTZ, VT, Expand);
843     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
844     setOperationAction(ISD::CTLZ, VT, Expand);
845     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
846     setOperationAction(ISD::SHL, VT, Expand);
847     setOperationAction(ISD::SRA, VT, Expand);
848     setOperationAction(ISD::SRL, VT, Expand);
849     setOperationAction(ISD::ROTL, VT, Expand);
850     setOperationAction(ISD::ROTR, VT, Expand);
851     setOperationAction(ISD::BSWAP, VT, Expand);
852     setOperationAction(ISD::SETCC, VT, Expand);
853     setOperationAction(ISD::FLOG, VT, Expand);
854     setOperationAction(ISD::FLOG2, VT, Expand);
855     setOperationAction(ISD::FLOG10, VT, Expand);
856     setOperationAction(ISD::FEXP, VT, Expand);
857     setOperationAction(ISD::FEXP2, VT, Expand);
858     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
859     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
860     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
861     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
862     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
863     setOperationAction(ISD::TRUNCATE, VT, Expand);
864     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
865     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
866     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
867     setOperationAction(ISD::VSELECT, VT, Expand);
868     setOperationAction(ISD::SELECT_CC, VT, Expand);
869     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
870              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
871       setTruncStoreAction(VT,
872                           (MVT::SimpleValueType)InnerVT, Expand);
873     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
874     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
875     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
876   }
877
878   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
879   // with -msoft-float, disable use of MMX as well.
880   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
881     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
882     // No operations on x86mmx supported, everything uses intrinsics.
883   }
884
885   // MMX-sized vectors (other than x86mmx) are expected to be expanded
886   // into smaller operations.
887   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
888   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
889   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
890   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
891   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
892   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
893   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
894   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
895   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
896   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
897   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
898   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
899   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
900   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
901   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
902   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
903   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
904   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
905   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
906   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
907   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
908   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
909   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
910   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
911   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
912   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
913   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
914   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
915   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
916
917   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
918     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
919
920     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
921     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
922     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
923     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
924     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
925     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
926     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
927     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
928     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
929     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
930     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
931     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
932   }
933
934   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
935     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
936
937     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
938     // registers cannot be used even for integer operations.
939     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
940     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
941     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
942     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
943
944     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
945     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
946     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
947     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
948     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
949     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
950     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
951     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
952     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
953     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
954     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
955     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
956     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
957     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
958     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
959     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
960     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
961     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
962     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
963     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
964     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
965     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
966
967     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
968     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
969     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
970     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
971
972     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
973     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
974     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
975     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
976     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
977
978     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
979     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
980       MVT VT = (MVT::SimpleValueType)i;
981       // Do not attempt to custom lower non-power-of-2 vectors
982       if (!isPowerOf2_32(VT.getVectorNumElements()))
983         continue;
984       // Do not attempt to custom lower non-128-bit vectors
985       if (!VT.is128BitVector())
986         continue;
987       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
988       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
989       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
990     }
991
992     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
993     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
994     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
995     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
997     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
998
999     if (Subtarget->is64Bit()) {
1000       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1001       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1002     }
1003
1004     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1005     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1006       MVT VT = (MVT::SimpleValueType)i;
1007
1008       // Do not attempt to promote non-128-bit vectors
1009       if (!VT.is128BitVector())
1010         continue;
1011
1012       setOperationAction(ISD::AND,    VT, Promote);
1013       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1014       setOperationAction(ISD::OR,     VT, Promote);
1015       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1016       setOperationAction(ISD::XOR,    VT, Promote);
1017       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1018       setOperationAction(ISD::LOAD,   VT, Promote);
1019       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1020       setOperationAction(ISD::SELECT, VT, Promote);
1021       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1022     }
1023
1024     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1025
1026     // Custom lower v2i64 and v2f64 selects.
1027     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1028     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1029     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1030     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1031
1032     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1033     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1034
1035     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1036     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1037     // As there is no 64-bit GPR available, we need build a special custom
1038     // sequence to convert from v2i32 to v2f32.
1039     if (!Subtarget->is64Bit())
1040       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1041
1042     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1043     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1044
1045     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1046
1047     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1048     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1049     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1050   }
1051
1052   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1053     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1054     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1055     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1056     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1057     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1058     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1059     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1060     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1061     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1062     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1063
1064     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1065     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1066     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1067     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1068     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1074
1075     // FIXME: Do we need to handle scalar-to-vector here?
1076     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1077
1078     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1079     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1080     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1081     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1082     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1083     // There is no BLENDI for byte vectors. We don't need to custom lower
1084     // some vselects for now.
1085     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1086
1087     // i8 and i16 vectors are custom , because the source register and source
1088     // source memory operand types are not the same width.  f32 vectors are
1089     // custom since the immediate controlling the insert encodes additional
1090     // information.
1091     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1092     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1093     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1094     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1095
1096     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1097     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1098     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1099     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1100
1101     // FIXME: these should be Legal but thats only for the case where
1102     // the index is constant.  For now custom expand to deal with that.
1103     if (Subtarget->is64Bit()) {
1104       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1105       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1106     }
1107   }
1108
1109   if (Subtarget->hasSSE2()) {
1110     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1111     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1112
1113     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1114     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1115
1116     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1117     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1118
1119     // In the customized shift lowering, the legal cases in AVX2 will be
1120     // recognized.
1121     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1122     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1125     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1126
1127     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1128   }
1129
1130   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1131     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1132     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1133     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1134     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1135     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1136     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1137
1138     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1139     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1140     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1141
1142     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1143     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1144     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1145     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1146     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1147     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1148     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1149     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1150     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1151     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1152     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1153     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1154
1155     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1156     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1157     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1158     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1159     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1160     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1161     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1162     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1163     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1164     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1165     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1166     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1167
1168     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1169     // even though v8i16 is a legal type.
1170     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1171     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1172     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1173
1174     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1175     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1176     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1177
1178     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1179     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1180
1181     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1182
1183     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1184     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1185
1186     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1187     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1188
1189     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1190     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1191
1192     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1193     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1194     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1195     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1196
1197     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1198     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1199     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1200
1201     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1202     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1203     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1204     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1205
1206     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1207     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1208     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1209     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1210     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1211     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1212     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1213     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1214     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1215     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1216     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1217     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1218
1219     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1220       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1221       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1222       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1223       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1224       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1225       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1226     }
1227
1228     if (Subtarget->hasInt256()) {
1229       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1230       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1231       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1232       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1233
1234       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1235       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1236       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1237       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1238
1239       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1240       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1241       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1242       // Don't lower v32i8 because there is no 128-bit byte mul
1243
1244       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1245       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1246       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1247       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1248
1249       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1250       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1251     } else {
1252       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1253       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1254       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1255       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1256
1257       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1258       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1259       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1260       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1261
1262       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1263       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1264       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1265       // Don't lower v32i8 because there is no 128-bit byte mul
1266     }
1267
1268     // In the customized shift lowering, the legal cases in AVX2 will be
1269     // recognized.
1270     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1271     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1272
1273     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1274     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1275
1276     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1277
1278     // Custom lower several nodes for 256-bit types.
1279     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1280              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1281       MVT VT = (MVT::SimpleValueType)i;
1282
1283       // Extract subvector is special because the value type
1284       // (result) is 128-bit but the source is 256-bit wide.
1285       if (VT.is128BitVector())
1286         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1287
1288       // Do not attempt to custom lower other non-256-bit vectors
1289       if (!VT.is256BitVector())
1290         continue;
1291
1292       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1293       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1294       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1295       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1296       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1297       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1298       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1299     }
1300
1301     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1302     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1303       MVT VT = (MVT::SimpleValueType)i;
1304
1305       // Do not attempt to promote non-256-bit vectors
1306       if (!VT.is256BitVector())
1307         continue;
1308
1309       setOperationAction(ISD::AND,    VT, Promote);
1310       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1311       setOperationAction(ISD::OR,     VT, Promote);
1312       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1313       setOperationAction(ISD::XOR,    VT, Promote);
1314       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1315       setOperationAction(ISD::LOAD,   VT, Promote);
1316       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1317       setOperationAction(ISD::SELECT, VT, Promote);
1318       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1319     }
1320   }
1321
1322   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1323     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1324     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1325     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1326     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1327
1328     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1329     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1330     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1331
1332     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1333     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1334     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1335     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1336     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1337     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1338     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1339     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1340     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1341     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1342     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1343
1344     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1345     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1348     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1349     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1350
1351     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1352     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1353     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1354     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1355     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1356     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1357     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1358     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1359
1360     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1361     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1362     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1363     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1364     if (Subtarget->is64Bit()) {
1365       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1366       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1367       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1368       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1369     }
1370     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1371     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1373     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1374     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1375     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1376     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1378     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1379     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1380
1381     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1382     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1386     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1387     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1388     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1389     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1390     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1391     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1392     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1393     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1394
1395     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1396     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1397     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1398     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1399     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1400     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1401
1402     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1403     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1404
1405     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1406
1407     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1408     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1409     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1410     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1411     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1412     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1413     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1414     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1415     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1416
1417     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1418     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1419
1420     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1421     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1422
1423     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1424
1425     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1426     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1427
1428     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1429     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1430
1431     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1432     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1433
1434     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1435     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1436     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1437     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1438     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1439     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1440
1441     if (Subtarget->hasCDI()) {
1442       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1443       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1444     }
1445
1446     // Custom lower several nodes.
1447     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1448              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1449       MVT VT = (MVT::SimpleValueType)i;
1450
1451       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1452       // Extract subvector is special because the value type
1453       // (result) is 256/128-bit but the source is 512-bit wide.
1454       if (VT.is128BitVector() || VT.is256BitVector())
1455         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1456
1457       if (VT.getVectorElementType() == MVT::i1)
1458         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1459
1460       // Do not attempt to custom lower other non-512-bit vectors
1461       if (!VT.is512BitVector())
1462         continue;
1463
1464       if ( EltSize >= 32) {
1465         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1466         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1467         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1468         setOperationAction(ISD::VSELECT,             VT, Legal);
1469         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1470         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1471         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1472       }
1473     }
1474     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1475       MVT VT = (MVT::SimpleValueType)i;
1476
1477       // Do not attempt to promote non-256-bit vectors
1478       if (!VT.is512BitVector())
1479         continue;
1480
1481       setOperationAction(ISD::SELECT, VT, Promote);
1482       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1483     }
1484   }// has  AVX-512
1485
1486   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1487   // of this type with custom code.
1488   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1489            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1490     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1491                        Custom);
1492   }
1493
1494   // We want to custom lower some of our intrinsics.
1495   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1496   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1497   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1498   if (!Subtarget->is64Bit())
1499     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1500
1501   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1502   // handle type legalization for these operations here.
1503   //
1504   // FIXME: We really should do custom legalization for addition and
1505   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1506   // than generic legalization for 64-bit multiplication-with-overflow, though.
1507   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1508     // Add/Sub/Mul with overflow operations are custom lowered.
1509     MVT VT = IntVTs[i];
1510     setOperationAction(ISD::SADDO, VT, Custom);
1511     setOperationAction(ISD::UADDO, VT, Custom);
1512     setOperationAction(ISD::SSUBO, VT, Custom);
1513     setOperationAction(ISD::USUBO, VT, Custom);
1514     setOperationAction(ISD::SMULO, VT, Custom);
1515     setOperationAction(ISD::UMULO, VT, Custom);
1516   }
1517
1518   // There are no 8-bit 3-address imul/mul instructions
1519   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1520   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1521
1522   if (!Subtarget->is64Bit()) {
1523     // These libcalls are not available in 32-bit.
1524     setLibcallName(RTLIB::SHL_I128, nullptr);
1525     setLibcallName(RTLIB::SRL_I128, nullptr);
1526     setLibcallName(RTLIB::SRA_I128, nullptr);
1527   }
1528
1529   // Combine sin / cos into one node or libcall if possible.
1530   if (Subtarget->hasSinCos()) {
1531     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1532     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1533     if (Subtarget->isTargetDarwin()) {
1534       // For MacOSX, we don't want to the normal expansion of a libcall to
1535       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1536       // traffic.
1537       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1538       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1539     }
1540   }
1541
1542   if (Subtarget->isTargetWin64()) {
1543     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1544     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1545     setOperationAction(ISD::SREM, MVT::i128, Custom);
1546     setOperationAction(ISD::UREM, MVT::i128, Custom);
1547     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1548     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1549   }
1550
1551   // We have target-specific dag combine patterns for the following nodes:
1552   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1553   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1554   setTargetDAGCombine(ISD::VSELECT);
1555   setTargetDAGCombine(ISD::SELECT);
1556   setTargetDAGCombine(ISD::SHL);
1557   setTargetDAGCombine(ISD::SRA);
1558   setTargetDAGCombine(ISD::SRL);
1559   setTargetDAGCombine(ISD::OR);
1560   setTargetDAGCombine(ISD::AND);
1561   setTargetDAGCombine(ISD::ADD);
1562   setTargetDAGCombine(ISD::FADD);
1563   setTargetDAGCombine(ISD::FSUB);
1564   setTargetDAGCombine(ISD::FMA);
1565   setTargetDAGCombine(ISD::SUB);
1566   setTargetDAGCombine(ISD::LOAD);
1567   setTargetDAGCombine(ISD::STORE);
1568   setTargetDAGCombine(ISD::ZERO_EXTEND);
1569   setTargetDAGCombine(ISD::ANY_EXTEND);
1570   setTargetDAGCombine(ISD::SIGN_EXTEND);
1571   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1572   setTargetDAGCombine(ISD::TRUNCATE);
1573   setTargetDAGCombine(ISD::SINT_TO_FP);
1574   setTargetDAGCombine(ISD::SETCC);
1575   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1576   setTargetDAGCombine(ISD::BUILD_VECTOR);
1577   if (Subtarget->is64Bit())
1578     setTargetDAGCombine(ISD::MUL);
1579   setTargetDAGCombine(ISD::XOR);
1580
1581   computeRegisterProperties();
1582
1583   // On Darwin, -Os means optimize for size without hurting performance,
1584   // do not reduce the limit.
1585   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1586   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1587   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1588   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1589   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1590   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1591   setPrefLoopAlignment(4); // 2^4 bytes.
1592
1593   // Predictable cmov don't hurt on atom because it's in-order.
1594   PredictableSelectIsExpensive = !Subtarget->isAtom();
1595
1596   setPrefFunctionAlignment(4); // 2^4 bytes.
1597 }
1598
1599 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1600   if (!VT.isVector())
1601     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1602
1603   if (Subtarget->hasAVX512())
1604     switch(VT.getVectorNumElements()) {
1605     case  8: return MVT::v8i1;
1606     case 16: return MVT::v16i1;
1607   }
1608
1609   return VT.changeVectorElementTypeToInteger();
1610 }
1611
1612 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1613 /// the desired ByVal argument alignment.
1614 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1615   if (MaxAlign == 16)
1616     return;
1617   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1618     if (VTy->getBitWidth() == 128)
1619       MaxAlign = 16;
1620   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1621     unsigned EltAlign = 0;
1622     getMaxByValAlign(ATy->getElementType(), EltAlign);
1623     if (EltAlign > MaxAlign)
1624       MaxAlign = EltAlign;
1625   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1626     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1627       unsigned EltAlign = 0;
1628       getMaxByValAlign(STy->getElementType(i), EltAlign);
1629       if (EltAlign > MaxAlign)
1630         MaxAlign = EltAlign;
1631       if (MaxAlign == 16)
1632         break;
1633     }
1634   }
1635 }
1636
1637 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1638 /// function arguments in the caller parameter area. For X86, aggregates
1639 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1640 /// are at 4-byte boundaries.
1641 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1642   if (Subtarget->is64Bit()) {
1643     // Max of 8 and alignment of type.
1644     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1645     if (TyAlign > 8)
1646       return TyAlign;
1647     return 8;
1648   }
1649
1650   unsigned Align = 4;
1651   if (Subtarget->hasSSE1())
1652     getMaxByValAlign(Ty, Align);
1653   return Align;
1654 }
1655
1656 /// getOptimalMemOpType - Returns the target specific optimal type for load
1657 /// and store operations as a result of memset, memcpy, and memmove
1658 /// lowering. If DstAlign is zero that means it's safe to destination
1659 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1660 /// means there isn't a need to check it against alignment requirement,
1661 /// probably because the source does not need to be loaded. If 'IsMemset' is
1662 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1663 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1664 /// source is constant so it does not need to be loaded.
1665 /// It returns EVT::Other if the type should be determined using generic
1666 /// target-independent logic.
1667 EVT
1668 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1669                                        unsigned DstAlign, unsigned SrcAlign,
1670                                        bool IsMemset, bool ZeroMemset,
1671                                        bool MemcpyStrSrc,
1672                                        MachineFunction &MF) const {
1673   const Function *F = MF.getFunction();
1674   if ((!IsMemset || ZeroMemset) &&
1675       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1676                                        Attribute::NoImplicitFloat)) {
1677     if (Size >= 16 &&
1678         (Subtarget->isUnalignedMemAccessFast() ||
1679          ((DstAlign == 0 || DstAlign >= 16) &&
1680           (SrcAlign == 0 || SrcAlign >= 16)))) {
1681       if (Size >= 32) {
1682         if (Subtarget->hasInt256())
1683           return MVT::v8i32;
1684         if (Subtarget->hasFp256())
1685           return MVT::v8f32;
1686       }
1687       if (Subtarget->hasSSE2())
1688         return MVT::v4i32;
1689       if (Subtarget->hasSSE1())
1690         return MVT::v4f32;
1691     } else if (!MemcpyStrSrc && Size >= 8 &&
1692                !Subtarget->is64Bit() &&
1693                Subtarget->hasSSE2()) {
1694       // Do not use f64 to lower memcpy if source is string constant. It's
1695       // better to use i32 to avoid the loads.
1696       return MVT::f64;
1697     }
1698   }
1699   if (Subtarget->is64Bit() && Size >= 8)
1700     return MVT::i64;
1701   return MVT::i32;
1702 }
1703
1704 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1705   if (VT == MVT::f32)
1706     return X86ScalarSSEf32;
1707   else if (VT == MVT::f64)
1708     return X86ScalarSSEf64;
1709   return true;
1710 }
1711
1712 bool
1713 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1714                                                  unsigned,
1715                                                  bool *Fast) const {
1716   if (Fast)
1717     *Fast = Subtarget->isUnalignedMemAccessFast();
1718   return true;
1719 }
1720
1721 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1722 /// current function.  The returned value is a member of the
1723 /// MachineJumpTableInfo::JTEntryKind enum.
1724 unsigned X86TargetLowering::getJumpTableEncoding() const {
1725   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1726   // symbol.
1727   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1728       Subtarget->isPICStyleGOT())
1729     return MachineJumpTableInfo::EK_Custom32;
1730
1731   // Otherwise, use the normal jump table encoding heuristics.
1732   return TargetLowering::getJumpTableEncoding();
1733 }
1734
1735 const MCExpr *
1736 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1737                                              const MachineBasicBlock *MBB,
1738                                              unsigned uid,MCContext &Ctx) const{
1739   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1740          Subtarget->isPICStyleGOT());
1741   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1742   // entries.
1743   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1744                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1745 }
1746
1747 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1748 /// jumptable.
1749 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1750                                                     SelectionDAG &DAG) const {
1751   if (!Subtarget->is64Bit())
1752     // This doesn't have SDLoc associated with it, but is not really the
1753     // same as a Register.
1754     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1755   return Table;
1756 }
1757
1758 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1759 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1760 /// MCExpr.
1761 const MCExpr *X86TargetLowering::
1762 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1763                              MCContext &Ctx) const {
1764   // X86-64 uses RIP relative addressing based on the jump table label.
1765   if (Subtarget->isPICStyleRIPRel())
1766     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1767
1768   // Otherwise, the reference is relative to the PIC base.
1769   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1770 }
1771
1772 // FIXME: Why this routine is here? Move to RegInfo!
1773 std::pair<const TargetRegisterClass*, uint8_t>
1774 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1775   const TargetRegisterClass *RRC = nullptr;
1776   uint8_t Cost = 1;
1777   switch (VT.SimpleTy) {
1778   default:
1779     return TargetLowering::findRepresentativeClass(VT);
1780   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1781     RRC = Subtarget->is64Bit() ?
1782       (const TargetRegisterClass*)&X86::GR64RegClass :
1783       (const TargetRegisterClass*)&X86::GR32RegClass;
1784     break;
1785   case MVT::x86mmx:
1786     RRC = &X86::VR64RegClass;
1787     break;
1788   case MVT::f32: case MVT::f64:
1789   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1790   case MVT::v4f32: case MVT::v2f64:
1791   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1792   case MVT::v4f64:
1793     RRC = &X86::VR128RegClass;
1794     break;
1795   }
1796   return std::make_pair(RRC, Cost);
1797 }
1798
1799 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1800                                                unsigned &Offset) const {
1801   if (!Subtarget->isTargetLinux())
1802     return false;
1803
1804   if (Subtarget->is64Bit()) {
1805     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1806     Offset = 0x28;
1807     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1808       AddressSpace = 256;
1809     else
1810       AddressSpace = 257;
1811   } else {
1812     // %gs:0x14 on i386
1813     Offset = 0x14;
1814     AddressSpace = 256;
1815   }
1816   return true;
1817 }
1818
1819 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1820                                             unsigned DestAS) const {
1821   assert(SrcAS != DestAS && "Expected different address spaces!");
1822
1823   return SrcAS < 256 && DestAS < 256;
1824 }
1825
1826 //===----------------------------------------------------------------------===//
1827 //               Return Value Calling Convention Implementation
1828 //===----------------------------------------------------------------------===//
1829
1830 #include "X86GenCallingConv.inc"
1831
1832 bool
1833 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1834                                   MachineFunction &MF, bool isVarArg,
1835                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1836                         LLVMContext &Context) const {
1837   SmallVector<CCValAssign, 16> RVLocs;
1838   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1839                  RVLocs, Context);
1840   return CCInfo.CheckReturn(Outs, RetCC_X86);
1841 }
1842
1843 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1844   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1845   return ScratchRegs;
1846 }
1847
1848 SDValue
1849 X86TargetLowering::LowerReturn(SDValue Chain,
1850                                CallingConv::ID CallConv, bool isVarArg,
1851                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1852                                const SmallVectorImpl<SDValue> &OutVals,
1853                                SDLoc dl, SelectionDAG &DAG) const {
1854   MachineFunction &MF = DAG.getMachineFunction();
1855   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1856
1857   SmallVector<CCValAssign, 16> RVLocs;
1858   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1859                  RVLocs, *DAG.getContext());
1860   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1861
1862   SDValue Flag;
1863   SmallVector<SDValue, 6> RetOps;
1864   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1865   // Operand #1 = Bytes To Pop
1866   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1867                    MVT::i16));
1868
1869   // Copy the result values into the output registers.
1870   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1871     CCValAssign &VA = RVLocs[i];
1872     assert(VA.isRegLoc() && "Can only return in registers!");
1873     SDValue ValToCopy = OutVals[i];
1874     EVT ValVT = ValToCopy.getValueType();
1875
1876     // Promote values to the appropriate types
1877     if (VA.getLocInfo() == CCValAssign::SExt)
1878       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1879     else if (VA.getLocInfo() == CCValAssign::ZExt)
1880       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1881     else if (VA.getLocInfo() == CCValAssign::AExt)
1882       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1883     else if (VA.getLocInfo() == CCValAssign::BCvt)
1884       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1885
1886     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1887            "Unexpected FP-extend for return value.");  
1888
1889     // If this is x86-64, and we disabled SSE, we can't return FP values,
1890     // or SSE or MMX vectors.
1891     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1892          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1893           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1894       report_fatal_error("SSE register return with SSE disabled");
1895     }
1896     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1897     // llvm-gcc has never done it right and no one has noticed, so this
1898     // should be OK for now.
1899     if (ValVT == MVT::f64 &&
1900         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1901       report_fatal_error("SSE2 register return with SSE2 disabled");
1902
1903     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1904     // the RET instruction and handled by the FP Stackifier.
1905     if (VA.getLocReg() == X86::ST0 ||
1906         VA.getLocReg() == X86::ST1) {
1907       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1908       // change the value to the FP stack register class.
1909       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1910         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1911       RetOps.push_back(ValToCopy);
1912       // Don't emit a copytoreg.
1913       continue;
1914     }
1915
1916     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1917     // which is returned in RAX / RDX.
1918     if (Subtarget->is64Bit()) {
1919       if (ValVT == MVT::x86mmx) {
1920         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1921           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1922           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1923                                   ValToCopy);
1924           // If we don't have SSE2 available, convert to v4f32 so the generated
1925           // register is legal.
1926           if (!Subtarget->hasSSE2())
1927             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1928         }
1929       }
1930     }
1931
1932     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1933     Flag = Chain.getValue(1);
1934     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1935   }
1936
1937   // The x86-64 ABIs require that for returning structs by value we copy
1938   // the sret argument into %rax/%eax (depending on ABI) for the return.
1939   // Win32 requires us to put the sret argument to %eax as well.
1940   // We saved the argument into a virtual register in the entry block,
1941   // so now we copy the value out and into %rax/%eax.
1942   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1943       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1944     MachineFunction &MF = DAG.getMachineFunction();
1945     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1946     unsigned Reg = FuncInfo->getSRetReturnReg();
1947     assert(Reg &&
1948            "SRetReturnReg should have been set in LowerFormalArguments().");
1949     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1950
1951     unsigned RetValReg
1952         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1953           X86::RAX : X86::EAX;
1954     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1955     Flag = Chain.getValue(1);
1956
1957     // RAX/EAX now acts like a return value.
1958     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1959   }
1960
1961   RetOps[0] = Chain;  // Update chain.
1962
1963   // Add the flag if we have it.
1964   if (Flag.getNode())
1965     RetOps.push_back(Flag);
1966
1967   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1968 }
1969
1970 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1971   if (N->getNumValues() != 1)
1972     return false;
1973   if (!N->hasNUsesOfValue(1, 0))
1974     return false;
1975
1976   SDValue TCChain = Chain;
1977   SDNode *Copy = *N->use_begin();
1978   if (Copy->getOpcode() == ISD::CopyToReg) {
1979     // If the copy has a glue operand, we conservatively assume it isn't safe to
1980     // perform a tail call.
1981     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1982       return false;
1983     TCChain = Copy->getOperand(0);
1984   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1985     return false;
1986
1987   bool HasRet = false;
1988   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1989        UI != UE; ++UI) {
1990     if (UI->getOpcode() != X86ISD::RET_FLAG)
1991       return false;
1992     HasRet = true;
1993   }
1994
1995   if (!HasRet)
1996     return false;
1997
1998   Chain = TCChain;
1999   return true;
2000 }
2001
2002 MVT
2003 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2004                                             ISD::NodeType ExtendKind) const {
2005   MVT ReturnMVT;
2006   // TODO: Is this also valid on 32-bit?
2007   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2008     ReturnMVT = MVT::i8;
2009   else
2010     ReturnMVT = MVT::i32;
2011
2012   MVT MinVT = getRegisterType(ReturnMVT);
2013   return VT.bitsLT(MinVT) ? MinVT : VT;
2014 }
2015
2016 /// LowerCallResult - Lower the result values of a call into the
2017 /// appropriate copies out of appropriate physical registers.
2018 ///
2019 SDValue
2020 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2021                                    CallingConv::ID CallConv, bool isVarArg,
2022                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2023                                    SDLoc dl, SelectionDAG &DAG,
2024                                    SmallVectorImpl<SDValue> &InVals) const {
2025
2026   // Assign locations to each value returned by this call.
2027   SmallVector<CCValAssign, 16> RVLocs;
2028   bool Is64Bit = Subtarget->is64Bit();
2029   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2030                  DAG.getTarget(), RVLocs, *DAG.getContext());
2031   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2032
2033   // Copy all of the result registers out of their specified physreg.
2034   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2035     CCValAssign &VA = RVLocs[i];
2036     EVT CopyVT = VA.getValVT();
2037
2038     // If this is x86-64, and we disabled SSE, we can't return FP values
2039     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2040         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2041       report_fatal_error("SSE register return with SSE disabled");
2042     }
2043
2044     SDValue Val;
2045
2046     // If this is a call to a function that returns an fp value on the floating
2047     // point stack, we must guarantee the value is popped from the stack, so
2048     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2049     // if the return value is not used. We use the FpPOP_RETVAL instruction
2050     // instead.
2051     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2052       // If we prefer to use the value in xmm registers, copy it out as f80 and
2053       // use a truncate to move it from fp stack reg to xmm reg.
2054       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2055       SDValue Ops[] = { Chain, InFlag };
2056       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2057                                          MVT::Other, MVT::Glue, Ops), 1);
2058       Val = Chain.getValue(0);
2059
2060       // Round the f80 to the right size, which also moves it to the appropriate
2061       // xmm register.
2062       if (CopyVT != VA.getValVT())
2063         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2064                           // This truncation won't change the value.
2065                           DAG.getIntPtrConstant(1));
2066     } else {
2067       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2068                                  CopyVT, InFlag).getValue(1);
2069       Val = Chain.getValue(0);
2070     }
2071     InFlag = Chain.getValue(2);
2072     InVals.push_back(Val);
2073   }
2074
2075   return Chain;
2076 }
2077
2078 //===----------------------------------------------------------------------===//
2079 //                C & StdCall & Fast Calling Convention implementation
2080 //===----------------------------------------------------------------------===//
2081 //  StdCall calling convention seems to be standard for many Windows' API
2082 //  routines and around. It differs from C calling convention just a little:
2083 //  callee should clean up the stack, not caller. Symbols should be also
2084 //  decorated in some fancy way :) It doesn't support any vector arguments.
2085 //  For info on fast calling convention see Fast Calling Convention (tail call)
2086 //  implementation LowerX86_32FastCCCallTo.
2087
2088 /// CallIsStructReturn - Determines whether a call uses struct return
2089 /// semantics.
2090 enum StructReturnType {
2091   NotStructReturn,
2092   RegStructReturn,
2093   StackStructReturn
2094 };
2095 static StructReturnType
2096 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2097   if (Outs.empty())
2098     return NotStructReturn;
2099
2100   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2101   if (!Flags.isSRet())
2102     return NotStructReturn;
2103   if (Flags.isInReg())
2104     return RegStructReturn;
2105   return StackStructReturn;
2106 }
2107
2108 /// ArgsAreStructReturn - Determines whether a function uses struct
2109 /// return semantics.
2110 static StructReturnType
2111 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2112   if (Ins.empty())
2113     return NotStructReturn;
2114
2115   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2116   if (!Flags.isSRet())
2117     return NotStructReturn;
2118   if (Flags.isInReg())
2119     return RegStructReturn;
2120   return StackStructReturn;
2121 }
2122
2123 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2124 /// by "Src" to address "Dst" with size and alignment information specified by
2125 /// the specific parameter attribute. The copy will be passed as a byval
2126 /// function parameter.
2127 static SDValue
2128 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2129                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2130                           SDLoc dl) {
2131   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2132
2133   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2134                        /*isVolatile*/false, /*AlwaysInline=*/true,
2135                        MachinePointerInfo(), MachinePointerInfo());
2136 }
2137
2138 /// IsTailCallConvention - Return true if the calling convention is one that
2139 /// supports tail call optimization.
2140 static bool IsTailCallConvention(CallingConv::ID CC) {
2141   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2142           CC == CallingConv::HiPE);
2143 }
2144
2145 /// \brief Return true if the calling convention is a C calling convention.
2146 static bool IsCCallConvention(CallingConv::ID CC) {
2147   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2148           CC == CallingConv::X86_64_SysV);
2149 }
2150
2151 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2152   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2153     return false;
2154
2155   CallSite CS(CI);
2156   CallingConv::ID CalleeCC = CS.getCallingConv();
2157   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2158     return false;
2159
2160   return true;
2161 }
2162
2163 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2164 /// a tailcall target by changing its ABI.
2165 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2166                                    bool GuaranteedTailCallOpt) {
2167   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2168 }
2169
2170 SDValue
2171 X86TargetLowering::LowerMemArgument(SDValue Chain,
2172                                     CallingConv::ID CallConv,
2173                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2174                                     SDLoc dl, SelectionDAG &DAG,
2175                                     const CCValAssign &VA,
2176                                     MachineFrameInfo *MFI,
2177                                     unsigned i) const {
2178   // Create the nodes corresponding to a load from this parameter slot.
2179   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2180   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2181       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2182   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2183   EVT ValVT;
2184
2185   // If value is passed by pointer we have address passed instead of the value
2186   // itself.
2187   if (VA.getLocInfo() == CCValAssign::Indirect)
2188     ValVT = VA.getLocVT();
2189   else
2190     ValVT = VA.getValVT();
2191
2192   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2193   // changed with more analysis.
2194   // In case of tail call optimization mark all arguments mutable. Since they
2195   // could be overwritten by lowering of arguments in case of a tail call.
2196   if (Flags.isByVal()) {
2197     unsigned Bytes = Flags.getByValSize();
2198     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2199     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2200     return DAG.getFrameIndex(FI, getPointerTy());
2201   } else {
2202     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2203                                     VA.getLocMemOffset(), isImmutable);
2204     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2205     return DAG.getLoad(ValVT, dl, Chain, FIN,
2206                        MachinePointerInfo::getFixedStack(FI),
2207                        false, false, false, 0);
2208   }
2209 }
2210
2211 SDValue
2212 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2213                                         CallingConv::ID CallConv,
2214                                         bool isVarArg,
2215                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2216                                         SDLoc dl,
2217                                         SelectionDAG &DAG,
2218                                         SmallVectorImpl<SDValue> &InVals)
2219                                           const {
2220   MachineFunction &MF = DAG.getMachineFunction();
2221   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2222
2223   const Function* Fn = MF.getFunction();
2224   if (Fn->hasExternalLinkage() &&
2225       Subtarget->isTargetCygMing() &&
2226       Fn->getName() == "main")
2227     FuncInfo->setForceFramePointer(true);
2228
2229   MachineFrameInfo *MFI = MF.getFrameInfo();
2230   bool Is64Bit = Subtarget->is64Bit();
2231   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2232
2233   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2234          "Var args not supported with calling convention fastcc, ghc or hipe");
2235
2236   // Assign locations to all of the incoming arguments.
2237   SmallVector<CCValAssign, 16> ArgLocs;
2238   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2239                  ArgLocs, *DAG.getContext());
2240
2241   // Allocate shadow area for Win64
2242   if (IsWin64)
2243     CCInfo.AllocateStack(32, 8);
2244
2245   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2246
2247   unsigned LastVal = ~0U;
2248   SDValue ArgValue;
2249   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2250     CCValAssign &VA = ArgLocs[i];
2251     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2252     // places.
2253     assert(VA.getValNo() != LastVal &&
2254            "Don't support value assigned to multiple locs yet");
2255     (void)LastVal;
2256     LastVal = VA.getValNo();
2257
2258     if (VA.isRegLoc()) {
2259       EVT RegVT = VA.getLocVT();
2260       const TargetRegisterClass *RC;
2261       if (RegVT == MVT::i32)
2262         RC = &X86::GR32RegClass;
2263       else if (Is64Bit && RegVT == MVT::i64)
2264         RC = &X86::GR64RegClass;
2265       else if (RegVT == MVT::f32)
2266         RC = &X86::FR32RegClass;
2267       else if (RegVT == MVT::f64)
2268         RC = &X86::FR64RegClass;
2269       else if (RegVT.is512BitVector())
2270         RC = &X86::VR512RegClass;
2271       else if (RegVT.is256BitVector())
2272         RC = &X86::VR256RegClass;
2273       else if (RegVT.is128BitVector())
2274         RC = &X86::VR128RegClass;
2275       else if (RegVT == MVT::x86mmx)
2276         RC = &X86::VR64RegClass;
2277       else if (RegVT == MVT::i1)
2278         RC = &X86::VK1RegClass;
2279       else if (RegVT == MVT::v8i1)
2280         RC = &X86::VK8RegClass;
2281       else if (RegVT == MVT::v16i1)
2282         RC = &X86::VK16RegClass;
2283       else
2284         llvm_unreachable("Unknown argument type!");
2285
2286       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2287       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2288
2289       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2290       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2291       // right size.
2292       if (VA.getLocInfo() == CCValAssign::SExt)
2293         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2294                                DAG.getValueType(VA.getValVT()));
2295       else if (VA.getLocInfo() == CCValAssign::ZExt)
2296         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2297                                DAG.getValueType(VA.getValVT()));
2298       else if (VA.getLocInfo() == CCValAssign::BCvt)
2299         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2300
2301       if (VA.isExtInLoc()) {
2302         // Handle MMX values passed in XMM regs.
2303         if (RegVT.isVector())
2304           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2305         else
2306           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2307       }
2308     } else {
2309       assert(VA.isMemLoc());
2310       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2311     }
2312
2313     // If value is passed via pointer - do a load.
2314     if (VA.getLocInfo() == CCValAssign::Indirect)
2315       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2316                              MachinePointerInfo(), false, false, false, 0);
2317
2318     InVals.push_back(ArgValue);
2319   }
2320
2321   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2322     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2323       // The x86-64 ABIs require that for returning structs by value we copy
2324       // the sret argument into %rax/%eax (depending on ABI) for the return.
2325       // Win32 requires us to put the sret argument to %eax as well.
2326       // Save the argument into a virtual register so that we can access it
2327       // from the return points.
2328       if (Ins[i].Flags.isSRet()) {
2329         unsigned Reg = FuncInfo->getSRetReturnReg();
2330         if (!Reg) {
2331           MVT PtrTy = getPointerTy();
2332           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2333           FuncInfo->setSRetReturnReg(Reg);
2334         }
2335         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2336         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2337         break;
2338       }
2339     }
2340   }
2341
2342   unsigned StackSize = CCInfo.getNextStackOffset();
2343   // Align stack specially for tail calls.
2344   if (FuncIsMadeTailCallSafe(CallConv,
2345                              MF.getTarget().Options.GuaranteedTailCallOpt))
2346     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2347
2348   // If the function takes variable number of arguments, make a frame index for
2349   // the start of the first vararg value... for expansion of llvm.va_start.
2350   if (isVarArg) {
2351     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2352                     CallConv != CallingConv::X86_ThisCall)) {
2353       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2354     }
2355     if (Is64Bit) {
2356       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2357
2358       // FIXME: We should really autogenerate these arrays
2359       static const MCPhysReg GPR64ArgRegsWin64[] = {
2360         X86::RCX, X86::RDX, X86::R8,  X86::R9
2361       };
2362       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2363         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2364       };
2365       static const MCPhysReg XMMArgRegs64Bit[] = {
2366         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2367         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2368       };
2369       const MCPhysReg *GPR64ArgRegs;
2370       unsigned NumXMMRegs = 0;
2371
2372       if (IsWin64) {
2373         // The XMM registers which might contain var arg parameters are shadowed
2374         // in their paired GPR.  So we only need to save the GPR to their home
2375         // slots.
2376         TotalNumIntRegs = 4;
2377         GPR64ArgRegs = GPR64ArgRegsWin64;
2378       } else {
2379         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2380         GPR64ArgRegs = GPR64ArgRegs64Bit;
2381
2382         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2383                                                 TotalNumXMMRegs);
2384       }
2385       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2386                                                        TotalNumIntRegs);
2387
2388       bool NoImplicitFloatOps = Fn->getAttributes().
2389         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2390       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2391              "SSE register cannot be used when SSE is disabled!");
2392       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2393                NoImplicitFloatOps) &&
2394              "SSE register cannot be used when SSE is disabled!");
2395       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2396           !Subtarget->hasSSE1())
2397         // Kernel mode asks for SSE to be disabled, so don't push them
2398         // on the stack.
2399         TotalNumXMMRegs = 0;
2400
2401       if (IsWin64) {
2402         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2403         // Get to the caller-allocated home save location.  Add 8 to account
2404         // for the return address.
2405         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2406         FuncInfo->setRegSaveFrameIndex(
2407           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2408         // Fixup to set vararg frame on shadow area (4 x i64).
2409         if (NumIntRegs < 4)
2410           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2411       } else {
2412         // For X86-64, if there are vararg parameters that are passed via
2413         // registers, then we must store them to their spots on the stack so
2414         // they may be loaded by deferencing the result of va_next.
2415         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2416         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2417         FuncInfo->setRegSaveFrameIndex(
2418           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2419                                false));
2420       }
2421
2422       // Store the integer parameter registers.
2423       SmallVector<SDValue, 8> MemOps;
2424       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2425                                         getPointerTy());
2426       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2427       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2428         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2429                                   DAG.getIntPtrConstant(Offset));
2430         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2431                                      &X86::GR64RegClass);
2432         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2433         SDValue Store =
2434           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2435                        MachinePointerInfo::getFixedStack(
2436                          FuncInfo->getRegSaveFrameIndex(), Offset),
2437                        false, false, 0);
2438         MemOps.push_back(Store);
2439         Offset += 8;
2440       }
2441
2442       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2443         // Now store the XMM (fp + vector) parameter registers.
2444         SmallVector<SDValue, 11> SaveXMMOps;
2445         SaveXMMOps.push_back(Chain);
2446
2447         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2448         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2449         SaveXMMOps.push_back(ALVal);
2450
2451         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2452                                FuncInfo->getRegSaveFrameIndex()));
2453         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2454                                FuncInfo->getVarArgsFPOffset()));
2455
2456         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2457           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2458                                        &X86::VR128RegClass);
2459           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2460           SaveXMMOps.push_back(Val);
2461         }
2462         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2463                                      MVT::Other, SaveXMMOps));
2464       }
2465
2466       if (!MemOps.empty())
2467         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2468     }
2469   }
2470
2471   // Some CCs need callee pop.
2472   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2473                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2474     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2475   } else {
2476     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2477     // If this is an sret function, the return should pop the hidden pointer.
2478     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2479         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2480         argsAreStructReturn(Ins) == StackStructReturn)
2481       FuncInfo->setBytesToPopOnReturn(4);
2482   }
2483
2484   if (!Is64Bit) {
2485     // RegSaveFrameIndex is X86-64 only.
2486     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2487     if (CallConv == CallingConv::X86_FastCall ||
2488         CallConv == CallingConv::X86_ThisCall)
2489       // fastcc functions can't have varargs.
2490       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2491   }
2492
2493   FuncInfo->setArgumentStackSize(StackSize);
2494
2495   return Chain;
2496 }
2497
2498 SDValue
2499 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2500                                     SDValue StackPtr, SDValue Arg,
2501                                     SDLoc dl, SelectionDAG &DAG,
2502                                     const CCValAssign &VA,
2503                                     ISD::ArgFlagsTy Flags) const {
2504   unsigned LocMemOffset = VA.getLocMemOffset();
2505   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2506   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2507   if (Flags.isByVal())
2508     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2509
2510   return DAG.getStore(Chain, dl, Arg, PtrOff,
2511                       MachinePointerInfo::getStack(LocMemOffset),
2512                       false, false, 0);
2513 }
2514
2515 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2516 /// optimization is performed and it is required.
2517 SDValue
2518 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2519                                            SDValue &OutRetAddr, SDValue Chain,
2520                                            bool IsTailCall, bool Is64Bit,
2521                                            int FPDiff, SDLoc dl) const {
2522   // Adjust the Return address stack slot.
2523   EVT VT = getPointerTy();
2524   OutRetAddr = getReturnAddressFrameIndex(DAG);
2525
2526   // Load the "old" Return address.
2527   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2528                            false, false, false, 0);
2529   return SDValue(OutRetAddr.getNode(), 1);
2530 }
2531
2532 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2533 /// optimization is performed and it is required (FPDiff!=0).
2534 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2535                                         SDValue Chain, SDValue RetAddrFrIdx,
2536                                         EVT PtrVT, unsigned SlotSize,
2537                                         int FPDiff, SDLoc dl) {
2538   // Store the return address to the appropriate stack slot.
2539   if (!FPDiff) return Chain;
2540   // Calculate the new stack slot for the return address.
2541   int NewReturnAddrFI =
2542     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2543                                          false);
2544   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2545   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2546                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2547                        false, false, 0);
2548   return Chain;
2549 }
2550
2551 SDValue
2552 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2553                              SmallVectorImpl<SDValue> &InVals) const {
2554   SelectionDAG &DAG                     = CLI.DAG;
2555   SDLoc &dl                             = CLI.DL;
2556   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2557   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2558   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2559   SDValue Chain                         = CLI.Chain;
2560   SDValue Callee                        = CLI.Callee;
2561   CallingConv::ID CallConv              = CLI.CallConv;
2562   bool &isTailCall                      = CLI.IsTailCall;
2563   bool isVarArg                         = CLI.IsVarArg;
2564
2565   MachineFunction &MF = DAG.getMachineFunction();
2566   bool Is64Bit        = Subtarget->is64Bit();
2567   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2568   StructReturnType SR = callIsStructReturn(Outs);
2569   bool IsSibcall      = false;
2570
2571   if (MF.getTarget().Options.DisableTailCalls)
2572     isTailCall = false;
2573
2574   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2575   if (IsMustTail) {
2576     // Force this to be a tail call.  The verifier rules are enough to ensure
2577     // that we can lower this successfully without moving the return address
2578     // around.
2579     isTailCall = true;
2580   } else if (isTailCall) {
2581     // Check if it's really possible to do a tail call.
2582     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2583                     isVarArg, SR != NotStructReturn,
2584                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2585                     Outs, OutVals, Ins, DAG);
2586
2587     // Sibcalls are automatically detected tailcalls which do not require
2588     // ABI changes.
2589     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2590       IsSibcall = true;
2591
2592     if (isTailCall)
2593       ++NumTailCalls;
2594   }
2595
2596   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2597          "Var args not supported with calling convention fastcc, ghc or hipe");
2598
2599   // Analyze operands of the call, assigning locations to each operand.
2600   SmallVector<CCValAssign, 16> ArgLocs;
2601   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2602                  ArgLocs, *DAG.getContext());
2603
2604   // Allocate shadow area for Win64
2605   if (IsWin64)
2606     CCInfo.AllocateStack(32, 8);
2607
2608   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2609
2610   // Get a count of how many bytes are to be pushed on the stack.
2611   unsigned NumBytes = CCInfo.getNextStackOffset();
2612   if (IsSibcall)
2613     // This is a sibcall. The memory operands are available in caller's
2614     // own caller's stack.
2615     NumBytes = 0;
2616   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2617            IsTailCallConvention(CallConv))
2618     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2619
2620   int FPDiff = 0;
2621   if (isTailCall && !IsSibcall && !IsMustTail) {
2622     // Lower arguments at fp - stackoffset + fpdiff.
2623     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2624     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2625
2626     FPDiff = NumBytesCallerPushed - NumBytes;
2627
2628     // Set the delta of movement of the returnaddr stackslot.
2629     // But only set if delta is greater than previous delta.
2630     if (FPDiff < X86Info->getTCReturnAddrDelta())
2631       X86Info->setTCReturnAddrDelta(FPDiff);
2632   }
2633
2634   unsigned NumBytesToPush = NumBytes;
2635   unsigned NumBytesToPop = NumBytes;
2636
2637   // If we have an inalloca argument, all stack space has already been allocated
2638   // for us and be right at the top of the stack.  We don't support multiple
2639   // arguments passed in memory when using inalloca.
2640   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2641     NumBytesToPush = 0;
2642     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2643            "an inalloca argument must be the only memory argument");
2644   }
2645
2646   if (!IsSibcall)
2647     Chain = DAG.getCALLSEQ_START(
2648         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2649
2650   SDValue RetAddrFrIdx;
2651   // Load return address for tail calls.
2652   if (isTailCall && FPDiff)
2653     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2654                                     Is64Bit, FPDiff, dl);
2655
2656   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2657   SmallVector<SDValue, 8> MemOpChains;
2658   SDValue StackPtr;
2659
2660   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2661   // of tail call optimization arguments are handle later.
2662   const X86RegisterInfo *RegInfo =
2663     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2664   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2665     // Skip inalloca arguments, they have already been written.
2666     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2667     if (Flags.isInAlloca())
2668       continue;
2669
2670     CCValAssign &VA = ArgLocs[i];
2671     EVT RegVT = VA.getLocVT();
2672     SDValue Arg = OutVals[i];
2673     bool isByVal = Flags.isByVal();
2674
2675     // Promote the value if needed.
2676     switch (VA.getLocInfo()) {
2677     default: llvm_unreachable("Unknown loc info!");
2678     case CCValAssign::Full: break;
2679     case CCValAssign::SExt:
2680       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2681       break;
2682     case CCValAssign::ZExt:
2683       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2684       break;
2685     case CCValAssign::AExt:
2686       if (RegVT.is128BitVector()) {
2687         // Special case: passing MMX values in XMM registers.
2688         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2689         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2690         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2691       } else
2692         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2693       break;
2694     case CCValAssign::BCvt:
2695       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2696       break;
2697     case CCValAssign::Indirect: {
2698       // Store the argument.
2699       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2700       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2701       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2702                            MachinePointerInfo::getFixedStack(FI),
2703                            false, false, 0);
2704       Arg = SpillSlot;
2705       break;
2706     }
2707     }
2708
2709     if (VA.isRegLoc()) {
2710       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2711       if (isVarArg && IsWin64) {
2712         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2713         // shadow reg if callee is a varargs function.
2714         unsigned ShadowReg = 0;
2715         switch (VA.getLocReg()) {
2716         case X86::XMM0: ShadowReg = X86::RCX; break;
2717         case X86::XMM1: ShadowReg = X86::RDX; break;
2718         case X86::XMM2: ShadowReg = X86::R8; break;
2719         case X86::XMM3: ShadowReg = X86::R9; break;
2720         }
2721         if (ShadowReg)
2722           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2723       }
2724     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2725       assert(VA.isMemLoc());
2726       if (!StackPtr.getNode())
2727         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2728                                       getPointerTy());
2729       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2730                                              dl, DAG, VA, Flags));
2731     }
2732   }
2733
2734   if (!MemOpChains.empty())
2735     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2736
2737   if (Subtarget->isPICStyleGOT()) {
2738     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2739     // GOT pointer.
2740     if (!isTailCall) {
2741       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2742                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2743     } else {
2744       // If we are tail calling and generating PIC/GOT style code load the
2745       // address of the callee into ECX. The value in ecx is used as target of
2746       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2747       // for tail calls on PIC/GOT architectures. Normally we would just put the
2748       // address of GOT into ebx and then call target@PLT. But for tail calls
2749       // ebx would be restored (since ebx is callee saved) before jumping to the
2750       // target@PLT.
2751
2752       // Note: The actual moving to ECX is done further down.
2753       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2754       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2755           !G->getGlobal()->hasProtectedVisibility())
2756         Callee = LowerGlobalAddress(Callee, DAG);
2757       else if (isa<ExternalSymbolSDNode>(Callee))
2758         Callee = LowerExternalSymbol(Callee, DAG);
2759     }
2760   }
2761
2762   if (Is64Bit && isVarArg && !IsWin64) {
2763     // From AMD64 ABI document:
2764     // For calls that may call functions that use varargs or stdargs
2765     // (prototype-less calls or calls to functions containing ellipsis (...) in
2766     // the declaration) %al is used as hidden argument to specify the number
2767     // of SSE registers used. The contents of %al do not need to match exactly
2768     // the number of registers, but must be an ubound on the number of SSE
2769     // registers used and is in the range 0 - 8 inclusive.
2770
2771     // Count the number of XMM registers allocated.
2772     static const MCPhysReg XMMArgRegs[] = {
2773       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2774       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2775     };
2776     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2777     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2778            && "SSE registers cannot be used when SSE is disabled");
2779
2780     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2781                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2782   }
2783
2784   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2785   // don't need this because the eligibility check rejects calls that require
2786   // shuffling arguments passed in memory.
2787   if (!IsSibcall && isTailCall) {
2788     // Force all the incoming stack arguments to be loaded from the stack
2789     // before any new outgoing arguments are stored to the stack, because the
2790     // outgoing stack slots may alias the incoming argument stack slots, and
2791     // the alias isn't otherwise explicit. This is slightly more conservative
2792     // than necessary, because it means that each store effectively depends
2793     // on every argument instead of just those arguments it would clobber.
2794     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2795
2796     SmallVector<SDValue, 8> MemOpChains2;
2797     SDValue FIN;
2798     int FI = 0;
2799     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2800       CCValAssign &VA = ArgLocs[i];
2801       if (VA.isRegLoc())
2802         continue;
2803       assert(VA.isMemLoc());
2804       SDValue Arg = OutVals[i];
2805       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2806       // Skip inalloca arguments.  They don't require any work.
2807       if (Flags.isInAlloca())
2808         continue;
2809       // Create frame index.
2810       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2811       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2812       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2813       FIN = DAG.getFrameIndex(FI, getPointerTy());
2814
2815       if (Flags.isByVal()) {
2816         // Copy relative to framepointer.
2817         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2818         if (!StackPtr.getNode())
2819           StackPtr = DAG.getCopyFromReg(Chain, dl,
2820                                         RegInfo->getStackRegister(),
2821                                         getPointerTy());
2822         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2823
2824         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2825                                                          ArgChain,
2826                                                          Flags, DAG, dl));
2827       } else {
2828         // Store relative to framepointer.
2829         MemOpChains2.push_back(
2830           DAG.getStore(ArgChain, dl, Arg, FIN,
2831                        MachinePointerInfo::getFixedStack(FI),
2832                        false, false, 0));
2833       }
2834     }
2835
2836     if (!MemOpChains2.empty())
2837       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2838
2839     // Store the return address to the appropriate stack slot.
2840     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2841                                      getPointerTy(), RegInfo->getSlotSize(),
2842                                      FPDiff, dl);
2843   }
2844
2845   // Build a sequence of copy-to-reg nodes chained together with token chain
2846   // and flag operands which copy the outgoing args into registers.
2847   SDValue InFlag;
2848   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2849     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2850                              RegsToPass[i].second, InFlag);
2851     InFlag = Chain.getValue(1);
2852   }
2853
2854   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2855     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2856     // In the 64-bit large code model, we have to make all calls
2857     // through a register, since the call instruction's 32-bit
2858     // pc-relative offset may not be large enough to hold the whole
2859     // address.
2860   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2861     // If the callee is a GlobalAddress node (quite common, every direct call
2862     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2863     // it.
2864
2865     // We should use extra load for direct calls to dllimported functions in
2866     // non-JIT mode.
2867     const GlobalValue *GV = G->getGlobal();
2868     if (!GV->hasDLLImportStorageClass()) {
2869       unsigned char OpFlags = 0;
2870       bool ExtraLoad = false;
2871       unsigned WrapperKind = ISD::DELETED_NODE;
2872
2873       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2874       // external symbols most go through the PLT in PIC mode.  If the symbol
2875       // has hidden or protected visibility, or if it is static or local, then
2876       // we don't need to use the PLT - we can directly call it.
2877       if (Subtarget->isTargetELF() &&
2878           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2879           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2880         OpFlags = X86II::MO_PLT;
2881       } else if (Subtarget->isPICStyleStubAny() &&
2882                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2883                  (!Subtarget->getTargetTriple().isMacOSX() ||
2884                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2885         // PC-relative references to external symbols should go through $stub,
2886         // unless we're building with the leopard linker or later, which
2887         // automatically synthesizes these stubs.
2888         OpFlags = X86II::MO_DARWIN_STUB;
2889       } else if (Subtarget->isPICStyleRIPRel() &&
2890                  isa<Function>(GV) &&
2891                  cast<Function>(GV)->getAttributes().
2892                    hasAttribute(AttributeSet::FunctionIndex,
2893                                 Attribute::NonLazyBind)) {
2894         // If the function is marked as non-lazy, generate an indirect call
2895         // which loads from the GOT directly. This avoids runtime overhead
2896         // at the cost of eager binding (and one extra byte of encoding).
2897         OpFlags = X86II::MO_GOTPCREL;
2898         WrapperKind = X86ISD::WrapperRIP;
2899         ExtraLoad = true;
2900       }
2901
2902       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2903                                           G->getOffset(), OpFlags);
2904
2905       // Add a wrapper if needed.
2906       if (WrapperKind != ISD::DELETED_NODE)
2907         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2908       // Add extra indirection if needed.
2909       if (ExtraLoad)
2910         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2911                              MachinePointerInfo::getGOT(),
2912                              false, false, false, 0);
2913     }
2914   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2915     unsigned char OpFlags = 0;
2916
2917     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2918     // external symbols should go through the PLT.
2919     if (Subtarget->isTargetELF() &&
2920         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2921       OpFlags = X86II::MO_PLT;
2922     } else if (Subtarget->isPICStyleStubAny() &&
2923                (!Subtarget->getTargetTriple().isMacOSX() ||
2924                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2925       // PC-relative references to external symbols should go through $stub,
2926       // unless we're building with the leopard linker or later, which
2927       // automatically synthesizes these stubs.
2928       OpFlags = X86II::MO_DARWIN_STUB;
2929     }
2930
2931     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2932                                          OpFlags);
2933   }
2934
2935   // Returns a chain & a flag for retval copy to use.
2936   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2937   SmallVector<SDValue, 8> Ops;
2938
2939   if (!IsSibcall && isTailCall) {
2940     Chain = DAG.getCALLSEQ_END(Chain,
2941                                DAG.getIntPtrConstant(NumBytesToPop, true),
2942                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2943     InFlag = Chain.getValue(1);
2944   }
2945
2946   Ops.push_back(Chain);
2947   Ops.push_back(Callee);
2948
2949   if (isTailCall)
2950     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2951
2952   // Add argument registers to the end of the list so that they are known live
2953   // into the call.
2954   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2955     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2956                                   RegsToPass[i].second.getValueType()));
2957
2958   // Add a register mask operand representing the call-preserved registers.
2959   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2960   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2961   assert(Mask && "Missing call preserved mask for calling convention");
2962   Ops.push_back(DAG.getRegisterMask(Mask));
2963
2964   if (InFlag.getNode())
2965     Ops.push_back(InFlag);
2966
2967   if (isTailCall) {
2968     // We used to do:
2969     //// If this is the first return lowered for this function, add the regs
2970     //// to the liveout set for the function.
2971     // This isn't right, although it's probably harmless on x86; liveouts
2972     // should be computed from returns not tail calls.  Consider a void
2973     // function making a tail call to a function returning int.
2974     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2975   }
2976
2977   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2978   InFlag = Chain.getValue(1);
2979
2980   // Create the CALLSEQ_END node.
2981   unsigned NumBytesForCalleeToPop;
2982   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2983                        DAG.getTarget().Options.GuaranteedTailCallOpt))
2984     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2985   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2986            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2987            SR == StackStructReturn)
2988     // If this is a call to a struct-return function, the callee
2989     // pops the hidden struct pointer, so we have to push it back.
2990     // This is common for Darwin/X86, Linux & Mingw32 targets.
2991     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2992     NumBytesForCalleeToPop = 4;
2993   else
2994     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2995
2996   // Returns a flag for retval copy to use.
2997   if (!IsSibcall) {
2998     Chain = DAG.getCALLSEQ_END(Chain,
2999                                DAG.getIntPtrConstant(NumBytesToPop, true),
3000                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3001                                                      true),
3002                                InFlag, dl);
3003     InFlag = Chain.getValue(1);
3004   }
3005
3006   // Handle result values, copying them out of physregs into vregs that we
3007   // return.
3008   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3009                          Ins, dl, DAG, InVals);
3010 }
3011
3012 //===----------------------------------------------------------------------===//
3013 //                Fast Calling Convention (tail call) implementation
3014 //===----------------------------------------------------------------------===//
3015
3016 //  Like std call, callee cleans arguments, convention except that ECX is
3017 //  reserved for storing the tail called function address. Only 2 registers are
3018 //  free for argument passing (inreg). Tail call optimization is performed
3019 //  provided:
3020 //                * tailcallopt is enabled
3021 //                * caller/callee are fastcc
3022 //  On X86_64 architecture with GOT-style position independent code only local
3023 //  (within module) calls are supported at the moment.
3024 //  To keep the stack aligned according to platform abi the function
3025 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3026 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3027 //  If a tail called function callee has more arguments than the caller the
3028 //  caller needs to make sure that there is room to move the RETADDR to. This is
3029 //  achieved by reserving an area the size of the argument delta right after the
3030 //  original REtADDR, but before the saved framepointer or the spilled registers
3031 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3032 //  stack layout:
3033 //    arg1
3034 //    arg2
3035 //    RETADDR
3036 //    [ new RETADDR
3037 //      move area ]
3038 //    (possible EBP)
3039 //    ESI
3040 //    EDI
3041 //    local1 ..
3042
3043 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3044 /// for a 16 byte align requirement.
3045 unsigned
3046 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3047                                                SelectionDAG& DAG) const {
3048   MachineFunction &MF = DAG.getMachineFunction();
3049   const TargetMachine &TM = MF.getTarget();
3050   const X86RegisterInfo *RegInfo =
3051     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3052   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3053   unsigned StackAlignment = TFI.getStackAlignment();
3054   uint64_t AlignMask = StackAlignment - 1;
3055   int64_t Offset = StackSize;
3056   unsigned SlotSize = RegInfo->getSlotSize();
3057   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3058     // Number smaller than 12 so just add the difference.
3059     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3060   } else {
3061     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3062     Offset = ((~AlignMask) & Offset) + StackAlignment +
3063       (StackAlignment-SlotSize);
3064   }
3065   return Offset;
3066 }
3067
3068 /// MatchingStackOffset - Return true if the given stack call argument is
3069 /// already available in the same position (relatively) of the caller's
3070 /// incoming argument stack.
3071 static
3072 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3073                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3074                          const X86InstrInfo *TII) {
3075   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3076   int FI = INT_MAX;
3077   if (Arg.getOpcode() == ISD::CopyFromReg) {
3078     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3079     if (!TargetRegisterInfo::isVirtualRegister(VR))
3080       return false;
3081     MachineInstr *Def = MRI->getVRegDef(VR);
3082     if (!Def)
3083       return false;
3084     if (!Flags.isByVal()) {
3085       if (!TII->isLoadFromStackSlot(Def, FI))
3086         return false;
3087     } else {
3088       unsigned Opcode = Def->getOpcode();
3089       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3090           Def->getOperand(1).isFI()) {
3091         FI = Def->getOperand(1).getIndex();
3092         Bytes = Flags.getByValSize();
3093       } else
3094         return false;
3095     }
3096   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3097     if (Flags.isByVal())
3098       // ByVal argument is passed in as a pointer but it's now being
3099       // dereferenced. e.g.
3100       // define @foo(%struct.X* %A) {
3101       //   tail call @bar(%struct.X* byval %A)
3102       // }
3103       return false;
3104     SDValue Ptr = Ld->getBasePtr();
3105     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3106     if (!FINode)
3107       return false;
3108     FI = FINode->getIndex();
3109   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3110     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3111     FI = FINode->getIndex();
3112     Bytes = Flags.getByValSize();
3113   } else
3114     return false;
3115
3116   assert(FI != INT_MAX);
3117   if (!MFI->isFixedObjectIndex(FI))
3118     return false;
3119   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3120 }
3121
3122 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3123 /// for tail call optimization. Targets which want to do tail call
3124 /// optimization should implement this function.
3125 bool
3126 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3127                                                      CallingConv::ID CalleeCC,
3128                                                      bool isVarArg,
3129                                                      bool isCalleeStructRet,
3130                                                      bool isCallerStructRet,
3131                                                      Type *RetTy,
3132                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3133                                     const SmallVectorImpl<SDValue> &OutVals,
3134                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3135                                                      SelectionDAG &DAG) const {
3136   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3137     return false;
3138
3139   // If -tailcallopt is specified, make fastcc functions tail-callable.
3140   const MachineFunction &MF = DAG.getMachineFunction();
3141   const Function *CallerF = MF.getFunction();
3142
3143   // If the function return type is x86_fp80 and the callee return type is not,
3144   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3145   // perform a tailcall optimization here.
3146   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3147     return false;
3148
3149   CallingConv::ID CallerCC = CallerF->getCallingConv();
3150   bool CCMatch = CallerCC == CalleeCC;
3151   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3152   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3153
3154   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3155     if (IsTailCallConvention(CalleeCC) && CCMatch)
3156       return true;
3157     return false;
3158   }
3159
3160   // Look for obvious safe cases to perform tail call optimization that do not
3161   // require ABI changes. This is what gcc calls sibcall.
3162
3163   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3164   // emit a special epilogue.
3165   const X86RegisterInfo *RegInfo =
3166     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3167   if (RegInfo->needsStackRealignment(MF))
3168     return false;
3169
3170   // Also avoid sibcall optimization if either caller or callee uses struct
3171   // return semantics.
3172   if (isCalleeStructRet || isCallerStructRet)
3173     return false;
3174
3175   // An stdcall/thiscall caller is expected to clean up its arguments; the
3176   // callee isn't going to do that.
3177   // FIXME: this is more restrictive than needed. We could produce a tailcall
3178   // when the stack adjustment matches. For example, with a thiscall that takes
3179   // only one argument.
3180   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3181                    CallerCC == CallingConv::X86_ThisCall))
3182     return false;
3183
3184   // Do not sibcall optimize vararg calls unless all arguments are passed via
3185   // registers.
3186   if (isVarArg && !Outs.empty()) {
3187
3188     // Optimizing for varargs on Win64 is unlikely to be safe without
3189     // additional testing.
3190     if (IsCalleeWin64 || IsCallerWin64)
3191       return false;
3192
3193     SmallVector<CCValAssign, 16> ArgLocs;
3194     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3195                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3196
3197     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3198     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3199       if (!ArgLocs[i].isRegLoc())
3200         return false;
3201   }
3202
3203   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3204   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3205   // this into a sibcall.
3206   bool Unused = false;
3207   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3208     if (!Ins[i].Used) {
3209       Unused = true;
3210       break;
3211     }
3212   }
3213   if (Unused) {
3214     SmallVector<CCValAssign, 16> RVLocs;
3215     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3216                    DAG.getTarget(), RVLocs, *DAG.getContext());
3217     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3218     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3219       CCValAssign &VA = RVLocs[i];
3220       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3221         return false;
3222     }
3223   }
3224
3225   // If the calling conventions do not match, then we'd better make sure the
3226   // results are returned in the same way as what the caller expects.
3227   if (!CCMatch) {
3228     SmallVector<CCValAssign, 16> RVLocs1;
3229     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3230                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3231     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3232
3233     SmallVector<CCValAssign, 16> RVLocs2;
3234     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3235                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3236     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3237
3238     if (RVLocs1.size() != RVLocs2.size())
3239       return false;
3240     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3241       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3242         return false;
3243       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3244         return false;
3245       if (RVLocs1[i].isRegLoc()) {
3246         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3247           return false;
3248       } else {
3249         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3250           return false;
3251       }
3252     }
3253   }
3254
3255   // If the callee takes no arguments then go on to check the results of the
3256   // call.
3257   if (!Outs.empty()) {
3258     // Check if stack adjustment is needed. For now, do not do this if any
3259     // argument is passed on the stack.
3260     SmallVector<CCValAssign, 16> ArgLocs;
3261     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3262                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3263
3264     // Allocate shadow area for Win64
3265     if (IsCalleeWin64)
3266       CCInfo.AllocateStack(32, 8);
3267
3268     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3269     if (CCInfo.getNextStackOffset()) {
3270       MachineFunction &MF = DAG.getMachineFunction();
3271       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3272         return false;
3273
3274       // Check if the arguments are already laid out in the right way as
3275       // the caller's fixed stack objects.
3276       MachineFrameInfo *MFI = MF.getFrameInfo();
3277       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3278       const X86InstrInfo *TII =
3279           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3280       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3281         CCValAssign &VA = ArgLocs[i];
3282         SDValue Arg = OutVals[i];
3283         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3284         if (VA.getLocInfo() == CCValAssign::Indirect)
3285           return false;
3286         if (!VA.isRegLoc()) {
3287           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3288                                    MFI, MRI, TII))
3289             return false;
3290         }
3291       }
3292     }
3293
3294     // If the tailcall address may be in a register, then make sure it's
3295     // possible to register allocate for it. In 32-bit, the call address can
3296     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3297     // callee-saved registers are restored. These happen to be the same
3298     // registers used to pass 'inreg' arguments so watch out for those.
3299     if (!Subtarget->is64Bit() &&
3300         ((!isa<GlobalAddressSDNode>(Callee) &&
3301           !isa<ExternalSymbolSDNode>(Callee)) ||
3302          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3303       unsigned NumInRegs = 0;
3304       // In PIC we need an extra register to formulate the address computation
3305       // for the callee.
3306       unsigned MaxInRegs =
3307         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3308
3309       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3310         CCValAssign &VA = ArgLocs[i];
3311         if (!VA.isRegLoc())
3312           continue;
3313         unsigned Reg = VA.getLocReg();
3314         switch (Reg) {
3315         default: break;
3316         case X86::EAX: case X86::EDX: case X86::ECX:
3317           if (++NumInRegs == MaxInRegs)
3318             return false;
3319           break;
3320         }
3321       }
3322     }
3323   }
3324
3325   return true;
3326 }
3327
3328 FastISel *
3329 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3330                                   const TargetLibraryInfo *libInfo) const {
3331   return X86::createFastISel(funcInfo, libInfo);
3332 }
3333
3334 //===----------------------------------------------------------------------===//
3335 //                           Other Lowering Hooks
3336 //===----------------------------------------------------------------------===//
3337
3338 static bool MayFoldLoad(SDValue Op) {
3339   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3340 }
3341
3342 static bool MayFoldIntoStore(SDValue Op) {
3343   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3344 }
3345
3346 static bool isTargetShuffle(unsigned Opcode) {
3347   switch(Opcode) {
3348   default: return false;
3349   case X86ISD::PSHUFD:
3350   case X86ISD::PSHUFHW:
3351   case X86ISD::PSHUFLW:
3352   case X86ISD::SHUFP:
3353   case X86ISD::PALIGNR:
3354   case X86ISD::MOVLHPS:
3355   case X86ISD::MOVLHPD:
3356   case X86ISD::MOVHLPS:
3357   case X86ISD::MOVLPS:
3358   case X86ISD::MOVLPD:
3359   case X86ISD::MOVSHDUP:
3360   case X86ISD::MOVSLDUP:
3361   case X86ISD::MOVDDUP:
3362   case X86ISD::MOVSS:
3363   case X86ISD::MOVSD:
3364   case X86ISD::UNPCKL:
3365   case X86ISD::UNPCKH:
3366   case X86ISD::VPERMILP:
3367   case X86ISD::VPERM2X128:
3368   case X86ISD::VPERMI:
3369     return true;
3370   }
3371 }
3372
3373 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3374                                     SDValue V1, SelectionDAG &DAG) {
3375   switch(Opc) {
3376   default: llvm_unreachable("Unknown x86 shuffle node");
3377   case X86ISD::MOVSHDUP:
3378   case X86ISD::MOVSLDUP:
3379   case X86ISD::MOVDDUP:
3380     return DAG.getNode(Opc, dl, VT, V1);
3381   }
3382 }
3383
3384 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3385                                     SDValue V1, unsigned TargetMask,
3386                                     SelectionDAG &DAG) {
3387   switch(Opc) {
3388   default: llvm_unreachable("Unknown x86 shuffle node");
3389   case X86ISD::PSHUFD:
3390   case X86ISD::PSHUFHW:
3391   case X86ISD::PSHUFLW:
3392   case X86ISD::VPERMILP:
3393   case X86ISD::VPERMI:
3394     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3395   }
3396 }
3397
3398 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3399                                     SDValue V1, SDValue V2, unsigned TargetMask,
3400                                     SelectionDAG &DAG) {
3401   switch(Opc) {
3402   default: llvm_unreachable("Unknown x86 shuffle node");
3403   case X86ISD::PALIGNR:
3404   case X86ISD::SHUFP:
3405   case X86ISD::VPERM2X128:
3406     return DAG.getNode(Opc, dl, VT, V1, V2,
3407                        DAG.getConstant(TargetMask, MVT::i8));
3408   }
3409 }
3410
3411 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3412                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3413   switch(Opc) {
3414   default: llvm_unreachable("Unknown x86 shuffle node");
3415   case X86ISD::MOVLHPS:
3416   case X86ISD::MOVLHPD:
3417   case X86ISD::MOVHLPS:
3418   case X86ISD::MOVLPS:
3419   case X86ISD::MOVLPD:
3420   case X86ISD::MOVSS:
3421   case X86ISD::MOVSD:
3422   case X86ISD::UNPCKL:
3423   case X86ISD::UNPCKH:
3424     return DAG.getNode(Opc, dl, VT, V1, V2);
3425   }
3426 }
3427
3428 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3429   MachineFunction &MF = DAG.getMachineFunction();
3430   const X86RegisterInfo *RegInfo =
3431     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3432   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3433   int ReturnAddrIndex = FuncInfo->getRAIndex();
3434
3435   if (ReturnAddrIndex == 0) {
3436     // Set up a frame object for the return address.
3437     unsigned SlotSize = RegInfo->getSlotSize();
3438     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3439                                                            -(int64_t)SlotSize,
3440                                                            false);
3441     FuncInfo->setRAIndex(ReturnAddrIndex);
3442   }
3443
3444   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3445 }
3446
3447 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3448                                        bool hasSymbolicDisplacement) {
3449   // Offset should fit into 32 bit immediate field.
3450   if (!isInt<32>(Offset))
3451     return false;
3452
3453   // If we don't have a symbolic displacement - we don't have any extra
3454   // restrictions.
3455   if (!hasSymbolicDisplacement)
3456     return true;
3457
3458   // FIXME: Some tweaks might be needed for medium code model.
3459   if (M != CodeModel::Small && M != CodeModel::Kernel)
3460     return false;
3461
3462   // For small code model we assume that latest object is 16MB before end of 31
3463   // bits boundary. We may also accept pretty large negative constants knowing
3464   // that all objects are in the positive half of address space.
3465   if (M == CodeModel::Small && Offset < 16*1024*1024)
3466     return true;
3467
3468   // For kernel code model we know that all object resist in the negative half
3469   // of 32bits address space. We may not accept negative offsets, since they may
3470   // be just off and we may accept pretty large positive ones.
3471   if (M == CodeModel::Kernel && Offset > 0)
3472     return true;
3473
3474   return false;
3475 }
3476
3477 /// isCalleePop - Determines whether the callee is required to pop its
3478 /// own arguments. Callee pop is necessary to support tail calls.
3479 bool X86::isCalleePop(CallingConv::ID CallingConv,
3480                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3481   if (IsVarArg)
3482     return false;
3483
3484   switch (CallingConv) {
3485   default:
3486     return false;
3487   case CallingConv::X86_StdCall:
3488     return !is64Bit;
3489   case CallingConv::X86_FastCall:
3490     return !is64Bit;
3491   case CallingConv::X86_ThisCall:
3492     return !is64Bit;
3493   case CallingConv::Fast:
3494     return TailCallOpt;
3495   case CallingConv::GHC:
3496     return TailCallOpt;
3497   case CallingConv::HiPE:
3498     return TailCallOpt;
3499   }
3500 }
3501
3502 /// \brief Return true if the condition is an unsigned comparison operation.
3503 static bool isX86CCUnsigned(unsigned X86CC) {
3504   switch (X86CC) {
3505   default: llvm_unreachable("Invalid integer condition!");
3506   case X86::COND_E:     return true;
3507   case X86::COND_G:     return false;
3508   case X86::COND_GE:    return false;
3509   case X86::COND_L:     return false;
3510   case X86::COND_LE:    return false;
3511   case X86::COND_NE:    return true;
3512   case X86::COND_B:     return true;
3513   case X86::COND_A:     return true;
3514   case X86::COND_BE:    return true;
3515   case X86::COND_AE:    return true;
3516   }
3517   llvm_unreachable("covered switch fell through?!");
3518 }
3519
3520 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3521 /// specific condition code, returning the condition code and the LHS/RHS of the
3522 /// comparison to make.
3523 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3524                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3525   if (!isFP) {
3526     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3527       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3528         // X > -1   -> X == 0, jump !sign.
3529         RHS = DAG.getConstant(0, RHS.getValueType());
3530         return X86::COND_NS;
3531       }
3532       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3533         // X < 0   -> X == 0, jump on sign.
3534         return X86::COND_S;
3535       }
3536       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3537         // X < 1   -> X <= 0
3538         RHS = DAG.getConstant(0, RHS.getValueType());
3539         return X86::COND_LE;
3540       }
3541     }
3542
3543     switch (SetCCOpcode) {
3544     default: llvm_unreachable("Invalid integer condition!");
3545     case ISD::SETEQ:  return X86::COND_E;
3546     case ISD::SETGT:  return X86::COND_G;
3547     case ISD::SETGE:  return X86::COND_GE;
3548     case ISD::SETLT:  return X86::COND_L;
3549     case ISD::SETLE:  return X86::COND_LE;
3550     case ISD::SETNE:  return X86::COND_NE;
3551     case ISD::SETULT: return X86::COND_B;
3552     case ISD::SETUGT: return X86::COND_A;
3553     case ISD::SETULE: return X86::COND_BE;
3554     case ISD::SETUGE: return X86::COND_AE;
3555     }
3556   }
3557
3558   // First determine if it is required or is profitable to flip the operands.
3559
3560   // If LHS is a foldable load, but RHS is not, flip the condition.
3561   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3562       !ISD::isNON_EXTLoad(RHS.getNode())) {
3563     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3564     std::swap(LHS, RHS);
3565   }
3566
3567   switch (SetCCOpcode) {
3568   default: break;
3569   case ISD::SETOLT:
3570   case ISD::SETOLE:
3571   case ISD::SETUGT:
3572   case ISD::SETUGE:
3573     std::swap(LHS, RHS);
3574     break;
3575   }
3576
3577   // On a floating point condition, the flags are set as follows:
3578   // ZF  PF  CF   op
3579   //  0 | 0 | 0 | X > Y
3580   //  0 | 0 | 1 | X < Y
3581   //  1 | 0 | 0 | X == Y
3582   //  1 | 1 | 1 | unordered
3583   switch (SetCCOpcode) {
3584   default: llvm_unreachable("Condcode should be pre-legalized away");
3585   case ISD::SETUEQ:
3586   case ISD::SETEQ:   return X86::COND_E;
3587   case ISD::SETOLT:              // flipped
3588   case ISD::SETOGT:
3589   case ISD::SETGT:   return X86::COND_A;
3590   case ISD::SETOLE:              // flipped
3591   case ISD::SETOGE:
3592   case ISD::SETGE:   return X86::COND_AE;
3593   case ISD::SETUGT:              // flipped
3594   case ISD::SETULT:
3595   case ISD::SETLT:   return X86::COND_B;
3596   case ISD::SETUGE:              // flipped
3597   case ISD::SETULE:
3598   case ISD::SETLE:   return X86::COND_BE;
3599   case ISD::SETONE:
3600   case ISD::SETNE:   return X86::COND_NE;
3601   case ISD::SETUO:   return X86::COND_P;
3602   case ISD::SETO:    return X86::COND_NP;
3603   case ISD::SETOEQ:
3604   case ISD::SETUNE:  return X86::COND_INVALID;
3605   }
3606 }
3607
3608 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3609 /// code. Current x86 isa includes the following FP cmov instructions:
3610 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3611 static bool hasFPCMov(unsigned X86CC) {
3612   switch (X86CC) {
3613   default:
3614     return false;
3615   case X86::COND_B:
3616   case X86::COND_BE:
3617   case X86::COND_E:
3618   case X86::COND_P:
3619   case X86::COND_A:
3620   case X86::COND_AE:
3621   case X86::COND_NE:
3622   case X86::COND_NP:
3623     return true;
3624   }
3625 }
3626
3627 /// isFPImmLegal - Returns true if the target can instruction select the
3628 /// specified FP immediate natively. If false, the legalizer will
3629 /// materialize the FP immediate as a load from a constant pool.
3630 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3631   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3632     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3633       return true;
3634   }
3635   return false;
3636 }
3637
3638 /// \brief Returns true if it is beneficial to convert a load of a constant
3639 /// to just the constant itself.
3640 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3641                                                           Type *Ty) const {
3642   assert(Ty->isIntegerTy());
3643
3644   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3645   if (BitSize == 0 || BitSize > 64)
3646     return false;
3647   return true;
3648 }
3649
3650 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3651 /// the specified range (L, H].
3652 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3653   return (Val < 0) || (Val >= Low && Val < Hi);
3654 }
3655
3656 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3657 /// specified value.
3658 static bool isUndefOrEqual(int Val, int CmpVal) {
3659   return (Val < 0 || Val == CmpVal);
3660 }
3661
3662 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3663 /// from position Pos and ending in Pos+Size, falls within the specified
3664 /// sequential range (L, L+Pos]. or is undef.
3665 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3666                                        unsigned Pos, unsigned Size, int Low) {
3667   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3668     if (!isUndefOrEqual(Mask[i], Low))
3669       return false;
3670   return true;
3671 }
3672
3673 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3674 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3675 /// the second operand.
3676 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3677   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3678     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3679   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3680     return (Mask[0] < 2 && Mask[1] < 2);
3681   return false;
3682 }
3683
3684 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3685 /// is suitable for input to PSHUFHW.
3686 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3687   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3688     return false;
3689
3690   // Lower quadword copied in order or undef.
3691   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3692     return false;
3693
3694   // Upper quadword shuffled.
3695   for (unsigned i = 4; i != 8; ++i)
3696     if (!isUndefOrInRange(Mask[i], 4, 8))
3697       return false;
3698
3699   if (VT == MVT::v16i16) {
3700     // Lower quadword copied in order or undef.
3701     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3702       return false;
3703
3704     // Upper quadword shuffled.
3705     for (unsigned i = 12; i != 16; ++i)
3706       if (!isUndefOrInRange(Mask[i], 12, 16))
3707         return false;
3708   }
3709
3710   return true;
3711 }
3712
3713 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3714 /// is suitable for input to PSHUFLW.
3715 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3716   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3717     return false;
3718
3719   // Upper quadword copied in order.
3720   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3721     return false;
3722
3723   // Lower quadword shuffled.
3724   for (unsigned i = 0; i != 4; ++i)
3725     if (!isUndefOrInRange(Mask[i], 0, 4))
3726       return false;
3727
3728   if (VT == MVT::v16i16) {
3729     // Upper quadword copied in order.
3730     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3731       return false;
3732
3733     // Lower quadword shuffled.
3734     for (unsigned i = 8; i != 12; ++i)
3735       if (!isUndefOrInRange(Mask[i], 8, 12))
3736         return false;
3737   }
3738
3739   return true;
3740 }
3741
3742 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3743 /// is suitable for input to PALIGNR.
3744 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3745                           const X86Subtarget *Subtarget) {
3746   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3747       (VT.is256BitVector() && !Subtarget->hasInt256()))
3748     return false;
3749
3750   unsigned NumElts = VT.getVectorNumElements();
3751   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3752   unsigned NumLaneElts = NumElts/NumLanes;
3753
3754   // Do not handle 64-bit element shuffles with palignr.
3755   if (NumLaneElts == 2)
3756     return false;
3757
3758   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3759     unsigned i;
3760     for (i = 0; i != NumLaneElts; ++i) {
3761       if (Mask[i+l] >= 0)
3762         break;
3763     }
3764
3765     // Lane is all undef, go to next lane
3766     if (i == NumLaneElts)
3767       continue;
3768
3769     int Start = Mask[i+l];
3770
3771     // Make sure its in this lane in one of the sources
3772     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3773         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3774       return false;
3775
3776     // If not lane 0, then we must match lane 0
3777     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3778       return false;
3779
3780     // Correct second source to be contiguous with first source
3781     if (Start >= (int)NumElts)
3782       Start -= NumElts - NumLaneElts;
3783
3784     // Make sure we're shifting in the right direction.
3785     if (Start <= (int)(i+l))
3786       return false;
3787
3788     Start -= i;
3789
3790     // Check the rest of the elements to see if they are consecutive.
3791     for (++i; i != NumLaneElts; ++i) {
3792       int Idx = Mask[i+l];
3793
3794       // Make sure its in this lane
3795       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3796           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3797         return false;
3798
3799       // If not lane 0, then we must match lane 0
3800       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3801         return false;
3802
3803       if (Idx >= (int)NumElts)
3804         Idx -= NumElts - NumLaneElts;
3805
3806       if (!isUndefOrEqual(Idx, Start+i))
3807         return false;
3808
3809     }
3810   }
3811
3812   return true;
3813 }
3814
3815 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3816 /// the two vector operands have swapped position.
3817 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3818                                      unsigned NumElems) {
3819   for (unsigned i = 0; i != NumElems; ++i) {
3820     int idx = Mask[i];
3821     if (idx < 0)
3822       continue;
3823     else if (idx < (int)NumElems)
3824       Mask[i] = idx + NumElems;
3825     else
3826       Mask[i] = idx - NumElems;
3827   }
3828 }
3829
3830 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3831 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3832 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3833 /// reverse of what x86 shuffles want.
3834 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3835
3836   unsigned NumElems = VT.getVectorNumElements();
3837   unsigned NumLanes = VT.getSizeInBits()/128;
3838   unsigned NumLaneElems = NumElems/NumLanes;
3839
3840   if (NumLaneElems != 2 && NumLaneElems != 4)
3841     return false;
3842
3843   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3844   bool symetricMaskRequired =
3845     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3846
3847   // VSHUFPSY divides the resulting vector into 4 chunks.
3848   // The sources are also splitted into 4 chunks, and each destination
3849   // chunk must come from a different source chunk.
3850   //
3851   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3852   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3853   //
3854   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3855   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3856   //
3857   // VSHUFPDY divides the resulting vector into 4 chunks.
3858   // The sources are also splitted into 4 chunks, and each destination
3859   // chunk must come from a different source chunk.
3860   //
3861   //  SRC1 =>      X3       X2       X1       X0
3862   //  SRC2 =>      Y3       Y2       Y1       Y0
3863   //
3864   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3865   //
3866   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3867   unsigned HalfLaneElems = NumLaneElems/2;
3868   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3869     for (unsigned i = 0; i != NumLaneElems; ++i) {
3870       int Idx = Mask[i+l];
3871       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3872       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3873         return false;
3874       // For VSHUFPSY, the mask of the second half must be the same as the
3875       // first but with the appropriate offsets. This works in the same way as
3876       // VPERMILPS works with masks.
3877       if (!symetricMaskRequired || Idx < 0)
3878         continue;
3879       if (MaskVal[i] < 0) {
3880         MaskVal[i] = Idx - l;
3881         continue;
3882       }
3883       if ((signed)(Idx - l) != MaskVal[i])
3884         return false;
3885     }
3886   }
3887
3888   return true;
3889 }
3890
3891 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3892 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3893 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3894   if (!VT.is128BitVector())
3895     return false;
3896
3897   unsigned NumElems = VT.getVectorNumElements();
3898
3899   if (NumElems != 4)
3900     return false;
3901
3902   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3903   return isUndefOrEqual(Mask[0], 6) &&
3904          isUndefOrEqual(Mask[1], 7) &&
3905          isUndefOrEqual(Mask[2], 2) &&
3906          isUndefOrEqual(Mask[3], 3);
3907 }
3908
3909 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3910 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3911 /// <2, 3, 2, 3>
3912 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3913   if (!VT.is128BitVector())
3914     return false;
3915
3916   unsigned NumElems = VT.getVectorNumElements();
3917
3918   if (NumElems != 4)
3919     return false;
3920
3921   return isUndefOrEqual(Mask[0], 2) &&
3922          isUndefOrEqual(Mask[1], 3) &&
3923          isUndefOrEqual(Mask[2], 2) &&
3924          isUndefOrEqual(Mask[3], 3);
3925 }
3926
3927 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3928 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3929 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3930   if (!VT.is128BitVector())
3931     return false;
3932
3933   unsigned NumElems = VT.getVectorNumElements();
3934
3935   if (NumElems != 2 && NumElems != 4)
3936     return false;
3937
3938   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3939     if (!isUndefOrEqual(Mask[i], i + NumElems))
3940       return false;
3941
3942   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3943     if (!isUndefOrEqual(Mask[i], i))
3944       return false;
3945
3946   return true;
3947 }
3948
3949 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3950 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3951 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3952   if (!VT.is128BitVector())
3953     return false;
3954
3955   unsigned NumElems = VT.getVectorNumElements();
3956
3957   if (NumElems != 2 && NumElems != 4)
3958     return false;
3959
3960   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3961     if (!isUndefOrEqual(Mask[i], i))
3962       return false;
3963
3964   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3965     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3966       return false;
3967
3968   return true;
3969 }
3970
3971 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3972 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3973 /// i. e: If all but one element come from the same vector.
3974 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3975   // TODO: Deal with AVX's VINSERTPS
3976   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3977     return false;
3978
3979   unsigned CorrectPosV1 = 0;
3980   unsigned CorrectPosV2 = 0;
3981   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3982     if (Mask[i] == -1) {
3983       ++CorrectPosV1;
3984       ++CorrectPosV2;
3985       continue;
3986     }
3987
3988     if (Mask[i] == i)
3989       ++CorrectPosV1;
3990     else if (Mask[i] == i + 4)
3991       ++CorrectPosV2;
3992   }
3993
3994   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3995     // We have 3 elements (undefs count as elements from any vector) from one
3996     // vector, and one from another.
3997     return true;
3998
3999   return false;
4000 }
4001
4002 //
4003 // Some special combinations that can be optimized.
4004 //
4005 static
4006 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4007                                SelectionDAG &DAG) {
4008   MVT VT = SVOp->getSimpleValueType(0);
4009   SDLoc dl(SVOp);
4010
4011   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4012     return SDValue();
4013
4014   ArrayRef<int> Mask = SVOp->getMask();
4015
4016   // These are the special masks that may be optimized.
4017   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4018   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4019   bool MatchEvenMask = true;
4020   bool MatchOddMask  = true;
4021   for (int i=0; i<8; ++i) {
4022     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4023       MatchEvenMask = false;
4024     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4025       MatchOddMask = false;
4026   }
4027
4028   if (!MatchEvenMask && !MatchOddMask)
4029     return SDValue();
4030
4031   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4032
4033   SDValue Op0 = SVOp->getOperand(0);
4034   SDValue Op1 = SVOp->getOperand(1);
4035
4036   if (MatchEvenMask) {
4037     // Shift the second operand right to 32 bits.
4038     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4039     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4040   } else {
4041     // Shift the first operand left to 32 bits.
4042     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4043     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4044   }
4045   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4046   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4047 }
4048
4049 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4050 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4051 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4052                          bool HasInt256, bool V2IsSplat = false) {
4053
4054   assert(VT.getSizeInBits() >= 128 &&
4055          "Unsupported vector type for unpckl");
4056
4057   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4058   unsigned NumLanes;
4059   unsigned NumOf256BitLanes;
4060   unsigned NumElts = VT.getVectorNumElements();
4061   if (VT.is256BitVector()) {
4062     if (NumElts != 4 && NumElts != 8 &&
4063         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4064     return false;
4065     NumLanes = 2;
4066     NumOf256BitLanes = 1;
4067   } else if (VT.is512BitVector()) {
4068     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4069            "Unsupported vector type for unpckh");
4070     NumLanes = 2;
4071     NumOf256BitLanes = 2;
4072   } else {
4073     NumLanes = 1;
4074     NumOf256BitLanes = 1;
4075   }
4076
4077   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4078   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4079
4080   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4081     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4082       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4083         int BitI  = Mask[l256*NumEltsInStride+l+i];
4084         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4085         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4086           return false;
4087         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4088           return false;
4089         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4090           return false;
4091       }
4092     }
4093   }
4094   return true;
4095 }
4096
4097 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4098 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4099 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4100                          bool HasInt256, bool V2IsSplat = false) {
4101   assert(VT.getSizeInBits() >= 128 &&
4102          "Unsupported vector type for unpckh");
4103
4104   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4105   unsigned NumLanes;
4106   unsigned NumOf256BitLanes;
4107   unsigned NumElts = VT.getVectorNumElements();
4108   if (VT.is256BitVector()) {
4109     if (NumElts != 4 && NumElts != 8 &&
4110         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4111     return false;
4112     NumLanes = 2;
4113     NumOf256BitLanes = 1;
4114   } else if (VT.is512BitVector()) {
4115     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4116            "Unsupported vector type for unpckh");
4117     NumLanes = 2;
4118     NumOf256BitLanes = 2;
4119   } else {
4120     NumLanes = 1;
4121     NumOf256BitLanes = 1;
4122   }
4123
4124   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4125   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4126
4127   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4128     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4129       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4130         int BitI  = Mask[l256*NumEltsInStride+l+i];
4131         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4132         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4133           return false;
4134         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4135           return false;
4136         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4137           return false;
4138       }
4139     }
4140   }
4141   return true;
4142 }
4143
4144 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4145 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4146 /// <0, 0, 1, 1>
4147 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4148   unsigned NumElts = VT.getVectorNumElements();
4149   bool Is256BitVec = VT.is256BitVector();
4150
4151   if (VT.is512BitVector())
4152     return false;
4153   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4154          "Unsupported vector type for unpckh");
4155
4156   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4157       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4158     return false;
4159
4160   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4161   // FIXME: Need a better way to get rid of this, there's no latency difference
4162   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4163   // the former later. We should also remove the "_undef" special mask.
4164   if (NumElts == 4 && Is256BitVec)
4165     return false;
4166
4167   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4168   // independently on 128-bit lanes.
4169   unsigned NumLanes = VT.getSizeInBits()/128;
4170   unsigned NumLaneElts = NumElts/NumLanes;
4171
4172   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4173     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4174       int BitI  = Mask[l+i];
4175       int BitI1 = Mask[l+i+1];
4176
4177       if (!isUndefOrEqual(BitI, j))
4178         return false;
4179       if (!isUndefOrEqual(BitI1, j))
4180         return false;
4181     }
4182   }
4183
4184   return true;
4185 }
4186
4187 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4188 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4189 /// <2, 2, 3, 3>
4190 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4191   unsigned NumElts = VT.getVectorNumElements();
4192
4193   if (VT.is512BitVector())
4194     return false;
4195
4196   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4197          "Unsupported vector type for unpckh");
4198
4199   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4200       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4201     return false;
4202
4203   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4204   // independently on 128-bit lanes.
4205   unsigned NumLanes = VT.getSizeInBits()/128;
4206   unsigned NumLaneElts = NumElts/NumLanes;
4207
4208   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4209     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4210       int BitI  = Mask[l+i];
4211       int BitI1 = Mask[l+i+1];
4212       if (!isUndefOrEqual(BitI, j))
4213         return false;
4214       if (!isUndefOrEqual(BitI1, j))
4215         return false;
4216     }
4217   }
4218   return true;
4219 }
4220
4221 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4222 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4223 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4224   if (!VT.is512BitVector())
4225     return false;
4226
4227   unsigned NumElts = VT.getVectorNumElements();
4228   unsigned HalfSize = NumElts/2;
4229   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4230     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4231       *Imm = 1;
4232       return true;
4233     }
4234   }
4235   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4236     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4237       *Imm = 0;
4238       return true;
4239     }
4240   }
4241   return false;
4242 }
4243
4244 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4245 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4246 /// MOVSD, and MOVD, i.e. setting the lowest element.
4247 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4248   if (VT.getVectorElementType().getSizeInBits() < 32)
4249     return false;
4250   if (!VT.is128BitVector())
4251     return false;
4252
4253   unsigned NumElts = VT.getVectorNumElements();
4254
4255   if (!isUndefOrEqual(Mask[0], NumElts))
4256     return false;
4257
4258   for (unsigned i = 1; i != NumElts; ++i)
4259     if (!isUndefOrEqual(Mask[i], i))
4260       return false;
4261
4262   return true;
4263 }
4264
4265 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4266 /// as permutations between 128-bit chunks or halves. As an example: this
4267 /// shuffle bellow:
4268 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4269 /// The first half comes from the second half of V1 and the second half from the
4270 /// the second half of V2.
4271 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4272   if (!HasFp256 || !VT.is256BitVector())
4273     return false;
4274
4275   // The shuffle result is divided into half A and half B. In total the two
4276   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4277   // B must come from C, D, E or F.
4278   unsigned HalfSize = VT.getVectorNumElements()/2;
4279   bool MatchA = false, MatchB = false;
4280
4281   // Check if A comes from one of C, D, E, F.
4282   for (unsigned Half = 0; Half != 4; ++Half) {
4283     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4284       MatchA = true;
4285       break;
4286     }
4287   }
4288
4289   // Check if B comes from one of C, D, E, F.
4290   for (unsigned Half = 0; Half != 4; ++Half) {
4291     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4292       MatchB = true;
4293       break;
4294     }
4295   }
4296
4297   return MatchA && MatchB;
4298 }
4299
4300 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4301 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4302 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4303   MVT VT = SVOp->getSimpleValueType(0);
4304
4305   unsigned HalfSize = VT.getVectorNumElements()/2;
4306
4307   unsigned FstHalf = 0, SndHalf = 0;
4308   for (unsigned i = 0; i < HalfSize; ++i) {
4309     if (SVOp->getMaskElt(i) > 0) {
4310       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4311       break;
4312     }
4313   }
4314   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4315     if (SVOp->getMaskElt(i) > 0) {
4316       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4317       break;
4318     }
4319   }
4320
4321   return (FstHalf | (SndHalf << 4));
4322 }
4323
4324 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4325 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4326   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4327   if (EltSize < 32)
4328     return false;
4329
4330   unsigned NumElts = VT.getVectorNumElements();
4331   Imm8 = 0;
4332   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4333     for (unsigned i = 0; i != NumElts; ++i) {
4334       if (Mask[i] < 0)
4335         continue;
4336       Imm8 |= Mask[i] << (i*2);
4337     }
4338     return true;
4339   }
4340
4341   unsigned LaneSize = 4;
4342   SmallVector<int, 4> MaskVal(LaneSize, -1);
4343
4344   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4345     for (unsigned i = 0; i != LaneSize; ++i) {
4346       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4347         return false;
4348       if (Mask[i+l] < 0)
4349         continue;
4350       if (MaskVal[i] < 0) {
4351         MaskVal[i] = Mask[i+l] - l;
4352         Imm8 |= MaskVal[i] << (i*2);
4353         continue;
4354       }
4355       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4356         return false;
4357     }
4358   }
4359   return true;
4360 }
4361
4362 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4363 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4364 /// Note that VPERMIL mask matching is different depending whether theunderlying
4365 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4366 /// to the same elements of the low, but to the higher half of the source.
4367 /// In VPERMILPD the two lanes could be shuffled independently of each other
4368 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4369 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4370   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4371   if (VT.getSizeInBits() < 256 || EltSize < 32)
4372     return false;
4373   bool symetricMaskRequired = (EltSize == 32);
4374   unsigned NumElts = VT.getVectorNumElements();
4375
4376   unsigned NumLanes = VT.getSizeInBits()/128;
4377   unsigned LaneSize = NumElts/NumLanes;
4378   // 2 or 4 elements in one lane
4379
4380   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4381   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4382     for (unsigned i = 0; i != LaneSize; ++i) {
4383       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4384         return false;
4385       if (symetricMaskRequired) {
4386         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4387           ExpectedMaskVal[i] = Mask[i+l] - l;
4388           continue;
4389         }
4390         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4391           return false;
4392       }
4393     }
4394   }
4395   return true;
4396 }
4397
4398 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4399 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4400 /// element of vector 2 and the other elements to come from vector 1 in order.
4401 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4402                                bool V2IsSplat = false, bool V2IsUndef = false) {
4403   if (!VT.is128BitVector())
4404     return false;
4405
4406   unsigned NumOps = VT.getVectorNumElements();
4407   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4408     return false;
4409
4410   if (!isUndefOrEqual(Mask[0], 0))
4411     return false;
4412
4413   for (unsigned i = 1; i != NumOps; ++i)
4414     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4415           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4416           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4417       return false;
4418
4419   return true;
4420 }
4421
4422 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4423 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4424 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4425 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4426                            const X86Subtarget *Subtarget) {
4427   if (!Subtarget->hasSSE3())
4428     return false;
4429
4430   unsigned NumElems = VT.getVectorNumElements();
4431
4432   if ((VT.is128BitVector() && NumElems != 4) ||
4433       (VT.is256BitVector() && NumElems != 8) ||
4434       (VT.is512BitVector() && NumElems != 16))
4435     return false;
4436
4437   // "i+1" is the value the indexed mask element must have
4438   for (unsigned i = 0; i != NumElems; i += 2)
4439     if (!isUndefOrEqual(Mask[i], i+1) ||
4440         !isUndefOrEqual(Mask[i+1], i+1))
4441       return false;
4442
4443   return true;
4444 }
4445
4446 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4447 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4448 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4449 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4450                            const X86Subtarget *Subtarget) {
4451   if (!Subtarget->hasSSE3())
4452     return false;
4453
4454   unsigned NumElems = VT.getVectorNumElements();
4455
4456   if ((VT.is128BitVector() && NumElems != 4) ||
4457       (VT.is256BitVector() && NumElems != 8) ||
4458       (VT.is512BitVector() && NumElems != 16))
4459     return false;
4460
4461   // "i" is the value the indexed mask element must have
4462   for (unsigned i = 0; i != NumElems; i += 2)
4463     if (!isUndefOrEqual(Mask[i], i) ||
4464         !isUndefOrEqual(Mask[i+1], i))
4465       return false;
4466
4467   return true;
4468 }
4469
4470 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4471 /// specifies a shuffle of elements that is suitable for input to 256-bit
4472 /// version of MOVDDUP.
4473 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4474   if (!HasFp256 || !VT.is256BitVector())
4475     return false;
4476
4477   unsigned NumElts = VT.getVectorNumElements();
4478   if (NumElts != 4)
4479     return false;
4480
4481   for (unsigned i = 0; i != NumElts/2; ++i)
4482     if (!isUndefOrEqual(Mask[i], 0))
4483       return false;
4484   for (unsigned i = NumElts/2; i != NumElts; ++i)
4485     if (!isUndefOrEqual(Mask[i], NumElts/2))
4486       return false;
4487   return true;
4488 }
4489
4490 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4491 /// specifies a shuffle of elements that is suitable for input to 128-bit
4492 /// version of MOVDDUP.
4493 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4494   if (!VT.is128BitVector())
4495     return false;
4496
4497   unsigned e = VT.getVectorNumElements() / 2;
4498   for (unsigned i = 0; i != e; ++i)
4499     if (!isUndefOrEqual(Mask[i], i))
4500       return false;
4501   for (unsigned i = 0; i != e; ++i)
4502     if (!isUndefOrEqual(Mask[e+i], i))
4503       return false;
4504   return true;
4505 }
4506
4507 /// isVEXTRACTIndex - Return true if the specified
4508 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4509 /// suitable for instruction that extract 128 or 256 bit vectors
4510 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4511   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4512   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4513     return false;
4514
4515   // The index should be aligned on a vecWidth-bit boundary.
4516   uint64_t Index =
4517     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4518
4519   MVT VT = N->getSimpleValueType(0);
4520   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4521   bool Result = (Index * ElSize) % vecWidth == 0;
4522
4523   return Result;
4524 }
4525
4526 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4527 /// operand specifies a subvector insert that is suitable for input to
4528 /// insertion of 128 or 256-bit subvectors
4529 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4530   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4531   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4532     return false;
4533   // The index should be aligned on a vecWidth-bit boundary.
4534   uint64_t Index =
4535     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4536
4537   MVT VT = N->getSimpleValueType(0);
4538   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4539   bool Result = (Index * ElSize) % vecWidth == 0;
4540
4541   return Result;
4542 }
4543
4544 bool X86::isVINSERT128Index(SDNode *N) {
4545   return isVINSERTIndex(N, 128);
4546 }
4547
4548 bool X86::isVINSERT256Index(SDNode *N) {
4549   return isVINSERTIndex(N, 256);
4550 }
4551
4552 bool X86::isVEXTRACT128Index(SDNode *N) {
4553   return isVEXTRACTIndex(N, 128);
4554 }
4555
4556 bool X86::isVEXTRACT256Index(SDNode *N) {
4557   return isVEXTRACTIndex(N, 256);
4558 }
4559
4560 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4561 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4562 /// Handles 128-bit and 256-bit.
4563 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4564   MVT VT = N->getSimpleValueType(0);
4565
4566   assert((VT.getSizeInBits() >= 128) &&
4567          "Unsupported vector type for PSHUF/SHUFP");
4568
4569   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4570   // independently on 128-bit lanes.
4571   unsigned NumElts = VT.getVectorNumElements();
4572   unsigned NumLanes = VT.getSizeInBits()/128;
4573   unsigned NumLaneElts = NumElts/NumLanes;
4574
4575   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4576          "Only supports 2, 4 or 8 elements per lane");
4577
4578   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4579   unsigned Mask = 0;
4580   for (unsigned i = 0; i != NumElts; ++i) {
4581     int Elt = N->getMaskElt(i);
4582     if (Elt < 0) continue;
4583     Elt &= NumLaneElts - 1;
4584     unsigned ShAmt = (i << Shift) % 8;
4585     Mask |= Elt << ShAmt;
4586   }
4587
4588   return Mask;
4589 }
4590
4591 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4592 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4593 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4594   MVT VT = N->getSimpleValueType(0);
4595
4596   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4597          "Unsupported vector type for PSHUFHW");
4598
4599   unsigned NumElts = VT.getVectorNumElements();
4600
4601   unsigned Mask = 0;
4602   for (unsigned l = 0; l != NumElts; l += 8) {
4603     // 8 nodes per lane, but we only care about the last 4.
4604     for (unsigned i = 0; i < 4; ++i) {
4605       int Elt = N->getMaskElt(l+i+4);
4606       if (Elt < 0) continue;
4607       Elt &= 0x3; // only 2-bits.
4608       Mask |= Elt << (i * 2);
4609     }
4610   }
4611
4612   return Mask;
4613 }
4614
4615 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4616 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4617 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4618   MVT VT = N->getSimpleValueType(0);
4619
4620   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4621          "Unsupported vector type for PSHUFHW");
4622
4623   unsigned NumElts = VT.getVectorNumElements();
4624
4625   unsigned Mask = 0;
4626   for (unsigned l = 0; l != NumElts; l += 8) {
4627     // 8 nodes per lane, but we only care about the first 4.
4628     for (unsigned i = 0; i < 4; ++i) {
4629       int Elt = N->getMaskElt(l+i);
4630       if (Elt < 0) continue;
4631       Elt &= 0x3; // only 2-bits
4632       Mask |= Elt << (i * 2);
4633     }
4634   }
4635
4636   return Mask;
4637 }
4638
4639 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4640 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4641 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4642   MVT VT = SVOp->getSimpleValueType(0);
4643   unsigned EltSize = VT.is512BitVector() ? 1 :
4644     VT.getVectorElementType().getSizeInBits() >> 3;
4645
4646   unsigned NumElts = VT.getVectorNumElements();
4647   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4648   unsigned NumLaneElts = NumElts/NumLanes;
4649
4650   int Val = 0;
4651   unsigned i;
4652   for (i = 0; i != NumElts; ++i) {
4653     Val = SVOp->getMaskElt(i);
4654     if (Val >= 0)
4655       break;
4656   }
4657   if (Val >= (int)NumElts)
4658     Val -= NumElts - NumLaneElts;
4659
4660   assert(Val - i > 0 && "PALIGNR imm should be positive");
4661   return (Val - i) * EltSize;
4662 }
4663
4664 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4665   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4666   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4667     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4668
4669   uint64_t Index =
4670     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4671
4672   MVT VecVT = N->getOperand(0).getSimpleValueType();
4673   MVT ElVT = VecVT.getVectorElementType();
4674
4675   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4676   return Index / NumElemsPerChunk;
4677 }
4678
4679 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4680   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4681   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4682     llvm_unreachable("Illegal insert subvector for VINSERT");
4683
4684   uint64_t Index =
4685     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4686
4687   MVT VecVT = N->getSimpleValueType(0);
4688   MVT ElVT = VecVT.getVectorElementType();
4689
4690   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4691   return Index / NumElemsPerChunk;
4692 }
4693
4694 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4695 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4696 /// and VINSERTI128 instructions.
4697 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4698   return getExtractVEXTRACTImmediate(N, 128);
4699 }
4700
4701 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4702 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4703 /// and VINSERTI64x4 instructions.
4704 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4705   return getExtractVEXTRACTImmediate(N, 256);
4706 }
4707
4708 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4709 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4710 /// and VINSERTI128 instructions.
4711 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4712   return getInsertVINSERTImmediate(N, 128);
4713 }
4714
4715 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4716 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4717 /// and VINSERTI64x4 instructions.
4718 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4719   return getInsertVINSERTImmediate(N, 256);
4720 }
4721
4722 /// isZero - Returns true if Elt is a constant integer zero
4723 static bool isZero(SDValue V) {
4724   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4725   return C && C->isNullValue();
4726 }
4727
4728 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4729 /// constant +0.0.
4730 bool X86::isZeroNode(SDValue Elt) {
4731   if (isZero(Elt))
4732     return true;
4733   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4734     return CFP->getValueAPF().isPosZero();
4735   return false;
4736 }
4737
4738 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4739 /// their permute mask.
4740 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4741                                     SelectionDAG &DAG) {
4742   MVT VT = SVOp->getSimpleValueType(0);
4743   unsigned NumElems = VT.getVectorNumElements();
4744   SmallVector<int, 8> MaskVec;
4745
4746   for (unsigned i = 0; i != NumElems; ++i) {
4747     int Idx = SVOp->getMaskElt(i);
4748     if (Idx >= 0) {
4749       if (Idx < (int)NumElems)
4750         Idx += NumElems;
4751       else
4752         Idx -= NumElems;
4753     }
4754     MaskVec.push_back(Idx);
4755   }
4756   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4757                               SVOp->getOperand(0), &MaskVec[0]);
4758 }
4759
4760 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4761 /// match movhlps. The lower half elements should come from upper half of
4762 /// V1 (and in order), and the upper half elements should come from the upper
4763 /// half of V2 (and in order).
4764 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4765   if (!VT.is128BitVector())
4766     return false;
4767   if (VT.getVectorNumElements() != 4)
4768     return false;
4769   for (unsigned i = 0, e = 2; i != e; ++i)
4770     if (!isUndefOrEqual(Mask[i], i+2))
4771       return false;
4772   for (unsigned i = 2; i != 4; ++i)
4773     if (!isUndefOrEqual(Mask[i], i+4))
4774       return false;
4775   return true;
4776 }
4777
4778 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4779 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4780 /// required.
4781 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4782   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4783     return false;
4784   N = N->getOperand(0).getNode();
4785   if (!ISD::isNON_EXTLoad(N))
4786     return false;
4787   if (LD)
4788     *LD = cast<LoadSDNode>(N);
4789   return true;
4790 }
4791
4792 // Test whether the given value is a vector value which will be legalized
4793 // into a load.
4794 static bool WillBeConstantPoolLoad(SDNode *N) {
4795   if (N->getOpcode() != ISD::BUILD_VECTOR)
4796     return false;
4797
4798   // Check for any non-constant elements.
4799   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4800     switch (N->getOperand(i).getNode()->getOpcode()) {
4801     case ISD::UNDEF:
4802     case ISD::ConstantFP:
4803     case ISD::Constant:
4804       break;
4805     default:
4806       return false;
4807     }
4808
4809   // Vectors of all-zeros and all-ones are materialized with special
4810   // instructions rather than being loaded.
4811   return !ISD::isBuildVectorAllZeros(N) &&
4812          !ISD::isBuildVectorAllOnes(N);
4813 }
4814
4815 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4816 /// match movlp{s|d}. The lower half elements should come from lower half of
4817 /// V1 (and in order), and the upper half elements should come from the upper
4818 /// half of V2 (and in order). And since V1 will become the source of the
4819 /// MOVLP, it must be either a vector load or a scalar load to vector.
4820 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4821                                ArrayRef<int> Mask, MVT VT) {
4822   if (!VT.is128BitVector())
4823     return false;
4824
4825   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4826     return false;
4827   // Is V2 is a vector load, don't do this transformation. We will try to use
4828   // load folding shufps op.
4829   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4830     return false;
4831
4832   unsigned NumElems = VT.getVectorNumElements();
4833
4834   if (NumElems != 2 && NumElems != 4)
4835     return false;
4836   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4837     if (!isUndefOrEqual(Mask[i], i))
4838       return false;
4839   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4840     if (!isUndefOrEqual(Mask[i], i+NumElems))
4841       return false;
4842   return true;
4843 }
4844
4845 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4846 /// all the same.
4847 static bool isSplatVector(SDNode *N) {
4848   if (N->getOpcode() != ISD::BUILD_VECTOR)
4849     return false;
4850
4851   SDValue SplatValue = N->getOperand(0);
4852   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4853     if (N->getOperand(i) != SplatValue)
4854       return false;
4855   return true;
4856 }
4857
4858 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4859 /// to an zero vector.
4860 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4861 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4862   SDValue V1 = N->getOperand(0);
4863   SDValue V2 = N->getOperand(1);
4864   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4865   for (unsigned i = 0; i != NumElems; ++i) {
4866     int Idx = N->getMaskElt(i);
4867     if (Idx >= (int)NumElems) {
4868       unsigned Opc = V2.getOpcode();
4869       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4870         continue;
4871       if (Opc != ISD::BUILD_VECTOR ||
4872           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4873         return false;
4874     } else if (Idx >= 0) {
4875       unsigned Opc = V1.getOpcode();
4876       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4877         continue;
4878       if (Opc != ISD::BUILD_VECTOR ||
4879           !X86::isZeroNode(V1.getOperand(Idx)))
4880         return false;
4881     }
4882   }
4883   return true;
4884 }
4885
4886 /// getZeroVector - Returns a vector of specified type with all zero elements.
4887 ///
4888 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4889                              SelectionDAG &DAG, SDLoc dl) {
4890   assert(VT.isVector() && "Expected a vector type");
4891
4892   // Always build SSE zero vectors as <4 x i32> bitcasted
4893   // to their dest type. This ensures they get CSE'd.
4894   SDValue Vec;
4895   if (VT.is128BitVector()) {  // SSE
4896     if (Subtarget->hasSSE2()) {  // SSE2
4897       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4898       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4899     } else { // SSE1
4900       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4901       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4902     }
4903   } else if (VT.is256BitVector()) { // AVX
4904     if (Subtarget->hasInt256()) { // AVX2
4905       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4906       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4907       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4908     } else {
4909       // 256-bit logic and arithmetic instructions in AVX are all
4910       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4911       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4912       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4913       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4914     }
4915   } else if (VT.is512BitVector()) { // AVX-512
4916       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4917       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4918                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4919       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4920   } else if (VT.getScalarType() == MVT::i1) {
4921     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4922     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4923     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4924     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4925   } else
4926     llvm_unreachable("Unexpected vector type");
4927
4928   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4929 }
4930
4931 /// getOnesVector - Returns a vector of specified type with all bits set.
4932 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4933 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4934 /// Then bitcast to their original type, ensuring they get CSE'd.
4935 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4936                              SDLoc dl) {
4937   assert(VT.isVector() && "Expected a vector type");
4938
4939   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4940   SDValue Vec;
4941   if (VT.is256BitVector()) {
4942     if (HasInt256) { // AVX2
4943       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4944       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4945     } else { // AVX
4946       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4947       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4948     }
4949   } else if (VT.is128BitVector()) {
4950     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4951   } else
4952     llvm_unreachable("Unexpected vector type");
4953
4954   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4955 }
4956
4957 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4958 /// that point to V2 points to its first element.
4959 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4960   for (unsigned i = 0; i != NumElems; ++i) {
4961     if (Mask[i] > (int)NumElems) {
4962       Mask[i] = NumElems;
4963     }
4964   }
4965 }
4966
4967 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4968 /// operation of specified width.
4969 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4970                        SDValue V2) {
4971   unsigned NumElems = VT.getVectorNumElements();
4972   SmallVector<int, 8> Mask;
4973   Mask.push_back(NumElems);
4974   for (unsigned i = 1; i != NumElems; ++i)
4975     Mask.push_back(i);
4976   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4977 }
4978
4979 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4980 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4981                           SDValue V2) {
4982   unsigned NumElems = VT.getVectorNumElements();
4983   SmallVector<int, 8> Mask;
4984   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4985     Mask.push_back(i);
4986     Mask.push_back(i + NumElems);
4987   }
4988   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4989 }
4990
4991 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4992 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4993                           SDValue V2) {
4994   unsigned NumElems = VT.getVectorNumElements();
4995   SmallVector<int, 8> Mask;
4996   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4997     Mask.push_back(i + Half);
4998     Mask.push_back(i + NumElems + Half);
4999   }
5000   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5001 }
5002
5003 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5004 // a generic shuffle instruction because the target has no such instructions.
5005 // Generate shuffles which repeat i16 and i8 several times until they can be
5006 // represented by v4f32 and then be manipulated by target suported shuffles.
5007 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5008   MVT VT = V.getSimpleValueType();
5009   int NumElems = VT.getVectorNumElements();
5010   SDLoc dl(V);
5011
5012   while (NumElems > 4) {
5013     if (EltNo < NumElems/2) {
5014       V = getUnpackl(DAG, dl, VT, V, V);
5015     } else {
5016       V = getUnpackh(DAG, dl, VT, V, V);
5017       EltNo -= NumElems/2;
5018     }
5019     NumElems >>= 1;
5020   }
5021   return V;
5022 }
5023
5024 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5025 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5026   MVT VT = V.getSimpleValueType();
5027   SDLoc dl(V);
5028
5029   if (VT.is128BitVector()) {
5030     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5031     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5032     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5033                              &SplatMask[0]);
5034   } else if (VT.is256BitVector()) {
5035     // To use VPERMILPS to splat scalars, the second half of indicies must
5036     // refer to the higher part, which is a duplication of the lower one,
5037     // because VPERMILPS can only handle in-lane permutations.
5038     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5039                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5040
5041     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5042     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5043                              &SplatMask[0]);
5044   } else
5045     llvm_unreachable("Vector size not supported");
5046
5047   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5048 }
5049
5050 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5051 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5052   MVT SrcVT = SV->getSimpleValueType(0);
5053   SDValue V1 = SV->getOperand(0);
5054   SDLoc dl(SV);
5055
5056   int EltNo = SV->getSplatIndex();
5057   int NumElems = SrcVT.getVectorNumElements();
5058   bool Is256BitVec = SrcVT.is256BitVector();
5059
5060   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5061          "Unknown how to promote splat for type");
5062
5063   // Extract the 128-bit part containing the splat element and update
5064   // the splat element index when it refers to the higher register.
5065   if (Is256BitVec) {
5066     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5067     if (EltNo >= NumElems/2)
5068       EltNo -= NumElems/2;
5069   }
5070
5071   // All i16 and i8 vector types can't be used directly by a generic shuffle
5072   // instruction because the target has no such instruction. Generate shuffles
5073   // which repeat i16 and i8 several times until they fit in i32, and then can
5074   // be manipulated by target suported shuffles.
5075   MVT EltVT = SrcVT.getVectorElementType();
5076   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5077     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5078
5079   // Recreate the 256-bit vector and place the same 128-bit vector
5080   // into the low and high part. This is necessary because we want
5081   // to use VPERM* to shuffle the vectors
5082   if (Is256BitVec) {
5083     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5084   }
5085
5086   return getLegalSplat(DAG, V1, EltNo);
5087 }
5088
5089 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5090 /// vector of zero or undef vector.  This produces a shuffle where the low
5091 /// element of V2 is swizzled into the zero/undef vector, landing at element
5092 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5093 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5094                                            bool IsZero,
5095                                            const X86Subtarget *Subtarget,
5096                                            SelectionDAG &DAG) {
5097   MVT VT = V2.getSimpleValueType();
5098   SDValue V1 = IsZero
5099     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5100   unsigned NumElems = VT.getVectorNumElements();
5101   SmallVector<int, 16> MaskVec;
5102   for (unsigned i = 0; i != NumElems; ++i)
5103     // If this is the insertion idx, put the low elt of V2 here.
5104     MaskVec.push_back(i == Idx ? NumElems : i);
5105   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5106 }
5107
5108 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5109 /// target specific opcode. Returns true if the Mask could be calculated.
5110 /// Sets IsUnary to true if only uses one source.
5111 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5112                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5113   unsigned NumElems = VT.getVectorNumElements();
5114   SDValue ImmN;
5115
5116   IsUnary = false;
5117   switch(N->getOpcode()) {
5118   case X86ISD::SHUFP:
5119     ImmN = N->getOperand(N->getNumOperands()-1);
5120     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5121     break;
5122   case X86ISD::UNPCKH:
5123     DecodeUNPCKHMask(VT, Mask);
5124     break;
5125   case X86ISD::UNPCKL:
5126     DecodeUNPCKLMask(VT, Mask);
5127     break;
5128   case X86ISD::MOVHLPS:
5129     DecodeMOVHLPSMask(NumElems, Mask);
5130     break;
5131   case X86ISD::MOVLHPS:
5132     DecodeMOVLHPSMask(NumElems, Mask);
5133     break;
5134   case X86ISD::PALIGNR:
5135     ImmN = N->getOperand(N->getNumOperands()-1);
5136     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5137     break;
5138   case X86ISD::PSHUFD:
5139   case X86ISD::VPERMILP:
5140     ImmN = N->getOperand(N->getNumOperands()-1);
5141     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5142     IsUnary = true;
5143     break;
5144   case X86ISD::PSHUFHW:
5145     ImmN = N->getOperand(N->getNumOperands()-1);
5146     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5147     IsUnary = true;
5148     break;
5149   case X86ISD::PSHUFLW:
5150     ImmN = N->getOperand(N->getNumOperands()-1);
5151     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5152     IsUnary = true;
5153     break;
5154   case X86ISD::VPERMI:
5155     ImmN = N->getOperand(N->getNumOperands()-1);
5156     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5157     IsUnary = true;
5158     break;
5159   case X86ISD::MOVSS:
5160   case X86ISD::MOVSD: {
5161     // The index 0 always comes from the first element of the second source,
5162     // this is why MOVSS and MOVSD are used in the first place. The other
5163     // elements come from the other positions of the first source vector
5164     Mask.push_back(NumElems);
5165     for (unsigned i = 1; i != NumElems; ++i) {
5166       Mask.push_back(i);
5167     }
5168     break;
5169   }
5170   case X86ISD::VPERM2X128:
5171     ImmN = N->getOperand(N->getNumOperands()-1);
5172     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5173     if (Mask.empty()) return false;
5174     break;
5175   case X86ISD::MOVDDUP:
5176   case X86ISD::MOVLHPD:
5177   case X86ISD::MOVLPD:
5178   case X86ISD::MOVLPS:
5179   case X86ISD::MOVSHDUP:
5180   case X86ISD::MOVSLDUP:
5181     // Not yet implemented
5182     return false;
5183   default: llvm_unreachable("unknown target shuffle node");
5184   }
5185
5186   return true;
5187 }
5188
5189 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5190 /// element of the result of the vector shuffle.
5191 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5192                                    unsigned Depth) {
5193   if (Depth == 6)
5194     return SDValue();  // Limit search depth.
5195
5196   SDValue V = SDValue(N, 0);
5197   EVT VT = V.getValueType();
5198   unsigned Opcode = V.getOpcode();
5199
5200   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5201   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5202     int Elt = SV->getMaskElt(Index);
5203
5204     if (Elt < 0)
5205       return DAG.getUNDEF(VT.getVectorElementType());
5206
5207     unsigned NumElems = VT.getVectorNumElements();
5208     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5209                                          : SV->getOperand(1);
5210     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5211   }
5212
5213   // Recurse into target specific vector shuffles to find scalars.
5214   if (isTargetShuffle(Opcode)) {
5215     MVT ShufVT = V.getSimpleValueType();
5216     unsigned NumElems = ShufVT.getVectorNumElements();
5217     SmallVector<int, 16> ShuffleMask;
5218     bool IsUnary;
5219
5220     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5221       return SDValue();
5222
5223     int Elt = ShuffleMask[Index];
5224     if (Elt < 0)
5225       return DAG.getUNDEF(ShufVT.getVectorElementType());
5226
5227     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5228                                          : N->getOperand(1);
5229     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5230                                Depth+1);
5231   }
5232
5233   // Actual nodes that may contain scalar elements
5234   if (Opcode == ISD::BITCAST) {
5235     V = V.getOperand(0);
5236     EVT SrcVT = V.getValueType();
5237     unsigned NumElems = VT.getVectorNumElements();
5238
5239     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5240       return SDValue();
5241   }
5242
5243   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5244     return (Index == 0) ? V.getOperand(0)
5245                         : DAG.getUNDEF(VT.getVectorElementType());
5246
5247   if (V.getOpcode() == ISD::BUILD_VECTOR)
5248     return V.getOperand(Index);
5249
5250   return SDValue();
5251 }
5252
5253 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5254 /// shuffle operation which come from a consecutively from a zero. The
5255 /// search can start in two different directions, from left or right.
5256 /// We count undefs as zeros until PreferredNum is reached.
5257 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5258                                          unsigned NumElems, bool ZerosFromLeft,
5259                                          SelectionDAG &DAG,
5260                                          unsigned PreferredNum = -1U) {
5261   unsigned NumZeros = 0;
5262   for (unsigned i = 0; i != NumElems; ++i) {
5263     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5264     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5265     if (!Elt.getNode())
5266       break;
5267
5268     if (X86::isZeroNode(Elt))
5269       ++NumZeros;
5270     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5271       NumZeros = std::min(NumZeros + 1, PreferredNum);
5272     else
5273       break;
5274   }
5275
5276   return NumZeros;
5277 }
5278
5279 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5280 /// correspond consecutively to elements from one of the vector operands,
5281 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5282 static
5283 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5284                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5285                               unsigned NumElems, unsigned &OpNum) {
5286   bool SeenV1 = false;
5287   bool SeenV2 = false;
5288
5289   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5290     int Idx = SVOp->getMaskElt(i);
5291     // Ignore undef indicies
5292     if (Idx < 0)
5293       continue;
5294
5295     if (Idx < (int)NumElems)
5296       SeenV1 = true;
5297     else
5298       SeenV2 = true;
5299
5300     // Only accept consecutive elements from the same vector
5301     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5302       return false;
5303   }
5304
5305   OpNum = SeenV1 ? 0 : 1;
5306   return true;
5307 }
5308
5309 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5310 /// logical left shift of a vector.
5311 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5312                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5313   unsigned NumElems =
5314     SVOp->getSimpleValueType(0).getVectorNumElements();
5315   unsigned NumZeros = getNumOfConsecutiveZeros(
5316       SVOp, NumElems, false /* check zeros from right */, DAG,
5317       SVOp->getMaskElt(0));
5318   unsigned OpSrc;
5319
5320   if (!NumZeros)
5321     return false;
5322
5323   // Considering the elements in the mask that are not consecutive zeros,
5324   // check if they consecutively come from only one of the source vectors.
5325   //
5326   //               V1 = {X, A, B, C}     0
5327   //                         \  \  \    /
5328   //   vector_shuffle V1, V2 <1, 2, 3, X>
5329   //
5330   if (!isShuffleMaskConsecutive(SVOp,
5331             0,                   // Mask Start Index
5332             NumElems-NumZeros,   // Mask End Index(exclusive)
5333             NumZeros,            // Where to start looking in the src vector
5334             NumElems,            // Number of elements in vector
5335             OpSrc))              // Which source operand ?
5336     return false;
5337
5338   isLeft = false;
5339   ShAmt = NumZeros;
5340   ShVal = SVOp->getOperand(OpSrc);
5341   return true;
5342 }
5343
5344 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5345 /// logical left shift of a vector.
5346 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5347                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5348   unsigned NumElems =
5349     SVOp->getSimpleValueType(0).getVectorNumElements();
5350   unsigned NumZeros = getNumOfConsecutiveZeros(
5351       SVOp, NumElems, true /* check zeros from left */, DAG,
5352       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5353   unsigned OpSrc;
5354
5355   if (!NumZeros)
5356     return false;
5357
5358   // Considering the elements in the mask that are not consecutive zeros,
5359   // check if they consecutively come from only one of the source vectors.
5360   //
5361   //                           0    { A, B, X, X } = V2
5362   //                          / \    /  /
5363   //   vector_shuffle V1, V2 <X, X, 4, 5>
5364   //
5365   if (!isShuffleMaskConsecutive(SVOp,
5366             NumZeros,     // Mask Start Index
5367             NumElems,     // Mask End Index(exclusive)
5368             0,            // Where to start looking in the src vector
5369             NumElems,     // Number of elements in vector
5370             OpSrc))       // Which source operand ?
5371     return false;
5372
5373   isLeft = true;
5374   ShAmt = NumZeros;
5375   ShVal = SVOp->getOperand(OpSrc);
5376   return true;
5377 }
5378
5379 /// isVectorShift - Returns true if the shuffle can be implemented as a
5380 /// logical left or right shift of a vector.
5381 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5382                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5383   // Although the logic below support any bitwidth size, there are no
5384   // shift instructions which handle more than 128-bit vectors.
5385   if (!SVOp->getSimpleValueType(0).is128BitVector())
5386     return false;
5387
5388   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5389       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5390     return true;
5391
5392   return false;
5393 }
5394
5395 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5396 ///
5397 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5398                                        unsigned NumNonZero, unsigned NumZero,
5399                                        SelectionDAG &DAG,
5400                                        const X86Subtarget* Subtarget,
5401                                        const TargetLowering &TLI) {
5402   if (NumNonZero > 8)
5403     return SDValue();
5404
5405   SDLoc dl(Op);
5406   SDValue V;
5407   bool First = true;
5408   for (unsigned i = 0; i < 16; ++i) {
5409     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5410     if (ThisIsNonZero && First) {
5411       if (NumZero)
5412         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5413       else
5414         V = DAG.getUNDEF(MVT::v8i16);
5415       First = false;
5416     }
5417
5418     if ((i & 1) != 0) {
5419       SDValue ThisElt, LastElt;
5420       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5421       if (LastIsNonZero) {
5422         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5423                               MVT::i16, Op.getOperand(i-1));
5424       }
5425       if (ThisIsNonZero) {
5426         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5427         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5428                               ThisElt, DAG.getConstant(8, MVT::i8));
5429         if (LastIsNonZero)
5430           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5431       } else
5432         ThisElt = LastElt;
5433
5434       if (ThisElt.getNode())
5435         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5436                         DAG.getIntPtrConstant(i/2));
5437     }
5438   }
5439
5440   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5441 }
5442
5443 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5444 ///
5445 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5446                                      unsigned NumNonZero, unsigned NumZero,
5447                                      SelectionDAG &DAG,
5448                                      const X86Subtarget* Subtarget,
5449                                      const TargetLowering &TLI) {
5450   if (NumNonZero > 4)
5451     return SDValue();
5452
5453   SDLoc dl(Op);
5454   SDValue V;
5455   bool First = true;
5456   for (unsigned i = 0; i < 8; ++i) {
5457     bool isNonZero = (NonZeros & (1 << i)) != 0;
5458     if (isNonZero) {
5459       if (First) {
5460         if (NumZero)
5461           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5462         else
5463           V = DAG.getUNDEF(MVT::v8i16);
5464         First = false;
5465       }
5466       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5467                       MVT::v8i16, V, Op.getOperand(i),
5468                       DAG.getIntPtrConstant(i));
5469     }
5470   }
5471
5472   return V;
5473 }
5474
5475 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5476 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5477                                      unsigned NonZeros, unsigned NumNonZero,
5478                                      unsigned NumZero, SelectionDAG &DAG,
5479                                      const X86Subtarget *Subtarget,
5480                                      const TargetLowering &TLI) {
5481   // We know there's at least one non-zero element
5482   unsigned FirstNonZeroIdx = 0;
5483   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5484   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5485          X86::isZeroNode(FirstNonZero)) {
5486     ++FirstNonZeroIdx;
5487     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5488   }
5489
5490   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5491       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5492     return SDValue();
5493
5494   SDValue V = FirstNonZero.getOperand(0);
5495   MVT VVT = V.getSimpleValueType();
5496   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5497     return SDValue();
5498
5499   unsigned FirstNonZeroDst =
5500       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5501   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5502   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5503   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5504
5505   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5506     SDValue Elem = Op.getOperand(Idx);
5507     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5508       continue;
5509
5510     // TODO: What else can be here? Deal with it.
5511     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5512       return SDValue();
5513
5514     // TODO: Some optimizations are still possible here
5515     // ex: Getting one element from a vector, and the rest from another.
5516     if (Elem.getOperand(0) != V)
5517       return SDValue();
5518
5519     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5520     if (Dst == Idx)
5521       ++CorrectIdx;
5522     else if (IncorrectIdx == -1U) {
5523       IncorrectIdx = Idx;
5524       IncorrectDst = Dst;
5525     } else
5526       // There was already one element with an incorrect index.
5527       // We can't optimize this case to an insertps.
5528       return SDValue();
5529   }
5530
5531   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5532     SDLoc dl(Op);
5533     EVT VT = Op.getSimpleValueType();
5534     unsigned ElementMoveMask = 0;
5535     if (IncorrectIdx == -1U)
5536       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5537     else
5538       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5539
5540     SDValue InsertpsMask =
5541         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5542     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5543   }
5544
5545   return SDValue();
5546 }
5547
5548 /// getVShift - Return a vector logical shift node.
5549 ///
5550 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5551                          unsigned NumBits, SelectionDAG &DAG,
5552                          const TargetLowering &TLI, SDLoc dl) {
5553   assert(VT.is128BitVector() && "Unknown type for VShift");
5554   EVT ShVT = MVT::v2i64;
5555   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5556   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5557   return DAG.getNode(ISD::BITCAST, dl, VT,
5558                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5559                              DAG.getConstant(NumBits,
5560                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5561 }
5562
5563 static SDValue
5564 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5565
5566   // Check if the scalar load can be widened into a vector load. And if
5567   // the address is "base + cst" see if the cst can be "absorbed" into
5568   // the shuffle mask.
5569   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5570     SDValue Ptr = LD->getBasePtr();
5571     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5572       return SDValue();
5573     EVT PVT = LD->getValueType(0);
5574     if (PVT != MVT::i32 && PVT != MVT::f32)
5575       return SDValue();
5576
5577     int FI = -1;
5578     int64_t Offset = 0;
5579     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5580       FI = FINode->getIndex();
5581       Offset = 0;
5582     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5583                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5584       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5585       Offset = Ptr.getConstantOperandVal(1);
5586       Ptr = Ptr.getOperand(0);
5587     } else {
5588       return SDValue();
5589     }
5590
5591     // FIXME: 256-bit vector instructions don't require a strict alignment,
5592     // improve this code to support it better.
5593     unsigned RequiredAlign = VT.getSizeInBits()/8;
5594     SDValue Chain = LD->getChain();
5595     // Make sure the stack object alignment is at least 16 or 32.
5596     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5597     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5598       if (MFI->isFixedObjectIndex(FI)) {
5599         // Can't change the alignment. FIXME: It's possible to compute
5600         // the exact stack offset and reference FI + adjust offset instead.
5601         // If someone *really* cares about this. That's the way to implement it.
5602         return SDValue();
5603       } else {
5604         MFI->setObjectAlignment(FI, RequiredAlign);
5605       }
5606     }
5607
5608     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5609     // Ptr + (Offset & ~15).
5610     if (Offset < 0)
5611       return SDValue();
5612     if ((Offset % RequiredAlign) & 3)
5613       return SDValue();
5614     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5615     if (StartOffset)
5616       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5617                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5618
5619     int EltNo = (Offset - StartOffset) >> 2;
5620     unsigned NumElems = VT.getVectorNumElements();
5621
5622     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5623     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5624                              LD->getPointerInfo().getWithOffset(StartOffset),
5625                              false, false, false, 0);
5626
5627     SmallVector<int, 8> Mask;
5628     for (unsigned i = 0; i != NumElems; ++i)
5629       Mask.push_back(EltNo);
5630
5631     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5632   }
5633
5634   return SDValue();
5635 }
5636
5637 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5638 /// vector of type 'VT', see if the elements can be replaced by a single large
5639 /// load which has the same value as a build_vector whose operands are 'elts'.
5640 ///
5641 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5642 ///
5643 /// FIXME: we'd also like to handle the case where the last elements are zero
5644 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5645 /// There's even a handy isZeroNode for that purpose.
5646 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5647                                         SDLoc &DL, SelectionDAG &DAG,
5648                                         bool isAfterLegalize) {
5649   EVT EltVT = VT.getVectorElementType();
5650   unsigned NumElems = Elts.size();
5651
5652   LoadSDNode *LDBase = nullptr;
5653   unsigned LastLoadedElt = -1U;
5654
5655   // For each element in the initializer, see if we've found a load or an undef.
5656   // If we don't find an initial load element, or later load elements are
5657   // non-consecutive, bail out.
5658   for (unsigned i = 0; i < NumElems; ++i) {
5659     SDValue Elt = Elts[i];
5660
5661     if (!Elt.getNode() ||
5662         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5663       return SDValue();
5664     if (!LDBase) {
5665       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5666         return SDValue();
5667       LDBase = cast<LoadSDNode>(Elt.getNode());
5668       LastLoadedElt = i;
5669       continue;
5670     }
5671     if (Elt.getOpcode() == ISD::UNDEF)
5672       continue;
5673
5674     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5675     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5676       return SDValue();
5677     LastLoadedElt = i;
5678   }
5679
5680   // If we have found an entire vector of loads and undefs, then return a large
5681   // load of the entire vector width starting at the base pointer.  If we found
5682   // consecutive loads for the low half, generate a vzext_load node.
5683   if (LastLoadedElt == NumElems - 1) {
5684
5685     if (isAfterLegalize &&
5686         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5687       return SDValue();
5688
5689     SDValue NewLd = SDValue();
5690
5691     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5692       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5693                           LDBase->getPointerInfo(),
5694                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5695                           LDBase->isInvariant(), 0);
5696     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5697                         LDBase->getPointerInfo(),
5698                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5699                         LDBase->isInvariant(), LDBase->getAlignment());
5700
5701     if (LDBase->hasAnyUseOfValue(1)) {
5702       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5703                                      SDValue(LDBase, 1),
5704                                      SDValue(NewLd.getNode(), 1));
5705       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5706       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5707                              SDValue(NewLd.getNode(), 1));
5708     }
5709
5710     return NewLd;
5711   }
5712   if (NumElems == 4 && LastLoadedElt == 1 &&
5713       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5714     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5715     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5716     SDValue ResNode =
5717         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5718                                 LDBase->getPointerInfo(),
5719                                 LDBase->getAlignment(),
5720                                 false/*isVolatile*/, true/*ReadMem*/,
5721                                 false/*WriteMem*/);
5722
5723     // Make sure the newly-created LOAD is in the same position as LDBase in
5724     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5725     // update uses of LDBase's output chain to use the TokenFactor.
5726     if (LDBase->hasAnyUseOfValue(1)) {
5727       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5728                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5729       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5730       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5731                              SDValue(ResNode.getNode(), 1));
5732     }
5733
5734     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5735   }
5736   return SDValue();
5737 }
5738
5739 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5740 /// to generate a splat value for the following cases:
5741 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5742 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5743 /// a scalar load, or a constant.
5744 /// The VBROADCAST node is returned when a pattern is found,
5745 /// or SDValue() otherwise.
5746 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5747                                     SelectionDAG &DAG) {
5748   if (!Subtarget->hasFp256())
5749     return SDValue();
5750
5751   MVT VT = Op.getSimpleValueType();
5752   SDLoc dl(Op);
5753
5754   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5755          "Unsupported vector type for broadcast.");
5756
5757   SDValue Ld;
5758   bool ConstSplatVal;
5759
5760   switch (Op.getOpcode()) {
5761     default:
5762       // Unknown pattern found.
5763       return SDValue();
5764
5765     case ISD::BUILD_VECTOR: {
5766       // The BUILD_VECTOR node must be a splat.
5767       if (!isSplatVector(Op.getNode()))
5768         return SDValue();
5769
5770       Ld = Op.getOperand(0);
5771       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5772                      Ld.getOpcode() == ISD::ConstantFP);
5773
5774       // The suspected load node has several users. Make sure that all
5775       // of its users are from the BUILD_VECTOR node.
5776       // Constants may have multiple users.
5777       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5778         return SDValue();
5779       break;
5780     }
5781
5782     case ISD::VECTOR_SHUFFLE: {
5783       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5784
5785       // Shuffles must have a splat mask where the first element is
5786       // broadcasted.
5787       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5788         return SDValue();
5789
5790       SDValue Sc = Op.getOperand(0);
5791       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5792           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5793
5794         if (!Subtarget->hasInt256())
5795           return SDValue();
5796
5797         // Use the register form of the broadcast instruction available on AVX2.
5798         if (VT.getSizeInBits() >= 256)
5799           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5800         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5801       }
5802
5803       Ld = Sc.getOperand(0);
5804       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5805                        Ld.getOpcode() == ISD::ConstantFP);
5806
5807       // The scalar_to_vector node and the suspected
5808       // load node must have exactly one user.
5809       // Constants may have multiple users.
5810
5811       // AVX-512 has register version of the broadcast
5812       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5813         Ld.getValueType().getSizeInBits() >= 32;
5814       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5815           !hasRegVer))
5816         return SDValue();
5817       break;
5818     }
5819   }
5820
5821   bool IsGE256 = (VT.getSizeInBits() >= 256);
5822
5823   // Handle the broadcasting a single constant scalar from the constant pool
5824   // into a vector. On Sandybridge it is still better to load a constant vector
5825   // from the constant pool and not to broadcast it from a scalar.
5826   if (ConstSplatVal && Subtarget->hasInt256()) {
5827     EVT CVT = Ld.getValueType();
5828     assert(!CVT.isVector() && "Must not broadcast a vector type");
5829     unsigned ScalarSize = CVT.getSizeInBits();
5830
5831     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5832       const Constant *C = nullptr;
5833       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5834         C = CI->getConstantIntValue();
5835       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5836         C = CF->getConstantFPValue();
5837
5838       assert(C && "Invalid constant type");
5839
5840       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5841       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5842       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5843       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5844                        MachinePointerInfo::getConstantPool(),
5845                        false, false, false, Alignment);
5846
5847       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5848     }
5849   }
5850
5851   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5852   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5853
5854   // Handle AVX2 in-register broadcasts.
5855   if (!IsLoad && Subtarget->hasInt256() &&
5856       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5857     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5858
5859   // The scalar source must be a normal load.
5860   if (!IsLoad)
5861     return SDValue();
5862
5863   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5864     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5865
5866   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5867   // double since there is no vbroadcastsd xmm
5868   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5869     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5870       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5871   }
5872
5873   // Unsupported broadcast.
5874   return SDValue();
5875 }
5876
5877 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5878 /// underlying vector and index.
5879 ///
5880 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5881 /// index.
5882 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5883                                          SDValue ExtIdx) {
5884   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5885   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5886     return Idx;
5887
5888   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5889   // lowered this:
5890   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5891   // to:
5892   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5893   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5894   //                           undef)
5895   //                       Constant<0>)
5896   // In this case the vector is the extract_subvector expression and the index
5897   // is 2, as specified by the shuffle.
5898   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5899   SDValue ShuffleVec = SVOp->getOperand(0);
5900   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5901   assert(ShuffleVecVT.getVectorElementType() ==
5902          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5903
5904   int ShuffleIdx = SVOp->getMaskElt(Idx);
5905   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5906     ExtractedFromVec = ShuffleVec;
5907     return ShuffleIdx;
5908   }
5909   return Idx;
5910 }
5911
5912 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5913   MVT VT = Op.getSimpleValueType();
5914
5915   // Skip if insert_vec_elt is not supported.
5916   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5917   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5918     return SDValue();
5919
5920   SDLoc DL(Op);
5921   unsigned NumElems = Op.getNumOperands();
5922
5923   SDValue VecIn1;
5924   SDValue VecIn2;
5925   SmallVector<unsigned, 4> InsertIndices;
5926   SmallVector<int, 8> Mask(NumElems, -1);
5927
5928   for (unsigned i = 0; i != NumElems; ++i) {
5929     unsigned Opc = Op.getOperand(i).getOpcode();
5930
5931     if (Opc == ISD::UNDEF)
5932       continue;
5933
5934     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5935       // Quit if more than 1 elements need inserting.
5936       if (InsertIndices.size() > 1)
5937         return SDValue();
5938
5939       InsertIndices.push_back(i);
5940       continue;
5941     }
5942
5943     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5944     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5945     // Quit if non-constant index.
5946     if (!isa<ConstantSDNode>(ExtIdx))
5947       return SDValue();
5948     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5949
5950     // Quit if extracted from vector of different type.
5951     if (ExtractedFromVec.getValueType() != VT)
5952       return SDValue();
5953
5954     if (!VecIn1.getNode())
5955       VecIn1 = ExtractedFromVec;
5956     else if (VecIn1 != ExtractedFromVec) {
5957       if (!VecIn2.getNode())
5958         VecIn2 = ExtractedFromVec;
5959       else if (VecIn2 != ExtractedFromVec)
5960         // Quit if more than 2 vectors to shuffle
5961         return SDValue();
5962     }
5963
5964     if (ExtractedFromVec == VecIn1)
5965       Mask[i] = Idx;
5966     else if (ExtractedFromVec == VecIn2)
5967       Mask[i] = Idx + NumElems;
5968   }
5969
5970   if (!VecIn1.getNode())
5971     return SDValue();
5972
5973   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5974   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5975   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5976     unsigned Idx = InsertIndices[i];
5977     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5978                      DAG.getIntPtrConstant(Idx));
5979   }
5980
5981   return NV;
5982 }
5983
5984 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5985 SDValue
5986 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5987
5988   MVT VT = Op.getSimpleValueType();
5989   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5990          "Unexpected type in LowerBUILD_VECTORvXi1!");
5991
5992   SDLoc dl(Op);
5993   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5994     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5995     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5996     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5997   }
5998
5999   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6000     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6001     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6002     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6003   }
6004
6005   bool AllContants = true;
6006   uint64_t Immediate = 0;
6007   int NonConstIdx = -1;
6008   bool IsSplat = true;
6009   unsigned NumNonConsts = 0;
6010   unsigned NumConsts = 0;
6011   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6012     SDValue In = Op.getOperand(idx);
6013     if (In.getOpcode() == ISD::UNDEF)
6014       continue;
6015     if (!isa<ConstantSDNode>(In)) {
6016       AllContants = false;
6017       NonConstIdx = idx;
6018       NumNonConsts++;
6019     }
6020     else {
6021       NumConsts++;
6022       if (cast<ConstantSDNode>(In)->getZExtValue())
6023       Immediate |= (1ULL << idx);
6024     }
6025     if (In != Op.getOperand(0))
6026       IsSplat = false;
6027   }
6028
6029   if (AllContants) {
6030     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6031       DAG.getConstant(Immediate, MVT::i16));
6032     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6033                        DAG.getIntPtrConstant(0));
6034   }
6035
6036   if (NumNonConsts == 1 && NonConstIdx != 0) {
6037     SDValue DstVec;
6038     if (NumConsts) {
6039       SDValue VecAsImm = DAG.getConstant(Immediate,
6040                                          MVT::getIntegerVT(VT.getSizeInBits()));
6041       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6042     }
6043     else 
6044       DstVec = DAG.getUNDEF(VT);
6045     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6046                        Op.getOperand(NonConstIdx),
6047                        DAG.getIntPtrConstant(NonConstIdx));
6048   }
6049   if (!IsSplat && (NonConstIdx != 0))
6050     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6051   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6052   SDValue Select;
6053   if (IsSplat)
6054     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6055                           DAG.getConstant(-1, SelectVT),
6056                           DAG.getConstant(0, SelectVT));
6057   else
6058     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6059                          DAG.getConstant((Immediate | 1), SelectVT),
6060                          DAG.getConstant(Immediate, SelectVT));
6061   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6062 }
6063
6064 /// \brief Return true if \p N implements a horizontal binop and return the
6065 /// operands for the horizontal binop into V0 and V1.
6066 /// 
6067 /// This is a helper function of PerformBUILD_VECTORCombine.
6068 /// This function checks that the build_vector \p N in input implements a
6069 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6070 /// operation to match.
6071 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6072 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6073 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6074 /// arithmetic sub.
6075 ///
6076 /// This function only analyzes elements of \p N whose indices are
6077 /// in range [BaseIdx, LastIdx).
6078 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6079                               SelectionDAG &DAG,
6080                               unsigned BaseIdx, unsigned LastIdx,
6081                               SDValue &V0, SDValue &V1) {
6082   EVT VT = N->getValueType(0);
6083
6084   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6085   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6086          "Invalid Vector in input!");
6087   
6088   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6089   bool CanFold = true;
6090   unsigned ExpectedVExtractIdx = BaseIdx;
6091   unsigned NumElts = LastIdx - BaseIdx;
6092   V0 = DAG.getUNDEF(VT);
6093   V1 = DAG.getUNDEF(VT);
6094
6095   // Check if N implements a horizontal binop.
6096   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6097     SDValue Op = N->getOperand(i + BaseIdx);
6098
6099     // Skip UNDEFs.
6100     if (Op->getOpcode() == ISD::UNDEF) {
6101       // Update the expected vector extract index.
6102       if (i * 2 == NumElts)
6103         ExpectedVExtractIdx = BaseIdx;
6104       ExpectedVExtractIdx += 2;
6105       continue;
6106     }
6107
6108     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6109
6110     if (!CanFold)
6111       break;
6112
6113     SDValue Op0 = Op.getOperand(0);
6114     SDValue Op1 = Op.getOperand(1);
6115
6116     // Try to match the following pattern:
6117     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6118     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6119         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6120         Op0.getOperand(0) == Op1.getOperand(0) &&
6121         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6122         isa<ConstantSDNode>(Op1.getOperand(1)));
6123     if (!CanFold)
6124       break;
6125
6126     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6127     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6128
6129     if (i * 2 < NumElts) {
6130       if (V0.getOpcode() == ISD::UNDEF)
6131         V0 = Op0.getOperand(0);
6132     } else {
6133       if (V1.getOpcode() == ISD::UNDEF)
6134         V1 = Op0.getOperand(0);
6135       if (i * 2 == NumElts)
6136         ExpectedVExtractIdx = BaseIdx;
6137     }
6138
6139     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6140     if (I0 == ExpectedVExtractIdx)
6141       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6142     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6143       // Try to match the following dag sequence:
6144       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6145       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6146     } else
6147       CanFold = false;
6148
6149     ExpectedVExtractIdx += 2;
6150   }
6151
6152   return CanFold;
6153 }
6154
6155 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6156 /// a concat_vector. 
6157 ///
6158 /// This is a helper function of PerformBUILD_VECTORCombine.
6159 /// This function expects two 256-bit vectors called V0 and V1.
6160 /// At first, each vector is split into two separate 128-bit vectors.
6161 /// Then, the resulting 128-bit vectors are used to implement two
6162 /// horizontal binary operations. 
6163 ///
6164 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6165 ///
6166 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6167 /// the two new horizontal binop.
6168 /// When Mode is set, the first horizontal binop dag node would take as input
6169 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6170 /// horizontal binop dag node would take as input the lower 128-bit of V1
6171 /// and the upper 128-bit of V1.
6172 ///   Example:
6173 ///     HADD V0_LO, V0_HI
6174 ///     HADD V1_LO, V1_HI
6175 ///
6176 /// Otherwise, the first horizontal binop dag node takes as input the lower
6177 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6178 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6179 ///   Example:
6180 ///     HADD V0_LO, V1_LO
6181 ///     HADD V0_HI, V1_HI
6182 ///
6183 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6184 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6185 /// the upper 128-bits of the result.
6186 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6187                                      SDLoc DL, SelectionDAG &DAG,
6188                                      unsigned X86Opcode, bool Mode,
6189                                      bool isUndefLO, bool isUndefHI) {
6190   EVT VT = V0.getValueType();
6191   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6192          "Invalid nodes in input!");
6193
6194   unsigned NumElts = VT.getVectorNumElements();
6195   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6196   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6197   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6198   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6199   EVT NewVT = V0_LO.getValueType();
6200
6201   SDValue LO = DAG.getUNDEF(NewVT);
6202   SDValue HI = DAG.getUNDEF(NewVT);
6203
6204   if (Mode) {
6205     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6206     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6207       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6208     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6209       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6210   } else {
6211     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6212     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6213                        V1_LO->getOpcode() != ISD::UNDEF))
6214       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6215
6216     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6217                        V1_HI->getOpcode() != ISD::UNDEF))
6218       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6219   }
6220
6221   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6222 }
6223
6224 /// \brief Try to fold a build_vector that performs an 'addsub' into the
6225 /// sequence of 'vadd + vsub + blendi'.
6226 static SDValue matchAddSub(const BuildVectorSDNode *BV, SelectionDAG &DAG,
6227                            const X86Subtarget *Subtarget) {
6228   SDLoc DL(BV);
6229   EVT VT = BV->getValueType(0);
6230   unsigned NumElts = VT.getVectorNumElements();
6231   SDValue InVec0 = DAG.getUNDEF(VT);
6232   SDValue InVec1 = DAG.getUNDEF(VT);
6233
6234   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
6235           VT == MVT::v2f64) && "build_vector with an invalid type found!");
6236
6237   // Don't try to emit a VSELECT that cannot be lowered into a blend.
6238   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6239   if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
6240     return SDValue();
6241
6242   // Odd-numbered elements in the input build vector are obtained from
6243   // adding two integer/float elements.
6244   // Even-numbered elements in the input build vector are obtained from
6245   // subtracting two integer/float elements.
6246   unsigned ExpectedOpcode = ISD::FSUB;
6247   unsigned NextExpectedOpcode = ISD::FADD;
6248   bool AddFound = false;
6249   bool SubFound = false;
6250
6251   for (unsigned i = 0, e = NumElts; i != e; i++) {
6252     SDValue Op = BV->getOperand(i);
6253       
6254     // Skip 'undef' values.
6255     unsigned Opcode = Op.getOpcode();
6256     if (Opcode == ISD::UNDEF) {
6257       std::swap(ExpectedOpcode, NextExpectedOpcode);
6258       continue;
6259     }
6260       
6261     // Early exit if we found an unexpected opcode.
6262     if (Opcode != ExpectedOpcode)
6263       return SDValue();
6264
6265     SDValue Op0 = Op.getOperand(0);
6266     SDValue Op1 = Op.getOperand(1);
6267
6268     // Try to match the following pattern:
6269     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
6270     // Early exit if we cannot match that sequence.
6271     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6272         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6273         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
6274         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
6275         Op0.getOperand(1) != Op1.getOperand(1))
6276       return SDValue();
6277
6278     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6279     if (I0 != i)
6280       return SDValue();
6281
6282     // We found a valid add/sub node. Update the information accordingly.
6283     if (i & 1)
6284       AddFound = true;
6285     else
6286       SubFound = true;
6287
6288     // Update InVec0 and InVec1.
6289     if (InVec0.getOpcode() == ISD::UNDEF)
6290       InVec0 = Op0.getOperand(0);
6291     if (InVec1.getOpcode() == ISD::UNDEF)
6292       InVec1 = Op1.getOperand(0);
6293
6294     // Make sure that operands in input to each add/sub node always
6295     // come from a same pair of vectors.
6296     if (InVec0 != Op0.getOperand(0)) {
6297       if (ExpectedOpcode == ISD::FSUB)
6298         return SDValue();
6299
6300       // FADD is commutable. Try to commute the operands
6301       // and then test again.
6302       std::swap(Op0, Op1);
6303       if (InVec0 != Op0.getOperand(0))
6304         return SDValue();
6305     }
6306
6307     if (InVec1 != Op1.getOperand(0))
6308       return SDValue();
6309
6310     // Update the pair of expected opcodes.
6311     std::swap(ExpectedOpcode, NextExpectedOpcode);
6312   }
6313
6314   // Don't try to fold this build_vector into a VSELECT if it has
6315   // too many UNDEF operands.
6316   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
6317       InVec1.getOpcode() != ISD::UNDEF) {
6318     // Emit a sequence of vector add and sub followed by a VSELECT.
6319     // The new VSELECT will be lowered into a BLENDI.
6320     // At ISel stage, we pattern-match the sequence 'add + sub + BLENDI'
6321     // and emit a single ADDSUB instruction.
6322     SDValue Sub = DAG.getNode(ExpectedOpcode, DL, VT, InVec0, InVec1);
6323     SDValue Add = DAG.getNode(NextExpectedOpcode, DL, VT, InVec0, InVec1);
6324
6325     // Construct the VSELECT mask.
6326     EVT MaskVT = VT.changeVectorElementTypeToInteger();
6327     EVT SVT = MaskVT.getVectorElementType();
6328     unsigned SVTBits = SVT.getSizeInBits();
6329     SmallVector<SDValue, 8> Ops;
6330
6331     for (unsigned i = 0, e = NumElts; i != e; ++i) {
6332       APInt Value = i & 1 ? APInt::getNullValue(SVTBits) :
6333                             APInt::getAllOnesValue(SVTBits);
6334       SDValue Constant = DAG.getConstant(Value, SVT);
6335       Ops.push_back(Constant);
6336     }
6337
6338     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, MaskVT, Ops);
6339     return DAG.getSelect(DL, VT, Mask, Sub, Add);
6340   }
6341   
6342   return SDValue();
6343 }
6344
6345 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6346                                           const X86Subtarget *Subtarget) {
6347   SDLoc DL(N);
6348   EVT VT = N->getValueType(0);
6349   unsigned NumElts = VT.getVectorNumElements();
6350   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6351   SDValue InVec0, InVec1;
6352
6353   // Try to match an ADDSUB.
6354   if ((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
6355       (Subtarget->hasAVX() && (VT == MVT::v8f32 || VT == MVT::v4f64))) {
6356     SDValue Value = matchAddSub(BV, DAG, Subtarget);
6357     if (Value.getNode())
6358       return Value;
6359   }
6360
6361   // Try to match horizontal ADD/SUB.
6362   unsigned NumUndefsLO = 0;
6363   unsigned NumUndefsHI = 0;
6364   unsigned Half = NumElts/2;
6365
6366   // Count the number of UNDEF operands in the build_vector in input.
6367   for (unsigned i = 0, e = Half; i != e; ++i)
6368     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6369       NumUndefsLO++;
6370
6371   for (unsigned i = Half, e = NumElts; i != e; ++i)
6372     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6373       NumUndefsHI++;
6374
6375   // Early exit if this is either a build_vector of all UNDEFs or all the
6376   // operands but one are UNDEF.
6377   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6378     return SDValue();
6379
6380   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6381     // Try to match an SSE3 float HADD/HSUB.
6382     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6383       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6384     
6385     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6386       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6387   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6388     // Try to match an SSSE3 integer HADD/HSUB.
6389     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6390       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6391     
6392     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6393       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6394   }
6395   
6396   if (!Subtarget->hasAVX())
6397     return SDValue();
6398
6399   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6400     // Try to match an AVX horizontal add/sub of packed single/double
6401     // precision floating point values from 256-bit vectors.
6402     SDValue InVec2, InVec3;
6403     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6404         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6405         ((InVec0.getOpcode() == ISD::UNDEF ||
6406           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6407         ((InVec1.getOpcode() == ISD::UNDEF ||
6408           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6409       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6410
6411     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6412         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6413         ((InVec0.getOpcode() == ISD::UNDEF ||
6414           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6415         ((InVec1.getOpcode() == ISD::UNDEF ||
6416           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6417       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6418   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6419     // Try to match an AVX2 horizontal add/sub of signed integers.
6420     SDValue InVec2, InVec3;
6421     unsigned X86Opcode;
6422     bool CanFold = true;
6423
6424     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6425         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6426         ((InVec0.getOpcode() == ISD::UNDEF ||
6427           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6428         ((InVec1.getOpcode() == ISD::UNDEF ||
6429           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6430       X86Opcode = X86ISD::HADD;
6431     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6432         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6433         ((InVec0.getOpcode() == ISD::UNDEF ||
6434           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6435         ((InVec1.getOpcode() == ISD::UNDEF ||
6436           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6437       X86Opcode = X86ISD::HSUB;
6438     else
6439       CanFold = false;
6440
6441     if (CanFold) {
6442       // Fold this build_vector into a single horizontal add/sub.
6443       // Do this only if the target has AVX2.
6444       if (Subtarget->hasAVX2())
6445         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6446  
6447       // Do not try to expand this build_vector into a pair of horizontal
6448       // add/sub if we can emit a pair of scalar add/sub.
6449       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6450         return SDValue();
6451
6452       // Convert this build_vector into a pair of horizontal binop followed by
6453       // a concat vector.
6454       bool isUndefLO = NumUndefsLO == Half;
6455       bool isUndefHI = NumUndefsHI == Half;
6456       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6457                                    isUndefLO, isUndefHI);
6458     }
6459   }
6460
6461   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6462        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6463     unsigned X86Opcode;
6464     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6465       X86Opcode = X86ISD::HADD;
6466     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6467       X86Opcode = X86ISD::HSUB;
6468     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6469       X86Opcode = X86ISD::FHADD;
6470     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6471       X86Opcode = X86ISD::FHSUB;
6472     else
6473       return SDValue();
6474
6475     // Don't try to expand this build_vector into a pair of horizontal add/sub
6476     // if we can simply emit a pair of scalar add/sub.
6477     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6478       return SDValue();
6479
6480     // Convert this build_vector into two horizontal add/sub followed by
6481     // a concat vector.
6482     bool isUndefLO = NumUndefsLO == Half;
6483     bool isUndefHI = NumUndefsHI == Half;
6484     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6485                                  isUndefLO, isUndefHI);
6486   }
6487
6488   return SDValue();
6489 }
6490
6491 SDValue
6492 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6493   SDLoc dl(Op);
6494
6495   MVT VT = Op.getSimpleValueType();
6496   MVT ExtVT = VT.getVectorElementType();
6497   unsigned NumElems = Op.getNumOperands();
6498
6499   // Generate vectors for predicate vectors.
6500   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6501     return LowerBUILD_VECTORvXi1(Op, DAG);
6502
6503   // Vectors containing all zeros can be matched by pxor and xorps later
6504   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6505     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6506     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6507     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6508       return Op;
6509
6510     return getZeroVector(VT, Subtarget, DAG, dl);
6511   }
6512
6513   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6514   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6515   // vpcmpeqd on 256-bit vectors.
6516   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6517     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6518       return Op;
6519
6520     if (!VT.is512BitVector())
6521       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6522   }
6523
6524   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6525   if (Broadcast.getNode())
6526     return Broadcast;
6527
6528   unsigned EVTBits = ExtVT.getSizeInBits();
6529
6530   unsigned NumZero  = 0;
6531   unsigned NumNonZero = 0;
6532   unsigned NonZeros = 0;
6533   bool IsAllConstants = true;
6534   SmallSet<SDValue, 8> Values;
6535   for (unsigned i = 0; i < NumElems; ++i) {
6536     SDValue Elt = Op.getOperand(i);
6537     if (Elt.getOpcode() == ISD::UNDEF)
6538       continue;
6539     Values.insert(Elt);
6540     if (Elt.getOpcode() != ISD::Constant &&
6541         Elt.getOpcode() != ISD::ConstantFP)
6542       IsAllConstants = false;
6543     if (X86::isZeroNode(Elt))
6544       NumZero++;
6545     else {
6546       NonZeros |= (1 << i);
6547       NumNonZero++;
6548     }
6549   }
6550
6551   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6552   if (NumNonZero == 0)
6553     return DAG.getUNDEF(VT);
6554
6555   // Special case for single non-zero, non-undef, element.
6556   if (NumNonZero == 1) {
6557     unsigned Idx = countTrailingZeros(NonZeros);
6558     SDValue Item = Op.getOperand(Idx);
6559
6560     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6561     // the value are obviously zero, truncate the value to i32 and do the
6562     // insertion that way.  Only do this if the value is non-constant or if the
6563     // value is a constant being inserted into element 0.  It is cheaper to do
6564     // a constant pool load than it is to do a movd + shuffle.
6565     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6566         (!IsAllConstants || Idx == 0)) {
6567       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6568         // Handle SSE only.
6569         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6570         EVT VecVT = MVT::v4i32;
6571         unsigned VecElts = 4;
6572
6573         // Truncate the value (which may itself be a constant) to i32, and
6574         // convert it to a vector with movd (S2V+shuffle to zero extend).
6575         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6576         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6577         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6578
6579         // Now we have our 32-bit value zero extended in the low element of
6580         // a vector.  If Idx != 0, swizzle it into place.
6581         if (Idx != 0) {
6582           SmallVector<int, 4> Mask;
6583           Mask.push_back(Idx);
6584           for (unsigned i = 1; i != VecElts; ++i)
6585             Mask.push_back(i);
6586           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6587                                       &Mask[0]);
6588         }
6589         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6590       }
6591     }
6592
6593     // If we have a constant or non-constant insertion into the low element of
6594     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6595     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6596     // depending on what the source datatype is.
6597     if (Idx == 0) {
6598       if (NumZero == 0)
6599         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6600
6601       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6602           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6603         if (VT.is256BitVector() || VT.is512BitVector()) {
6604           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6605           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6606                              Item, DAG.getIntPtrConstant(0));
6607         }
6608         assert(VT.is128BitVector() && "Expected an SSE value type!");
6609         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6610         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6611         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6612       }
6613
6614       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6615         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6616         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6617         if (VT.is256BitVector()) {
6618           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6619           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6620         } else {
6621           assert(VT.is128BitVector() && "Expected an SSE value type!");
6622           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6623         }
6624         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6625       }
6626     }
6627
6628     // Is it a vector logical left shift?
6629     if (NumElems == 2 && Idx == 1 &&
6630         X86::isZeroNode(Op.getOperand(0)) &&
6631         !X86::isZeroNode(Op.getOperand(1))) {
6632       unsigned NumBits = VT.getSizeInBits();
6633       return getVShift(true, VT,
6634                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6635                                    VT, Op.getOperand(1)),
6636                        NumBits/2, DAG, *this, dl);
6637     }
6638
6639     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6640       return SDValue();
6641
6642     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6643     // is a non-constant being inserted into an element other than the low one,
6644     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6645     // movd/movss) to move this into the low element, then shuffle it into
6646     // place.
6647     if (EVTBits == 32) {
6648       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6649
6650       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6651       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6652       SmallVector<int, 8> MaskVec;
6653       for (unsigned i = 0; i != NumElems; ++i)
6654         MaskVec.push_back(i == Idx ? 0 : 1);
6655       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6656     }
6657   }
6658
6659   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6660   if (Values.size() == 1) {
6661     if (EVTBits == 32) {
6662       // Instead of a shuffle like this:
6663       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6664       // Check if it's possible to issue this instead.
6665       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6666       unsigned Idx = countTrailingZeros(NonZeros);
6667       SDValue Item = Op.getOperand(Idx);
6668       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6669         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6670     }
6671     return SDValue();
6672   }
6673
6674   // A vector full of immediates; various special cases are already
6675   // handled, so this is best done with a single constant-pool load.
6676   if (IsAllConstants)
6677     return SDValue();
6678
6679   // For AVX-length vectors, build the individual 128-bit pieces and use
6680   // shuffles to put them in place.
6681   if (VT.is256BitVector() || VT.is512BitVector()) {
6682     SmallVector<SDValue, 64> V;
6683     for (unsigned i = 0; i != NumElems; ++i)
6684       V.push_back(Op.getOperand(i));
6685
6686     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6687
6688     // Build both the lower and upper subvector.
6689     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6690                                 makeArrayRef(&V[0], NumElems/2));
6691     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6692                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6693
6694     // Recreate the wider vector with the lower and upper part.
6695     if (VT.is256BitVector())
6696       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6697     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6698   }
6699
6700   // Let legalizer expand 2-wide build_vectors.
6701   if (EVTBits == 64) {
6702     if (NumNonZero == 1) {
6703       // One half is zero or undef.
6704       unsigned Idx = countTrailingZeros(NonZeros);
6705       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6706                                  Op.getOperand(Idx));
6707       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6708     }
6709     return SDValue();
6710   }
6711
6712   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6713   if (EVTBits == 8 && NumElems == 16) {
6714     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6715                                         Subtarget, *this);
6716     if (V.getNode()) return V;
6717   }
6718
6719   if (EVTBits == 16 && NumElems == 8) {
6720     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6721                                       Subtarget, *this);
6722     if (V.getNode()) return V;
6723   }
6724
6725   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6726   if (EVTBits == 32 && NumElems == 4) {
6727     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6728                                       NumZero, DAG, Subtarget, *this);
6729     if (V.getNode())
6730       return V;
6731   }
6732
6733   // If element VT is == 32 bits, turn it into a number of shuffles.
6734   SmallVector<SDValue, 8> V(NumElems);
6735   if (NumElems == 4 && NumZero > 0) {
6736     for (unsigned i = 0; i < 4; ++i) {
6737       bool isZero = !(NonZeros & (1 << i));
6738       if (isZero)
6739         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6740       else
6741         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6742     }
6743
6744     for (unsigned i = 0; i < 2; ++i) {
6745       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6746         default: break;
6747         case 0:
6748           V[i] = V[i*2];  // Must be a zero vector.
6749           break;
6750         case 1:
6751           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6752           break;
6753         case 2:
6754           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6755           break;
6756         case 3:
6757           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6758           break;
6759       }
6760     }
6761
6762     bool Reverse1 = (NonZeros & 0x3) == 2;
6763     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6764     int MaskVec[] = {
6765       Reverse1 ? 1 : 0,
6766       Reverse1 ? 0 : 1,
6767       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6768       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6769     };
6770     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6771   }
6772
6773   if (Values.size() > 1 && VT.is128BitVector()) {
6774     // Check for a build vector of consecutive loads.
6775     for (unsigned i = 0; i < NumElems; ++i)
6776       V[i] = Op.getOperand(i);
6777
6778     // Check for elements which are consecutive loads.
6779     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6780     if (LD.getNode())
6781       return LD;
6782
6783     // Check for a build vector from mostly shuffle plus few inserting.
6784     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6785     if (Sh.getNode())
6786       return Sh;
6787
6788     // For SSE 4.1, use insertps to put the high elements into the low element.
6789     if (getSubtarget()->hasSSE41()) {
6790       SDValue Result;
6791       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6792         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6793       else
6794         Result = DAG.getUNDEF(VT);
6795
6796       for (unsigned i = 1; i < NumElems; ++i) {
6797         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6798         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6799                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6800       }
6801       return Result;
6802     }
6803
6804     // Otherwise, expand into a number of unpckl*, start by extending each of
6805     // our (non-undef) elements to the full vector width with the element in the
6806     // bottom slot of the vector (which generates no code for SSE).
6807     for (unsigned i = 0; i < NumElems; ++i) {
6808       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6809         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6810       else
6811         V[i] = DAG.getUNDEF(VT);
6812     }
6813
6814     // Next, we iteratively mix elements, e.g. for v4f32:
6815     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6816     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6817     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6818     unsigned EltStride = NumElems >> 1;
6819     while (EltStride != 0) {
6820       for (unsigned i = 0; i < EltStride; ++i) {
6821         // If V[i+EltStride] is undef and this is the first round of mixing,
6822         // then it is safe to just drop this shuffle: V[i] is already in the
6823         // right place, the one element (since it's the first round) being
6824         // inserted as undef can be dropped.  This isn't safe for successive
6825         // rounds because they will permute elements within both vectors.
6826         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6827             EltStride == NumElems/2)
6828           continue;
6829
6830         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6831       }
6832       EltStride >>= 1;
6833     }
6834     return V[0];
6835   }
6836   return SDValue();
6837 }
6838
6839 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6840 // to create 256-bit vectors from two other 128-bit ones.
6841 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6842   SDLoc dl(Op);
6843   MVT ResVT = Op.getSimpleValueType();
6844
6845   assert((ResVT.is256BitVector() ||
6846           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6847
6848   SDValue V1 = Op.getOperand(0);
6849   SDValue V2 = Op.getOperand(1);
6850   unsigned NumElems = ResVT.getVectorNumElements();
6851   if(ResVT.is256BitVector())
6852     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6853
6854   if (Op.getNumOperands() == 4) {
6855     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6856                                 ResVT.getVectorNumElements()/2);
6857     SDValue V3 = Op.getOperand(2);
6858     SDValue V4 = Op.getOperand(3);
6859     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6860       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6861   }
6862   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6863 }
6864
6865 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6866   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6867   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6868          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6869           Op.getNumOperands() == 4)));
6870
6871   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6872   // from two other 128-bit ones.
6873
6874   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6875   return LowerAVXCONCAT_VECTORS(Op, DAG);
6876 }
6877
6878 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6879                         bool hasInt256, unsigned *MaskOut = nullptr) {
6880   MVT EltVT = VT.getVectorElementType();
6881
6882   // There is no blend with immediate in AVX-512.
6883   if (VT.is512BitVector())
6884     return false;
6885
6886   if (!hasSSE41 || EltVT == MVT::i8)
6887     return false;
6888   if (!hasInt256 && VT == MVT::v16i16)
6889     return false;
6890
6891   unsigned MaskValue = 0;
6892   unsigned NumElems = VT.getVectorNumElements();
6893   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6894   unsigned NumLanes = (NumElems - 1) / 8 + 1;
6895   unsigned NumElemsInLane = NumElems / NumLanes;
6896
6897   // Blend for v16i16 should be symetric for the both lanes.
6898   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6899
6900     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6901     int EltIdx = MaskVals[i];
6902
6903     if ((EltIdx < 0 || EltIdx == (int)i) &&
6904         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6905       continue;
6906
6907     if (((unsigned)EltIdx == (i + NumElems)) &&
6908         (SndLaneEltIdx < 0 ||
6909          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6910       MaskValue |= (1 << i);
6911     else
6912       return false;
6913   }
6914
6915   if (MaskOut)
6916     *MaskOut = MaskValue;
6917   return true;
6918 }
6919
6920 // Try to lower a shuffle node into a simple blend instruction.
6921 // This function assumes isBlendMask returns true for this
6922 // SuffleVectorSDNode
6923 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6924                                           unsigned MaskValue,
6925                                           const X86Subtarget *Subtarget,
6926                                           SelectionDAG &DAG) {
6927   MVT VT = SVOp->getSimpleValueType(0);
6928   MVT EltVT = VT.getVectorElementType();
6929   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6930                      Subtarget->hasInt256() && "Trying to lower a "
6931                                                "VECTOR_SHUFFLE to a Blend but "
6932                                                "with the wrong mask"));
6933   SDValue V1 = SVOp->getOperand(0);
6934   SDValue V2 = SVOp->getOperand(1);
6935   SDLoc dl(SVOp);
6936   unsigned NumElems = VT.getVectorNumElements();
6937
6938   // Convert i32 vectors to floating point if it is not AVX2.
6939   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6940   MVT BlendVT = VT;
6941   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6942     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6943                                NumElems);
6944     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6945     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6946   }
6947
6948   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6949                             DAG.getConstant(MaskValue, MVT::i32));
6950   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6951 }
6952
6953 /// In vector type \p VT, return true if the element at index \p InputIdx
6954 /// falls on a different 128-bit lane than \p OutputIdx.
6955 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6956                                      unsigned OutputIdx) {
6957   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6958   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6959 }
6960
6961 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6962 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6963 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6964 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6965 /// zero.
6966 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6967                          SelectionDAG &DAG) {
6968   MVT VT = V1.getSimpleValueType();
6969   assert(VT.is128BitVector() || VT.is256BitVector());
6970
6971   MVT EltVT = VT.getVectorElementType();
6972   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6973   unsigned NumElts = VT.getVectorNumElements();
6974
6975   SmallVector<SDValue, 32> PshufbMask;
6976   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6977     int InputIdx = MaskVals[OutputIdx];
6978     unsigned InputByteIdx;
6979
6980     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6981       InputByteIdx = 0x80;
6982     else {
6983       // Cross lane is not allowed.
6984       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6985         return SDValue();
6986       InputByteIdx = InputIdx * EltSizeInBytes;
6987       // Index is an byte offset within the 128-bit lane.
6988       InputByteIdx &= 0xf;
6989     }
6990
6991     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6992       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6993       if (InputByteIdx != 0x80)
6994         ++InputByteIdx;
6995     }
6996   }
6997
6998   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6999   if (ShufVT != VT)
7000     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
7001   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
7002                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
7003 }
7004
7005 // v8i16 shuffles - Prefer shuffles in the following order:
7006 // 1. [all]   pshuflw, pshufhw, optional move
7007 // 2. [ssse3] 1 x pshufb
7008 // 3. [ssse3] 2 x pshufb + 1 x por
7009 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
7010 static SDValue
7011 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
7012                          SelectionDAG &DAG) {
7013   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7014   SDValue V1 = SVOp->getOperand(0);
7015   SDValue V2 = SVOp->getOperand(1);
7016   SDLoc dl(SVOp);
7017   SmallVector<int, 8> MaskVals;
7018
7019   // Determine if more than 1 of the words in each of the low and high quadwords
7020   // of the result come from the same quadword of one of the two inputs.  Undef
7021   // mask values count as coming from any quadword, for better codegen.
7022   //
7023   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
7024   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
7025   unsigned LoQuad[] = { 0, 0, 0, 0 };
7026   unsigned HiQuad[] = { 0, 0, 0, 0 };
7027   // Indices of quads used.
7028   std::bitset<4> InputQuads;
7029   for (unsigned i = 0; i < 8; ++i) {
7030     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
7031     int EltIdx = SVOp->getMaskElt(i);
7032     MaskVals.push_back(EltIdx);
7033     if (EltIdx < 0) {
7034       ++Quad[0];
7035       ++Quad[1];
7036       ++Quad[2];
7037       ++Quad[3];
7038       continue;
7039     }
7040     ++Quad[EltIdx / 4];
7041     InputQuads.set(EltIdx / 4);
7042   }
7043
7044   int BestLoQuad = -1;
7045   unsigned MaxQuad = 1;
7046   for (unsigned i = 0; i < 4; ++i) {
7047     if (LoQuad[i] > MaxQuad) {
7048       BestLoQuad = i;
7049       MaxQuad = LoQuad[i];
7050     }
7051   }
7052
7053   int BestHiQuad = -1;
7054   MaxQuad = 1;
7055   for (unsigned i = 0; i < 4; ++i) {
7056     if (HiQuad[i] > MaxQuad) {
7057       BestHiQuad = i;
7058       MaxQuad = HiQuad[i];
7059     }
7060   }
7061
7062   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
7063   // of the two input vectors, shuffle them into one input vector so only a
7064   // single pshufb instruction is necessary. If there are more than 2 input
7065   // quads, disable the next transformation since it does not help SSSE3.
7066   bool V1Used = InputQuads[0] || InputQuads[1];
7067   bool V2Used = InputQuads[2] || InputQuads[3];
7068   if (Subtarget->hasSSSE3()) {
7069     if (InputQuads.count() == 2 && V1Used && V2Used) {
7070       BestLoQuad = InputQuads[0] ? 0 : 1;
7071       BestHiQuad = InputQuads[2] ? 2 : 3;
7072     }
7073     if (InputQuads.count() > 2) {
7074       BestLoQuad = -1;
7075       BestHiQuad = -1;
7076     }
7077   }
7078
7079   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
7080   // the shuffle mask.  If a quad is scored as -1, that means that it contains
7081   // words from all 4 input quadwords.
7082   SDValue NewV;
7083   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
7084     int MaskV[] = {
7085       BestLoQuad < 0 ? 0 : BestLoQuad,
7086       BestHiQuad < 0 ? 1 : BestHiQuad
7087     };
7088     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
7089                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
7090                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
7091     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
7092
7093     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
7094     // source words for the shuffle, to aid later transformations.
7095     bool AllWordsInNewV = true;
7096     bool InOrder[2] = { true, true };
7097     for (unsigned i = 0; i != 8; ++i) {
7098       int idx = MaskVals[i];
7099       if (idx != (int)i)
7100         InOrder[i/4] = false;
7101       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
7102         continue;
7103       AllWordsInNewV = false;
7104       break;
7105     }
7106
7107     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
7108     if (AllWordsInNewV) {
7109       for (int i = 0; i != 8; ++i) {
7110         int idx = MaskVals[i];
7111         if (idx < 0)
7112           continue;
7113         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
7114         if ((idx != i) && idx < 4)
7115           pshufhw = false;
7116         if ((idx != i) && idx > 3)
7117           pshuflw = false;
7118       }
7119       V1 = NewV;
7120       V2Used = false;
7121       BestLoQuad = 0;
7122       BestHiQuad = 1;
7123     }
7124
7125     // If we've eliminated the use of V2, and the new mask is a pshuflw or
7126     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
7127     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
7128       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
7129       unsigned TargetMask = 0;
7130       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
7131                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
7132       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7133       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
7134                              getShufflePSHUFLWImmediate(SVOp);
7135       V1 = NewV.getOperand(0);
7136       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
7137     }
7138   }
7139
7140   // Promote splats to a larger type which usually leads to more efficient code.
7141   // FIXME: Is this true if pshufb is available?
7142   if (SVOp->isSplat())
7143     return PromoteSplat(SVOp, DAG);
7144
7145   // If we have SSSE3, and all words of the result are from 1 input vector,
7146   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
7147   // is present, fall back to case 4.
7148   if (Subtarget->hasSSSE3()) {
7149     SmallVector<SDValue,16> pshufbMask;
7150
7151     // If we have elements from both input vectors, set the high bit of the
7152     // shuffle mask element to zero out elements that come from V2 in the V1
7153     // mask, and elements that come from V1 in the V2 mask, so that the two
7154     // results can be OR'd together.
7155     bool TwoInputs = V1Used && V2Used;
7156     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
7157     if (!TwoInputs)
7158       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7159
7160     // Calculate the shuffle mask for the second input, shuffle it, and
7161     // OR it with the first shuffled input.
7162     CommuteVectorShuffleMask(MaskVals, 8);
7163     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
7164     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7165     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7166   }
7167
7168   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
7169   // and update MaskVals with new element order.
7170   std::bitset<8> InOrder;
7171   if (BestLoQuad >= 0) {
7172     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
7173     for (int i = 0; i != 4; ++i) {
7174       int idx = MaskVals[i];
7175       if (idx < 0) {
7176         InOrder.set(i);
7177       } else if ((idx / 4) == BestLoQuad) {
7178         MaskV[i] = idx & 3;
7179         InOrder.set(i);
7180       }
7181     }
7182     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7183                                 &MaskV[0]);
7184
7185     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7186       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7187       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
7188                                   NewV.getOperand(0),
7189                                   getShufflePSHUFLWImmediate(SVOp), DAG);
7190     }
7191   }
7192
7193   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
7194   // and update MaskVals with the new element order.
7195   if (BestHiQuad >= 0) {
7196     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
7197     for (unsigned i = 4; i != 8; ++i) {
7198       int idx = MaskVals[i];
7199       if (idx < 0) {
7200         InOrder.set(i);
7201       } else if ((idx / 4) == BestHiQuad) {
7202         MaskV[i] = (idx & 3) + 4;
7203         InOrder.set(i);
7204       }
7205     }
7206     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7207                                 &MaskV[0]);
7208
7209     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7210       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7211       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
7212                                   NewV.getOperand(0),
7213                                   getShufflePSHUFHWImmediate(SVOp), DAG);
7214     }
7215   }
7216
7217   // In case BestHi & BestLo were both -1, which means each quadword has a word
7218   // from each of the four input quadwords, calculate the InOrder bitvector now
7219   // before falling through to the insert/extract cleanup.
7220   if (BestLoQuad == -1 && BestHiQuad == -1) {
7221     NewV = V1;
7222     for (int i = 0; i != 8; ++i)
7223       if (MaskVals[i] < 0 || MaskVals[i] == i)
7224         InOrder.set(i);
7225   }
7226
7227   // The other elements are put in the right place using pextrw and pinsrw.
7228   for (unsigned i = 0; i != 8; ++i) {
7229     if (InOrder[i])
7230       continue;
7231     int EltIdx = MaskVals[i];
7232     if (EltIdx < 0)
7233       continue;
7234     SDValue ExtOp = (EltIdx < 8) ?
7235       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
7236                   DAG.getIntPtrConstant(EltIdx)) :
7237       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
7238                   DAG.getIntPtrConstant(EltIdx - 8));
7239     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
7240                        DAG.getIntPtrConstant(i));
7241   }
7242   return NewV;
7243 }
7244
7245 /// \brief v16i16 shuffles
7246 ///
7247 /// FIXME: We only support generation of a single pshufb currently.  We can
7248 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
7249 /// well (e.g 2 x pshufb + 1 x por).
7250 static SDValue
7251 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
7252   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7253   SDValue V1 = SVOp->getOperand(0);
7254   SDValue V2 = SVOp->getOperand(1);
7255   SDLoc dl(SVOp);
7256
7257   if (V2.getOpcode() != ISD::UNDEF)
7258     return SDValue();
7259
7260   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7261   return getPSHUFB(MaskVals, V1, dl, DAG);
7262 }
7263
7264 // v16i8 shuffles - Prefer shuffles in the following order:
7265 // 1. [ssse3] 1 x pshufb
7266 // 2. [ssse3] 2 x pshufb + 1 x por
7267 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
7268 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
7269                                         const X86Subtarget* Subtarget,
7270                                         SelectionDAG &DAG) {
7271   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7272   SDValue V1 = SVOp->getOperand(0);
7273   SDValue V2 = SVOp->getOperand(1);
7274   SDLoc dl(SVOp);
7275   ArrayRef<int> MaskVals = SVOp->getMask();
7276
7277   // Promote splats to a larger type which usually leads to more efficient code.
7278   // FIXME: Is this true if pshufb is available?
7279   if (SVOp->isSplat())
7280     return PromoteSplat(SVOp, DAG);
7281
7282   // If we have SSSE3, case 1 is generated when all result bytes come from
7283   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
7284   // present, fall back to case 3.
7285
7286   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
7287   if (Subtarget->hasSSSE3()) {
7288     SmallVector<SDValue,16> pshufbMask;
7289
7290     // If all result elements are from one input vector, then only translate
7291     // undef mask values to 0x80 (zero out result) in the pshufb mask.
7292     //
7293     // Otherwise, we have elements from both input vectors, and must zero out
7294     // elements that come from V2 in the first mask, and V1 in the second mask
7295     // so that we can OR them together.
7296     for (unsigned i = 0; i != 16; ++i) {
7297       int EltIdx = MaskVals[i];
7298       if (EltIdx < 0 || EltIdx >= 16)
7299         EltIdx = 0x80;
7300       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7301     }
7302     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7303                      DAG.getNode(ISD::BUILD_VECTOR, dl,
7304                                  MVT::v16i8, pshufbMask));
7305
7306     // As PSHUFB will zero elements with negative indices, it's safe to ignore
7307     // the 2nd operand if it's undefined or zero.
7308     if (V2.getOpcode() == ISD::UNDEF ||
7309         ISD::isBuildVectorAllZeros(V2.getNode()))
7310       return V1;
7311
7312     // Calculate the shuffle mask for the second input, shuffle it, and
7313     // OR it with the first shuffled input.
7314     pshufbMask.clear();
7315     for (unsigned i = 0; i != 16; ++i) {
7316       int EltIdx = MaskVals[i];
7317       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7318       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7319     }
7320     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7321                      DAG.getNode(ISD::BUILD_VECTOR, dl,
7322                                  MVT::v16i8, pshufbMask));
7323     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7324   }
7325
7326   // No SSSE3 - Calculate in place words and then fix all out of place words
7327   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
7328   // the 16 different words that comprise the two doublequadword input vectors.
7329   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7330   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7331   SDValue NewV = V1;
7332   for (int i = 0; i != 8; ++i) {
7333     int Elt0 = MaskVals[i*2];
7334     int Elt1 = MaskVals[i*2+1];
7335
7336     // This word of the result is all undef, skip it.
7337     if (Elt0 < 0 && Elt1 < 0)
7338       continue;
7339
7340     // This word of the result is already in the correct place, skip it.
7341     if ((Elt0 == i*2) && (Elt1 == i*2+1))
7342       continue;
7343
7344     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7345     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7346     SDValue InsElt;
7347
7348     // If Elt0 and Elt1 are defined, are consecutive, and can be load
7349     // using a single extract together, load it and store it.
7350     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7351       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7352                            DAG.getIntPtrConstant(Elt1 / 2));
7353       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7354                         DAG.getIntPtrConstant(i));
7355       continue;
7356     }
7357
7358     // If Elt1 is defined, extract it from the appropriate source.  If the
7359     // source byte is not also odd, shift the extracted word left 8 bits
7360     // otherwise clear the bottom 8 bits if we need to do an or.
7361     if (Elt1 >= 0) {
7362       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7363                            DAG.getIntPtrConstant(Elt1 / 2));
7364       if ((Elt1 & 1) == 0)
7365         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7366                              DAG.getConstant(8,
7367                                   TLI.getShiftAmountTy(InsElt.getValueType())));
7368       else if (Elt0 >= 0)
7369         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7370                              DAG.getConstant(0xFF00, MVT::i16));
7371     }
7372     // If Elt0 is defined, extract it from the appropriate source.  If the
7373     // source byte is not also even, shift the extracted word right 8 bits. If
7374     // Elt1 was also defined, OR the extracted values together before
7375     // inserting them in the result.
7376     if (Elt0 >= 0) {
7377       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7378                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7379       if ((Elt0 & 1) != 0)
7380         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7381                               DAG.getConstant(8,
7382                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
7383       else if (Elt1 >= 0)
7384         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7385                              DAG.getConstant(0x00FF, MVT::i16));
7386       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7387                          : InsElt0;
7388     }
7389     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7390                        DAG.getIntPtrConstant(i));
7391   }
7392   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7393 }
7394
7395 // v32i8 shuffles - Translate to VPSHUFB if possible.
7396 static
7397 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7398                                  const X86Subtarget *Subtarget,
7399                                  SelectionDAG &DAG) {
7400   MVT VT = SVOp->getSimpleValueType(0);
7401   SDValue V1 = SVOp->getOperand(0);
7402   SDValue V2 = SVOp->getOperand(1);
7403   SDLoc dl(SVOp);
7404   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7405
7406   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7407   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7408   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7409
7410   // VPSHUFB may be generated if
7411   // (1) one of input vector is undefined or zeroinitializer.
7412   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7413   // And (2) the mask indexes don't cross the 128-bit lane.
7414   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7415       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7416     return SDValue();
7417
7418   if (V1IsAllZero && !V2IsAllZero) {
7419     CommuteVectorShuffleMask(MaskVals, 32);
7420     V1 = V2;
7421   }
7422   return getPSHUFB(MaskVals, V1, dl, DAG);
7423 }
7424
7425 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7426 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7427 /// done when every pair / quad of shuffle mask elements point to elements in
7428 /// the right sequence. e.g.
7429 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7430 static
7431 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7432                                  SelectionDAG &DAG) {
7433   MVT VT = SVOp->getSimpleValueType(0);
7434   SDLoc dl(SVOp);
7435   unsigned NumElems = VT.getVectorNumElements();
7436   MVT NewVT;
7437   unsigned Scale;
7438   switch (VT.SimpleTy) {
7439   default: llvm_unreachable("Unexpected!");
7440   case MVT::v2i64:
7441   case MVT::v2f64:
7442            return SDValue(SVOp, 0);
7443   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
7444   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
7445   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
7446   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
7447   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7448   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
7449   }
7450
7451   SmallVector<int, 8> MaskVec;
7452   for (unsigned i = 0; i != NumElems; i += Scale) {
7453     int StartIdx = -1;
7454     for (unsigned j = 0; j != Scale; ++j) {
7455       int EltIdx = SVOp->getMaskElt(i+j);
7456       if (EltIdx < 0)
7457         continue;
7458       if (StartIdx < 0)
7459         StartIdx = (EltIdx / Scale);
7460       if (EltIdx != (int)(StartIdx*Scale + j))
7461         return SDValue();
7462     }
7463     MaskVec.push_back(StartIdx);
7464   }
7465
7466   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7467   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7468   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7469 }
7470
7471 /// getVZextMovL - Return a zero-extending vector move low node.
7472 ///
7473 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7474                             SDValue SrcOp, SelectionDAG &DAG,
7475                             const X86Subtarget *Subtarget, SDLoc dl) {
7476   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7477     LoadSDNode *LD = nullptr;
7478     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7479       LD = dyn_cast<LoadSDNode>(SrcOp);
7480     if (!LD) {
7481       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7482       // instead.
7483       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7484       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7485           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7486           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7487           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7488         // PR2108
7489         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7490         return DAG.getNode(ISD::BITCAST, dl, VT,
7491                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7492                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7493                                                    OpVT,
7494                                                    SrcOp.getOperand(0)
7495                                                           .getOperand(0))));
7496       }
7497     }
7498   }
7499
7500   return DAG.getNode(ISD::BITCAST, dl, VT,
7501                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7502                                  DAG.getNode(ISD::BITCAST, dl,
7503                                              OpVT, SrcOp)));
7504 }
7505
7506 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7507 /// which could not be matched by any known target speficic shuffle
7508 static SDValue
7509 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7510
7511   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7512   if (NewOp.getNode())
7513     return NewOp;
7514
7515   MVT VT = SVOp->getSimpleValueType(0);
7516
7517   unsigned NumElems = VT.getVectorNumElements();
7518   unsigned NumLaneElems = NumElems / 2;
7519
7520   SDLoc dl(SVOp);
7521   MVT EltVT = VT.getVectorElementType();
7522   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7523   SDValue Output[2];
7524
7525   SmallVector<int, 16> Mask;
7526   for (unsigned l = 0; l < 2; ++l) {
7527     // Build a shuffle mask for the output, discovering on the fly which
7528     // input vectors to use as shuffle operands (recorded in InputUsed).
7529     // If building a suitable shuffle vector proves too hard, then bail
7530     // out with UseBuildVector set.
7531     bool UseBuildVector = false;
7532     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7533     unsigned LaneStart = l * NumLaneElems;
7534     for (unsigned i = 0; i != NumLaneElems; ++i) {
7535       // The mask element.  This indexes into the input.
7536       int Idx = SVOp->getMaskElt(i+LaneStart);
7537       if (Idx < 0) {
7538         // the mask element does not index into any input vector.
7539         Mask.push_back(-1);
7540         continue;
7541       }
7542
7543       // The input vector this mask element indexes into.
7544       int Input = Idx / NumLaneElems;
7545
7546       // Turn the index into an offset from the start of the input vector.
7547       Idx -= Input * NumLaneElems;
7548
7549       // Find or create a shuffle vector operand to hold this input.
7550       unsigned OpNo;
7551       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7552         if (InputUsed[OpNo] == Input)
7553           // This input vector is already an operand.
7554           break;
7555         if (InputUsed[OpNo] < 0) {
7556           // Create a new operand for this input vector.
7557           InputUsed[OpNo] = Input;
7558           break;
7559         }
7560       }
7561
7562       if (OpNo >= array_lengthof(InputUsed)) {
7563         // More than two input vectors used!  Give up on trying to create a
7564         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7565         UseBuildVector = true;
7566         break;
7567       }
7568
7569       // Add the mask index for the new shuffle vector.
7570       Mask.push_back(Idx + OpNo * NumLaneElems);
7571     }
7572
7573     if (UseBuildVector) {
7574       SmallVector<SDValue, 16> SVOps;
7575       for (unsigned i = 0; i != NumLaneElems; ++i) {
7576         // The mask element.  This indexes into the input.
7577         int Idx = SVOp->getMaskElt(i+LaneStart);
7578         if (Idx < 0) {
7579           SVOps.push_back(DAG.getUNDEF(EltVT));
7580           continue;
7581         }
7582
7583         // The input vector this mask element indexes into.
7584         int Input = Idx / NumElems;
7585
7586         // Turn the index into an offset from the start of the input vector.
7587         Idx -= Input * NumElems;
7588
7589         // Extract the vector element by hand.
7590         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7591                                     SVOp->getOperand(Input),
7592                                     DAG.getIntPtrConstant(Idx)));
7593       }
7594
7595       // Construct the output using a BUILD_VECTOR.
7596       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7597     } else if (InputUsed[0] < 0) {
7598       // No input vectors were used! The result is undefined.
7599       Output[l] = DAG.getUNDEF(NVT);
7600     } else {
7601       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7602                                         (InputUsed[0] % 2) * NumLaneElems,
7603                                         DAG, dl);
7604       // If only one input was used, use an undefined vector for the other.
7605       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7606         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7607                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7608       // At least one input vector was used. Create a new shuffle vector.
7609       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7610     }
7611
7612     Mask.clear();
7613   }
7614
7615   // Concatenate the result back
7616   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7617 }
7618
7619 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7620 /// 4 elements, and match them with several different shuffle types.
7621 static SDValue
7622 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7623   SDValue V1 = SVOp->getOperand(0);
7624   SDValue V2 = SVOp->getOperand(1);
7625   SDLoc dl(SVOp);
7626   MVT VT = SVOp->getSimpleValueType(0);
7627
7628   assert(VT.is128BitVector() && "Unsupported vector size");
7629
7630   std::pair<int, int> Locs[4];
7631   int Mask1[] = { -1, -1, -1, -1 };
7632   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7633
7634   unsigned NumHi = 0;
7635   unsigned NumLo = 0;
7636   for (unsigned i = 0; i != 4; ++i) {
7637     int Idx = PermMask[i];
7638     if (Idx < 0) {
7639       Locs[i] = std::make_pair(-1, -1);
7640     } else {
7641       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7642       if (Idx < 4) {
7643         Locs[i] = std::make_pair(0, NumLo);
7644         Mask1[NumLo] = Idx;
7645         NumLo++;
7646       } else {
7647         Locs[i] = std::make_pair(1, NumHi);
7648         if (2+NumHi < 4)
7649           Mask1[2+NumHi] = Idx;
7650         NumHi++;
7651       }
7652     }
7653   }
7654
7655   if (NumLo <= 2 && NumHi <= 2) {
7656     // If no more than two elements come from either vector. This can be
7657     // implemented with two shuffles. First shuffle gather the elements.
7658     // The second shuffle, which takes the first shuffle as both of its
7659     // vector operands, put the elements into the right order.
7660     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7661
7662     int Mask2[] = { -1, -1, -1, -1 };
7663
7664     for (unsigned i = 0; i != 4; ++i)
7665       if (Locs[i].first != -1) {
7666         unsigned Idx = (i < 2) ? 0 : 4;
7667         Idx += Locs[i].first * 2 + Locs[i].second;
7668         Mask2[i] = Idx;
7669       }
7670
7671     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7672   }
7673
7674   if (NumLo == 3 || NumHi == 3) {
7675     // Otherwise, we must have three elements from one vector, call it X, and
7676     // one element from the other, call it Y.  First, use a shufps to build an
7677     // intermediate vector with the one element from Y and the element from X
7678     // that will be in the same half in the final destination (the indexes don't
7679     // matter). Then, use a shufps to build the final vector, taking the half
7680     // containing the element from Y from the intermediate, and the other half
7681     // from X.
7682     if (NumHi == 3) {
7683       // Normalize it so the 3 elements come from V1.
7684       CommuteVectorShuffleMask(PermMask, 4);
7685       std::swap(V1, V2);
7686     }
7687
7688     // Find the element from V2.
7689     unsigned HiIndex;
7690     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7691       int Val = PermMask[HiIndex];
7692       if (Val < 0)
7693         continue;
7694       if (Val >= 4)
7695         break;
7696     }
7697
7698     Mask1[0] = PermMask[HiIndex];
7699     Mask1[1] = -1;
7700     Mask1[2] = PermMask[HiIndex^1];
7701     Mask1[3] = -1;
7702     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7703
7704     if (HiIndex >= 2) {
7705       Mask1[0] = PermMask[0];
7706       Mask1[1] = PermMask[1];
7707       Mask1[2] = HiIndex & 1 ? 6 : 4;
7708       Mask1[3] = HiIndex & 1 ? 4 : 6;
7709       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7710     }
7711
7712     Mask1[0] = HiIndex & 1 ? 2 : 0;
7713     Mask1[1] = HiIndex & 1 ? 0 : 2;
7714     Mask1[2] = PermMask[2];
7715     Mask1[3] = PermMask[3];
7716     if (Mask1[2] >= 0)
7717       Mask1[2] += 4;
7718     if (Mask1[3] >= 0)
7719       Mask1[3] += 4;
7720     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7721   }
7722
7723   // Break it into (shuffle shuffle_hi, shuffle_lo).
7724   int LoMask[] = { -1, -1, -1, -1 };
7725   int HiMask[] = { -1, -1, -1, -1 };
7726
7727   int *MaskPtr = LoMask;
7728   unsigned MaskIdx = 0;
7729   unsigned LoIdx = 0;
7730   unsigned HiIdx = 2;
7731   for (unsigned i = 0; i != 4; ++i) {
7732     if (i == 2) {
7733       MaskPtr = HiMask;
7734       MaskIdx = 1;
7735       LoIdx = 0;
7736       HiIdx = 2;
7737     }
7738     int Idx = PermMask[i];
7739     if (Idx < 0) {
7740       Locs[i] = std::make_pair(-1, -1);
7741     } else if (Idx < 4) {
7742       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7743       MaskPtr[LoIdx] = Idx;
7744       LoIdx++;
7745     } else {
7746       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7747       MaskPtr[HiIdx] = Idx;
7748       HiIdx++;
7749     }
7750   }
7751
7752   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7753   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7754   int MaskOps[] = { -1, -1, -1, -1 };
7755   for (unsigned i = 0; i != 4; ++i)
7756     if (Locs[i].first != -1)
7757       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7758   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7759 }
7760
7761 static bool MayFoldVectorLoad(SDValue V) {
7762   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7763     V = V.getOperand(0);
7764
7765   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7766     V = V.getOperand(0);
7767   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7768       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7769     // BUILD_VECTOR (load), undef
7770     V = V.getOperand(0);
7771
7772   return MayFoldLoad(V);
7773 }
7774
7775 static
7776 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7777   MVT VT = Op.getSimpleValueType();
7778
7779   // Canonizalize to v2f64.
7780   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7781   return DAG.getNode(ISD::BITCAST, dl, VT,
7782                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7783                                           V1, DAG));
7784 }
7785
7786 static
7787 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7788                         bool HasSSE2) {
7789   SDValue V1 = Op.getOperand(0);
7790   SDValue V2 = Op.getOperand(1);
7791   MVT VT = Op.getSimpleValueType();
7792
7793   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7794
7795   if (HasSSE2 && VT == MVT::v2f64)
7796     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7797
7798   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7799   return DAG.getNode(ISD::BITCAST, dl, VT,
7800                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7801                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7802                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7803 }
7804
7805 static
7806 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7807   SDValue V1 = Op.getOperand(0);
7808   SDValue V2 = Op.getOperand(1);
7809   MVT VT = Op.getSimpleValueType();
7810
7811   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7812          "unsupported shuffle type");
7813
7814   if (V2.getOpcode() == ISD::UNDEF)
7815     V2 = V1;
7816
7817   // v4i32 or v4f32
7818   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7819 }
7820
7821 static
7822 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7823   SDValue V1 = Op.getOperand(0);
7824   SDValue V2 = Op.getOperand(1);
7825   MVT VT = Op.getSimpleValueType();
7826   unsigned NumElems = VT.getVectorNumElements();
7827
7828   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7829   // operand of these instructions is only memory, so check if there's a
7830   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7831   // same masks.
7832   bool CanFoldLoad = false;
7833
7834   // Trivial case, when V2 comes from a load.
7835   if (MayFoldVectorLoad(V2))
7836     CanFoldLoad = true;
7837
7838   // When V1 is a load, it can be folded later into a store in isel, example:
7839   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7840   //    turns into:
7841   //  (MOVLPSmr addr:$src1, VR128:$src2)
7842   // So, recognize this potential and also use MOVLPS or MOVLPD
7843   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7844     CanFoldLoad = true;
7845
7846   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7847   if (CanFoldLoad) {
7848     if (HasSSE2 && NumElems == 2)
7849       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7850
7851     if (NumElems == 4)
7852       // If we don't care about the second element, proceed to use movss.
7853       if (SVOp->getMaskElt(1) != -1)
7854         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7855   }
7856
7857   // movl and movlp will both match v2i64, but v2i64 is never matched by
7858   // movl earlier because we make it strict to avoid messing with the movlp load
7859   // folding logic (see the code above getMOVLP call). Match it here then,
7860   // this is horrible, but will stay like this until we move all shuffle
7861   // matching to x86 specific nodes. Note that for the 1st condition all
7862   // types are matched with movsd.
7863   if (HasSSE2) {
7864     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7865     // as to remove this logic from here, as much as possible
7866     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7867       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7868     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7869   }
7870
7871   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7872
7873   // Invert the operand order and use SHUFPS to match it.
7874   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7875                               getShuffleSHUFImmediate(SVOp), DAG);
7876 }
7877
7878 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7879                                          SelectionDAG &DAG) {
7880   SDLoc dl(Load);
7881   MVT VT = Load->getSimpleValueType(0);
7882   MVT EVT = VT.getVectorElementType();
7883   SDValue Addr = Load->getOperand(1);
7884   SDValue NewAddr = DAG.getNode(
7885       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7886       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7887
7888   SDValue NewLoad =
7889       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7890                   DAG.getMachineFunction().getMachineMemOperand(
7891                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7892   return NewLoad;
7893 }
7894
7895 // It is only safe to call this function if isINSERTPSMask is true for
7896 // this shufflevector mask.
7897 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7898                            SelectionDAG &DAG) {
7899   // Generate an insertps instruction when inserting an f32 from memory onto a
7900   // v4f32 or when copying a member from one v4f32 to another.
7901   // We also use it for transferring i32 from one register to another,
7902   // since it simply copies the same bits.
7903   // If we're transferring an i32 from memory to a specific element in a
7904   // register, we output a generic DAG that will match the PINSRD
7905   // instruction.
7906   MVT VT = SVOp->getSimpleValueType(0);
7907   MVT EVT = VT.getVectorElementType();
7908   SDValue V1 = SVOp->getOperand(0);
7909   SDValue V2 = SVOp->getOperand(1);
7910   auto Mask = SVOp->getMask();
7911   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7912          "unsupported vector type for insertps/pinsrd");
7913
7914   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7915   auto FromV2Predicate = [](const int &i) { return i >= 4; };
7916   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7917
7918   SDValue From;
7919   SDValue To;
7920   unsigned DestIndex;
7921   if (FromV1 == 1) {
7922     From = V1;
7923     To = V2;
7924     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7925                 Mask.begin();
7926   } else {
7927     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7928            "More than one element from V1 and from V2, or no elements from one "
7929            "of the vectors. This case should not have returned true from "
7930            "isINSERTPSMask");
7931     From = V2;
7932     To = V1;
7933     DestIndex =
7934         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7935   }
7936
7937   unsigned SrcIndex = Mask[DestIndex] % 4;
7938   if (MayFoldLoad(From)) {
7939     // Trivial case, when From comes from a load and is only used by the
7940     // shuffle. Make it use insertps from the vector that we need from that
7941     // load.
7942     SDValue NewLoad =
7943         NarrowVectorLoadToElement(cast<LoadSDNode>(From), SrcIndex, DAG);
7944     if (!NewLoad.getNode())
7945       return SDValue();
7946
7947     if (EVT == MVT::f32) {
7948       // Create this as a scalar to vector to match the instruction pattern.
7949       SDValue LoadScalarToVector =
7950           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7951       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7952       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7953                          InsertpsMask);
7954     } else { // EVT == MVT::i32
7955       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7956       // instruction, to match the PINSRD instruction, which loads an i32 to a
7957       // certain vector element.
7958       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7959                          DAG.getConstant(DestIndex, MVT::i32));
7960     }
7961   }
7962
7963   // Vector-element-to-vector
7964   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7965   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7966 }
7967
7968 // Reduce a vector shuffle to zext.
7969 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7970                                     SelectionDAG &DAG) {
7971   // PMOVZX is only available from SSE41.
7972   if (!Subtarget->hasSSE41())
7973     return SDValue();
7974
7975   MVT VT = Op.getSimpleValueType();
7976
7977   // Only AVX2 support 256-bit vector integer extending.
7978   if (!Subtarget->hasInt256() && VT.is256BitVector())
7979     return SDValue();
7980
7981   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7982   SDLoc DL(Op);
7983   SDValue V1 = Op.getOperand(0);
7984   SDValue V2 = Op.getOperand(1);
7985   unsigned NumElems = VT.getVectorNumElements();
7986
7987   // Extending is an unary operation and the element type of the source vector
7988   // won't be equal to or larger than i64.
7989   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7990       VT.getVectorElementType() == MVT::i64)
7991     return SDValue();
7992
7993   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7994   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7995   while ((1U << Shift) < NumElems) {
7996     if (SVOp->getMaskElt(1U << Shift) == 1)
7997       break;
7998     Shift += 1;
7999     // The maximal ratio is 8, i.e. from i8 to i64.
8000     if (Shift > 3)
8001       return SDValue();
8002   }
8003
8004   // Check the shuffle mask.
8005   unsigned Mask = (1U << Shift) - 1;
8006   for (unsigned i = 0; i != NumElems; ++i) {
8007     int EltIdx = SVOp->getMaskElt(i);
8008     if ((i & Mask) != 0 && EltIdx != -1)
8009       return SDValue();
8010     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
8011       return SDValue();
8012   }
8013
8014   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
8015   MVT NeVT = MVT::getIntegerVT(NBits);
8016   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
8017
8018   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
8019     return SDValue();
8020
8021   // Simplify the operand as it's prepared to be fed into shuffle.
8022   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
8023   if (V1.getOpcode() == ISD::BITCAST &&
8024       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
8025       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
8026       V1.getOperand(0).getOperand(0)
8027         .getSimpleValueType().getSizeInBits() == SignificantBits) {
8028     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
8029     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
8030     ConstantSDNode *CIdx =
8031       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
8032     // If it's foldable, i.e. normal load with single use, we will let code
8033     // selection to fold it. Otherwise, we will short the conversion sequence.
8034     if (CIdx && CIdx->getZExtValue() == 0 &&
8035         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
8036       MVT FullVT = V.getSimpleValueType();
8037       MVT V1VT = V1.getSimpleValueType();
8038       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
8039         // The "ext_vec_elt" node is wider than the result node.
8040         // In this case we should extract subvector from V.
8041         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
8042         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
8043         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
8044                                         FullVT.getVectorNumElements()/Ratio);
8045         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
8046                         DAG.getIntPtrConstant(0));
8047       }
8048       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
8049     }
8050   }
8051
8052   return DAG.getNode(ISD::BITCAST, DL, VT,
8053                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
8054 }
8055
8056 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
8057                                       SelectionDAG &DAG) {
8058   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8059   MVT VT = Op.getSimpleValueType();
8060   SDLoc dl(Op);
8061   SDValue V1 = Op.getOperand(0);
8062   SDValue V2 = Op.getOperand(1);
8063
8064   if (isZeroShuffle(SVOp))
8065     return getZeroVector(VT, Subtarget, DAG, dl);
8066
8067   // Handle splat operations
8068   if (SVOp->isSplat()) {
8069     // Use vbroadcast whenever the splat comes from a foldable load
8070     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
8071     if (Broadcast.getNode())
8072       return Broadcast;
8073   }
8074
8075   // Check integer expanding shuffles.
8076   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
8077   if (NewOp.getNode())
8078     return NewOp;
8079
8080   // If the shuffle can be profitably rewritten as a narrower shuffle, then
8081   // do it!
8082   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
8083       VT == MVT::v32i8) {
8084     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8085     if (NewOp.getNode())
8086       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
8087   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
8088     // FIXME: Figure out a cleaner way to do this.
8089     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
8090       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8091       if (NewOp.getNode()) {
8092         MVT NewVT = NewOp.getSimpleValueType();
8093         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
8094                                NewVT, true, false))
8095           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
8096                               dl);
8097       }
8098     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
8099       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
8100       if (NewOp.getNode()) {
8101         MVT NewVT = NewOp.getSimpleValueType();
8102         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
8103           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
8104                               dl);
8105       }
8106     }
8107   }
8108   return SDValue();
8109 }
8110
8111 SDValue
8112 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
8113   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8114   SDValue V1 = Op.getOperand(0);
8115   SDValue V2 = Op.getOperand(1);
8116   MVT VT = Op.getSimpleValueType();
8117   SDLoc dl(Op);
8118   unsigned NumElems = VT.getVectorNumElements();
8119   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
8120   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
8121   bool V1IsSplat = false;
8122   bool V2IsSplat = false;
8123   bool HasSSE2 = Subtarget->hasSSE2();
8124   bool HasFp256    = Subtarget->hasFp256();
8125   bool HasInt256   = Subtarget->hasInt256();
8126   MachineFunction &MF = DAG.getMachineFunction();
8127   bool OptForSize = MF.getFunction()->getAttributes().
8128     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
8129
8130   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8131
8132   if (V1IsUndef && V2IsUndef)
8133     return DAG.getUNDEF(VT);
8134
8135   // When we create a shuffle node we put the UNDEF node to second operand,
8136   // but in some cases the first operand may be transformed to UNDEF.
8137   // In this case we should just commute the node.
8138   if (V1IsUndef)
8139     return CommuteVectorShuffle(SVOp, DAG);
8140
8141   // Vector shuffle lowering takes 3 steps:
8142   //
8143   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
8144   //    narrowing and commutation of operands should be handled.
8145   // 2) Matching of shuffles with known shuffle masks to x86 target specific
8146   //    shuffle nodes.
8147   // 3) Rewriting of unmatched masks into new generic shuffle operations,
8148   //    so the shuffle can be broken into other shuffles and the legalizer can
8149   //    try the lowering again.
8150   //
8151   // The general idea is that no vector_shuffle operation should be left to
8152   // be matched during isel, all of them must be converted to a target specific
8153   // node here.
8154
8155   // Normalize the input vectors. Here splats, zeroed vectors, profitable
8156   // narrowing and commutation of operands should be handled. The actual code
8157   // doesn't include all of those, work in progress...
8158   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
8159   if (NewOp.getNode())
8160     return NewOp;
8161
8162   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
8163
8164   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
8165   // unpckh_undef). Only use pshufd if speed is more important than size.
8166   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8167     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8168   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8169     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8170
8171   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
8172       V2IsUndef && MayFoldVectorLoad(V1))
8173     return getMOVDDup(Op, dl, V1, DAG);
8174
8175   if (isMOVHLPS_v_undef_Mask(M, VT))
8176     return getMOVHighToLow(Op, dl, DAG);
8177
8178   // Use to match splats
8179   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
8180       (VT == MVT::v2f64 || VT == MVT::v2i64))
8181     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8182
8183   if (isPSHUFDMask(M, VT)) {
8184     // The actual implementation will match the mask in the if above and then
8185     // during isel it can match several different instructions, not only pshufd
8186     // as its name says, sad but true, emulate the behavior for now...
8187     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
8188       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
8189
8190     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
8191
8192     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
8193       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
8194
8195     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
8196       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
8197                                   DAG);
8198
8199     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
8200                                 TargetMask, DAG);
8201   }
8202
8203   if (isPALIGNRMask(M, VT, Subtarget))
8204     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
8205                                 getShufflePALIGNRImmediate(SVOp),
8206                                 DAG);
8207
8208   // Check if this can be converted into a logical shift.
8209   bool isLeft = false;
8210   unsigned ShAmt = 0;
8211   SDValue ShVal;
8212   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
8213   if (isShift && ShVal.hasOneUse()) {
8214     // If the shifted value has multiple uses, it may be cheaper to use
8215     // v_set0 + movlhps or movhlps, etc.
8216     MVT EltVT = VT.getVectorElementType();
8217     ShAmt *= EltVT.getSizeInBits();
8218     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8219   }
8220
8221   if (isMOVLMask(M, VT)) {
8222     if (ISD::isBuildVectorAllZeros(V1.getNode()))
8223       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
8224     if (!isMOVLPMask(M, VT)) {
8225       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
8226         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8227
8228       if (VT == MVT::v4i32 || VT == MVT::v4f32)
8229         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8230     }
8231   }
8232
8233   // FIXME: fold these into legal mask.
8234   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
8235     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
8236
8237   if (isMOVHLPSMask(M, VT))
8238     return getMOVHighToLow(Op, dl, DAG);
8239
8240   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
8241     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
8242
8243   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
8244     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
8245
8246   if (isMOVLPMask(M, VT))
8247     return getMOVLP(Op, dl, DAG, HasSSE2);
8248
8249   if (ShouldXformToMOVHLPS(M, VT) ||
8250       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
8251     return CommuteVectorShuffle(SVOp, DAG);
8252
8253   if (isShift) {
8254     // No better options. Use a vshldq / vsrldq.
8255     MVT EltVT = VT.getVectorElementType();
8256     ShAmt *= EltVT.getSizeInBits();
8257     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8258   }
8259
8260   bool Commuted = false;
8261   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
8262   // 1,1,1,1 -> v8i16 though.
8263   V1IsSplat = isSplatVector(V1.getNode());
8264   V2IsSplat = isSplatVector(V2.getNode());
8265
8266   // Canonicalize the splat or undef, if present, to be on the RHS.
8267   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
8268     CommuteVectorShuffleMask(M, NumElems);
8269     std::swap(V1, V2);
8270     std::swap(V1IsSplat, V2IsSplat);
8271     Commuted = true;
8272   }
8273
8274   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
8275     // Shuffling low element of v1 into undef, just return v1.
8276     if (V2IsUndef)
8277       return V1;
8278     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
8279     // the instruction selector will not match, so get a canonical MOVL with
8280     // swapped operands to undo the commute.
8281     return getMOVL(DAG, dl, VT, V2, V1);
8282   }
8283
8284   if (isUNPCKLMask(M, VT, HasInt256))
8285     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8286
8287   if (isUNPCKHMask(M, VT, HasInt256))
8288     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8289
8290   if (V2IsSplat) {
8291     // Normalize mask so all entries that point to V2 points to its first
8292     // element then try to match unpck{h|l} again. If match, return a
8293     // new vector_shuffle with the corrected mask.p
8294     SmallVector<int, 8> NewMask(M.begin(), M.end());
8295     NormalizeMask(NewMask, NumElems);
8296     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
8297       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8298     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
8299       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8300   }
8301
8302   if (Commuted) {
8303     // Commute is back and try unpck* again.
8304     // FIXME: this seems wrong.
8305     CommuteVectorShuffleMask(M, NumElems);
8306     std::swap(V1, V2);
8307     std::swap(V1IsSplat, V2IsSplat);
8308
8309     if (isUNPCKLMask(M, VT, HasInt256))
8310       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8311
8312     if (isUNPCKHMask(M, VT, HasInt256))
8313       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8314   }
8315
8316   // Normalize the node to match x86 shuffle ops if needed
8317   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8318     return CommuteVectorShuffle(SVOp, DAG);
8319
8320   // The checks below are all present in isShuffleMaskLegal, but they are
8321   // inlined here right now to enable us to directly emit target specific
8322   // nodes, and remove one by one until they don't return Op anymore.
8323
8324   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8325       SVOp->getSplatIndex() == 0 && V2IsUndef) {
8326     if (VT == MVT::v2f64 || VT == MVT::v2i64)
8327       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8328   }
8329
8330   if (isPSHUFHWMask(M, VT, HasInt256))
8331     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8332                                 getShufflePSHUFHWImmediate(SVOp),
8333                                 DAG);
8334
8335   if (isPSHUFLWMask(M, VT, HasInt256))
8336     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8337                                 getShufflePSHUFLWImmediate(SVOp),
8338                                 DAG);
8339
8340   if (isSHUFPMask(M, VT))
8341     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8342                                 getShuffleSHUFImmediate(SVOp), DAG);
8343
8344   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8345     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8346   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8347     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8348
8349   //===--------------------------------------------------------------------===//
8350   // Generate target specific nodes for 128 or 256-bit shuffles only
8351   // supported in the AVX instruction set.
8352   //
8353
8354   // Handle VMOVDDUPY permutations
8355   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8356     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8357
8358   // Handle VPERMILPS/D* permutations
8359   if (isVPERMILPMask(M, VT)) {
8360     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8361       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8362                                   getShuffleSHUFImmediate(SVOp), DAG);
8363     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8364                                 getShuffleSHUFImmediate(SVOp), DAG);
8365   }
8366
8367   unsigned Idx;
8368   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8369     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8370                               Idx*(NumElems/2), DAG, dl);
8371
8372   // Handle VPERM2F128/VPERM2I128 permutations
8373   if (isVPERM2X128Mask(M, VT, HasFp256))
8374     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8375                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8376
8377   unsigned MaskValue;
8378   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8379                   &MaskValue))
8380     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8381
8382   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8383     return getINSERTPS(SVOp, dl, DAG);
8384
8385   unsigned Imm8;
8386   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8387     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8388
8389   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8390       VT.is512BitVector()) {
8391     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8392     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8393     SmallVector<SDValue, 16> permclMask;
8394     for (unsigned i = 0; i != NumElems; ++i) {
8395       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8396     }
8397
8398     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8399     if (V2IsUndef)
8400       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8401       return DAG.getNode(X86ISD::VPERMV, dl, VT,
8402                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8403     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8404                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8405   }
8406
8407   //===--------------------------------------------------------------------===//
8408   // Since no target specific shuffle was selected for this generic one,
8409   // lower it into other known shuffles. FIXME: this isn't true yet, but
8410   // this is the plan.
8411   //
8412
8413   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8414   if (VT == MVT::v8i16) {
8415     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8416     if (NewOp.getNode())
8417       return NewOp;
8418   }
8419
8420   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8421     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8422     if (NewOp.getNode())
8423       return NewOp;
8424   }
8425
8426   if (VT == MVT::v16i8) {
8427     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8428     if (NewOp.getNode())
8429       return NewOp;
8430   }
8431
8432   if (VT == MVT::v32i8) {
8433     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8434     if (NewOp.getNode())
8435       return NewOp;
8436   }
8437
8438   // Handle all 128-bit wide vectors with 4 elements, and match them with
8439   // several different shuffle types.
8440   if (NumElems == 4 && VT.is128BitVector())
8441     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8442
8443   // Handle general 256-bit shuffles
8444   if (VT.is256BitVector())
8445     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8446
8447   return SDValue();
8448 }
8449
8450 // This function assumes its argument is a BUILD_VECTOR of constants or
8451 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8452 // true.
8453 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8454                                     unsigned &MaskValue) {
8455   MaskValue = 0;
8456   unsigned NumElems = BuildVector->getNumOperands();
8457   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8458   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8459   unsigned NumElemsInLane = NumElems / NumLanes;
8460
8461   // Blend for v16i16 should be symetric for the both lanes.
8462   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8463     SDValue EltCond = BuildVector->getOperand(i);
8464     SDValue SndLaneEltCond =
8465         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8466
8467     int Lane1Cond = -1, Lane2Cond = -1;
8468     if (isa<ConstantSDNode>(EltCond))
8469       Lane1Cond = !isZero(EltCond);
8470     if (isa<ConstantSDNode>(SndLaneEltCond))
8471       Lane2Cond = !isZero(SndLaneEltCond);
8472
8473     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8474       // Lane1Cond != 0, means we want the first argument.
8475       // Lane1Cond == 0, means we want the second argument.
8476       // The encoding of this argument is 0 for the first argument, 1
8477       // for the second. Therefore, invert the condition.
8478       MaskValue |= !Lane1Cond << i;
8479     else if (Lane1Cond < 0)
8480       MaskValue |= !Lane2Cond << i;
8481     else
8482       return false;
8483   }
8484   return true;
8485 }
8486
8487 // Try to lower a vselect node into a simple blend instruction.
8488 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8489                                    SelectionDAG &DAG) {
8490   SDValue Cond = Op.getOperand(0);
8491   SDValue LHS = Op.getOperand(1);
8492   SDValue RHS = Op.getOperand(2);
8493   SDLoc dl(Op);
8494   MVT VT = Op.getSimpleValueType();
8495   MVT EltVT = VT.getVectorElementType();
8496   unsigned NumElems = VT.getVectorNumElements();
8497
8498   // There is no blend with immediate in AVX-512.
8499   if (VT.is512BitVector())
8500     return SDValue();
8501
8502   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8503     return SDValue();
8504   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8505     return SDValue();
8506
8507   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8508     return SDValue();
8509
8510   // Check the mask for BLEND and build the value.
8511   unsigned MaskValue = 0;
8512   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8513     return SDValue();
8514
8515   // Convert i32 vectors to floating point if it is not AVX2.
8516   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8517   MVT BlendVT = VT;
8518   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8519     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8520                                NumElems);
8521     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8522     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8523   }
8524
8525   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8526                             DAG.getConstant(MaskValue, MVT::i32));
8527   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8528 }
8529
8530 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8531   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8532   if (BlendOp.getNode())
8533     return BlendOp;
8534
8535   // Some types for vselect were previously set to Expand, not Legal or
8536   // Custom. Return an empty SDValue so we fall-through to Expand, after
8537   // the Custom lowering phase.
8538   MVT VT = Op.getSimpleValueType();
8539   switch (VT.SimpleTy) {
8540   default:
8541     break;
8542   case MVT::v8i16:
8543   case MVT::v16i16:
8544     return SDValue();
8545   }
8546
8547   // We couldn't create a "Blend with immediate" node.
8548   // This node should still be legal, but we'll have to emit a blendv*
8549   // instruction.
8550   return Op;
8551 }
8552
8553 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8554   MVT VT = Op.getSimpleValueType();
8555   SDLoc dl(Op);
8556
8557   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8558     return SDValue();
8559
8560   if (VT.getSizeInBits() == 8) {
8561     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8562                                   Op.getOperand(0), Op.getOperand(1));
8563     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8564                                   DAG.getValueType(VT));
8565     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8566   }
8567
8568   if (VT.getSizeInBits() == 16) {
8569     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8570     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8571     if (Idx == 0)
8572       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8573                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8574                                      DAG.getNode(ISD::BITCAST, dl,
8575                                                  MVT::v4i32,
8576                                                  Op.getOperand(0)),
8577                                      Op.getOperand(1)));
8578     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8579                                   Op.getOperand(0), Op.getOperand(1));
8580     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8581                                   DAG.getValueType(VT));
8582     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8583   }
8584
8585   if (VT == MVT::f32) {
8586     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8587     // the result back to FR32 register. It's only worth matching if the
8588     // result has a single use which is a store or a bitcast to i32.  And in
8589     // the case of a store, it's not worth it if the index is a constant 0,
8590     // because a MOVSSmr can be used instead, which is smaller and faster.
8591     if (!Op.hasOneUse())
8592       return SDValue();
8593     SDNode *User = *Op.getNode()->use_begin();
8594     if ((User->getOpcode() != ISD::STORE ||
8595          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8596           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8597         (User->getOpcode() != ISD::BITCAST ||
8598          User->getValueType(0) != MVT::i32))
8599       return SDValue();
8600     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8601                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8602                                               Op.getOperand(0)),
8603                                               Op.getOperand(1));
8604     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8605   }
8606
8607   if (VT == MVT::i32 || VT == MVT::i64) {
8608     // ExtractPS/pextrq works with constant index.
8609     if (isa<ConstantSDNode>(Op.getOperand(1)))
8610       return Op;
8611   }
8612   return SDValue();
8613 }
8614
8615 /// Extract one bit from mask vector, like v16i1 or v8i1.
8616 /// AVX-512 feature.
8617 SDValue
8618 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8619   SDValue Vec = Op.getOperand(0);
8620   SDLoc dl(Vec);
8621   MVT VecVT = Vec.getSimpleValueType();
8622   SDValue Idx = Op.getOperand(1);
8623   MVT EltVT = Op.getSimpleValueType();
8624
8625   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8626
8627   // variable index can't be handled in mask registers,
8628   // extend vector to VR512
8629   if (!isa<ConstantSDNode>(Idx)) {
8630     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8631     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8632     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8633                               ExtVT.getVectorElementType(), Ext, Idx);
8634     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8635   }
8636
8637   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8638   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8639   unsigned MaxSift = rc->getSize()*8 - 1;
8640   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8641                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8642   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8643                     DAG.getConstant(MaxSift, MVT::i8));
8644   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8645                        DAG.getIntPtrConstant(0));
8646 }
8647
8648 SDValue
8649 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8650                                            SelectionDAG &DAG) const {
8651   SDLoc dl(Op);
8652   SDValue Vec = Op.getOperand(0);
8653   MVT VecVT = Vec.getSimpleValueType();
8654   SDValue Idx = Op.getOperand(1);
8655
8656   if (Op.getSimpleValueType() == MVT::i1)
8657     return ExtractBitFromMaskVector(Op, DAG);
8658
8659   if (!isa<ConstantSDNode>(Idx)) {
8660     if (VecVT.is512BitVector() ||
8661         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8662          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8663
8664       MVT MaskEltVT =
8665         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8666       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8667                                     MaskEltVT.getSizeInBits());
8668
8669       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8670       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8671                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8672                                 Idx, DAG.getConstant(0, getPointerTy()));
8673       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8674       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8675                         Perm, DAG.getConstant(0, getPointerTy()));
8676     }
8677     return SDValue();
8678   }
8679
8680   // If this is a 256-bit vector result, first extract the 128-bit vector and
8681   // then extract the element from the 128-bit vector.
8682   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8683
8684     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8685     // Get the 128-bit vector.
8686     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8687     MVT EltVT = VecVT.getVectorElementType();
8688
8689     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8690
8691     //if (IdxVal >= NumElems/2)
8692     //  IdxVal -= NumElems/2;
8693     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8694     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8695                        DAG.getConstant(IdxVal, MVT::i32));
8696   }
8697
8698   assert(VecVT.is128BitVector() && "Unexpected vector length");
8699
8700   if (Subtarget->hasSSE41()) {
8701     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8702     if (Res.getNode())
8703       return Res;
8704   }
8705
8706   MVT VT = Op.getSimpleValueType();
8707   // TODO: handle v16i8.
8708   if (VT.getSizeInBits() == 16) {
8709     SDValue Vec = Op.getOperand(0);
8710     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8711     if (Idx == 0)
8712       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8713                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8714                                      DAG.getNode(ISD::BITCAST, dl,
8715                                                  MVT::v4i32, Vec),
8716                                      Op.getOperand(1)));
8717     // Transform it so it match pextrw which produces a 32-bit result.
8718     MVT EltVT = MVT::i32;
8719     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8720                                   Op.getOperand(0), Op.getOperand(1));
8721     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8722                                   DAG.getValueType(VT));
8723     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8724   }
8725
8726   if (VT.getSizeInBits() == 32) {
8727     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8728     if (Idx == 0)
8729       return Op;
8730
8731     // SHUFPS the element to the lowest double word, then movss.
8732     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8733     MVT VVT = Op.getOperand(0).getSimpleValueType();
8734     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8735                                        DAG.getUNDEF(VVT), Mask);
8736     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8737                        DAG.getIntPtrConstant(0));
8738   }
8739
8740   if (VT.getSizeInBits() == 64) {
8741     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8742     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8743     //        to match extract_elt for f64.
8744     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8745     if (Idx == 0)
8746       return Op;
8747
8748     // UNPCKHPD the element to the lowest double word, then movsd.
8749     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8750     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8751     int Mask[2] = { 1, -1 };
8752     MVT VVT = Op.getOperand(0).getSimpleValueType();
8753     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8754                                        DAG.getUNDEF(VVT), Mask);
8755     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8756                        DAG.getIntPtrConstant(0));
8757   }
8758
8759   return SDValue();
8760 }
8761
8762 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8763   MVT VT = Op.getSimpleValueType();
8764   MVT EltVT = VT.getVectorElementType();
8765   SDLoc dl(Op);
8766
8767   SDValue N0 = Op.getOperand(0);
8768   SDValue N1 = Op.getOperand(1);
8769   SDValue N2 = Op.getOperand(2);
8770
8771   if (!VT.is128BitVector())
8772     return SDValue();
8773
8774   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8775       isa<ConstantSDNode>(N2)) {
8776     unsigned Opc;
8777     if (VT == MVT::v8i16)
8778       Opc = X86ISD::PINSRW;
8779     else if (VT == MVT::v16i8)
8780       Opc = X86ISD::PINSRB;
8781     else
8782       Opc = X86ISD::PINSRB;
8783
8784     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8785     // argument.
8786     if (N1.getValueType() != MVT::i32)
8787       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8788     if (N2.getValueType() != MVT::i32)
8789       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8790     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8791   }
8792
8793   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8794     // Bits [7:6] of the constant are the source select.  This will always be
8795     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8796     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8797     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8798     // Bits [5:4] of the constant are the destination select.  This is the
8799     //  value of the incoming immediate.
8800     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8801     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8802     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8803     // Create this as a scalar to vector..
8804     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8805     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8806   }
8807
8808   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8809     // PINSR* works with constant index.
8810     return Op;
8811   }
8812   return SDValue();
8813 }
8814
8815 /// Insert one bit to mask vector, like v16i1 or v8i1.
8816 /// AVX-512 feature.
8817 SDValue 
8818 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8819   SDLoc dl(Op);
8820   SDValue Vec = Op.getOperand(0);
8821   SDValue Elt = Op.getOperand(1);
8822   SDValue Idx = Op.getOperand(2);
8823   MVT VecVT = Vec.getSimpleValueType();
8824
8825   if (!isa<ConstantSDNode>(Idx)) {
8826     // Non constant index. Extend source and destination,
8827     // insert element and then truncate the result.
8828     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8829     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8830     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8831       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8832       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8833     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8834   }
8835
8836   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8837   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8838   if (Vec.getOpcode() == ISD::UNDEF)
8839     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8840                        DAG.getConstant(IdxVal, MVT::i8));
8841   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8842   unsigned MaxSift = rc->getSize()*8 - 1;
8843   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8844                     DAG.getConstant(MaxSift, MVT::i8));
8845   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8846                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8847   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8848 }
8849 SDValue
8850 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8851   MVT VT = Op.getSimpleValueType();
8852   MVT EltVT = VT.getVectorElementType();
8853   
8854   if (EltVT == MVT::i1)
8855     return InsertBitToMaskVector(Op, DAG);
8856
8857   SDLoc dl(Op);
8858   SDValue N0 = Op.getOperand(0);
8859   SDValue N1 = Op.getOperand(1);
8860   SDValue N2 = Op.getOperand(2);
8861
8862   // If this is a 256-bit vector result, first extract the 128-bit vector,
8863   // insert the element into the extracted half and then place it back.
8864   if (VT.is256BitVector() || VT.is512BitVector()) {
8865     if (!isa<ConstantSDNode>(N2))
8866       return SDValue();
8867
8868     // Get the desired 128-bit vector half.
8869     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8870     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8871
8872     // Insert the element into the desired half.
8873     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8874     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8875
8876     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8877                     DAG.getConstant(IdxIn128, MVT::i32));
8878
8879     // Insert the changed part back to the 256-bit vector
8880     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8881   }
8882
8883   if (Subtarget->hasSSE41())
8884     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8885
8886   if (EltVT == MVT::i8)
8887     return SDValue();
8888
8889   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8890     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8891     // as its second argument.
8892     if (N1.getValueType() != MVT::i32)
8893       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8894     if (N2.getValueType() != MVT::i32)
8895       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8896     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8897   }
8898   return SDValue();
8899 }
8900
8901 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8902   SDLoc dl(Op);
8903   MVT OpVT = Op.getSimpleValueType();
8904
8905   // If this is a 256-bit vector result, first insert into a 128-bit
8906   // vector and then insert into the 256-bit vector.
8907   if (!OpVT.is128BitVector()) {
8908     // Insert into a 128-bit vector.
8909     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8910     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8911                                  OpVT.getVectorNumElements() / SizeFactor);
8912
8913     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8914
8915     // Insert the 128-bit vector.
8916     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8917   }
8918
8919   if (OpVT == MVT::v1i64 &&
8920       Op.getOperand(0).getValueType() == MVT::i64)
8921     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8922
8923   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8924   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8925   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8926                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8927 }
8928
8929 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8930 // a simple subregister reference or explicit instructions to grab
8931 // upper bits of a vector.
8932 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8933                                       SelectionDAG &DAG) {
8934   SDLoc dl(Op);
8935   SDValue In =  Op.getOperand(0);
8936   SDValue Idx = Op.getOperand(1);
8937   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8938   MVT ResVT   = Op.getSimpleValueType();
8939   MVT InVT    = In.getSimpleValueType();
8940
8941   if (Subtarget->hasFp256()) {
8942     if (ResVT.is128BitVector() &&
8943         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8944         isa<ConstantSDNode>(Idx)) {
8945       return Extract128BitVector(In, IdxVal, DAG, dl);
8946     }
8947     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8948         isa<ConstantSDNode>(Idx)) {
8949       return Extract256BitVector(In, IdxVal, DAG, dl);
8950     }
8951   }
8952   return SDValue();
8953 }
8954
8955 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8956 // simple superregister reference or explicit instructions to insert
8957 // the upper bits of a vector.
8958 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8959                                      SelectionDAG &DAG) {
8960   if (Subtarget->hasFp256()) {
8961     SDLoc dl(Op.getNode());
8962     SDValue Vec = Op.getNode()->getOperand(0);
8963     SDValue SubVec = Op.getNode()->getOperand(1);
8964     SDValue Idx = Op.getNode()->getOperand(2);
8965
8966     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8967          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8968         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8969         isa<ConstantSDNode>(Idx)) {
8970       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8971       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8972     }
8973
8974     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8975         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8976         isa<ConstantSDNode>(Idx)) {
8977       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8978       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8979     }
8980   }
8981   return SDValue();
8982 }
8983
8984 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8985 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8986 // one of the above mentioned nodes. It has to be wrapped because otherwise
8987 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8988 // be used to form addressing mode. These wrapped nodes will be selected
8989 // into MOV32ri.
8990 SDValue
8991 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8992   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8993
8994   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8995   // global base reg.
8996   unsigned char OpFlag = 0;
8997   unsigned WrapperKind = X86ISD::Wrapper;
8998   CodeModel::Model M = DAG.getTarget().getCodeModel();
8999
9000   if (Subtarget->isPICStyleRIPRel() &&
9001       (M == CodeModel::Small || M == CodeModel::Kernel))
9002     WrapperKind = X86ISD::WrapperRIP;
9003   else if (Subtarget->isPICStyleGOT())
9004     OpFlag = X86II::MO_GOTOFF;
9005   else if (Subtarget->isPICStyleStubPIC())
9006     OpFlag = X86II::MO_PIC_BASE_OFFSET;
9007
9008   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
9009                                              CP->getAlignment(),
9010                                              CP->getOffset(), OpFlag);
9011   SDLoc DL(CP);
9012   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9013   // With PIC, the address is actually $g + Offset.
9014   if (OpFlag) {
9015     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9016                          DAG.getNode(X86ISD::GlobalBaseReg,
9017                                      SDLoc(), getPointerTy()),
9018                          Result);
9019   }
9020
9021   return Result;
9022 }
9023
9024 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
9025   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
9026
9027   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9028   // global base reg.
9029   unsigned char OpFlag = 0;
9030   unsigned WrapperKind = X86ISD::Wrapper;
9031   CodeModel::Model M = DAG.getTarget().getCodeModel();
9032
9033   if (Subtarget->isPICStyleRIPRel() &&
9034       (M == CodeModel::Small || M == CodeModel::Kernel))
9035     WrapperKind = X86ISD::WrapperRIP;
9036   else if (Subtarget->isPICStyleGOT())
9037     OpFlag = X86II::MO_GOTOFF;
9038   else if (Subtarget->isPICStyleStubPIC())
9039     OpFlag = X86II::MO_PIC_BASE_OFFSET;
9040
9041   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
9042                                           OpFlag);
9043   SDLoc DL(JT);
9044   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9045
9046   // With PIC, the address is actually $g + Offset.
9047   if (OpFlag)
9048     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9049                          DAG.getNode(X86ISD::GlobalBaseReg,
9050                                      SDLoc(), getPointerTy()),
9051                          Result);
9052
9053   return Result;
9054 }
9055
9056 SDValue
9057 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
9058   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
9059
9060   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9061   // global base reg.
9062   unsigned char OpFlag = 0;
9063   unsigned WrapperKind = X86ISD::Wrapper;
9064   CodeModel::Model M = DAG.getTarget().getCodeModel();
9065
9066   if (Subtarget->isPICStyleRIPRel() &&
9067       (M == CodeModel::Small || M == CodeModel::Kernel)) {
9068     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
9069       OpFlag = X86II::MO_GOTPCREL;
9070     WrapperKind = X86ISD::WrapperRIP;
9071   } else if (Subtarget->isPICStyleGOT()) {
9072     OpFlag = X86II::MO_GOT;
9073   } else if (Subtarget->isPICStyleStubPIC()) {
9074     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
9075   } else if (Subtarget->isPICStyleStubNoDynamic()) {
9076     OpFlag = X86II::MO_DARWIN_NONLAZY;
9077   }
9078
9079   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
9080
9081   SDLoc DL(Op);
9082   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9083
9084   // With PIC, the address is actually $g + Offset.
9085   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
9086       !Subtarget->is64Bit()) {
9087     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9088                          DAG.getNode(X86ISD::GlobalBaseReg,
9089                                      SDLoc(), getPointerTy()),
9090                          Result);
9091   }
9092
9093   // For symbols that require a load from a stub to get the address, emit the
9094   // load.
9095   if (isGlobalStubReference(OpFlag))
9096     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
9097                          MachinePointerInfo::getGOT(), false, false, false, 0);
9098
9099   return Result;
9100 }
9101
9102 SDValue
9103 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
9104   // Create the TargetBlockAddressAddress node.
9105   unsigned char OpFlags =
9106     Subtarget->ClassifyBlockAddressReference();
9107   CodeModel::Model M = DAG.getTarget().getCodeModel();
9108   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
9109   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
9110   SDLoc dl(Op);
9111   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
9112                                              OpFlags);
9113
9114   if (Subtarget->isPICStyleRIPRel() &&
9115       (M == CodeModel::Small || M == CodeModel::Kernel))
9116     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9117   else
9118     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9119
9120   // With PIC, the address is actually $g + Offset.
9121   if (isGlobalRelativeToPICBase(OpFlags)) {
9122     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9123                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9124                          Result);
9125   }
9126
9127   return Result;
9128 }
9129
9130 SDValue
9131 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
9132                                       int64_t Offset, SelectionDAG &DAG) const {
9133   // Create the TargetGlobalAddress node, folding in the constant
9134   // offset if it is legal.
9135   unsigned char OpFlags =
9136       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
9137   CodeModel::Model M = DAG.getTarget().getCodeModel();
9138   SDValue Result;
9139   if (OpFlags == X86II::MO_NO_FLAG &&
9140       X86::isOffsetSuitableForCodeModel(Offset, M)) {
9141     // A direct static reference to a global.
9142     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
9143     Offset = 0;
9144   } else {
9145     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
9146   }
9147
9148   if (Subtarget->isPICStyleRIPRel() &&
9149       (M == CodeModel::Small || M == CodeModel::Kernel))
9150     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9151   else
9152     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9153
9154   // With PIC, the address is actually $g + Offset.
9155   if (isGlobalRelativeToPICBase(OpFlags)) {
9156     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9157                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9158                          Result);
9159   }
9160
9161   // For globals that require a load from a stub to get the address, emit the
9162   // load.
9163   if (isGlobalStubReference(OpFlags))
9164     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
9165                          MachinePointerInfo::getGOT(), false, false, false, 0);
9166
9167   // If there was a non-zero offset that we didn't fold, create an explicit
9168   // addition for it.
9169   if (Offset != 0)
9170     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
9171                          DAG.getConstant(Offset, getPointerTy()));
9172
9173   return Result;
9174 }
9175
9176 SDValue
9177 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
9178   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
9179   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
9180   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
9181 }
9182
9183 static SDValue
9184 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
9185            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
9186            unsigned char OperandFlags, bool LocalDynamic = false) {
9187   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9188   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9189   SDLoc dl(GA);
9190   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9191                                            GA->getValueType(0),
9192                                            GA->getOffset(),
9193                                            OperandFlags);
9194
9195   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
9196                                            : X86ISD::TLSADDR;
9197
9198   if (InFlag) {
9199     SDValue Ops[] = { Chain,  TGA, *InFlag };
9200     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9201   } else {
9202     SDValue Ops[]  = { Chain, TGA };
9203     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9204   }
9205
9206   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9207   MFI->setAdjustsStack(true);
9208
9209   SDValue Flag = Chain.getValue(1);
9210   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
9211 }
9212
9213 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
9214 static SDValue
9215 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9216                                 const EVT PtrVT) {
9217   SDValue InFlag;
9218   SDLoc dl(GA);  // ? function entry point might be better
9219   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9220                                    DAG.getNode(X86ISD::GlobalBaseReg,
9221                                                SDLoc(), PtrVT), InFlag);
9222   InFlag = Chain.getValue(1);
9223
9224   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
9225 }
9226
9227 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
9228 static SDValue
9229 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9230                                 const EVT PtrVT) {
9231   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
9232                     X86::RAX, X86II::MO_TLSGD);
9233 }
9234
9235 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
9236                                            SelectionDAG &DAG,
9237                                            const EVT PtrVT,
9238                                            bool is64Bit) {
9239   SDLoc dl(GA);
9240
9241   // Get the start address of the TLS block for this module.
9242   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
9243       .getInfo<X86MachineFunctionInfo>();
9244   MFI->incNumLocalDynamicTLSAccesses();
9245
9246   SDValue Base;
9247   if (is64Bit) {
9248     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
9249                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
9250   } else {
9251     SDValue InFlag;
9252     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9253         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
9254     InFlag = Chain.getValue(1);
9255     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
9256                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
9257   }
9258
9259   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
9260   // of Base.
9261
9262   // Build x@dtpoff.
9263   unsigned char OperandFlags = X86II::MO_DTPOFF;
9264   unsigned WrapperKind = X86ISD::Wrapper;
9265   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9266                                            GA->getValueType(0),
9267                                            GA->getOffset(), OperandFlags);
9268   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9269
9270   // Add x@dtpoff with the base.
9271   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
9272 }
9273
9274 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
9275 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9276                                    const EVT PtrVT, TLSModel::Model model,
9277                                    bool is64Bit, bool isPIC) {
9278   SDLoc dl(GA);
9279
9280   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
9281   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
9282                                                          is64Bit ? 257 : 256));
9283
9284   SDValue ThreadPointer =
9285       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
9286                   MachinePointerInfo(Ptr), false, false, false, 0);
9287
9288   unsigned char OperandFlags = 0;
9289   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
9290   // initialexec.
9291   unsigned WrapperKind = X86ISD::Wrapper;
9292   if (model == TLSModel::LocalExec) {
9293     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
9294   } else if (model == TLSModel::InitialExec) {
9295     if (is64Bit) {
9296       OperandFlags = X86II::MO_GOTTPOFF;
9297       WrapperKind = X86ISD::WrapperRIP;
9298     } else {
9299       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9300     }
9301   } else {
9302     llvm_unreachable("Unexpected model");
9303   }
9304
9305   // emit "addl x@ntpoff,%eax" (local exec)
9306   // or "addl x@indntpoff,%eax" (initial exec)
9307   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9308   SDValue TGA =
9309       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9310                                  GA->getOffset(), OperandFlags);
9311   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9312
9313   if (model == TLSModel::InitialExec) {
9314     if (isPIC && !is64Bit) {
9315       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9316                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9317                            Offset);
9318     }
9319
9320     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9321                          MachinePointerInfo::getGOT(), false, false, false, 0);
9322   }
9323
9324   // The address of the thread local variable is the add of the thread
9325   // pointer with the offset of the variable.
9326   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9327 }
9328
9329 SDValue
9330 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9331
9332   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9333   const GlobalValue *GV = GA->getGlobal();
9334
9335   if (Subtarget->isTargetELF()) {
9336     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9337
9338     switch (model) {
9339       case TLSModel::GeneralDynamic:
9340         if (Subtarget->is64Bit())
9341           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9342         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9343       case TLSModel::LocalDynamic:
9344         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9345                                            Subtarget->is64Bit());
9346       case TLSModel::InitialExec:
9347       case TLSModel::LocalExec:
9348         return LowerToTLSExecModel(
9349             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9350             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9351     }
9352     llvm_unreachable("Unknown TLS model.");
9353   }
9354
9355   if (Subtarget->isTargetDarwin()) {
9356     // Darwin only has one model of TLS.  Lower to that.
9357     unsigned char OpFlag = 0;
9358     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9359                            X86ISD::WrapperRIP : X86ISD::Wrapper;
9360
9361     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9362     // global base reg.
9363     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9364                  !Subtarget->is64Bit();
9365     if (PIC32)
9366       OpFlag = X86II::MO_TLVP_PIC_BASE;
9367     else
9368       OpFlag = X86II::MO_TLVP;
9369     SDLoc DL(Op);
9370     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9371                                                 GA->getValueType(0),
9372                                                 GA->getOffset(), OpFlag);
9373     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9374
9375     // With PIC32, the address is actually $g + Offset.
9376     if (PIC32)
9377       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9378                            DAG.getNode(X86ISD::GlobalBaseReg,
9379                                        SDLoc(), getPointerTy()),
9380                            Offset);
9381
9382     // Lowering the machine isd will make sure everything is in the right
9383     // location.
9384     SDValue Chain = DAG.getEntryNode();
9385     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9386     SDValue Args[] = { Chain, Offset };
9387     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9388
9389     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9390     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9391     MFI->setAdjustsStack(true);
9392
9393     // And our return value (tls address) is in the standard call return value
9394     // location.
9395     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9396     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9397                               Chain.getValue(1));
9398   }
9399
9400   if (Subtarget->isTargetKnownWindowsMSVC() ||
9401       Subtarget->isTargetWindowsGNU()) {
9402     // Just use the implicit TLS architecture
9403     // Need to generate someting similar to:
9404     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9405     //                                  ; from TEB
9406     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
9407     //   mov     rcx, qword [rdx+rcx*8]
9408     //   mov     eax, .tls$:tlsvar
9409     //   [rax+rcx] contains the address
9410     // Windows 64bit: gs:0x58
9411     // Windows 32bit: fs:__tls_array
9412
9413     SDLoc dl(GA);
9414     SDValue Chain = DAG.getEntryNode();
9415
9416     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9417     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9418     // use its literal value of 0x2C.
9419     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9420                                         ? Type::getInt8PtrTy(*DAG.getContext(),
9421                                                              256)
9422                                         : Type::getInt32PtrTy(*DAG.getContext(),
9423                                                               257));
9424
9425     SDValue TlsArray =
9426         Subtarget->is64Bit()
9427             ? DAG.getIntPtrConstant(0x58)
9428             : (Subtarget->isTargetWindowsGNU()
9429                    ? DAG.getIntPtrConstant(0x2C)
9430                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9431
9432     SDValue ThreadPointer =
9433         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9434                     MachinePointerInfo(Ptr), false, false, false, 0);
9435
9436     // Load the _tls_index variable
9437     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9438     if (Subtarget->is64Bit())
9439       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9440                            IDX, MachinePointerInfo(), MVT::i32,
9441                            false, false, 0);
9442     else
9443       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9444                         false, false, false, 0);
9445
9446     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9447                                     getPointerTy());
9448     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9449
9450     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9451     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9452                       false, false, false, 0);
9453
9454     // Get the offset of start of .tls section
9455     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9456                                              GA->getValueType(0),
9457                                              GA->getOffset(), X86II::MO_SECREL);
9458     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9459
9460     // The address of the thread local variable is the add of the thread
9461     // pointer with the offset of the variable.
9462     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9463   }
9464
9465   llvm_unreachable("TLS not implemented for this target.");
9466 }
9467
9468 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9469 /// and take a 2 x i32 value to shift plus a shift amount.
9470 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9471   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9472   MVT VT = Op.getSimpleValueType();
9473   unsigned VTBits = VT.getSizeInBits();
9474   SDLoc dl(Op);
9475   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9476   SDValue ShOpLo = Op.getOperand(0);
9477   SDValue ShOpHi = Op.getOperand(1);
9478   SDValue ShAmt  = Op.getOperand(2);
9479   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9480   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9481   // during isel.
9482   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9483                                   DAG.getConstant(VTBits - 1, MVT::i8));
9484   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9485                                      DAG.getConstant(VTBits - 1, MVT::i8))
9486                        : DAG.getConstant(0, VT);
9487
9488   SDValue Tmp2, Tmp3;
9489   if (Op.getOpcode() == ISD::SHL_PARTS) {
9490     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9491     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9492   } else {
9493     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9494     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9495   }
9496
9497   // If the shift amount is larger or equal than the width of a part we can't
9498   // rely on the results of shld/shrd. Insert a test and select the appropriate
9499   // values for large shift amounts.
9500   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9501                                 DAG.getConstant(VTBits, MVT::i8));
9502   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9503                              AndNode, DAG.getConstant(0, MVT::i8));
9504
9505   SDValue Hi, Lo;
9506   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9507   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9508   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9509
9510   if (Op.getOpcode() == ISD::SHL_PARTS) {
9511     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9512     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9513   } else {
9514     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9515     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9516   }
9517
9518   SDValue Ops[2] = { Lo, Hi };
9519   return DAG.getMergeValues(Ops, dl);
9520 }
9521
9522 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9523                                            SelectionDAG &DAG) const {
9524   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9525
9526   if (SrcVT.isVector())
9527     return SDValue();
9528
9529   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9530          "Unknown SINT_TO_FP to lower!");
9531
9532   // These are really Legal; return the operand so the caller accepts it as
9533   // Legal.
9534   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9535     return Op;
9536   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9537       Subtarget->is64Bit()) {
9538     return Op;
9539   }
9540
9541   SDLoc dl(Op);
9542   unsigned Size = SrcVT.getSizeInBits()/8;
9543   MachineFunction &MF = DAG.getMachineFunction();
9544   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9545   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9546   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9547                                StackSlot,
9548                                MachinePointerInfo::getFixedStack(SSFI),
9549                                false, false, 0);
9550   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9551 }
9552
9553 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9554                                      SDValue StackSlot,
9555                                      SelectionDAG &DAG) const {
9556   // Build the FILD
9557   SDLoc DL(Op);
9558   SDVTList Tys;
9559   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9560   if (useSSE)
9561     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9562   else
9563     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9564
9565   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9566
9567   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9568   MachineMemOperand *MMO;
9569   if (FI) {
9570     int SSFI = FI->getIndex();
9571     MMO =
9572       DAG.getMachineFunction()
9573       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9574                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9575   } else {
9576     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9577     StackSlot = StackSlot.getOperand(1);
9578   }
9579   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9580   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9581                                            X86ISD::FILD, DL,
9582                                            Tys, Ops, SrcVT, MMO);
9583
9584   if (useSSE) {
9585     Chain = Result.getValue(1);
9586     SDValue InFlag = Result.getValue(2);
9587
9588     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9589     // shouldn't be necessary except that RFP cannot be live across
9590     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9591     MachineFunction &MF = DAG.getMachineFunction();
9592     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9593     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9594     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9595     Tys = DAG.getVTList(MVT::Other);
9596     SDValue Ops[] = {
9597       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9598     };
9599     MachineMemOperand *MMO =
9600       DAG.getMachineFunction()
9601       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9602                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9603
9604     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9605                                     Ops, Op.getValueType(), MMO);
9606     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9607                          MachinePointerInfo::getFixedStack(SSFI),
9608                          false, false, false, 0);
9609   }
9610
9611   return Result;
9612 }
9613
9614 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9615 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9616                                                SelectionDAG &DAG) const {
9617   // This algorithm is not obvious. Here it is what we're trying to output:
9618   /*
9619      movq       %rax,  %xmm0
9620      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9621      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9622      #ifdef __SSE3__
9623        haddpd   %xmm0, %xmm0
9624      #else
9625        pshufd   $0x4e, %xmm0, %xmm1
9626        addpd    %xmm1, %xmm0
9627      #endif
9628   */
9629
9630   SDLoc dl(Op);
9631   LLVMContext *Context = DAG.getContext();
9632
9633   // Build some magic constants.
9634   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9635   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9636   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9637
9638   SmallVector<Constant*,2> CV1;
9639   CV1.push_back(
9640     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9641                                       APInt(64, 0x4330000000000000ULL))));
9642   CV1.push_back(
9643     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9644                                       APInt(64, 0x4530000000000000ULL))));
9645   Constant *C1 = ConstantVector::get(CV1);
9646   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9647
9648   // Load the 64-bit value into an XMM register.
9649   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9650                             Op.getOperand(0));
9651   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9652                               MachinePointerInfo::getConstantPool(),
9653                               false, false, false, 16);
9654   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9655                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9656                               CLod0);
9657
9658   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9659                               MachinePointerInfo::getConstantPool(),
9660                               false, false, false, 16);
9661   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9662   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9663   SDValue Result;
9664
9665   if (Subtarget->hasSSE3()) {
9666     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9667     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9668   } else {
9669     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9670     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9671                                            S2F, 0x4E, DAG);
9672     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9673                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9674                          Sub);
9675   }
9676
9677   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9678                      DAG.getIntPtrConstant(0));
9679 }
9680
9681 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9682 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9683                                                SelectionDAG &DAG) const {
9684   SDLoc dl(Op);
9685   // FP constant to bias correct the final result.
9686   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9687                                    MVT::f64);
9688
9689   // Load the 32-bit value into an XMM register.
9690   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9691                              Op.getOperand(0));
9692
9693   // Zero out the upper parts of the register.
9694   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9695
9696   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9697                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9698                      DAG.getIntPtrConstant(0));
9699
9700   // Or the load with the bias.
9701   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9702                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9703                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9704                                                    MVT::v2f64, Load)),
9705                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9706                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9707                                                    MVT::v2f64, Bias)));
9708   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9709                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9710                    DAG.getIntPtrConstant(0));
9711
9712   // Subtract the bias.
9713   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9714
9715   // Handle final rounding.
9716   EVT DestVT = Op.getValueType();
9717
9718   if (DestVT.bitsLT(MVT::f64))
9719     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9720                        DAG.getIntPtrConstant(0));
9721   if (DestVT.bitsGT(MVT::f64))
9722     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9723
9724   // Handle final rounding.
9725   return Sub;
9726 }
9727
9728 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9729                                                SelectionDAG &DAG) const {
9730   SDValue N0 = Op.getOperand(0);
9731   MVT SVT = N0.getSimpleValueType();
9732   SDLoc dl(Op);
9733
9734   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9735           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9736          "Custom UINT_TO_FP is not supported!");
9737
9738   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9739   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9740                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9741 }
9742
9743 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9744                                            SelectionDAG &DAG) const {
9745   SDValue N0 = Op.getOperand(0);
9746   SDLoc dl(Op);
9747
9748   if (Op.getValueType().isVector())
9749     return lowerUINT_TO_FP_vec(Op, DAG);
9750
9751   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9752   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9753   // the optimization here.
9754   if (DAG.SignBitIsZero(N0))
9755     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9756
9757   MVT SrcVT = N0.getSimpleValueType();
9758   MVT DstVT = Op.getSimpleValueType();
9759   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9760     return LowerUINT_TO_FP_i64(Op, DAG);
9761   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9762     return LowerUINT_TO_FP_i32(Op, DAG);
9763   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9764     return SDValue();
9765
9766   // Make a 64-bit buffer, and use it to build an FILD.
9767   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9768   if (SrcVT == MVT::i32) {
9769     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9770     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9771                                      getPointerTy(), StackSlot, WordOff);
9772     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9773                                   StackSlot, MachinePointerInfo(),
9774                                   false, false, 0);
9775     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9776                                   OffsetSlot, MachinePointerInfo(),
9777                                   false, false, 0);
9778     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9779     return Fild;
9780   }
9781
9782   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9783   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9784                                StackSlot, MachinePointerInfo(),
9785                                false, false, 0);
9786   // For i64 source, we need to add the appropriate power of 2 if the input
9787   // was negative.  This is the same as the optimization in
9788   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9789   // we must be careful to do the computation in x87 extended precision, not
9790   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9791   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9792   MachineMemOperand *MMO =
9793     DAG.getMachineFunction()
9794     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9795                           MachineMemOperand::MOLoad, 8, 8);
9796
9797   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9798   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9799   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9800                                          MVT::i64, MMO);
9801
9802   APInt FF(32, 0x5F800000ULL);
9803
9804   // Check whether the sign bit is set.
9805   SDValue SignSet = DAG.getSetCC(dl,
9806                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9807                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9808                                  ISD::SETLT);
9809
9810   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9811   SDValue FudgePtr = DAG.getConstantPool(
9812                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9813                                          getPointerTy());
9814
9815   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9816   SDValue Zero = DAG.getIntPtrConstant(0);
9817   SDValue Four = DAG.getIntPtrConstant(4);
9818   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9819                                Zero, Four);
9820   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9821
9822   // Load the value out, extending it from f32 to f80.
9823   // FIXME: Avoid the extend by constructing the right constant pool?
9824   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9825                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9826                                  MVT::f32, false, false, 4);
9827   // Extend everything to 80 bits to force it to be done on x87.
9828   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9829   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9830 }
9831
9832 std::pair<SDValue,SDValue>
9833 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9834                                     bool IsSigned, bool IsReplace) const {
9835   SDLoc DL(Op);
9836
9837   EVT DstTy = Op.getValueType();
9838
9839   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9840     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9841     DstTy = MVT::i64;
9842   }
9843
9844   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9845          DstTy.getSimpleVT() >= MVT::i16 &&
9846          "Unknown FP_TO_INT to lower!");
9847
9848   // These are really Legal.
9849   if (DstTy == MVT::i32 &&
9850       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9851     return std::make_pair(SDValue(), SDValue());
9852   if (Subtarget->is64Bit() &&
9853       DstTy == MVT::i64 &&
9854       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9855     return std::make_pair(SDValue(), SDValue());
9856
9857   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9858   // stack slot, or into the FTOL runtime function.
9859   MachineFunction &MF = DAG.getMachineFunction();
9860   unsigned MemSize = DstTy.getSizeInBits()/8;
9861   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9862   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9863
9864   unsigned Opc;
9865   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9866     Opc = X86ISD::WIN_FTOL;
9867   else
9868     switch (DstTy.getSimpleVT().SimpleTy) {
9869     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9870     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9871     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9872     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9873     }
9874
9875   SDValue Chain = DAG.getEntryNode();
9876   SDValue Value = Op.getOperand(0);
9877   EVT TheVT = Op.getOperand(0).getValueType();
9878   // FIXME This causes a redundant load/store if the SSE-class value is already
9879   // in memory, such as if it is on the callstack.
9880   if (isScalarFPTypeInSSEReg(TheVT)) {
9881     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9882     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9883                          MachinePointerInfo::getFixedStack(SSFI),
9884                          false, false, 0);
9885     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9886     SDValue Ops[] = {
9887       Chain, StackSlot, DAG.getValueType(TheVT)
9888     };
9889
9890     MachineMemOperand *MMO =
9891       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9892                               MachineMemOperand::MOLoad, MemSize, MemSize);
9893     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9894     Chain = Value.getValue(1);
9895     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9896     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9897   }
9898
9899   MachineMemOperand *MMO =
9900     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9901                             MachineMemOperand::MOStore, MemSize, MemSize);
9902
9903   if (Opc != X86ISD::WIN_FTOL) {
9904     // Build the FP_TO_INT*_IN_MEM
9905     SDValue Ops[] = { Chain, Value, StackSlot };
9906     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9907                                            Ops, DstTy, MMO);
9908     return std::make_pair(FIST, StackSlot);
9909   } else {
9910     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9911       DAG.getVTList(MVT::Other, MVT::Glue),
9912       Chain, Value);
9913     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9914       MVT::i32, ftol.getValue(1));
9915     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9916       MVT::i32, eax.getValue(2));
9917     SDValue Ops[] = { eax, edx };
9918     SDValue pair = IsReplace
9919       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9920       : DAG.getMergeValues(Ops, DL);
9921     return std::make_pair(pair, SDValue());
9922   }
9923 }
9924
9925 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9926                               const X86Subtarget *Subtarget) {
9927   MVT VT = Op->getSimpleValueType(0);
9928   SDValue In = Op->getOperand(0);
9929   MVT InVT = In.getSimpleValueType();
9930   SDLoc dl(Op);
9931
9932   // Optimize vectors in AVX mode:
9933   //
9934   //   v8i16 -> v8i32
9935   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9936   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9937   //   Concat upper and lower parts.
9938   //
9939   //   v4i32 -> v4i64
9940   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9941   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9942   //   Concat upper and lower parts.
9943   //
9944
9945   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9946       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9947       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9948     return SDValue();
9949
9950   if (Subtarget->hasInt256())
9951     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9952
9953   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9954   SDValue Undef = DAG.getUNDEF(InVT);
9955   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9956   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9957   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9958
9959   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9960                              VT.getVectorNumElements()/2);
9961
9962   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9963   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9964
9965   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9966 }
9967
9968 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9969                                         SelectionDAG &DAG) {
9970   MVT VT = Op->getSimpleValueType(0);
9971   SDValue In = Op->getOperand(0);
9972   MVT InVT = In.getSimpleValueType();
9973   SDLoc DL(Op);
9974   unsigned int NumElts = VT.getVectorNumElements();
9975   if (NumElts != 8 && NumElts != 16)
9976     return SDValue();
9977
9978   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9979     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9980
9981   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9982   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9983   // Now we have only mask extension
9984   assert(InVT.getVectorElementType() == MVT::i1);
9985   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9986   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9987   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9988   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9989   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9990                            MachinePointerInfo::getConstantPool(),
9991                            false, false, false, Alignment);
9992
9993   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9994   if (VT.is512BitVector())
9995     return Brcst;
9996   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9997 }
9998
9999 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10000                                SelectionDAG &DAG) {
10001   if (Subtarget->hasFp256()) {
10002     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
10003     if (Res.getNode())
10004       return Res;
10005   }
10006
10007   return SDValue();
10008 }
10009
10010 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
10011                                 SelectionDAG &DAG) {
10012   SDLoc DL(Op);
10013   MVT VT = Op.getSimpleValueType();
10014   SDValue In = Op.getOperand(0);
10015   MVT SVT = In.getSimpleValueType();
10016
10017   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
10018     return LowerZERO_EXTEND_AVX512(Op, DAG);
10019
10020   if (Subtarget->hasFp256()) {
10021     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
10022     if (Res.getNode())
10023       return Res;
10024   }
10025
10026   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
10027          VT.getVectorNumElements() != SVT.getVectorNumElements());
10028   return SDValue();
10029 }
10030
10031 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
10032   SDLoc DL(Op);
10033   MVT VT = Op.getSimpleValueType();
10034   SDValue In = Op.getOperand(0);
10035   MVT InVT = In.getSimpleValueType();
10036
10037   if (VT == MVT::i1) {
10038     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
10039            "Invalid scalar TRUNCATE operation");
10040     if (InVT == MVT::i32)
10041       return SDValue();
10042     if (InVT.getSizeInBits() == 64)
10043       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
10044     else if (InVT.getSizeInBits() < 32)
10045       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
10046     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
10047   }
10048   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
10049          "Invalid TRUNCATE operation");
10050
10051   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
10052     if (VT.getVectorElementType().getSizeInBits() >=8)
10053       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
10054
10055     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
10056     unsigned NumElts = InVT.getVectorNumElements();
10057     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
10058     if (InVT.getSizeInBits() < 512) {
10059       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
10060       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
10061       InVT = ExtVT;
10062     }
10063     
10064     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
10065     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
10066     SDValue CP = DAG.getConstantPool(C, getPointerTy());
10067     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
10068     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
10069                            MachinePointerInfo::getConstantPool(),
10070                            false, false, false, Alignment);
10071     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
10072     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
10073     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
10074   }
10075
10076   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
10077     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
10078     if (Subtarget->hasInt256()) {
10079       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
10080       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
10081       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
10082                                 ShufMask);
10083       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
10084                          DAG.getIntPtrConstant(0));
10085     }
10086
10087     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10088                                DAG.getIntPtrConstant(0));
10089     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10090                                DAG.getIntPtrConstant(2));
10091     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10092     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10093     static const int ShufMask[] = {0, 2, 4, 6};
10094     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
10095   }
10096
10097   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
10098     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
10099     if (Subtarget->hasInt256()) {
10100       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
10101
10102       SmallVector<SDValue,32> pshufbMask;
10103       for (unsigned i = 0; i < 2; ++i) {
10104         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
10105         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
10106         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
10107         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
10108         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
10109         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
10110         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
10111         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
10112         for (unsigned j = 0; j < 8; ++j)
10113           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
10114       }
10115       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
10116       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
10117       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
10118
10119       static const int ShufMask[] = {0,  2,  -1,  -1};
10120       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
10121                                 &ShufMask[0]);
10122       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
10123                        DAG.getIntPtrConstant(0));
10124       return DAG.getNode(ISD::BITCAST, DL, VT, In);
10125     }
10126
10127     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10128                                DAG.getIntPtrConstant(0));
10129
10130     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10131                                DAG.getIntPtrConstant(4));
10132
10133     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
10134     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
10135
10136     // The PSHUFB mask:
10137     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
10138                                    -1, -1, -1, -1, -1, -1, -1, -1};
10139
10140     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
10141     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
10142     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
10143
10144     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10145     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10146
10147     // The MOVLHPS Mask:
10148     static const int ShufMask2[] = {0, 1, 4, 5};
10149     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
10150     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
10151   }
10152
10153   // Handle truncation of V256 to V128 using shuffles.
10154   if (!VT.is128BitVector() || !InVT.is256BitVector())
10155     return SDValue();
10156
10157   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
10158
10159   unsigned NumElems = VT.getVectorNumElements();
10160   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
10161
10162   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
10163   // Prepare truncation shuffle mask
10164   for (unsigned i = 0; i != NumElems; ++i)
10165     MaskVec[i] = i * 2;
10166   SDValue V = DAG.getVectorShuffle(NVT, DL,
10167                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
10168                                    DAG.getUNDEF(NVT), &MaskVec[0]);
10169   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
10170                      DAG.getIntPtrConstant(0));
10171 }
10172
10173 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
10174                                            SelectionDAG &DAG) const {
10175   assert(!Op.getSimpleValueType().isVector());
10176
10177   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10178     /*IsSigned=*/ true, /*IsReplace=*/ false);
10179   SDValue FIST = Vals.first, StackSlot = Vals.second;
10180   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
10181   if (!FIST.getNode()) return Op;
10182
10183   if (StackSlot.getNode())
10184     // Load the result.
10185     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10186                        FIST, StackSlot, MachinePointerInfo(),
10187                        false, false, false, 0);
10188
10189   // The node is the result.
10190   return FIST;
10191 }
10192
10193 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
10194                                            SelectionDAG &DAG) const {
10195   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10196     /*IsSigned=*/ false, /*IsReplace=*/ false);
10197   SDValue FIST = Vals.first, StackSlot = Vals.second;
10198   assert(FIST.getNode() && "Unexpected failure");
10199
10200   if (StackSlot.getNode())
10201     // Load the result.
10202     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10203                        FIST, StackSlot, MachinePointerInfo(),
10204                        false, false, false, 0);
10205
10206   // The node is the result.
10207   return FIST;
10208 }
10209
10210 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
10211   SDLoc DL(Op);
10212   MVT VT = Op.getSimpleValueType();
10213   SDValue In = Op.getOperand(0);
10214   MVT SVT = In.getSimpleValueType();
10215
10216   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
10217
10218   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
10219                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
10220                                  In, DAG.getUNDEF(SVT)));
10221 }
10222
10223 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
10224   LLVMContext *Context = DAG.getContext();
10225   SDLoc dl(Op);
10226   MVT VT = Op.getSimpleValueType();
10227   MVT EltVT = VT;
10228   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10229   if (VT.isVector()) {
10230     EltVT = VT.getVectorElementType();
10231     NumElts = VT.getVectorNumElements();
10232   }
10233   Constant *C;
10234   if (EltVT == MVT::f64)
10235     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10236                                           APInt(64, ~(1ULL << 63))));
10237   else
10238     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10239                                           APInt(32, ~(1U << 31))));
10240   C = ConstantVector::getSplat(NumElts, C);
10241   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10242   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10243   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10244   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10245                              MachinePointerInfo::getConstantPool(),
10246                              false, false, false, Alignment);
10247   if (VT.isVector()) {
10248     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10249     return DAG.getNode(ISD::BITCAST, dl, VT,
10250                        DAG.getNode(ISD::AND, dl, ANDVT,
10251                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
10252                                                Op.getOperand(0)),
10253                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
10254   }
10255   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
10256 }
10257
10258 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
10259   LLVMContext *Context = DAG.getContext();
10260   SDLoc dl(Op);
10261   MVT VT = Op.getSimpleValueType();
10262   MVT EltVT = VT;
10263   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10264   if (VT.isVector()) {
10265     EltVT = VT.getVectorElementType();
10266     NumElts = VT.getVectorNumElements();
10267   }
10268   Constant *C;
10269   if (EltVT == MVT::f64)
10270     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10271                                           APInt(64, 1ULL << 63)));
10272   else
10273     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10274                                           APInt(32, 1U << 31)));
10275   C = ConstantVector::getSplat(NumElts, C);
10276   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10277   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10278   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10279   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10280                              MachinePointerInfo::getConstantPool(),
10281                              false, false, false, Alignment);
10282   if (VT.isVector()) {
10283     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
10284     return DAG.getNode(ISD::BITCAST, dl, VT,
10285                        DAG.getNode(ISD::XOR, dl, XORVT,
10286                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
10287                                                Op.getOperand(0)),
10288                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
10289   }
10290
10291   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
10292 }
10293
10294 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
10295   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10296   LLVMContext *Context = DAG.getContext();
10297   SDValue Op0 = Op.getOperand(0);
10298   SDValue Op1 = Op.getOperand(1);
10299   SDLoc dl(Op);
10300   MVT VT = Op.getSimpleValueType();
10301   MVT SrcVT = Op1.getSimpleValueType();
10302
10303   // If second operand is smaller, extend it first.
10304   if (SrcVT.bitsLT(VT)) {
10305     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10306     SrcVT = VT;
10307   }
10308   // And if it is bigger, shrink it first.
10309   if (SrcVT.bitsGT(VT)) {
10310     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10311     SrcVT = VT;
10312   }
10313
10314   // At this point the operands and the result should have the same
10315   // type, and that won't be f80 since that is not custom lowered.
10316
10317   // First get the sign bit of second operand.
10318   SmallVector<Constant*,4> CV;
10319   if (SrcVT == MVT::f64) {
10320     const fltSemantics &Sem = APFloat::IEEEdouble;
10321     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10322     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10323   } else {
10324     const fltSemantics &Sem = APFloat::IEEEsingle;
10325     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10326     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10327     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10328     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10329   }
10330   Constant *C = ConstantVector::get(CV);
10331   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10332   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10333                               MachinePointerInfo::getConstantPool(),
10334                               false, false, false, 16);
10335   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10336
10337   // Shift sign bit right or left if the two operands have different types.
10338   if (SrcVT.bitsGT(VT)) {
10339     // Op0 is MVT::f32, Op1 is MVT::f64.
10340     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10341     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10342                           DAG.getConstant(32, MVT::i32));
10343     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10344     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10345                           DAG.getIntPtrConstant(0));
10346   }
10347
10348   // Clear first operand sign bit.
10349   CV.clear();
10350   if (VT == MVT::f64) {
10351     const fltSemantics &Sem = APFloat::IEEEdouble;
10352     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10353                                                    APInt(64, ~(1ULL << 63)))));
10354     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10355   } else {
10356     const fltSemantics &Sem = APFloat::IEEEsingle;
10357     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10358                                                    APInt(32, ~(1U << 31)))));
10359     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10360     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10361     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10362   }
10363   C = ConstantVector::get(CV);
10364   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10365   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10366                               MachinePointerInfo::getConstantPool(),
10367                               false, false, false, 16);
10368   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10369
10370   // Or the value with the sign bit.
10371   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10372 }
10373
10374 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10375   SDValue N0 = Op.getOperand(0);
10376   SDLoc dl(Op);
10377   MVT VT = Op.getSimpleValueType();
10378
10379   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10380   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10381                                   DAG.getConstant(1, VT));
10382   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10383 }
10384
10385 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10386 //
10387 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10388                                       SelectionDAG &DAG) {
10389   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10390
10391   if (!Subtarget->hasSSE41())
10392     return SDValue();
10393
10394   if (!Op->hasOneUse())
10395     return SDValue();
10396
10397   SDNode *N = Op.getNode();
10398   SDLoc DL(N);
10399
10400   SmallVector<SDValue, 8> Opnds;
10401   DenseMap<SDValue, unsigned> VecInMap;
10402   SmallVector<SDValue, 8> VecIns;
10403   EVT VT = MVT::Other;
10404
10405   // Recognize a special case where a vector is casted into wide integer to
10406   // test all 0s.
10407   Opnds.push_back(N->getOperand(0));
10408   Opnds.push_back(N->getOperand(1));
10409
10410   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10411     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10412     // BFS traverse all OR'd operands.
10413     if (I->getOpcode() == ISD::OR) {
10414       Opnds.push_back(I->getOperand(0));
10415       Opnds.push_back(I->getOperand(1));
10416       // Re-evaluate the number of nodes to be traversed.
10417       e += 2; // 2 more nodes (LHS and RHS) are pushed.
10418       continue;
10419     }
10420
10421     // Quit if a non-EXTRACT_VECTOR_ELT
10422     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10423       return SDValue();
10424
10425     // Quit if without a constant index.
10426     SDValue Idx = I->getOperand(1);
10427     if (!isa<ConstantSDNode>(Idx))
10428       return SDValue();
10429
10430     SDValue ExtractedFromVec = I->getOperand(0);
10431     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10432     if (M == VecInMap.end()) {
10433       VT = ExtractedFromVec.getValueType();
10434       // Quit if not 128/256-bit vector.
10435       if (!VT.is128BitVector() && !VT.is256BitVector())
10436         return SDValue();
10437       // Quit if not the same type.
10438       if (VecInMap.begin() != VecInMap.end() &&
10439           VT != VecInMap.begin()->first.getValueType())
10440         return SDValue();
10441       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10442       VecIns.push_back(ExtractedFromVec);
10443     }
10444     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10445   }
10446
10447   assert((VT.is128BitVector() || VT.is256BitVector()) &&
10448          "Not extracted from 128-/256-bit vector.");
10449
10450   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10451
10452   for (DenseMap<SDValue, unsigned>::const_iterator
10453         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10454     // Quit if not all elements are used.
10455     if (I->second != FullMask)
10456       return SDValue();
10457   }
10458
10459   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10460
10461   // Cast all vectors into TestVT for PTEST.
10462   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10463     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10464
10465   // If more than one full vectors are evaluated, OR them first before PTEST.
10466   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10467     // Each iteration will OR 2 nodes and append the result until there is only
10468     // 1 node left, i.e. the final OR'd value of all vectors.
10469     SDValue LHS = VecIns[Slot];
10470     SDValue RHS = VecIns[Slot + 1];
10471     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10472   }
10473
10474   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10475                      VecIns.back(), VecIns.back());
10476 }
10477
10478 /// \brief return true if \c Op has a use that doesn't just read flags.
10479 static bool hasNonFlagsUse(SDValue Op) {
10480   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10481        ++UI) {
10482     SDNode *User = *UI;
10483     unsigned UOpNo = UI.getOperandNo();
10484     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10485       // Look pass truncate.
10486       UOpNo = User->use_begin().getOperandNo();
10487       User = *User->use_begin();
10488     }
10489
10490     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10491         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10492       return true;
10493   }
10494   return false;
10495 }
10496
10497 /// Emit nodes that will be selected as "test Op0,Op0", or something
10498 /// equivalent.
10499 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10500                                     SelectionDAG &DAG) const {
10501   if (Op.getValueType() == MVT::i1)
10502     // KORTEST instruction should be selected
10503     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10504                        DAG.getConstant(0, Op.getValueType()));
10505
10506   // CF and OF aren't always set the way we want. Determine which
10507   // of these we need.
10508   bool NeedCF = false;
10509   bool NeedOF = false;
10510   switch (X86CC) {
10511   default: break;
10512   case X86::COND_A: case X86::COND_AE:
10513   case X86::COND_B: case X86::COND_BE:
10514     NeedCF = true;
10515     break;
10516   case X86::COND_G: case X86::COND_GE:
10517   case X86::COND_L: case X86::COND_LE:
10518   case X86::COND_O: case X86::COND_NO: {
10519     // Check if we really need to set the
10520     // Overflow flag. If NoSignedWrap is present
10521     // that is not actually needed.
10522     switch (Op->getOpcode()) {
10523     case ISD::ADD:
10524     case ISD::SUB:
10525     case ISD::MUL:
10526     case ISD::SHL: {
10527       const BinaryWithFlagsSDNode *BinNode =
10528           cast<BinaryWithFlagsSDNode>(Op.getNode());
10529       if (BinNode->hasNoSignedWrap())
10530         break;
10531     }
10532     default:
10533       NeedOF = true;
10534       break;
10535     }
10536     break;
10537   }
10538   }
10539   // See if we can use the EFLAGS value from the operand instead of
10540   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10541   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10542   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10543     // Emit a CMP with 0, which is the TEST pattern.
10544     //if (Op.getValueType() == MVT::i1)
10545     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10546     //                     DAG.getConstant(0, MVT::i1));
10547     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10548                        DAG.getConstant(0, Op.getValueType()));
10549   }
10550   unsigned Opcode = 0;
10551   unsigned NumOperands = 0;
10552
10553   // Truncate operations may prevent the merge of the SETCC instruction
10554   // and the arithmetic instruction before it. Attempt to truncate the operands
10555   // of the arithmetic instruction and use a reduced bit-width instruction.
10556   bool NeedTruncation = false;
10557   SDValue ArithOp = Op;
10558   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10559     SDValue Arith = Op->getOperand(0);
10560     // Both the trunc and the arithmetic op need to have one user each.
10561     if (Arith->hasOneUse())
10562       switch (Arith.getOpcode()) {
10563         default: break;
10564         case ISD::ADD:
10565         case ISD::SUB:
10566         case ISD::AND:
10567         case ISD::OR:
10568         case ISD::XOR: {
10569           NeedTruncation = true;
10570           ArithOp = Arith;
10571         }
10572       }
10573   }
10574
10575   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10576   // which may be the result of a CAST.  We use the variable 'Op', which is the
10577   // non-casted variable when we check for possible users.
10578   switch (ArithOp.getOpcode()) {
10579   case ISD::ADD:
10580     // Due to an isel shortcoming, be conservative if this add is likely to be
10581     // selected as part of a load-modify-store instruction. When the root node
10582     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10583     // uses of other nodes in the match, such as the ADD in this case. This
10584     // leads to the ADD being left around and reselected, with the result being
10585     // two adds in the output.  Alas, even if none our users are stores, that
10586     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10587     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10588     // climbing the DAG back to the root, and it doesn't seem to be worth the
10589     // effort.
10590     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10591          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10592       if (UI->getOpcode() != ISD::CopyToReg &&
10593           UI->getOpcode() != ISD::SETCC &&
10594           UI->getOpcode() != ISD::STORE)
10595         goto default_case;
10596
10597     if (ConstantSDNode *C =
10598         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10599       // An add of one will be selected as an INC.
10600       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10601         Opcode = X86ISD::INC;
10602         NumOperands = 1;
10603         break;
10604       }
10605
10606       // An add of negative one (subtract of one) will be selected as a DEC.
10607       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10608         Opcode = X86ISD::DEC;
10609         NumOperands = 1;
10610         break;
10611       }
10612     }
10613
10614     // Otherwise use a regular EFLAGS-setting add.
10615     Opcode = X86ISD::ADD;
10616     NumOperands = 2;
10617     break;
10618   case ISD::SHL:
10619   case ISD::SRL:
10620     // If we have a constant logical shift that's only used in a comparison
10621     // against zero turn it into an equivalent AND. This allows turning it into
10622     // a TEST instruction later.
10623     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10624         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10625       EVT VT = Op.getValueType();
10626       unsigned BitWidth = VT.getSizeInBits();
10627       unsigned ShAmt = Op->getConstantOperandVal(1);
10628       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10629         break;
10630       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10631                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10632                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10633       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10634         break;
10635       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10636                                 DAG.getConstant(Mask, VT));
10637       DAG.ReplaceAllUsesWith(Op, New);
10638       Op = New;
10639     }
10640     break;
10641
10642   case ISD::AND:
10643     // If the primary and result isn't used, don't bother using X86ISD::AND,
10644     // because a TEST instruction will be better.
10645     if (!hasNonFlagsUse(Op))
10646       break;
10647     // FALL THROUGH
10648   case ISD::SUB:
10649   case ISD::OR:
10650   case ISD::XOR:
10651     // Due to the ISEL shortcoming noted above, be conservative if this op is
10652     // likely to be selected as part of a load-modify-store instruction.
10653     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10654            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10655       if (UI->getOpcode() == ISD::STORE)
10656         goto default_case;
10657
10658     // Otherwise use a regular EFLAGS-setting instruction.
10659     switch (ArithOp.getOpcode()) {
10660     default: llvm_unreachable("unexpected operator!");
10661     case ISD::SUB: Opcode = X86ISD::SUB; break;
10662     case ISD::XOR: Opcode = X86ISD::XOR; break;
10663     case ISD::AND: Opcode = X86ISD::AND; break;
10664     case ISD::OR: {
10665       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10666         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10667         if (EFLAGS.getNode())
10668           return EFLAGS;
10669       }
10670       Opcode = X86ISD::OR;
10671       break;
10672     }
10673     }
10674
10675     NumOperands = 2;
10676     break;
10677   case X86ISD::ADD:
10678   case X86ISD::SUB:
10679   case X86ISD::INC:
10680   case X86ISD::DEC:
10681   case X86ISD::OR:
10682   case X86ISD::XOR:
10683   case X86ISD::AND:
10684     return SDValue(Op.getNode(), 1);
10685   default:
10686   default_case:
10687     break;
10688   }
10689
10690   // If we found that truncation is beneficial, perform the truncation and
10691   // update 'Op'.
10692   if (NeedTruncation) {
10693     EVT VT = Op.getValueType();
10694     SDValue WideVal = Op->getOperand(0);
10695     EVT WideVT = WideVal.getValueType();
10696     unsigned ConvertedOp = 0;
10697     // Use a target machine opcode to prevent further DAGCombine
10698     // optimizations that may separate the arithmetic operations
10699     // from the setcc node.
10700     switch (WideVal.getOpcode()) {
10701       default: break;
10702       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10703       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10704       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10705       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10706       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10707     }
10708
10709     if (ConvertedOp) {
10710       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10711       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10712         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10713         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10714         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10715       }
10716     }
10717   }
10718
10719   if (Opcode == 0)
10720     // Emit a CMP with 0, which is the TEST pattern.
10721     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10722                        DAG.getConstant(0, Op.getValueType()));
10723
10724   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10725   SmallVector<SDValue, 4> Ops;
10726   for (unsigned i = 0; i != NumOperands; ++i)
10727     Ops.push_back(Op.getOperand(i));
10728
10729   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10730   DAG.ReplaceAllUsesWith(Op, New);
10731   return SDValue(New.getNode(), 1);
10732 }
10733
10734 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10735 /// equivalent.
10736 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10737                                    SDLoc dl, SelectionDAG &DAG) const {
10738   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10739     if (C->getAPIntValue() == 0)
10740       return EmitTest(Op0, X86CC, dl, DAG);
10741
10742      if (Op0.getValueType() == MVT::i1)
10743        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10744   }
10745  
10746   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10747        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10748     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10749     // This avoids subregister aliasing issues. Keep the smaller reference 
10750     // if we're optimizing for size, however, as that'll allow better folding 
10751     // of memory operations.
10752     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10753         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10754              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10755         !Subtarget->isAtom()) {
10756       unsigned ExtendOp =
10757           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10758       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10759       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10760     }
10761     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10762     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10763     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10764                               Op0, Op1);
10765     return SDValue(Sub.getNode(), 1);
10766   }
10767   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10768 }
10769
10770 /// Convert a comparison if required by the subtarget.
10771 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10772                                                  SelectionDAG &DAG) const {
10773   // If the subtarget does not support the FUCOMI instruction, floating-point
10774   // comparisons have to be converted.
10775   if (Subtarget->hasCMov() ||
10776       Cmp.getOpcode() != X86ISD::CMP ||
10777       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10778       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10779     return Cmp;
10780
10781   // The instruction selector will select an FUCOM instruction instead of
10782   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10783   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10784   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10785   SDLoc dl(Cmp);
10786   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10787   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10788   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10789                             DAG.getConstant(8, MVT::i8));
10790   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10791   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10792 }
10793
10794 static bool isAllOnes(SDValue V) {
10795   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10796   return C && C->isAllOnesValue();
10797 }
10798
10799 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10800 /// if it's possible.
10801 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10802                                      SDLoc dl, SelectionDAG &DAG) const {
10803   SDValue Op0 = And.getOperand(0);
10804   SDValue Op1 = And.getOperand(1);
10805   if (Op0.getOpcode() == ISD::TRUNCATE)
10806     Op0 = Op0.getOperand(0);
10807   if (Op1.getOpcode() == ISD::TRUNCATE)
10808     Op1 = Op1.getOperand(0);
10809
10810   SDValue LHS, RHS;
10811   if (Op1.getOpcode() == ISD::SHL)
10812     std::swap(Op0, Op1);
10813   if (Op0.getOpcode() == ISD::SHL) {
10814     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10815       if (And00C->getZExtValue() == 1) {
10816         // If we looked past a truncate, check that it's only truncating away
10817         // known zeros.
10818         unsigned BitWidth = Op0.getValueSizeInBits();
10819         unsigned AndBitWidth = And.getValueSizeInBits();
10820         if (BitWidth > AndBitWidth) {
10821           APInt Zeros, Ones;
10822           DAG.computeKnownBits(Op0, Zeros, Ones);
10823           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10824             return SDValue();
10825         }
10826         LHS = Op1;
10827         RHS = Op0.getOperand(1);
10828       }
10829   } else if (Op1.getOpcode() == ISD::Constant) {
10830     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10831     uint64_t AndRHSVal = AndRHS->getZExtValue();
10832     SDValue AndLHS = Op0;
10833
10834     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10835       LHS = AndLHS.getOperand(0);
10836       RHS = AndLHS.getOperand(1);
10837     }
10838
10839     // Use BT if the immediate can't be encoded in a TEST instruction.
10840     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10841       LHS = AndLHS;
10842       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10843     }
10844   }
10845
10846   if (LHS.getNode()) {
10847     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10848     // instruction.  Since the shift amount is in-range-or-undefined, we know
10849     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10850     // the encoding for the i16 version is larger than the i32 version.
10851     // Also promote i16 to i32 for performance / code size reason.
10852     if (LHS.getValueType() == MVT::i8 ||
10853         LHS.getValueType() == MVT::i16)
10854       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10855
10856     // If the operand types disagree, extend the shift amount to match.  Since
10857     // BT ignores high bits (like shifts) we can use anyextend.
10858     if (LHS.getValueType() != RHS.getValueType())
10859       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10860
10861     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10862     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10863     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10864                        DAG.getConstant(Cond, MVT::i8), BT);
10865   }
10866
10867   return SDValue();
10868 }
10869
10870 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10871 /// mask CMPs.
10872 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10873                               SDValue &Op1) {
10874   unsigned SSECC;
10875   bool Swap = false;
10876
10877   // SSE Condition code mapping:
10878   //  0 - EQ
10879   //  1 - LT
10880   //  2 - LE
10881   //  3 - UNORD
10882   //  4 - NEQ
10883   //  5 - NLT
10884   //  6 - NLE
10885   //  7 - ORD
10886   switch (SetCCOpcode) {
10887   default: llvm_unreachable("Unexpected SETCC condition");
10888   case ISD::SETOEQ:
10889   case ISD::SETEQ:  SSECC = 0; break;
10890   case ISD::SETOGT:
10891   case ISD::SETGT:  Swap = true; // Fallthrough
10892   case ISD::SETLT:
10893   case ISD::SETOLT: SSECC = 1; break;
10894   case ISD::SETOGE:
10895   case ISD::SETGE:  Swap = true; // Fallthrough
10896   case ISD::SETLE:
10897   case ISD::SETOLE: SSECC = 2; break;
10898   case ISD::SETUO:  SSECC = 3; break;
10899   case ISD::SETUNE:
10900   case ISD::SETNE:  SSECC = 4; break;
10901   case ISD::SETULE: Swap = true; // Fallthrough
10902   case ISD::SETUGE: SSECC = 5; break;
10903   case ISD::SETULT: Swap = true; // Fallthrough
10904   case ISD::SETUGT: SSECC = 6; break;
10905   case ISD::SETO:   SSECC = 7; break;
10906   case ISD::SETUEQ:
10907   case ISD::SETONE: SSECC = 8; break;
10908   }
10909   if (Swap)
10910     std::swap(Op0, Op1);
10911
10912   return SSECC;
10913 }
10914
10915 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10916 // ones, and then concatenate the result back.
10917 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10918   MVT VT = Op.getSimpleValueType();
10919
10920   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10921          "Unsupported value type for operation");
10922
10923   unsigned NumElems = VT.getVectorNumElements();
10924   SDLoc dl(Op);
10925   SDValue CC = Op.getOperand(2);
10926
10927   // Extract the LHS vectors
10928   SDValue LHS = Op.getOperand(0);
10929   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10930   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10931
10932   // Extract the RHS vectors
10933   SDValue RHS = Op.getOperand(1);
10934   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10935   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10936
10937   // Issue the operation on the smaller types and concatenate the result back
10938   MVT EltVT = VT.getVectorElementType();
10939   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10940   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10941                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10942                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10943 }
10944
10945 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10946                                      const X86Subtarget *Subtarget) {
10947   SDValue Op0 = Op.getOperand(0);
10948   SDValue Op1 = Op.getOperand(1);
10949   SDValue CC = Op.getOperand(2);
10950   MVT VT = Op.getSimpleValueType();
10951   SDLoc dl(Op);
10952
10953   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10954          Op.getValueType().getScalarType() == MVT::i1 &&
10955          "Cannot set masked compare for this operation");
10956
10957   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10958   unsigned  Opc = 0;
10959   bool Unsigned = false;
10960   bool Swap = false;
10961   unsigned SSECC;
10962   switch (SetCCOpcode) {
10963   default: llvm_unreachable("Unexpected SETCC condition");
10964   case ISD::SETNE:  SSECC = 4; break;
10965   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10966   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10967   case ISD::SETLT:  Swap = true; //fall-through
10968   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10969   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10970   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10971   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10972   case ISD::SETULE: Unsigned = true; //fall-through
10973   case ISD::SETLE:  SSECC = 2; break;
10974   }
10975
10976   if (Swap)
10977     std::swap(Op0, Op1);
10978   if (Opc)
10979     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10980   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10981   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10982                      DAG.getConstant(SSECC, MVT::i8));
10983 }
10984
10985 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10986 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10987 /// return an empty value.
10988 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10989 {
10990   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10991   if (!BV)
10992     return SDValue();
10993
10994   MVT VT = Op1.getSimpleValueType();
10995   MVT EVT = VT.getVectorElementType();
10996   unsigned n = VT.getVectorNumElements();
10997   SmallVector<SDValue, 8> ULTOp1;
10998
10999   for (unsigned i = 0; i < n; ++i) {
11000     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
11001     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
11002       return SDValue();
11003
11004     // Avoid underflow.
11005     APInt Val = Elt->getAPIntValue();
11006     if (Val == 0)
11007       return SDValue();
11008
11009     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
11010   }
11011
11012   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
11013 }
11014
11015 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
11016                            SelectionDAG &DAG) {
11017   SDValue Op0 = Op.getOperand(0);
11018   SDValue Op1 = Op.getOperand(1);
11019   SDValue CC = Op.getOperand(2);
11020   MVT VT = Op.getSimpleValueType();
11021   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
11022   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
11023   SDLoc dl(Op);
11024
11025   if (isFP) {
11026 #ifndef NDEBUG
11027     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
11028     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
11029 #endif
11030
11031     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
11032     unsigned Opc = X86ISD::CMPP;
11033     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
11034       assert(VT.getVectorNumElements() <= 16);
11035       Opc = X86ISD::CMPM;
11036     }
11037     // In the two special cases we can't handle, emit two comparisons.
11038     if (SSECC == 8) {
11039       unsigned CC0, CC1;
11040       unsigned CombineOpc;
11041       if (SetCCOpcode == ISD::SETUEQ) {
11042         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
11043       } else {
11044         assert(SetCCOpcode == ISD::SETONE);
11045         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
11046       }
11047
11048       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
11049                                  DAG.getConstant(CC0, MVT::i8));
11050       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
11051                                  DAG.getConstant(CC1, MVT::i8));
11052       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
11053     }
11054     // Handle all other FP comparisons here.
11055     return DAG.getNode(Opc, dl, VT, Op0, Op1,
11056                        DAG.getConstant(SSECC, MVT::i8));
11057   }
11058
11059   // Break 256-bit integer vector compare into smaller ones.
11060   if (VT.is256BitVector() && !Subtarget->hasInt256())
11061     return Lower256IntVSETCC(Op, DAG);
11062
11063   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
11064   EVT OpVT = Op1.getValueType();
11065   if (Subtarget->hasAVX512()) {
11066     if (Op1.getValueType().is512BitVector() ||
11067         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
11068       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
11069
11070     // In AVX-512 architecture setcc returns mask with i1 elements,
11071     // But there is no compare instruction for i8 and i16 elements.
11072     // We are not talking about 512-bit operands in this case, these
11073     // types are illegal.
11074     if (MaskResult &&
11075         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
11076          OpVT.getVectorElementType().getSizeInBits() >= 8))
11077       return DAG.getNode(ISD::TRUNCATE, dl, VT,
11078                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
11079   }
11080
11081   // We are handling one of the integer comparisons here.  Since SSE only has
11082   // GT and EQ comparisons for integer, swapping operands and multiple
11083   // operations may be required for some comparisons.
11084   unsigned Opc;
11085   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
11086   bool Subus = false;
11087
11088   switch (SetCCOpcode) {
11089   default: llvm_unreachable("Unexpected SETCC condition");
11090   case ISD::SETNE:  Invert = true;
11091   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
11092   case ISD::SETLT:  Swap = true;
11093   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
11094   case ISD::SETGE:  Swap = true;
11095   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
11096                     Invert = true; break;
11097   case ISD::SETULT: Swap = true;
11098   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
11099                     FlipSigns = true; break;
11100   case ISD::SETUGE: Swap = true;
11101   case ISD::SETULE: Opc = X86ISD::PCMPGT;
11102                     FlipSigns = true; Invert = true; break;
11103   }
11104
11105   // Special case: Use min/max operations for SETULE/SETUGE
11106   MVT VET = VT.getVectorElementType();
11107   bool hasMinMax =
11108        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
11109     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
11110
11111   if (hasMinMax) {
11112     switch (SetCCOpcode) {
11113     default: break;
11114     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
11115     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
11116     }
11117
11118     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
11119   }
11120
11121   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
11122   if (!MinMax && hasSubus) {
11123     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
11124     // Op0 u<= Op1:
11125     //   t = psubus Op0, Op1
11126     //   pcmpeq t, <0..0>
11127     switch (SetCCOpcode) {
11128     default: break;
11129     case ISD::SETULT: {
11130       // If the comparison is against a constant we can turn this into a
11131       // setule.  With psubus, setule does not require a swap.  This is
11132       // beneficial because the constant in the register is no longer
11133       // destructed as the destination so it can be hoisted out of a loop.
11134       // Only do this pre-AVX since vpcmp* is no longer destructive.
11135       if (Subtarget->hasAVX())
11136         break;
11137       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
11138       if (ULEOp1.getNode()) {
11139         Op1 = ULEOp1;
11140         Subus = true; Invert = false; Swap = false;
11141       }
11142       break;
11143     }
11144     // Psubus is better than flip-sign because it requires no inversion.
11145     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
11146     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
11147     }
11148
11149     if (Subus) {
11150       Opc = X86ISD::SUBUS;
11151       FlipSigns = false;
11152     }
11153   }
11154
11155   if (Swap)
11156     std::swap(Op0, Op1);
11157
11158   // Check that the operation in question is available (most are plain SSE2,
11159   // but PCMPGTQ and PCMPEQQ have different requirements).
11160   if (VT == MVT::v2i64) {
11161     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
11162       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
11163
11164       // First cast everything to the right type.
11165       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11166       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11167
11168       // Since SSE has no unsigned integer comparisons, we need to flip the sign
11169       // bits of the inputs before performing those operations. The lower
11170       // compare is always unsigned.
11171       SDValue SB;
11172       if (FlipSigns) {
11173         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
11174       } else {
11175         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
11176         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
11177         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
11178                          Sign, Zero, Sign, Zero);
11179       }
11180       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
11181       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
11182
11183       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
11184       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
11185       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
11186
11187       // Create masks for only the low parts/high parts of the 64 bit integers.
11188       static const int MaskHi[] = { 1, 1, 3, 3 };
11189       static const int MaskLo[] = { 0, 0, 2, 2 };
11190       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
11191       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
11192       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
11193
11194       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
11195       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
11196
11197       if (Invert)
11198         Result = DAG.getNOT(dl, Result, MVT::v4i32);
11199
11200       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11201     }
11202
11203     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
11204       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
11205       // pcmpeqd + pshufd + pand.
11206       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
11207
11208       // First cast everything to the right type.
11209       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11210       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11211
11212       // Do the compare.
11213       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
11214
11215       // Make sure the lower and upper halves are both all-ones.
11216       static const int Mask[] = { 1, 0, 3, 2 };
11217       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
11218       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
11219
11220       if (Invert)
11221         Result = DAG.getNOT(dl, Result, MVT::v4i32);
11222
11223       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11224     }
11225   }
11226
11227   // Since SSE has no unsigned integer comparisons, we need to flip the sign
11228   // bits of the inputs before performing those operations.
11229   if (FlipSigns) {
11230     EVT EltVT = VT.getVectorElementType();
11231     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
11232     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
11233     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
11234   }
11235
11236   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
11237
11238   // If the logical-not of the result is required, perform that now.
11239   if (Invert)
11240     Result = DAG.getNOT(dl, Result, VT);
11241
11242   if (MinMax)
11243     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
11244
11245   if (Subus)
11246     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
11247                          getZeroVector(VT, Subtarget, DAG, dl));
11248
11249   return Result;
11250 }
11251
11252 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
11253
11254   MVT VT = Op.getSimpleValueType();
11255
11256   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
11257
11258   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
11259          && "SetCC type must be 8-bit or 1-bit integer");
11260   SDValue Op0 = Op.getOperand(0);
11261   SDValue Op1 = Op.getOperand(1);
11262   SDLoc dl(Op);
11263   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11264
11265   // Optimize to BT if possible.
11266   // Lower (X & (1 << N)) == 0 to BT(X, N).
11267   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
11268   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
11269   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
11270       Op1.getOpcode() == ISD::Constant &&
11271       cast<ConstantSDNode>(Op1)->isNullValue() &&
11272       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11273     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
11274     if (NewSetCC.getNode())
11275       return NewSetCC;
11276   }
11277
11278   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
11279   // these.
11280   if (Op1.getOpcode() == ISD::Constant &&
11281       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
11282        cast<ConstantSDNode>(Op1)->isNullValue()) &&
11283       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11284
11285     // If the input is a setcc, then reuse the input setcc or use a new one with
11286     // the inverted condition.
11287     if (Op0.getOpcode() == X86ISD::SETCC) {
11288       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11289       bool Invert = (CC == ISD::SETNE) ^
11290         cast<ConstantSDNode>(Op1)->isNullValue();
11291       if (!Invert)
11292         return Op0;
11293
11294       CCode = X86::GetOppositeBranchCondition(CCode);
11295       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11296                                   DAG.getConstant(CCode, MVT::i8),
11297                                   Op0.getOperand(1));
11298       if (VT == MVT::i1)
11299         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11300       return SetCC;
11301     }
11302   }
11303   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11304       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11305       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11306
11307     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11308     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11309   }
11310
11311   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11312   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11313   if (X86CC == X86::COND_INVALID)
11314     return SDValue();
11315
11316   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11317   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11318   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11319                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11320   if (VT == MVT::i1)
11321     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11322   return SetCC;
11323 }
11324
11325 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11326 static bool isX86LogicalCmp(SDValue Op) {
11327   unsigned Opc = Op.getNode()->getOpcode();
11328   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11329       Opc == X86ISD::SAHF)
11330     return true;
11331   if (Op.getResNo() == 1 &&
11332       (Opc == X86ISD::ADD ||
11333        Opc == X86ISD::SUB ||
11334        Opc == X86ISD::ADC ||
11335        Opc == X86ISD::SBB ||
11336        Opc == X86ISD::SMUL ||
11337        Opc == X86ISD::UMUL ||
11338        Opc == X86ISD::INC ||
11339        Opc == X86ISD::DEC ||
11340        Opc == X86ISD::OR ||
11341        Opc == X86ISD::XOR ||
11342        Opc == X86ISD::AND))
11343     return true;
11344
11345   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11346     return true;
11347
11348   return false;
11349 }
11350
11351 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11352   if (V.getOpcode() != ISD::TRUNCATE)
11353     return false;
11354
11355   SDValue VOp0 = V.getOperand(0);
11356   unsigned InBits = VOp0.getValueSizeInBits();
11357   unsigned Bits = V.getValueSizeInBits();
11358   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11359 }
11360
11361 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11362   bool addTest = true;
11363   SDValue Cond  = Op.getOperand(0);
11364   SDValue Op1 = Op.getOperand(1);
11365   SDValue Op2 = Op.getOperand(2);
11366   SDLoc DL(Op);
11367   EVT VT = Op1.getValueType();
11368   SDValue CC;
11369
11370   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11371   // are available. Otherwise fp cmovs get lowered into a less efficient branch
11372   // sequence later on.
11373   if (Cond.getOpcode() == ISD::SETCC &&
11374       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11375        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11376       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11377     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11378     int SSECC = translateX86FSETCC(
11379         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11380
11381     if (SSECC != 8) {
11382       if (Subtarget->hasAVX512()) {
11383         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11384                                   DAG.getConstant(SSECC, MVT::i8));
11385         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11386       }
11387       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11388                                 DAG.getConstant(SSECC, MVT::i8));
11389       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11390       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11391       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11392     }
11393   }
11394
11395   if (Cond.getOpcode() == ISD::SETCC) {
11396     SDValue NewCond = LowerSETCC(Cond, DAG);
11397     if (NewCond.getNode())
11398       Cond = NewCond;
11399   }
11400
11401   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11402   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11403   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11404   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11405   if (Cond.getOpcode() == X86ISD::SETCC &&
11406       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11407       isZero(Cond.getOperand(1).getOperand(1))) {
11408     SDValue Cmp = Cond.getOperand(1);
11409
11410     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11411
11412     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11413         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11414       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11415
11416       SDValue CmpOp0 = Cmp.getOperand(0);
11417       // Apply further optimizations for special cases
11418       // (select (x != 0), -1, 0) -> neg & sbb
11419       // (select (x == 0), 0, -1) -> neg & sbb
11420       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11421         if (YC->isNullValue() &&
11422             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11423           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11424           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11425                                     DAG.getConstant(0, CmpOp0.getValueType()),
11426                                     CmpOp0);
11427           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11428                                     DAG.getConstant(X86::COND_B, MVT::i8),
11429                                     SDValue(Neg.getNode(), 1));
11430           return Res;
11431         }
11432
11433       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11434                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11435       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11436
11437       SDValue Res =   // Res = 0 or -1.
11438         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11439                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11440
11441       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11442         Res = DAG.getNOT(DL, Res, Res.getValueType());
11443
11444       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11445       if (!N2C || !N2C->isNullValue())
11446         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11447       return Res;
11448     }
11449   }
11450
11451   // Look past (and (setcc_carry (cmp ...)), 1).
11452   if (Cond.getOpcode() == ISD::AND &&
11453       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11454     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11455     if (C && C->getAPIntValue() == 1)
11456       Cond = Cond.getOperand(0);
11457   }
11458
11459   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11460   // setting operand in place of the X86ISD::SETCC.
11461   unsigned CondOpcode = Cond.getOpcode();
11462   if (CondOpcode == X86ISD::SETCC ||
11463       CondOpcode == X86ISD::SETCC_CARRY) {
11464     CC = Cond.getOperand(0);
11465
11466     SDValue Cmp = Cond.getOperand(1);
11467     unsigned Opc = Cmp.getOpcode();
11468     MVT VT = Op.getSimpleValueType();
11469
11470     bool IllegalFPCMov = false;
11471     if (VT.isFloatingPoint() && !VT.isVector() &&
11472         !isScalarFPTypeInSSEReg(VT))  // FPStack?
11473       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11474
11475     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11476         Opc == X86ISD::BT) { // FIXME
11477       Cond = Cmp;
11478       addTest = false;
11479     }
11480   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11481              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11482              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11483               Cond.getOperand(0).getValueType() != MVT::i8)) {
11484     SDValue LHS = Cond.getOperand(0);
11485     SDValue RHS = Cond.getOperand(1);
11486     unsigned X86Opcode;
11487     unsigned X86Cond;
11488     SDVTList VTs;
11489     switch (CondOpcode) {
11490     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11491     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11492     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11493     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11494     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11495     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11496     default: llvm_unreachable("unexpected overflowing operator");
11497     }
11498     if (CondOpcode == ISD::UMULO)
11499       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11500                           MVT::i32);
11501     else
11502       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11503
11504     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11505
11506     if (CondOpcode == ISD::UMULO)
11507       Cond = X86Op.getValue(2);
11508     else
11509       Cond = X86Op.getValue(1);
11510
11511     CC = DAG.getConstant(X86Cond, MVT::i8);
11512     addTest = false;
11513   }
11514
11515   if (addTest) {
11516     // Look pass the truncate if the high bits are known zero.
11517     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11518         Cond = Cond.getOperand(0);
11519
11520     // We know the result of AND is compared against zero. Try to match
11521     // it to BT.
11522     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11523       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11524       if (NewSetCC.getNode()) {
11525         CC = NewSetCC.getOperand(0);
11526         Cond = NewSetCC.getOperand(1);
11527         addTest = false;
11528       }
11529     }
11530   }
11531
11532   if (addTest) {
11533     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11534     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11535   }
11536
11537   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11538   // a <  b ?  0 : -1 -> RES = setcc_carry
11539   // a >= b ? -1 :  0 -> RES = setcc_carry
11540   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11541   if (Cond.getOpcode() == X86ISD::SUB) {
11542     Cond = ConvertCmpIfNecessary(Cond, DAG);
11543     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11544
11545     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11546         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11547       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11548                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11549       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11550         return DAG.getNOT(DL, Res, Res.getValueType());
11551       return Res;
11552     }
11553   }
11554
11555   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11556   // widen the cmov and push the truncate through. This avoids introducing a new
11557   // branch during isel and doesn't add any extensions.
11558   if (Op.getValueType() == MVT::i8 &&
11559       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11560     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11561     if (T1.getValueType() == T2.getValueType() &&
11562         // Blacklist CopyFromReg to avoid partial register stalls.
11563         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11564       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11565       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11566       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11567     }
11568   }
11569
11570   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11571   // condition is true.
11572   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11573   SDValue Ops[] = { Op2, Op1, CC, Cond };
11574   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11575 }
11576
11577 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11578   MVT VT = Op->getSimpleValueType(0);
11579   SDValue In = Op->getOperand(0);
11580   MVT InVT = In.getSimpleValueType();
11581   SDLoc dl(Op);
11582
11583   unsigned int NumElts = VT.getVectorNumElements();
11584   if (NumElts != 8 && NumElts != 16)
11585     return SDValue();
11586
11587   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11588     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11589
11590   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11591   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11592
11593   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11594   Constant *C = ConstantInt::get(*DAG.getContext(),
11595     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11596
11597   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11598   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11599   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11600                           MachinePointerInfo::getConstantPool(),
11601                           false, false, false, Alignment);
11602   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11603   if (VT.is512BitVector())
11604     return Brcst;
11605   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11606 }
11607
11608 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11609                                 SelectionDAG &DAG) {
11610   MVT VT = Op->getSimpleValueType(0);
11611   SDValue In = Op->getOperand(0);
11612   MVT InVT = In.getSimpleValueType();
11613   SDLoc dl(Op);
11614
11615   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11616     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11617
11618   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11619       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11620       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11621     return SDValue();
11622
11623   if (Subtarget->hasInt256())
11624     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11625
11626   // Optimize vectors in AVX mode
11627   // Sign extend  v8i16 to v8i32 and
11628   //              v4i32 to v4i64
11629   //
11630   // Divide input vector into two parts
11631   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11632   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11633   // concat the vectors to original VT
11634
11635   unsigned NumElems = InVT.getVectorNumElements();
11636   SDValue Undef = DAG.getUNDEF(InVT);
11637
11638   SmallVector<int,8> ShufMask1(NumElems, -1);
11639   for (unsigned i = 0; i != NumElems/2; ++i)
11640     ShufMask1[i] = i;
11641
11642   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11643
11644   SmallVector<int,8> ShufMask2(NumElems, -1);
11645   for (unsigned i = 0; i != NumElems/2; ++i)
11646     ShufMask2[i] = i + NumElems/2;
11647
11648   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11649
11650   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11651                                 VT.getVectorNumElements()/2);
11652
11653   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11654   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11655
11656   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11657 }
11658
11659 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11660 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11661 // from the AND / OR.
11662 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11663   Opc = Op.getOpcode();
11664   if (Opc != ISD::OR && Opc != ISD::AND)
11665     return false;
11666   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11667           Op.getOperand(0).hasOneUse() &&
11668           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11669           Op.getOperand(1).hasOneUse());
11670 }
11671
11672 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11673 // 1 and that the SETCC node has a single use.
11674 static bool isXor1OfSetCC(SDValue Op) {
11675   if (Op.getOpcode() != ISD::XOR)
11676     return false;
11677   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11678   if (N1C && N1C->getAPIntValue() == 1) {
11679     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11680       Op.getOperand(0).hasOneUse();
11681   }
11682   return false;
11683 }
11684
11685 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11686   bool addTest = true;
11687   SDValue Chain = Op.getOperand(0);
11688   SDValue Cond  = Op.getOperand(1);
11689   SDValue Dest  = Op.getOperand(2);
11690   SDLoc dl(Op);
11691   SDValue CC;
11692   bool Inverted = false;
11693
11694   if (Cond.getOpcode() == ISD::SETCC) {
11695     // Check for setcc([su]{add,sub,mul}o == 0).
11696     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11697         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11698         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11699         Cond.getOperand(0).getResNo() == 1 &&
11700         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11701          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11702          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11703          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11704          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11705          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11706       Inverted = true;
11707       Cond = Cond.getOperand(0);
11708     } else {
11709       SDValue NewCond = LowerSETCC(Cond, DAG);
11710       if (NewCond.getNode())
11711         Cond = NewCond;
11712     }
11713   }
11714 #if 0
11715   // FIXME: LowerXALUO doesn't handle these!!
11716   else if (Cond.getOpcode() == X86ISD::ADD  ||
11717            Cond.getOpcode() == X86ISD::SUB  ||
11718            Cond.getOpcode() == X86ISD::SMUL ||
11719            Cond.getOpcode() == X86ISD::UMUL)
11720     Cond = LowerXALUO(Cond, DAG);
11721 #endif
11722
11723   // Look pass (and (setcc_carry (cmp ...)), 1).
11724   if (Cond.getOpcode() == ISD::AND &&
11725       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11726     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11727     if (C && C->getAPIntValue() == 1)
11728       Cond = Cond.getOperand(0);
11729   }
11730
11731   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11732   // setting operand in place of the X86ISD::SETCC.
11733   unsigned CondOpcode = Cond.getOpcode();
11734   if (CondOpcode == X86ISD::SETCC ||
11735       CondOpcode == X86ISD::SETCC_CARRY) {
11736     CC = Cond.getOperand(0);
11737
11738     SDValue Cmp = Cond.getOperand(1);
11739     unsigned Opc = Cmp.getOpcode();
11740     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11741     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11742       Cond = Cmp;
11743       addTest = false;
11744     } else {
11745       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11746       default: break;
11747       case X86::COND_O:
11748       case X86::COND_B:
11749         // These can only come from an arithmetic instruction with overflow,
11750         // e.g. SADDO, UADDO.
11751         Cond = Cond.getNode()->getOperand(1);
11752         addTest = false;
11753         break;
11754       }
11755     }
11756   }
11757   CondOpcode = Cond.getOpcode();
11758   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11759       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11760       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11761        Cond.getOperand(0).getValueType() != MVT::i8)) {
11762     SDValue LHS = Cond.getOperand(0);
11763     SDValue RHS = Cond.getOperand(1);
11764     unsigned X86Opcode;
11765     unsigned X86Cond;
11766     SDVTList VTs;
11767     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11768     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11769     // X86ISD::INC).
11770     switch (CondOpcode) {
11771     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11772     case ISD::SADDO:
11773       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11774         if (C->isOne()) {
11775           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11776           break;
11777         }
11778       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11779     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11780     case ISD::SSUBO:
11781       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11782         if (C->isOne()) {
11783           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11784           break;
11785         }
11786       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11787     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11788     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11789     default: llvm_unreachable("unexpected overflowing operator");
11790     }
11791     if (Inverted)
11792       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11793     if (CondOpcode == ISD::UMULO)
11794       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11795                           MVT::i32);
11796     else
11797       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11798
11799     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11800
11801     if (CondOpcode == ISD::UMULO)
11802       Cond = X86Op.getValue(2);
11803     else
11804       Cond = X86Op.getValue(1);
11805
11806     CC = DAG.getConstant(X86Cond, MVT::i8);
11807     addTest = false;
11808   } else {
11809     unsigned CondOpc;
11810     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11811       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11812       if (CondOpc == ISD::OR) {
11813         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11814         // two branches instead of an explicit OR instruction with a
11815         // separate test.
11816         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11817             isX86LogicalCmp(Cmp)) {
11818           CC = Cond.getOperand(0).getOperand(0);
11819           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11820                               Chain, Dest, CC, Cmp);
11821           CC = Cond.getOperand(1).getOperand(0);
11822           Cond = Cmp;
11823           addTest = false;
11824         }
11825       } else { // ISD::AND
11826         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11827         // two branches instead of an explicit AND instruction with a
11828         // separate test. However, we only do this if this block doesn't
11829         // have a fall-through edge, because this requires an explicit
11830         // jmp when the condition is false.
11831         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11832             isX86LogicalCmp(Cmp) &&
11833             Op.getNode()->hasOneUse()) {
11834           X86::CondCode CCode =
11835             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11836           CCode = X86::GetOppositeBranchCondition(CCode);
11837           CC = DAG.getConstant(CCode, MVT::i8);
11838           SDNode *User = *Op.getNode()->use_begin();
11839           // Look for an unconditional branch following this conditional branch.
11840           // We need this because we need to reverse the successors in order
11841           // to implement FCMP_OEQ.
11842           if (User->getOpcode() == ISD::BR) {
11843             SDValue FalseBB = User->getOperand(1);
11844             SDNode *NewBR =
11845               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11846             assert(NewBR == User);
11847             (void)NewBR;
11848             Dest = FalseBB;
11849
11850             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11851                                 Chain, Dest, CC, Cmp);
11852             X86::CondCode CCode =
11853               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11854             CCode = X86::GetOppositeBranchCondition(CCode);
11855             CC = DAG.getConstant(CCode, MVT::i8);
11856             Cond = Cmp;
11857             addTest = false;
11858           }
11859         }
11860       }
11861     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11862       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11863       // It should be transformed during dag combiner except when the condition
11864       // is set by a arithmetics with overflow node.
11865       X86::CondCode CCode =
11866         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11867       CCode = X86::GetOppositeBranchCondition(CCode);
11868       CC = DAG.getConstant(CCode, MVT::i8);
11869       Cond = Cond.getOperand(0).getOperand(1);
11870       addTest = false;
11871     } else if (Cond.getOpcode() == ISD::SETCC &&
11872                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11873       // For FCMP_OEQ, we can emit
11874       // two branches instead of an explicit AND instruction with a
11875       // separate test. However, we only do this if this block doesn't
11876       // have a fall-through edge, because this requires an explicit
11877       // jmp when the condition is false.
11878       if (Op.getNode()->hasOneUse()) {
11879         SDNode *User = *Op.getNode()->use_begin();
11880         // Look for an unconditional branch following this conditional branch.
11881         // We need this because we need to reverse the successors in order
11882         // to implement FCMP_OEQ.
11883         if (User->getOpcode() == ISD::BR) {
11884           SDValue FalseBB = User->getOperand(1);
11885           SDNode *NewBR =
11886             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11887           assert(NewBR == User);
11888           (void)NewBR;
11889           Dest = FalseBB;
11890
11891           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11892                                     Cond.getOperand(0), Cond.getOperand(1));
11893           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11894           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11895           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11896                               Chain, Dest, CC, Cmp);
11897           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11898           Cond = Cmp;
11899           addTest = false;
11900         }
11901       }
11902     } else if (Cond.getOpcode() == ISD::SETCC &&
11903                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11904       // For FCMP_UNE, we can emit
11905       // two branches instead of an explicit AND instruction with a
11906       // separate test. However, we only do this if this block doesn't
11907       // have a fall-through edge, because this requires an explicit
11908       // jmp when the condition is false.
11909       if (Op.getNode()->hasOneUse()) {
11910         SDNode *User = *Op.getNode()->use_begin();
11911         // Look for an unconditional branch following this conditional branch.
11912         // We need this because we need to reverse the successors in order
11913         // to implement FCMP_UNE.
11914         if (User->getOpcode() == ISD::BR) {
11915           SDValue FalseBB = User->getOperand(1);
11916           SDNode *NewBR =
11917             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11918           assert(NewBR == User);
11919           (void)NewBR;
11920
11921           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11922                                     Cond.getOperand(0), Cond.getOperand(1));
11923           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11924           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11925           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11926                               Chain, Dest, CC, Cmp);
11927           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11928           Cond = Cmp;
11929           addTest = false;
11930           Dest = FalseBB;
11931         }
11932       }
11933     }
11934   }
11935
11936   if (addTest) {
11937     // Look pass the truncate if the high bits are known zero.
11938     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11939         Cond = Cond.getOperand(0);
11940
11941     // We know the result of AND is compared against zero. Try to match
11942     // it to BT.
11943     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11944       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11945       if (NewSetCC.getNode()) {
11946         CC = NewSetCC.getOperand(0);
11947         Cond = NewSetCC.getOperand(1);
11948         addTest = false;
11949       }
11950     }
11951   }
11952
11953   if (addTest) {
11954     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11955     CC = DAG.getConstant(X86Cond, MVT::i8);
11956     Cond = EmitTest(Cond, X86Cond, dl, DAG);
11957   }
11958   Cond = ConvertCmpIfNecessary(Cond, DAG);
11959   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11960                      Chain, Dest, CC, Cond);
11961 }
11962
11963 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11964 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11965 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11966 // that the guard pages used by the OS virtual memory manager are allocated in
11967 // correct sequence.
11968 SDValue
11969 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11970                                            SelectionDAG &DAG) const {
11971   MachineFunction &MF = DAG.getMachineFunction();
11972   bool SplitStack = MF.shouldSplitStack();
11973   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11974                SplitStack;
11975   SDLoc dl(Op);
11976
11977   if (!Lower) {
11978     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11979     SDNode* Node = Op.getNode();
11980
11981     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11982     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11983         " not tell us which reg is the stack pointer!");
11984     EVT VT = Node->getValueType(0);
11985     SDValue Tmp1 = SDValue(Node, 0);
11986     SDValue Tmp2 = SDValue(Node, 1);
11987     SDValue Tmp3 = Node->getOperand(2);
11988     SDValue Chain = Tmp1.getOperand(0);
11989
11990     // Chain the dynamic stack allocation so that it doesn't modify the stack
11991     // pointer when other instructions are using the stack.
11992     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11993         SDLoc(Node));
11994
11995     SDValue Size = Tmp2.getOperand(1);
11996     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11997     Chain = SP.getValue(1);
11998     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11999     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
12000     unsigned StackAlign = TFI.getStackAlignment();
12001     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
12002     if (Align > StackAlign)
12003       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
12004           DAG.getConstant(-(uint64_t)Align, VT));
12005     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
12006
12007     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
12008         DAG.getIntPtrConstant(0, true), SDValue(),
12009         SDLoc(Node));
12010
12011     SDValue Ops[2] = { Tmp1, Tmp2 };
12012     return DAG.getMergeValues(Ops, dl);
12013   }
12014
12015   // Get the inputs.
12016   SDValue Chain = Op.getOperand(0);
12017   SDValue Size  = Op.getOperand(1);
12018   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
12019   EVT VT = Op.getNode()->getValueType(0);
12020
12021   bool Is64Bit = Subtarget->is64Bit();
12022   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
12023
12024   if (SplitStack) {
12025     MachineRegisterInfo &MRI = MF.getRegInfo();
12026
12027     if (Is64Bit) {
12028       // The 64 bit implementation of segmented stacks needs to clobber both r10
12029       // r11. This makes it impossible to use it along with nested parameters.
12030       const Function *F = MF.getFunction();
12031
12032       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
12033            I != E; ++I)
12034         if (I->hasNestAttr())
12035           report_fatal_error("Cannot use segmented stacks with functions that "
12036                              "have nested arguments.");
12037     }
12038
12039     const TargetRegisterClass *AddrRegClass =
12040       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
12041     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
12042     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
12043     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
12044                                 DAG.getRegister(Vreg, SPTy));
12045     SDValue Ops1[2] = { Value, Chain };
12046     return DAG.getMergeValues(Ops1, dl);
12047   } else {
12048     SDValue Flag;
12049     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
12050
12051     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
12052     Flag = Chain.getValue(1);
12053     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
12054
12055     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
12056
12057     const X86RegisterInfo *RegInfo =
12058       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
12059     unsigned SPReg = RegInfo->getStackRegister();
12060     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
12061     Chain = SP.getValue(1);
12062
12063     if (Align) {
12064       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
12065                        DAG.getConstant(-(uint64_t)Align, VT));
12066       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
12067     }
12068
12069     SDValue Ops1[2] = { SP, Chain };
12070     return DAG.getMergeValues(Ops1, dl);
12071   }
12072 }
12073
12074 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
12075   MachineFunction &MF = DAG.getMachineFunction();
12076   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
12077
12078   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12079   SDLoc DL(Op);
12080
12081   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
12082     // vastart just stores the address of the VarArgsFrameIndex slot into the
12083     // memory location argument.
12084     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
12085                                    getPointerTy());
12086     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
12087                         MachinePointerInfo(SV), false, false, 0);
12088   }
12089
12090   // __va_list_tag:
12091   //   gp_offset         (0 - 6 * 8)
12092   //   fp_offset         (48 - 48 + 8 * 16)
12093   //   overflow_arg_area (point to parameters coming in memory).
12094   //   reg_save_area
12095   SmallVector<SDValue, 8> MemOps;
12096   SDValue FIN = Op.getOperand(1);
12097   // Store gp_offset
12098   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
12099                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
12100                                                MVT::i32),
12101                                FIN, MachinePointerInfo(SV), false, false, 0);
12102   MemOps.push_back(Store);
12103
12104   // Store fp_offset
12105   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12106                     FIN, DAG.getIntPtrConstant(4));
12107   Store = DAG.getStore(Op.getOperand(0), DL,
12108                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
12109                                        MVT::i32),
12110                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
12111   MemOps.push_back(Store);
12112
12113   // Store ptr to overflow_arg_area
12114   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12115                     FIN, DAG.getIntPtrConstant(4));
12116   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
12117                                     getPointerTy());
12118   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
12119                        MachinePointerInfo(SV, 8),
12120                        false, false, 0);
12121   MemOps.push_back(Store);
12122
12123   // Store ptr to reg_save_area.
12124   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
12125                     FIN, DAG.getIntPtrConstant(8));
12126   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
12127                                     getPointerTy());
12128   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
12129                        MachinePointerInfo(SV, 16), false, false, 0);
12130   MemOps.push_back(Store);
12131   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
12132 }
12133
12134 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
12135   assert(Subtarget->is64Bit() &&
12136          "LowerVAARG only handles 64-bit va_arg!");
12137   assert((Subtarget->isTargetLinux() ||
12138           Subtarget->isTargetDarwin()) &&
12139           "Unhandled target in LowerVAARG");
12140   assert(Op.getNode()->getNumOperands() == 4);
12141   SDValue Chain = Op.getOperand(0);
12142   SDValue SrcPtr = Op.getOperand(1);
12143   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12144   unsigned Align = Op.getConstantOperandVal(3);
12145   SDLoc dl(Op);
12146
12147   EVT ArgVT = Op.getNode()->getValueType(0);
12148   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12149   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
12150   uint8_t ArgMode;
12151
12152   // Decide which area this value should be read from.
12153   // TODO: Implement the AMD64 ABI in its entirety. This simple
12154   // selection mechanism works only for the basic types.
12155   if (ArgVT == MVT::f80) {
12156     llvm_unreachable("va_arg for f80 not yet implemented");
12157   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
12158     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
12159   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
12160     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
12161   } else {
12162     llvm_unreachable("Unhandled argument type in LowerVAARG");
12163   }
12164
12165   if (ArgMode == 2) {
12166     // Sanity Check: Make sure using fp_offset makes sense.
12167     assert(!DAG.getTarget().Options.UseSoftFloat &&
12168            !(DAG.getMachineFunction()
12169                 .getFunction()->getAttributes()
12170                 .hasAttribute(AttributeSet::FunctionIndex,
12171                               Attribute::NoImplicitFloat)) &&
12172            Subtarget->hasSSE1());
12173   }
12174
12175   // Insert VAARG_64 node into the DAG
12176   // VAARG_64 returns two values: Variable Argument Address, Chain
12177   SmallVector<SDValue, 11> InstOps;
12178   InstOps.push_back(Chain);
12179   InstOps.push_back(SrcPtr);
12180   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
12181   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
12182   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
12183   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
12184   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
12185                                           VTs, InstOps, MVT::i64,
12186                                           MachinePointerInfo(SV),
12187                                           /*Align=*/0,
12188                                           /*Volatile=*/false,
12189                                           /*ReadMem=*/true,
12190                                           /*WriteMem=*/true);
12191   Chain = VAARG.getValue(1);
12192
12193   // Load the next argument and return it
12194   return DAG.getLoad(ArgVT, dl,
12195                      Chain,
12196                      VAARG,
12197                      MachinePointerInfo(),
12198                      false, false, false, 0);
12199 }
12200
12201 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
12202                            SelectionDAG &DAG) {
12203   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
12204   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
12205   SDValue Chain = Op.getOperand(0);
12206   SDValue DstPtr = Op.getOperand(1);
12207   SDValue SrcPtr = Op.getOperand(2);
12208   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
12209   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12210   SDLoc DL(Op);
12211
12212   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
12213                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
12214                        false,
12215                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
12216 }
12217
12218 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
12219 // amount is a constant. Takes immediate version of shift as input.
12220 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
12221                                           SDValue SrcOp, uint64_t ShiftAmt,
12222                                           SelectionDAG &DAG) {
12223   MVT ElementType = VT.getVectorElementType();
12224
12225   // Fold this packed shift into its first operand if ShiftAmt is 0.
12226   if (ShiftAmt == 0)
12227     return SrcOp;
12228
12229   // Check for ShiftAmt >= element width
12230   if (ShiftAmt >= ElementType.getSizeInBits()) {
12231     if (Opc == X86ISD::VSRAI)
12232       ShiftAmt = ElementType.getSizeInBits() - 1;
12233     else
12234       return DAG.getConstant(0, VT);
12235   }
12236
12237   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
12238          && "Unknown target vector shift-by-constant node");
12239
12240   // Fold this packed vector shift into a build vector if SrcOp is a
12241   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
12242   if (VT == SrcOp.getSimpleValueType() &&
12243       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
12244     SmallVector<SDValue, 8> Elts;
12245     unsigned NumElts = SrcOp->getNumOperands();
12246     ConstantSDNode *ND;
12247
12248     switch(Opc) {
12249     default: llvm_unreachable(nullptr);
12250     case X86ISD::VSHLI:
12251       for (unsigned i=0; i!=NumElts; ++i) {
12252         SDValue CurrentOp = SrcOp->getOperand(i);
12253         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12254           Elts.push_back(CurrentOp);
12255           continue;
12256         }
12257         ND = cast<ConstantSDNode>(CurrentOp);
12258         const APInt &C = ND->getAPIntValue();
12259         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
12260       }
12261       break;
12262     case X86ISD::VSRLI:
12263       for (unsigned i=0; i!=NumElts; ++i) {
12264         SDValue CurrentOp = SrcOp->getOperand(i);
12265         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12266           Elts.push_back(CurrentOp);
12267           continue;
12268         }
12269         ND = cast<ConstantSDNode>(CurrentOp);
12270         const APInt &C = ND->getAPIntValue();
12271         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
12272       }
12273       break;
12274     case X86ISD::VSRAI:
12275       for (unsigned i=0; i!=NumElts; ++i) {
12276         SDValue CurrentOp = SrcOp->getOperand(i);
12277         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12278           Elts.push_back(CurrentOp);
12279           continue;
12280         }
12281         ND = cast<ConstantSDNode>(CurrentOp);
12282         const APInt &C = ND->getAPIntValue();
12283         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12284       }
12285       break;
12286     }
12287
12288     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12289   }
12290
12291   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12292 }
12293
12294 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12295 // may or may not be a constant. Takes immediate version of shift as input.
12296 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12297                                    SDValue SrcOp, SDValue ShAmt,
12298                                    SelectionDAG &DAG) {
12299   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12300
12301   // Catch shift-by-constant.
12302   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12303     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12304                                       CShAmt->getZExtValue(), DAG);
12305
12306   // Change opcode to non-immediate version
12307   switch (Opc) {
12308     default: llvm_unreachable("Unknown target vector shift node");
12309     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12310     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12311     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12312   }
12313
12314   // Need to build a vector containing shift amount
12315   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12316   SDValue ShOps[4];
12317   ShOps[0] = ShAmt;
12318   ShOps[1] = DAG.getConstant(0, MVT::i32);
12319   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12320   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12321
12322   // The return type has to be a 128-bit type with the same element
12323   // type as the input type.
12324   MVT EltVT = VT.getVectorElementType();
12325   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12326
12327   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12328   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12329 }
12330
12331 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12332   SDLoc dl(Op);
12333   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12334   switch (IntNo) {
12335   default: return SDValue();    // Don't custom lower most intrinsics.
12336   // Comparison intrinsics.
12337   case Intrinsic::x86_sse_comieq_ss:
12338   case Intrinsic::x86_sse_comilt_ss:
12339   case Intrinsic::x86_sse_comile_ss:
12340   case Intrinsic::x86_sse_comigt_ss:
12341   case Intrinsic::x86_sse_comige_ss:
12342   case Intrinsic::x86_sse_comineq_ss:
12343   case Intrinsic::x86_sse_ucomieq_ss:
12344   case Intrinsic::x86_sse_ucomilt_ss:
12345   case Intrinsic::x86_sse_ucomile_ss:
12346   case Intrinsic::x86_sse_ucomigt_ss:
12347   case Intrinsic::x86_sse_ucomige_ss:
12348   case Intrinsic::x86_sse_ucomineq_ss:
12349   case Intrinsic::x86_sse2_comieq_sd:
12350   case Intrinsic::x86_sse2_comilt_sd:
12351   case Intrinsic::x86_sse2_comile_sd:
12352   case Intrinsic::x86_sse2_comigt_sd:
12353   case Intrinsic::x86_sse2_comige_sd:
12354   case Intrinsic::x86_sse2_comineq_sd:
12355   case Intrinsic::x86_sse2_ucomieq_sd:
12356   case Intrinsic::x86_sse2_ucomilt_sd:
12357   case Intrinsic::x86_sse2_ucomile_sd:
12358   case Intrinsic::x86_sse2_ucomigt_sd:
12359   case Intrinsic::x86_sse2_ucomige_sd:
12360   case Intrinsic::x86_sse2_ucomineq_sd: {
12361     unsigned Opc;
12362     ISD::CondCode CC;
12363     switch (IntNo) {
12364     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12365     case Intrinsic::x86_sse_comieq_ss:
12366     case Intrinsic::x86_sse2_comieq_sd:
12367       Opc = X86ISD::COMI;
12368       CC = ISD::SETEQ;
12369       break;
12370     case Intrinsic::x86_sse_comilt_ss:
12371     case Intrinsic::x86_sse2_comilt_sd:
12372       Opc = X86ISD::COMI;
12373       CC = ISD::SETLT;
12374       break;
12375     case Intrinsic::x86_sse_comile_ss:
12376     case Intrinsic::x86_sse2_comile_sd:
12377       Opc = X86ISD::COMI;
12378       CC = ISD::SETLE;
12379       break;
12380     case Intrinsic::x86_sse_comigt_ss:
12381     case Intrinsic::x86_sse2_comigt_sd:
12382       Opc = X86ISD::COMI;
12383       CC = ISD::SETGT;
12384       break;
12385     case Intrinsic::x86_sse_comige_ss:
12386     case Intrinsic::x86_sse2_comige_sd:
12387       Opc = X86ISD::COMI;
12388       CC = ISD::SETGE;
12389       break;
12390     case Intrinsic::x86_sse_comineq_ss:
12391     case Intrinsic::x86_sse2_comineq_sd:
12392       Opc = X86ISD::COMI;
12393       CC = ISD::SETNE;
12394       break;
12395     case Intrinsic::x86_sse_ucomieq_ss:
12396     case Intrinsic::x86_sse2_ucomieq_sd:
12397       Opc = X86ISD::UCOMI;
12398       CC = ISD::SETEQ;
12399       break;
12400     case Intrinsic::x86_sse_ucomilt_ss:
12401     case Intrinsic::x86_sse2_ucomilt_sd:
12402       Opc = X86ISD::UCOMI;
12403       CC = ISD::SETLT;
12404       break;
12405     case Intrinsic::x86_sse_ucomile_ss:
12406     case Intrinsic::x86_sse2_ucomile_sd:
12407       Opc = X86ISD::UCOMI;
12408       CC = ISD::SETLE;
12409       break;
12410     case Intrinsic::x86_sse_ucomigt_ss:
12411     case Intrinsic::x86_sse2_ucomigt_sd:
12412       Opc = X86ISD::UCOMI;
12413       CC = ISD::SETGT;
12414       break;
12415     case Intrinsic::x86_sse_ucomige_ss:
12416     case Intrinsic::x86_sse2_ucomige_sd:
12417       Opc = X86ISD::UCOMI;
12418       CC = ISD::SETGE;
12419       break;
12420     case Intrinsic::x86_sse_ucomineq_ss:
12421     case Intrinsic::x86_sse2_ucomineq_sd:
12422       Opc = X86ISD::UCOMI;
12423       CC = ISD::SETNE;
12424       break;
12425     }
12426
12427     SDValue LHS = Op.getOperand(1);
12428     SDValue RHS = Op.getOperand(2);
12429     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12430     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12431     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12432     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12433                                 DAG.getConstant(X86CC, MVT::i8), Cond);
12434     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12435   }
12436
12437   // Arithmetic intrinsics.
12438   case Intrinsic::x86_sse2_pmulu_dq:
12439   case Intrinsic::x86_avx2_pmulu_dq:
12440     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12441                        Op.getOperand(1), Op.getOperand(2));
12442
12443   case Intrinsic::x86_sse41_pmuldq:
12444   case Intrinsic::x86_avx2_pmul_dq:
12445     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12446                        Op.getOperand(1), Op.getOperand(2));
12447
12448   case Intrinsic::x86_sse2_pmulhu_w:
12449   case Intrinsic::x86_avx2_pmulhu_w:
12450     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12451                        Op.getOperand(1), Op.getOperand(2));
12452
12453   case Intrinsic::x86_sse2_pmulh_w:
12454   case Intrinsic::x86_avx2_pmulh_w:
12455     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12456                        Op.getOperand(1), Op.getOperand(2));
12457
12458   // SSE2/AVX2 sub with unsigned saturation intrinsics
12459   case Intrinsic::x86_sse2_psubus_b:
12460   case Intrinsic::x86_sse2_psubus_w:
12461   case Intrinsic::x86_avx2_psubus_b:
12462   case Intrinsic::x86_avx2_psubus_w:
12463     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12464                        Op.getOperand(1), Op.getOperand(2));
12465
12466   // SSE3/AVX horizontal add/sub intrinsics
12467   case Intrinsic::x86_sse3_hadd_ps:
12468   case Intrinsic::x86_sse3_hadd_pd:
12469   case Intrinsic::x86_avx_hadd_ps_256:
12470   case Intrinsic::x86_avx_hadd_pd_256:
12471   case Intrinsic::x86_sse3_hsub_ps:
12472   case Intrinsic::x86_sse3_hsub_pd:
12473   case Intrinsic::x86_avx_hsub_ps_256:
12474   case Intrinsic::x86_avx_hsub_pd_256:
12475   case Intrinsic::x86_ssse3_phadd_w_128:
12476   case Intrinsic::x86_ssse3_phadd_d_128:
12477   case Intrinsic::x86_avx2_phadd_w:
12478   case Intrinsic::x86_avx2_phadd_d:
12479   case Intrinsic::x86_ssse3_phsub_w_128:
12480   case Intrinsic::x86_ssse3_phsub_d_128:
12481   case Intrinsic::x86_avx2_phsub_w:
12482   case Intrinsic::x86_avx2_phsub_d: {
12483     unsigned Opcode;
12484     switch (IntNo) {
12485     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12486     case Intrinsic::x86_sse3_hadd_ps:
12487     case Intrinsic::x86_sse3_hadd_pd:
12488     case Intrinsic::x86_avx_hadd_ps_256:
12489     case Intrinsic::x86_avx_hadd_pd_256:
12490       Opcode = X86ISD::FHADD;
12491       break;
12492     case Intrinsic::x86_sse3_hsub_ps:
12493     case Intrinsic::x86_sse3_hsub_pd:
12494     case Intrinsic::x86_avx_hsub_ps_256:
12495     case Intrinsic::x86_avx_hsub_pd_256:
12496       Opcode = X86ISD::FHSUB;
12497       break;
12498     case Intrinsic::x86_ssse3_phadd_w_128:
12499     case Intrinsic::x86_ssse3_phadd_d_128:
12500     case Intrinsic::x86_avx2_phadd_w:
12501     case Intrinsic::x86_avx2_phadd_d:
12502       Opcode = X86ISD::HADD;
12503       break;
12504     case Intrinsic::x86_ssse3_phsub_w_128:
12505     case Intrinsic::x86_ssse3_phsub_d_128:
12506     case Intrinsic::x86_avx2_phsub_w:
12507     case Intrinsic::x86_avx2_phsub_d:
12508       Opcode = X86ISD::HSUB;
12509       break;
12510     }
12511     return DAG.getNode(Opcode, dl, Op.getValueType(),
12512                        Op.getOperand(1), Op.getOperand(2));
12513   }
12514
12515   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12516   case Intrinsic::x86_sse2_pmaxu_b:
12517   case Intrinsic::x86_sse41_pmaxuw:
12518   case Intrinsic::x86_sse41_pmaxud:
12519   case Intrinsic::x86_avx2_pmaxu_b:
12520   case Intrinsic::x86_avx2_pmaxu_w:
12521   case Intrinsic::x86_avx2_pmaxu_d:
12522   case Intrinsic::x86_sse2_pminu_b:
12523   case Intrinsic::x86_sse41_pminuw:
12524   case Intrinsic::x86_sse41_pminud:
12525   case Intrinsic::x86_avx2_pminu_b:
12526   case Intrinsic::x86_avx2_pminu_w:
12527   case Intrinsic::x86_avx2_pminu_d:
12528   case Intrinsic::x86_sse41_pmaxsb:
12529   case Intrinsic::x86_sse2_pmaxs_w:
12530   case Intrinsic::x86_sse41_pmaxsd:
12531   case Intrinsic::x86_avx2_pmaxs_b:
12532   case Intrinsic::x86_avx2_pmaxs_w:
12533   case Intrinsic::x86_avx2_pmaxs_d:
12534   case Intrinsic::x86_sse41_pminsb:
12535   case Intrinsic::x86_sse2_pmins_w:
12536   case Intrinsic::x86_sse41_pminsd:
12537   case Intrinsic::x86_avx2_pmins_b:
12538   case Intrinsic::x86_avx2_pmins_w:
12539   case Intrinsic::x86_avx2_pmins_d: {
12540     unsigned Opcode;
12541     switch (IntNo) {
12542     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12543     case Intrinsic::x86_sse2_pmaxu_b:
12544     case Intrinsic::x86_sse41_pmaxuw:
12545     case Intrinsic::x86_sse41_pmaxud:
12546     case Intrinsic::x86_avx2_pmaxu_b:
12547     case Intrinsic::x86_avx2_pmaxu_w:
12548     case Intrinsic::x86_avx2_pmaxu_d:
12549       Opcode = X86ISD::UMAX;
12550       break;
12551     case Intrinsic::x86_sse2_pminu_b:
12552     case Intrinsic::x86_sse41_pminuw:
12553     case Intrinsic::x86_sse41_pminud:
12554     case Intrinsic::x86_avx2_pminu_b:
12555     case Intrinsic::x86_avx2_pminu_w:
12556     case Intrinsic::x86_avx2_pminu_d:
12557       Opcode = X86ISD::UMIN;
12558       break;
12559     case Intrinsic::x86_sse41_pmaxsb:
12560     case Intrinsic::x86_sse2_pmaxs_w:
12561     case Intrinsic::x86_sse41_pmaxsd:
12562     case Intrinsic::x86_avx2_pmaxs_b:
12563     case Intrinsic::x86_avx2_pmaxs_w:
12564     case Intrinsic::x86_avx2_pmaxs_d:
12565       Opcode = X86ISD::SMAX;
12566       break;
12567     case Intrinsic::x86_sse41_pminsb:
12568     case Intrinsic::x86_sse2_pmins_w:
12569     case Intrinsic::x86_sse41_pminsd:
12570     case Intrinsic::x86_avx2_pmins_b:
12571     case Intrinsic::x86_avx2_pmins_w:
12572     case Intrinsic::x86_avx2_pmins_d:
12573       Opcode = X86ISD::SMIN;
12574       break;
12575     }
12576     return DAG.getNode(Opcode, dl, Op.getValueType(),
12577                        Op.getOperand(1), Op.getOperand(2));
12578   }
12579
12580   // SSE/SSE2/AVX floating point max/min intrinsics.
12581   case Intrinsic::x86_sse_max_ps:
12582   case Intrinsic::x86_sse2_max_pd:
12583   case Intrinsic::x86_avx_max_ps_256:
12584   case Intrinsic::x86_avx_max_pd_256:
12585   case Intrinsic::x86_sse_min_ps:
12586   case Intrinsic::x86_sse2_min_pd:
12587   case Intrinsic::x86_avx_min_ps_256:
12588   case Intrinsic::x86_avx_min_pd_256: {
12589     unsigned Opcode;
12590     switch (IntNo) {
12591     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12592     case Intrinsic::x86_sse_max_ps:
12593     case Intrinsic::x86_sse2_max_pd:
12594     case Intrinsic::x86_avx_max_ps_256:
12595     case Intrinsic::x86_avx_max_pd_256:
12596       Opcode = X86ISD::FMAX;
12597       break;
12598     case Intrinsic::x86_sse_min_ps:
12599     case Intrinsic::x86_sse2_min_pd:
12600     case Intrinsic::x86_avx_min_ps_256:
12601     case Intrinsic::x86_avx_min_pd_256:
12602       Opcode = X86ISD::FMIN;
12603       break;
12604     }
12605     return DAG.getNode(Opcode, dl, Op.getValueType(),
12606                        Op.getOperand(1), Op.getOperand(2));
12607   }
12608
12609   // AVX2 variable shift intrinsics
12610   case Intrinsic::x86_avx2_psllv_d:
12611   case Intrinsic::x86_avx2_psllv_q:
12612   case Intrinsic::x86_avx2_psllv_d_256:
12613   case Intrinsic::x86_avx2_psllv_q_256:
12614   case Intrinsic::x86_avx2_psrlv_d:
12615   case Intrinsic::x86_avx2_psrlv_q:
12616   case Intrinsic::x86_avx2_psrlv_d_256:
12617   case Intrinsic::x86_avx2_psrlv_q_256:
12618   case Intrinsic::x86_avx2_psrav_d:
12619   case Intrinsic::x86_avx2_psrav_d_256: {
12620     unsigned Opcode;
12621     switch (IntNo) {
12622     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12623     case Intrinsic::x86_avx2_psllv_d:
12624     case Intrinsic::x86_avx2_psllv_q:
12625     case Intrinsic::x86_avx2_psllv_d_256:
12626     case Intrinsic::x86_avx2_psllv_q_256:
12627       Opcode = ISD::SHL;
12628       break;
12629     case Intrinsic::x86_avx2_psrlv_d:
12630     case Intrinsic::x86_avx2_psrlv_q:
12631     case Intrinsic::x86_avx2_psrlv_d_256:
12632     case Intrinsic::x86_avx2_psrlv_q_256:
12633       Opcode = ISD::SRL;
12634       break;
12635     case Intrinsic::x86_avx2_psrav_d:
12636     case Intrinsic::x86_avx2_psrav_d_256:
12637       Opcode = ISD::SRA;
12638       break;
12639     }
12640     return DAG.getNode(Opcode, dl, Op.getValueType(),
12641                        Op.getOperand(1), Op.getOperand(2));
12642   }
12643
12644   case Intrinsic::x86_sse2_packssdw_128:
12645   case Intrinsic::x86_sse2_packsswb_128:
12646   case Intrinsic::x86_avx2_packssdw:
12647   case Intrinsic::x86_avx2_packsswb:
12648     return DAG.getNode(X86ISD::PACKSS, dl, Op.getValueType(),
12649                        Op.getOperand(1), Op.getOperand(2));
12650
12651   case Intrinsic::x86_sse2_packuswb_128:
12652   case Intrinsic::x86_sse41_packusdw:
12653   case Intrinsic::x86_avx2_packuswb:
12654   case Intrinsic::x86_avx2_packusdw:
12655     return DAG.getNode(X86ISD::PACKUS, dl, Op.getValueType(),
12656                        Op.getOperand(1), Op.getOperand(2));
12657
12658   case Intrinsic::x86_ssse3_pshuf_b_128:
12659   case Intrinsic::x86_avx2_pshuf_b:
12660     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12661                        Op.getOperand(1), Op.getOperand(2));
12662
12663   case Intrinsic::x86_ssse3_psign_b_128:
12664   case Intrinsic::x86_ssse3_psign_w_128:
12665   case Intrinsic::x86_ssse3_psign_d_128:
12666   case Intrinsic::x86_avx2_psign_b:
12667   case Intrinsic::x86_avx2_psign_w:
12668   case Intrinsic::x86_avx2_psign_d:
12669     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12670                        Op.getOperand(1), Op.getOperand(2));
12671
12672   case Intrinsic::x86_sse41_insertps:
12673     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12674                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12675
12676   case Intrinsic::x86_avx_vperm2f128_ps_256:
12677   case Intrinsic::x86_avx_vperm2f128_pd_256:
12678   case Intrinsic::x86_avx_vperm2f128_si_256:
12679   case Intrinsic::x86_avx2_vperm2i128:
12680     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12681                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12682
12683   case Intrinsic::x86_avx2_permd:
12684   case Intrinsic::x86_avx2_permps:
12685     // Operands intentionally swapped. Mask is last operand to intrinsic,
12686     // but second operand for node/instruction.
12687     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12688                        Op.getOperand(2), Op.getOperand(1));
12689
12690   case Intrinsic::x86_sse_sqrt_ps:
12691   case Intrinsic::x86_sse2_sqrt_pd:
12692   case Intrinsic::x86_avx_sqrt_ps_256:
12693   case Intrinsic::x86_avx_sqrt_pd_256:
12694     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12695
12696   // ptest and testp intrinsics. The intrinsic these come from are designed to
12697   // return an integer value, not just an instruction so lower it to the ptest
12698   // or testp pattern and a setcc for the result.
12699   case Intrinsic::x86_sse41_ptestz:
12700   case Intrinsic::x86_sse41_ptestc:
12701   case Intrinsic::x86_sse41_ptestnzc:
12702   case Intrinsic::x86_avx_ptestz_256:
12703   case Intrinsic::x86_avx_ptestc_256:
12704   case Intrinsic::x86_avx_ptestnzc_256:
12705   case Intrinsic::x86_avx_vtestz_ps:
12706   case Intrinsic::x86_avx_vtestc_ps:
12707   case Intrinsic::x86_avx_vtestnzc_ps:
12708   case Intrinsic::x86_avx_vtestz_pd:
12709   case Intrinsic::x86_avx_vtestc_pd:
12710   case Intrinsic::x86_avx_vtestnzc_pd:
12711   case Intrinsic::x86_avx_vtestz_ps_256:
12712   case Intrinsic::x86_avx_vtestc_ps_256:
12713   case Intrinsic::x86_avx_vtestnzc_ps_256:
12714   case Intrinsic::x86_avx_vtestz_pd_256:
12715   case Intrinsic::x86_avx_vtestc_pd_256:
12716   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12717     bool IsTestPacked = false;
12718     unsigned X86CC;
12719     switch (IntNo) {
12720     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12721     case Intrinsic::x86_avx_vtestz_ps:
12722     case Intrinsic::x86_avx_vtestz_pd:
12723     case Intrinsic::x86_avx_vtestz_ps_256:
12724     case Intrinsic::x86_avx_vtestz_pd_256:
12725       IsTestPacked = true; // Fallthrough
12726     case Intrinsic::x86_sse41_ptestz:
12727     case Intrinsic::x86_avx_ptestz_256:
12728       // ZF = 1
12729       X86CC = X86::COND_E;
12730       break;
12731     case Intrinsic::x86_avx_vtestc_ps:
12732     case Intrinsic::x86_avx_vtestc_pd:
12733     case Intrinsic::x86_avx_vtestc_ps_256:
12734     case Intrinsic::x86_avx_vtestc_pd_256:
12735       IsTestPacked = true; // Fallthrough
12736     case Intrinsic::x86_sse41_ptestc:
12737     case Intrinsic::x86_avx_ptestc_256:
12738       // CF = 1
12739       X86CC = X86::COND_B;
12740       break;
12741     case Intrinsic::x86_avx_vtestnzc_ps:
12742     case Intrinsic::x86_avx_vtestnzc_pd:
12743     case Intrinsic::x86_avx_vtestnzc_ps_256:
12744     case Intrinsic::x86_avx_vtestnzc_pd_256:
12745       IsTestPacked = true; // Fallthrough
12746     case Intrinsic::x86_sse41_ptestnzc:
12747     case Intrinsic::x86_avx_ptestnzc_256:
12748       // ZF and CF = 0
12749       X86CC = X86::COND_A;
12750       break;
12751     }
12752
12753     SDValue LHS = Op.getOperand(1);
12754     SDValue RHS = Op.getOperand(2);
12755     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12756     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12757     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12758     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12759     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12760   }
12761   case Intrinsic::x86_avx512_kortestz_w:
12762   case Intrinsic::x86_avx512_kortestc_w: {
12763     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12764     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12765     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12766     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12767     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12768     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12769     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12770   }
12771
12772   // SSE/AVX shift intrinsics
12773   case Intrinsic::x86_sse2_psll_w:
12774   case Intrinsic::x86_sse2_psll_d:
12775   case Intrinsic::x86_sse2_psll_q:
12776   case Intrinsic::x86_avx2_psll_w:
12777   case Intrinsic::x86_avx2_psll_d:
12778   case Intrinsic::x86_avx2_psll_q:
12779   case Intrinsic::x86_sse2_psrl_w:
12780   case Intrinsic::x86_sse2_psrl_d:
12781   case Intrinsic::x86_sse2_psrl_q:
12782   case Intrinsic::x86_avx2_psrl_w:
12783   case Intrinsic::x86_avx2_psrl_d:
12784   case Intrinsic::x86_avx2_psrl_q:
12785   case Intrinsic::x86_sse2_psra_w:
12786   case Intrinsic::x86_sse2_psra_d:
12787   case Intrinsic::x86_avx2_psra_w:
12788   case Intrinsic::x86_avx2_psra_d: {
12789     unsigned Opcode;
12790     switch (IntNo) {
12791     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12792     case Intrinsic::x86_sse2_psll_w:
12793     case Intrinsic::x86_sse2_psll_d:
12794     case Intrinsic::x86_sse2_psll_q:
12795     case Intrinsic::x86_avx2_psll_w:
12796     case Intrinsic::x86_avx2_psll_d:
12797     case Intrinsic::x86_avx2_psll_q:
12798       Opcode = X86ISD::VSHL;
12799       break;
12800     case Intrinsic::x86_sse2_psrl_w:
12801     case Intrinsic::x86_sse2_psrl_d:
12802     case Intrinsic::x86_sse2_psrl_q:
12803     case Intrinsic::x86_avx2_psrl_w:
12804     case Intrinsic::x86_avx2_psrl_d:
12805     case Intrinsic::x86_avx2_psrl_q:
12806       Opcode = X86ISD::VSRL;
12807       break;
12808     case Intrinsic::x86_sse2_psra_w:
12809     case Intrinsic::x86_sse2_psra_d:
12810     case Intrinsic::x86_avx2_psra_w:
12811     case Intrinsic::x86_avx2_psra_d:
12812       Opcode = X86ISD::VSRA;
12813       break;
12814     }
12815     return DAG.getNode(Opcode, dl, Op.getValueType(),
12816                        Op.getOperand(1), Op.getOperand(2));
12817   }
12818
12819   // SSE/AVX immediate shift intrinsics
12820   case Intrinsic::x86_sse2_pslli_w:
12821   case Intrinsic::x86_sse2_pslli_d:
12822   case Intrinsic::x86_sse2_pslli_q:
12823   case Intrinsic::x86_avx2_pslli_w:
12824   case Intrinsic::x86_avx2_pslli_d:
12825   case Intrinsic::x86_avx2_pslli_q:
12826   case Intrinsic::x86_sse2_psrli_w:
12827   case Intrinsic::x86_sse2_psrli_d:
12828   case Intrinsic::x86_sse2_psrli_q:
12829   case Intrinsic::x86_avx2_psrli_w:
12830   case Intrinsic::x86_avx2_psrli_d:
12831   case Intrinsic::x86_avx2_psrli_q:
12832   case Intrinsic::x86_sse2_psrai_w:
12833   case Intrinsic::x86_sse2_psrai_d:
12834   case Intrinsic::x86_avx2_psrai_w:
12835   case Intrinsic::x86_avx2_psrai_d: {
12836     unsigned Opcode;
12837     switch (IntNo) {
12838     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12839     case Intrinsic::x86_sse2_pslli_w:
12840     case Intrinsic::x86_sse2_pslli_d:
12841     case Intrinsic::x86_sse2_pslli_q:
12842     case Intrinsic::x86_avx2_pslli_w:
12843     case Intrinsic::x86_avx2_pslli_d:
12844     case Intrinsic::x86_avx2_pslli_q:
12845       Opcode = X86ISD::VSHLI;
12846       break;
12847     case Intrinsic::x86_sse2_psrli_w:
12848     case Intrinsic::x86_sse2_psrli_d:
12849     case Intrinsic::x86_sse2_psrli_q:
12850     case Intrinsic::x86_avx2_psrli_w:
12851     case Intrinsic::x86_avx2_psrli_d:
12852     case Intrinsic::x86_avx2_psrli_q:
12853       Opcode = X86ISD::VSRLI;
12854       break;
12855     case Intrinsic::x86_sse2_psrai_w:
12856     case Intrinsic::x86_sse2_psrai_d:
12857     case Intrinsic::x86_avx2_psrai_w:
12858     case Intrinsic::x86_avx2_psrai_d:
12859       Opcode = X86ISD::VSRAI;
12860       break;
12861     }
12862     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12863                                Op.getOperand(1), Op.getOperand(2), DAG);
12864   }
12865
12866   case Intrinsic::x86_sse42_pcmpistria128:
12867   case Intrinsic::x86_sse42_pcmpestria128:
12868   case Intrinsic::x86_sse42_pcmpistric128:
12869   case Intrinsic::x86_sse42_pcmpestric128:
12870   case Intrinsic::x86_sse42_pcmpistrio128:
12871   case Intrinsic::x86_sse42_pcmpestrio128:
12872   case Intrinsic::x86_sse42_pcmpistris128:
12873   case Intrinsic::x86_sse42_pcmpestris128:
12874   case Intrinsic::x86_sse42_pcmpistriz128:
12875   case Intrinsic::x86_sse42_pcmpestriz128: {
12876     unsigned Opcode;
12877     unsigned X86CC;
12878     switch (IntNo) {
12879     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12880     case Intrinsic::x86_sse42_pcmpistria128:
12881       Opcode = X86ISD::PCMPISTRI;
12882       X86CC = X86::COND_A;
12883       break;
12884     case Intrinsic::x86_sse42_pcmpestria128:
12885       Opcode = X86ISD::PCMPESTRI;
12886       X86CC = X86::COND_A;
12887       break;
12888     case Intrinsic::x86_sse42_pcmpistric128:
12889       Opcode = X86ISD::PCMPISTRI;
12890       X86CC = X86::COND_B;
12891       break;
12892     case Intrinsic::x86_sse42_pcmpestric128:
12893       Opcode = X86ISD::PCMPESTRI;
12894       X86CC = X86::COND_B;
12895       break;
12896     case Intrinsic::x86_sse42_pcmpistrio128:
12897       Opcode = X86ISD::PCMPISTRI;
12898       X86CC = X86::COND_O;
12899       break;
12900     case Intrinsic::x86_sse42_pcmpestrio128:
12901       Opcode = X86ISD::PCMPESTRI;
12902       X86CC = X86::COND_O;
12903       break;
12904     case Intrinsic::x86_sse42_pcmpistris128:
12905       Opcode = X86ISD::PCMPISTRI;
12906       X86CC = X86::COND_S;
12907       break;
12908     case Intrinsic::x86_sse42_pcmpestris128:
12909       Opcode = X86ISD::PCMPESTRI;
12910       X86CC = X86::COND_S;
12911       break;
12912     case Intrinsic::x86_sse42_pcmpistriz128:
12913       Opcode = X86ISD::PCMPISTRI;
12914       X86CC = X86::COND_E;
12915       break;
12916     case Intrinsic::x86_sse42_pcmpestriz128:
12917       Opcode = X86ISD::PCMPESTRI;
12918       X86CC = X86::COND_E;
12919       break;
12920     }
12921     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12922     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12923     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12924     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12925                                 DAG.getConstant(X86CC, MVT::i8),
12926                                 SDValue(PCMP.getNode(), 1));
12927     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12928   }
12929
12930   case Intrinsic::x86_sse42_pcmpistri128:
12931   case Intrinsic::x86_sse42_pcmpestri128: {
12932     unsigned Opcode;
12933     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12934       Opcode = X86ISD::PCMPISTRI;
12935     else
12936       Opcode = X86ISD::PCMPESTRI;
12937
12938     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12939     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12940     return DAG.getNode(Opcode, dl, VTs, NewOps);
12941   }
12942   case Intrinsic::x86_fma_vfmadd_ps:
12943   case Intrinsic::x86_fma_vfmadd_pd:
12944   case Intrinsic::x86_fma_vfmsub_ps:
12945   case Intrinsic::x86_fma_vfmsub_pd:
12946   case Intrinsic::x86_fma_vfnmadd_ps:
12947   case Intrinsic::x86_fma_vfnmadd_pd:
12948   case Intrinsic::x86_fma_vfnmsub_ps:
12949   case Intrinsic::x86_fma_vfnmsub_pd:
12950   case Intrinsic::x86_fma_vfmaddsub_ps:
12951   case Intrinsic::x86_fma_vfmaddsub_pd:
12952   case Intrinsic::x86_fma_vfmsubadd_ps:
12953   case Intrinsic::x86_fma_vfmsubadd_pd:
12954   case Intrinsic::x86_fma_vfmadd_ps_256:
12955   case Intrinsic::x86_fma_vfmadd_pd_256:
12956   case Intrinsic::x86_fma_vfmsub_ps_256:
12957   case Intrinsic::x86_fma_vfmsub_pd_256:
12958   case Intrinsic::x86_fma_vfnmadd_ps_256:
12959   case Intrinsic::x86_fma_vfnmadd_pd_256:
12960   case Intrinsic::x86_fma_vfnmsub_ps_256:
12961   case Intrinsic::x86_fma_vfnmsub_pd_256:
12962   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12963   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12964   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12965   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12966   case Intrinsic::x86_fma_vfmadd_ps_512:
12967   case Intrinsic::x86_fma_vfmadd_pd_512:
12968   case Intrinsic::x86_fma_vfmsub_ps_512:
12969   case Intrinsic::x86_fma_vfmsub_pd_512:
12970   case Intrinsic::x86_fma_vfnmadd_ps_512:
12971   case Intrinsic::x86_fma_vfnmadd_pd_512:
12972   case Intrinsic::x86_fma_vfnmsub_ps_512:
12973   case Intrinsic::x86_fma_vfnmsub_pd_512:
12974   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12975   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12976   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12977   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12978     unsigned Opc;
12979     switch (IntNo) {
12980     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12981     case Intrinsic::x86_fma_vfmadd_ps:
12982     case Intrinsic::x86_fma_vfmadd_pd:
12983     case Intrinsic::x86_fma_vfmadd_ps_256:
12984     case Intrinsic::x86_fma_vfmadd_pd_256:
12985     case Intrinsic::x86_fma_vfmadd_ps_512:
12986     case Intrinsic::x86_fma_vfmadd_pd_512:
12987       Opc = X86ISD::FMADD;
12988       break;
12989     case Intrinsic::x86_fma_vfmsub_ps:
12990     case Intrinsic::x86_fma_vfmsub_pd:
12991     case Intrinsic::x86_fma_vfmsub_ps_256:
12992     case Intrinsic::x86_fma_vfmsub_pd_256:
12993     case Intrinsic::x86_fma_vfmsub_ps_512:
12994     case Intrinsic::x86_fma_vfmsub_pd_512:
12995       Opc = X86ISD::FMSUB;
12996       break;
12997     case Intrinsic::x86_fma_vfnmadd_ps:
12998     case Intrinsic::x86_fma_vfnmadd_pd:
12999     case Intrinsic::x86_fma_vfnmadd_ps_256:
13000     case Intrinsic::x86_fma_vfnmadd_pd_256:
13001     case Intrinsic::x86_fma_vfnmadd_ps_512:
13002     case Intrinsic::x86_fma_vfnmadd_pd_512:
13003       Opc = X86ISD::FNMADD;
13004       break;
13005     case Intrinsic::x86_fma_vfnmsub_ps:
13006     case Intrinsic::x86_fma_vfnmsub_pd:
13007     case Intrinsic::x86_fma_vfnmsub_ps_256:
13008     case Intrinsic::x86_fma_vfnmsub_pd_256:
13009     case Intrinsic::x86_fma_vfnmsub_ps_512:
13010     case Intrinsic::x86_fma_vfnmsub_pd_512:
13011       Opc = X86ISD::FNMSUB;
13012       break;
13013     case Intrinsic::x86_fma_vfmaddsub_ps:
13014     case Intrinsic::x86_fma_vfmaddsub_pd:
13015     case Intrinsic::x86_fma_vfmaddsub_ps_256:
13016     case Intrinsic::x86_fma_vfmaddsub_pd_256:
13017     case Intrinsic::x86_fma_vfmaddsub_ps_512:
13018     case Intrinsic::x86_fma_vfmaddsub_pd_512:
13019       Opc = X86ISD::FMADDSUB;
13020       break;
13021     case Intrinsic::x86_fma_vfmsubadd_ps:
13022     case Intrinsic::x86_fma_vfmsubadd_pd:
13023     case Intrinsic::x86_fma_vfmsubadd_ps_256:
13024     case Intrinsic::x86_fma_vfmsubadd_pd_256:
13025     case Intrinsic::x86_fma_vfmsubadd_ps_512:
13026     case Intrinsic::x86_fma_vfmsubadd_pd_512:
13027       Opc = X86ISD::FMSUBADD;
13028       break;
13029     }
13030
13031     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
13032                        Op.getOperand(2), Op.getOperand(3));
13033   }
13034   }
13035 }
13036
13037 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13038                               SDValue Src, SDValue Mask, SDValue Base,
13039                               SDValue Index, SDValue ScaleOp, SDValue Chain,
13040                               const X86Subtarget * Subtarget) {
13041   SDLoc dl(Op);
13042   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13043   assert(C && "Invalid scale type");
13044   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13045   EVT MaskVT = MVT::getVectorVT(MVT::i1,
13046                              Index.getSimpleValueType().getVectorNumElements());
13047   SDValue MaskInReg;
13048   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13049   if (MaskC)
13050     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13051   else
13052     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13053   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
13054   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13055   SDValue Segment = DAG.getRegister(0, MVT::i32);
13056   if (Src.getOpcode() == ISD::UNDEF)
13057     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
13058   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
13059   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
13060   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
13061   return DAG.getMergeValues(RetOps, dl);
13062 }
13063
13064 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13065                                SDValue Src, SDValue Mask, SDValue Base,
13066                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
13067   SDLoc dl(Op);
13068   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13069   assert(C && "Invalid scale type");
13070   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13071   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13072   SDValue Segment = DAG.getRegister(0, MVT::i32);
13073   EVT MaskVT = MVT::getVectorVT(MVT::i1,
13074                              Index.getSimpleValueType().getVectorNumElements());
13075   SDValue MaskInReg;
13076   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13077   if (MaskC)
13078     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13079   else
13080     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13081   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
13082   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
13083   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
13084   return SDValue(Res, 1);
13085 }
13086
13087 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
13088                                SDValue Mask, SDValue Base, SDValue Index,
13089                                SDValue ScaleOp, SDValue Chain) {
13090   SDLoc dl(Op);
13091   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
13092   assert(C && "Invalid scale type");
13093   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
13094   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
13095   SDValue Segment = DAG.getRegister(0, MVT::i32);
13096   EVT MaskVT =
13097     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
13098   SDValue MaskInReg;
13099   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
13100   if (MaskC)
13101     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
13102   else
13103     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
13104   //SDVTList VTs = DAG.getVTList(MVT::Other);
13105   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
13106   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
13107   return SDValue(Res, 0);
13108 }
13109
13110 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
13111 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
13112 // also used to custom lower READCYCLECOUNTER nodes.
13113 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
13114                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
13115                               SmallVectorImpl<SDValue> &Results) {
13116   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
13117   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
13118   SDValue LO, HI;
13119
13120   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
13121   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
13122   // and the EAX register is loaded with the low-order 32 bits.
13123   if (Subtarget->is64Bit()) {
13124     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
13125     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
13126                             LO.getValue(2));
13127   } else {
13128     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
13129     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
13130                             LO.getValue(2));
13131   }
13132   SDValue Chain = HI.getValue(1);
13133
13134   if (Opcode == X86ISD::RDTSCP_DAG) {
13135     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
13136
13137     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
13138     // the ECX register. Add 'ecx' explicitly to the chain.
13139     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
13140                                      HI.getValue(2));
13141     // Explicitly store the content of ECX at the location passed in input
13142     // to the 'rdtscp' intrinsic.
13143     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
13144                          MachinePointerInfo(), false, false, 0);
13145   }
13146
13147   if (Subtarget->is64Bit()) {
13148     // The EDX register is loaded with the high-order 32 bits of the MSR, and
13149     // the EAX register is loaded with the low-order 32 bits.
13150     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
13151                               DAG.getConstant(32, MVT::i8));
13152     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
13153     Results.push_back(Chain);
13154     return;
13155   }
13156
13157   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13158   SDValue Ops[] = { LO, HI };
13159   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
13160   Results.push_back(Pair);
13161   Results.push_back(Chain);
13162 }
13163
13164 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13165                                      SelectionDAG &DAG) {
13166   SmallVector<SDValue, 2> Results;
13167   SDLoc DL(Op);
13168   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
13169                           Results);
13170   return DAG.getMergeValues(Results, DL);
13171 }
13172
13173 enum IntrinsicType {
13174   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
13175 };
13176
13177 struct IntrinsicData {
13178   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
13179     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
13180   IntrinsicType Type;
13181   unsigned      Opc0;
13182   unsigned      Opc1;
13183 };
13184
13185 std::map < unsigned, IntrinsicData> IntrMap;
13186 static void InitIntinsicsMap() {
13187   static bool Initialized = false;
13188   if (Initialized) 
13189     return;
13190   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13191                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13192   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13193                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13194   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
13195                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
13196   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
13197                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
13198   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
13199                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
13200   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
13201                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
13202   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
13203                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
13204   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
13205                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
13206   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
13207                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
13208
13209   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
13210                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
13211   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
13212                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
13213   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
13214                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
13215   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
13216                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
13217   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
13218                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
13219   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
13220                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
13221   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
13222                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
13223   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
13224                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
13225    
13226   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
13227                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
13228                                                         X86::VGATHERPF1QPSm)));
13229   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
13230                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
13231                                                         X86::VGATHERPF1QPDm)));
13232   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
13233                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
13234                                                         X86::VGATHERPF1DPDm)));
13235   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
13236                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
13237                                                         X86::VGATHERPF1DPSm)));
13238   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
13239                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
13240                                                         X86::VSCATTERPF1QPSm)));
13241   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
13242                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
13243                                                         X86::VSCATTERPF1QPDm)));
13244   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
13245                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
13246                                                         X86::VSCATTERPF1DPDm)));
13247   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
13248                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
13249                                                         X86::VSCATTERPF1DPSm)));
13250   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
13251                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13252   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
13253                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13254   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
13255                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13256   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
13257                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13258   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
13259                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13260   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
13261                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13262   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
13263                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
13264   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
13265                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
13266   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
13267                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
13268   Initialized = true;
13269 }
13270
13271 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
13272                                       SelectionDAG &DAG) {
13273   InitIntinsicsMap();
13274   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13275   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
13276   if (itr == IntrMap.end())
13277     return SDValue();
13278
13279   SDLoc dl(Op);
13280   IntrinsicData Intr = itr->second;
13281   switch(Intr.Type) {
13282   case RDSEED:
13283   case RDRAND: {
13284     // Emit the node with the right value type.
13285     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
13286     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
13287
13288     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
13289     // Otherwise return the value from Rand, which is always 0, casted to i32.
13290     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13291                       DAG.getConstant(1, Op->getValueType(1)),
13292                       DAG.getConstant(X86::COND_B, MVT::i32),
13293                       SDValue(Result.getNode(), 1) };
13294     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13295                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
13296                                   Ops);
13297
13298     // Return { result, isValid, chain }.
13299     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13300                        SDValue(Result.getNode(), 2));
13301   }
13302   case GATHER: {
13303   //gather(v1, mask, index, base, scale);
13304     SDValue Chain = Op.getOperand(0);
13305     SDValue Src   = Op.getOperand(2);
13306     SDValue Base  = Op.getOperand(3);
13307     SDValue Index = Op.getOperand(4);
13308     SDValue Mask  = Op.getOperand(5);
13309     SDValue Scale = Op.getOperand(6);
13310     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13311                           Subtarget);
13312   }
13313   case SCATTER: {
13314   //scatter(base, mask, index, v1, scale);
13315     SDValue Chain = Op.getOperand(0);
13316     SDValue Base  = Op.getOperand(2);
13317     SDValue Mask  = Op.getOperand(3);
13318     SDValue Index = Op.getOperand(4);
13319     SDValue Src   = Op.getOperand(5);
13320     SDValue Scale = Op.getOperand(6);
13321     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13322   }
13323   case PREFETCH: {
13324     SDValue Hint = Op.getOperand(6);
13325     unsigned HintVal;
13326     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13327         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13328       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13329     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13330     SDValue Chain = Op.getOperand(0);
13331     SDValue Mask  = Op.getOperand(2);
13332     SDValue Index = Op.getOperand(3);
13333     SDValue Base  = Op.getOperand(4);
13334     SDValue Scale = Op.getOperand(5);
13335     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13336   }
13337   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13338   case RDTSC: {
13339     SmallVector<SDValue, 2> Results;
13340     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13341     return DAG.getMergeValues(Results, dl);
13342   }
13343   // XTEST intrinsics.
13344   case XTEST: {
13345     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13346     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13347     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13348                                 DAG.getConstant(X86::COND_NE, MVT::i8),
13349                                 InTrans);
13350     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13351     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13352                        Ret, SDValue(InTrans.getNode(), 1));
13353   }
13354   }
13355   llvm_unreachable("Unknown Intrinsic Type");
13356 }
13357
13358 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13359                                            SelectionDAG &DAG) const {
13360   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13361   MFI->setReturnAddressIsTaken(true);
13362
13363   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13364     return SDValue();
13365
13366   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13367   SDLoc dl(Op);
13368   EVT PtrVT = getPointerTy();
13369
13370   if (Depth > 0) {
13371     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13372     const X86RegisterInfo *RegInfo =
13373       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13374     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13375     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13376                        DAG.getNode(ISD::ADD, dl, PtrVT,
13377                                    FrameAddr, Offset),
13378                        MachinePointerInfo(), false, false, false, 0);
13379   }
13380
13381   // Just load the return address.
13382   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13383   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13384                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13385 }
13386
13387 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13388   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13389   MFI->setFrameAddressIsTaken(true);
13390
13391   EVT VT = Op.getValueType();
13392   SDLoc dl(Op);  // FIXME probably not meaningful
13393   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13394   const X86RegisterInfo *RegInfo =
13395     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13396   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13397   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13398           (FrameReg == X86::EBP && VT == MVT::i32)) &&
13399          "Invalid Frame Register!");
13400   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13401   while (Depth--)
13402     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13403                             MachinePointerInfo(),
13404                             false, false, false, 0);
13405   return FrameAddr;
13406 }
13407
13408 // FIXME? Maybe this could be a TableGen attribute on some registers and
13409 // this table could be generated automatically from RegInfo.
13410 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13411                                               EVT VT) const {
13412   unsigned Reg = StringSwitch<unsigned>(RegName)
13413                        .Case("esp", X86::ESP)
13414                        .Case("rsp", X86::RSP)
13415                        .Default(0);
13416   if (Reg)
13417     return Reg;
13418   report_fatal_error("Invalid register name global variable");
13419 }
13420
13421 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13422                                                      SelectionDAG &DAG) const {
13423   const X86RegisterInfo *RegInfo =
13424     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13425   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13426 }
13427
13428 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13429   SDValue Chain     = Op.getOperand(0);
13430   SDValue Offset    = Op.getOperand(1);
13431   SDValue Handler   = Op.getOperand(2);
13432   SDLoc dl      (Op);
13433
13434   EVT PtrVT = getPointerTy();
13435   const X86RegisterInfo *RegInfo =
13436     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13437   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13438   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13439           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13440          "Invalid Frame Register!");
13441   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13442   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13443
13444   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13445                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13446   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13447   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13448                        false, false, 0);
13449   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13450
13451   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13452                      DAG.getRegister(StoreAddrReg, PtrVT));
13453 }
13454
13455 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13456                                                SelectionDAG &DAG) const {
13457   SDLoc DL(Op);
13458   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13459                      DAG.getVTList(MVT::i32, MVT::Other),
13460                      Op.getOperand(0), Op.getOperand(1));
13461 }
13462
13463 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13464                                                 SelectionDAG &DAG) const {
13465   SDLoc DL(Op);
13466   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13467                      Op.getOperand(0), Op.getOperand(1));
13468 }
13469
13470 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13471   return Op.getOperand(0);
13472 }
13473
13474 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13475                                                 SelectionDAG &DAG) const {
13476   SDValue Root = Op.getOperand(0);
13477   SDValue Trmp = Op.getOperand(1); // trampoline
13478   SDValue FPtr = Op.getOperand(2); // nested function
13479   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13480   SDLoc dl (Op);
13481
13482   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13483   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13484
13485   if (Subtarget->is64Bit()) {
13486     SDValue OutChains[6];
13487
13488     // Large code-model.
13489     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
13490     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13491
13492     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13493     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13494
13495     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13496
13497     // Load the pointer to the nested function into R11.
13498     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13499     SDValue Addr = Trmp;
13500     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13501                                 Addr, MachinePointerInfo(TrmpAddr),
13502                                 false, false, 0);
13503
13504     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13505                        DAG.getConstant(2, MVT::i64));
13506     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13507                                 MachinePointerInfo(TrmpAddr, 2),
13508                                 false, false, 2);
13509
13510     // Load the 'nest' parameter value into R10.
13511     // R10 is specified in X86CallingConv.td
13512     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13513     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13514                        DAG.getConstant(10, MVT::i64));
13515     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13516                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13517                                 false, false, 0);
13518
13519     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13520                        DAG.getConstant(12, MVT::i64));
13521     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13522                                 MachinePointerInfo(TrmpAddr, 12),
13523                                 false, false, 2);
13524
13525     // Jump to the nested function.
13526     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13527     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13528                        DAG.getConstant(20, MVT::i64));
13529     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13530                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13531                                 false, false, 0);
13532
13533     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13534     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13535                        DAG.getConstant(22, MVT::i64));
13536     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13537                                 MachinePointerInfo(TrmpAddr, 22),
13538                                 false, false, 0);
13539
13540     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13541   } else {
13542     const Function *Func =
13543       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13544     CallingConv::ID CC = Func->getCallingConv();
13545     unsigned NestReg;
13546
13547     switch (CC) {
13548     default:
13549       llvm_unreachable("Unsupported calling convention");
13550     case CallingConv::C:
13551     case CallingConv::X86_StdCall: {
13552       // Pass 'nest' parameter in ECX.
13553       // Must be kept in sync with X86CallingConv.td
13554       NestReg = X86::ECX;
13555
13556       // Check that ECX wasn't needed by an 'inreg' parameter.
13557       FunctionType *FTy = Func->getFunctionType();
13558       const AttributeSet &Attrs = Func->getAttributes();
13559
13560       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13561         unsigned InRegCount = 0;
13562         unsigned Idx = 1;
13563
13564         for (FunctionType::param_iterator I = FTy->param_begin(),
13565              E = FTy->param_end(); I != E; ++I, ++Idx)
13566           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13567             // FIXME: should only count parameters that are lowered to integers.
13568             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13569
13570         if (InRegCount > 2) {
13571           report_fatal_error("Nest register in use - reduce number of inreg"
13572                              " parameters!");
13573         }
13574       }
13575       break;
13576     }
13577     case CallingConv::X86_FastCall:
13578     case CallingConv::X86_ThisCall:
13579     case CallingConv::Fast:
13580       // Pass 'nest' parameter in EAX.
13581       // Must be kept in sync with X86CallingConv.td
13582       NestReg = X86::EAX;
13583       break;
13584     }
13585
13586     SDValue OutChains[4];
13587     SDValue Addr, Disp;
13588
13589     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13590                        DAG.getConstant(10, MVT::i32));
13591     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13592
13593     // This is storing the opcode for MOV32ri.
13594     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13595     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13596     OutChains[0] = DAG.getStore(Root, dl,
13597                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13598                                 Trmp, MachinePointerInfo(TrmpAddr),
13599                                 false, false, 0);
13600
13601     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13602                        DAG.getConstant(1, MVT::i32));
13603     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13604                                 MachinePointerInfo(TrmpAddr, 1),
13605                                 false, false, 1);
13606
13607     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13608     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13609                        DAG.getConstant(5, MVT::i32));
13610     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13611                                 MachinePointerInfo(TrmpAddr, 5),
13612                                 false, false, 1);
13613
13614     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13615                        DAG.getConstant(6, MVT::i32));
13616     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13617                                 MachinePointerInfo(TrmpAddr, 6),
13618                                 false, false, 1);
13619
13620     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13621   }
13622 }
13623
13624 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13625                                             SelectionDAG &DAG) const {
13626   /*
13627    The rounding mode is in bits 11:10 of FPSR, and has the following
13628    settings:
13629      00 Round to nearest
13630      01 Round to -inf
13631      10 Round to +inf
13632      11 Round to 0
13633
13634   FLT_ROUNDS, on the other hand, expects the following:
13635     -1 Undefined
13636      0 Round to 0
13637      1 Round to nearest
13638      2 Round to +inf
13639      3 Round to -inf
13640
13641   To perform the conversion, we do:
13642     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13643   */
13644
13645   MachineFunction &MF = DAG.getMachineFunction();
13646   const TargetMachine &TM = MF.getTarget();
13647   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13648   unsigned StackAlignment = TFI.getStackAlignment();
13649   MVT VT = Op.getSimpleValueType();
13650   SDLoc DL(Op);
13651
13652   // Save FP Control Word to stack slot
13653   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13654   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13655
13656   MachineMemOperand *MMO =
13657    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13658                            MachineMemOperand::MOStore, 2, 2);
13659
13660   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13661   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13662                                           DAG.getVTList(MVT::Other),
13663                                           Ops, MVT::i16, MMO);
13664
13665   // Load FP Control Word from stack slot
13666   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13667                             MachinePointerInfo(), false, false, false, 0);
13668
13669   // Transform as necessary
13670   SDValue CWD1 =
13671     DAG.getNode(ISD::SRL, DL, MVT::i16,
13672                 DAG.getNode(ISD::AND, DL, MVT::i16,
13673                             CWD, DAG.getConstant(0x800, MVT::i16)),
13674                 DAG.getConstant(11, MVT::i8));
13675   SDValue CWD2 =
13676     DAG.getNode(ISD::SRL, DL, MVT::i16,
13677                 DAG.getNode(ISD::AND, DL, MVT::i16,
13678                             CWD, DAG.getConstant(0x400, MVT::i16)),
13679                 DAG.getConstant(9, MVT::i8));
13680
13681   SDValue RetVal =
13682     DAG.getNode(ISD::AND, DL, MVT::i16,
13683                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13684                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13685                             DAG.getConstant(1, MVT::i16)),
13686                 DAG.getConstant(3, MVT::i16));
13687
13688   return DAG.getNode((VT.getSizeInBits() < 16 ?
13689                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13690 }
13691
13692 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13693   MVT VT = Op.getSimpleValueType();
13694   EVT OpVT = VT;
13695   unsigned NumBits = VT.getSizeInBits();
13696   SDLoc dl(Op);
13697
13698   Op = Op.getOperand(0);
13699   if (VT == MVT::i8) {
13700     // Zero extend to i32 since there is not an i8 bsr.
13701     OpVT = MVT::i32;
13702     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13703   }
13704
13705   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13706   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13707   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13708
13709   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13710   SDValue Ops[] = {
13711     Op,
13712     DAG.getConstant(NumBits+NumBits-1, OpVT),
13713     DAG.getConstant(X86::COND_E, MVT::i8),
13714     Op.getValue(1)
13715   };
13716   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13717
13718   // Finally xor with NumBits-1.
13719   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13720
13721   if (VT == MVT::i8)
13722     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13723   return Op;
13724 }
13725
13726 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13727   MVT VT = Op.getSimpleValueType();
13728   EVT OpVT = VT;
13729   unsigned NumBits = VT.getSizeInBits();
13730   SDLoc dl(Op);
13731
13732   Op = Op.getOperand(0);
13733   if (VT == MVT::i8) {
13734     // Zero extend to i32 since there is not an i8 bsr.
13735     OpVT = MVT::i32;
13736     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13737   }
13738
13739   // Issue a bsr (scan bits in reverse).
13740   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13741   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13742
13743   // And xor with NumBits-1.
13744   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13745
13746   if (VT == MVT::i8)
13747     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13748   return Op;
13749 }
13750
13751 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13752   MVT VT = Op.getSimpleValueType();
13753   unsigned NumBits = VT.getSizeInBits();
13754   SDLoc dl(Op);
13755   Op = Op.getOperand(0);
13756
13757   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13758   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13759   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13760
13761   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13762   SDValue Ops[] = {
13763     Op,
13764     DAG.getConstant(NumBits, VT),
13765     DAG.getConstant(X86::COND_E, MVT::i8),
13766     Op.getValue(1)
13767   };
13768   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13769 }
13770
13771 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13772 // ones, and then concatenate the result back.
13773 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13774   MVT VT = Op.getSimpleValueType();
13775
13776   assert(VT.is256BitVector() && VT.isInteger() &&
13777          "Unsupported value type for operation");
13778
13779   unsigned NumElems = VT.getVectorNumElements();
13780   SDLoc dl(Op);
13781
13782   // Extract the LHS vectors
13783   SDValue LHS = Op.getOperand(0);
13784   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13785   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13786
13787   // Extract the RHS vectors
13788   SDValue RHS = Op.getOperand(1);
13789   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13790   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13791
13792   MVT EltVT = VT.getVectorElementType();
13793   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13794
13795   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13796                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13797                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13798 }
13799
13800 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13801   assert(Op.getSimpleValueType().is256BitVector() &&
13802          Op.getSimpleValueType().isInteger() &&
13803          "Only handle AVX 256-bit vector integer operation");
13804   return Lower256IntArith(Op, DAG);
13805 }
13806
13807 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13808   assert(Op.getSimpleValueType().is256BitVector() &&
13809          Op.getSimpleValueType().isInteger() &&
13810          "Only handle AVX 256-bit vector integer operation");
13811   return Lower256IntArith(Op, DAG);
13812 }
13813
13814 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13815                         SelectionDAG &DAG) {
13816   SDLoc dl(Op);
13817   MVT VT = Op.getSimpleValueType();
13818
13819   // Decompose 256-bit ops into smaller 128-bit ops.
13820   if (VT.is256BitVector() && !Subtarget->hasInt256())
13821     return Lower256IntArith(Op, DAG);
13822
13823   SDValue A = Op.getOperand(0);
13824   SDValue B = Op.getOperand(1);
13825
13826   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13827   if (VT == MVT::v4i32) {
13828     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13829            "Should not custom lower when pmuldq is available!");
13830
13831     // Extract the odd parts.
13832     static const int UnpackMask[] = { 1, -1, 3, -1 };
13833     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13834     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13835
13836     // Multiply the even parts.
13837     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13838     // Now multiply odd parts.
13839     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13840
13841     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13842     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13843
13844     // Merge the two vectors back together with a shuffle. This expands into 2
13845     // shuffles.
13846     static const int ShufMask[] = { 0, 4, 2, 6 };
13847     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13848   }
13849
13850   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13851          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13852
13853   //  Ahi = psrlqi(a, 32);
13854   //  Bhi = psrlqi(b, 32);
13855   //
13856   //  AloBlo = pmuludq(a, b);
13857   //  AloBhi = pmuludq(a, Bhi);
13858   //  AhiBlo = pmuludq(Ahi, b);
13859
13860   //  AloBhi = psllqi(AloBhi, 32);
13861   //  AhiBlo = psllqi(AhiBlo, 32);
13862   //  return AloBlo + AloBhi + AhiBlo;
13863
13864   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13865   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13866
13867   // Bit cast to 32-bit vectors for MULUDQ
13868   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13869                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13870   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13871   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13872   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13873   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13874
13875   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13876   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13877   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13878
13879   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13880   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13881
13882   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13883   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13884 }
13885
13886 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13887   assert(Subtarget->isTargetWin64() && "Unexpected target");
13888   EVT VT = Op.getValueType();
13889   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13890          "Unexpected return type for lowering");
13891
13892   RTLIB::Libcall LC;
13893   bool isSigned;
13894   switch (Op->getOpcode()) {
13895   default: llvm_unreachable("Unexpected request for libcall!");
13896   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13897   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13898   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13899   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13900   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13901   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13902   }
13903
13904   SDLoc dl(Op);
13905   SDValue InChain = DAG.getEntryNode();
13906
13907   TargetLowering::ArgListTy Args;
13908   TargetLowering::ArgListEntry Entry;
13909   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13910     EVT ArgVT = Op->getOperand(i).getValueType();
13911     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13912            "Unexpected argument type for lowering");
13913     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13914     Entry.Node = StackPtr;
13915     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13916                            false, false, 16);
13917     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13918     Entry.Ty = PointerType::get(ArgTy,0);
13919     Entry.isSExt = false;
13920     Entry.isZExt = false;
13921     Args.push_back(Entry);
13922   }
13923
13924   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13925                                          getPointerTy());
13926
13927   TargetLowering::CallLoweringInfo CLI(DAG);
13928   CLI.setDebugLoc(dl).setChain(InChain)
13929     .setCallee(getLibcallCallingConv(LC),
13930                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13931                Callee, &Args, 0)
13932     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13933
13934   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13935   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13936 }
13937
13938 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13939                              SelectionDAG &DAG) {
13940   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13941   EVT VT = Op0.getValueType();
13942   SDLoc dl(Op);
13943
13944   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13945          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13946
13947   // Get the high parts.
13948   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13949   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13950   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13951
13952   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13953   // ints.
13954   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13955   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13956   unsigned Opcode =
13957       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13958   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13959                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13960   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13961                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13962
13963   // Shuffle it back into the right order.
13964   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13965   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13966   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13967   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13968
13969   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13970   // unsigned multiply.
13971   if (IsSigned && !Subtarget->hasSSE41()) {
13972     SDValue ShAmt =
13973         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13974     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13975                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13976     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13977                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13978
13979     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13980     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13981   }
13982
13983   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13984 }
13985
13986 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13987                                          const X86Subtarget *Subtarget) {
13988   MVT VT = Op.getSimpleValueType();
13989   SDLoc dl(Op);
13990   SDValue R = Op.getOperand(0);
13991   SDValue Amt = Op.getOperand(1);
13992
13993   // Optimize shl/srl/sra with constant shift amount.
13994   if (isSplatVector(Amt.getNode())) {
13995     SDValue SclrAmt = Amt->getOperand(0);
13996     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13997       uint64_t ShiftAmt = C->getZExtValue();
13998
13999       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
14000           (Subtarget->hasInt256() &&
14001            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14002           (Subtarget->hasAVX512() &&
14003            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14004         if (Op.getOpcode() == ISD::SHL)
14005           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14006                                             DAG);
14007         if (Op.getOpcode() == ISD::SRL)
14008           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14009                                             DAG);
14010         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
14011           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14012                                             DAG);
14013       }
14014
14015       if (VT == MVT::v16i8) {
14016         if (Op.getOpcode() == ISD::SHL) {
14017           // Make a large shift.
14018           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
14019                                                    MVT::v8i16, R, ShiftAmt,
14020                                                    DAG);
14021           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
14022           // Zero out the rightmost bits.
14023           SmallVector<SDValue, 16> V(16,
14024                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
14025                                                      MVT::i8));
14026           return DAG.getNode(ISD::AND, dl, VT, SHL,
14027                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14028         }
14029         if (Op.getOpcode() == ISD::SRL) {
14030           // Make a large shift.
14031           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
14032                                                    MVT::v8i16, R, ShiftAmt,
14033                                                    DAG);
14034           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
14035           // Zero out the leftmost bits.
14036           SmallVector<SDValue, 16> V(16,
14037                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
14038                                                      MVT::i8));
14039           return DAG.getNode(ISD::AND, dl, VT, SRL,
14040                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14041         }
14042         if (Op.getOpcode() == ISD::SRA) {
14043           if (ShiftAmt == 7) {
14044             // R s>> 7  ===  R s< 0
14045             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14046             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
14047           }
14048
14049           // R s>> a === ((R u>> a) ^ m) - m
14050           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
14051           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
14052                                                          MVT::i8));
14053           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
14054           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
14055           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
14056           return Res;
14057         }
14058         llvm_unreachable("Unknown shift opcode.");
14059       }
14060
14061       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
14062         if (Op.getOpcode() == ISD::SHL) {
14063           // Make a large shift.
14064           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
14065                                                    MVT::v16i16, R, ShiftAmt,
14066                                                    DAG);
14067           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
14068           // Zero out the rightmost bits.
14069           SmallVector<SDValue, 32> V(32,
14070                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
14071                                                      MVT::i8));
14072           return DAG.getNode(ISD::AND, dl, VT, SHL,
14073                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14074         }
14075         if (Op.getOpcode() == ISD::SRL) {
14076           // Make a large shift.
14077           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
14078                                                    MVT::v16i16, R, ShiftAmt,
14079                                                    DAG);
14080           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
14081           // Zero out the leftmost bits.
14082           SmallVector<SDValue, 32> V(32,
14083                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
14084                                                      MVT::i8));
14085           return DAG.getNode(ISD::AND, dl, VT, SRL,
14086                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
14087         }
14088         if (Op.getOpcode() == ISD::SRA) {
14089           if (ShiftAmt == 7) {
14090             // R s>> 7  ===  R s< 0
14091             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
14092             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
14093           }
14094
14095           // R s>> a === ((R u>> a) ^ m) - m
14096           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
14097           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
14098                                                          MVT::i8));
14099           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
14100           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
14101           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
14102           return Res;
14103         }
14104         llvm_unreachable("Unknown shift opcode.");
14105       }
14106     }
14107   }
14108
14109   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14110   if (!Subtarget->is64Bit() &&
14111       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
14112       Amt.getOpcode() == ISD::BITCAST &&
14113       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14114     Amt = Amt.getOperand(0);
14115     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14116                      VT.getVectorNumElements();
14117     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
14118     uint64_t ShiftAmt = 0;
14119     for (unsigned i = 0; i != Ratio; ++i) {
14120       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
14121       if (!C)
14122         return SDValue();
14123       // 6 == Log2(64)
14124       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
14125     }
14126     // Check remaining shift amounts.
14127     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14128       uint64_t ShAmt = 0;
14129       for (unsigned j = 0; j != Ratio; ++j) {
14130         ConstantSDNode *C =
14131           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
14132         if (!C)
14133           return SDValue();
14134         // 6 == Log2(64)
14135         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
14136       }
14137       if (ShAmt != ShiftAmt)
14138         return SDValue();
14139     }
14140     switch (Op.getOpcode()) {
14141     default:
14142       llvm_unreachable("Unknown shift opcode!");
14143     case ISD::SHL:
14144       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14145                                         DAG);
14146     case ISD::SRL:
14147       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14148                                         DAG);
14149     case ISD::SRA:
14150       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14151                                         DAG);
14152     }
14153   }
14154
14155   return SDValue();
14156 }
14157
14158 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
14159                                         const X86Subtarget* Subtarget) {
14160   MVT VT = Op.getSimpleValueType();
14161   SDLoc dl(Op);
14162   SDValue R = Op.getOperand(0);
14163   SDValue Amt = Op.getOperand(1);
14164
14165   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
14166       VT == MVT::v4i32 || VT == MVT::v8i16 ||
14167       (Subtarget->hasInt256() &&
14168        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
14169         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14170        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14171     SDValue BaseShAmt;
14172     EVT EltVT = VT.getVectorElementType();
14173
14174     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14175       unsigned NumElts = VT.getVectorNumElements();
14176       unsigned i, j;
14177       for (i = 0; i != NumElts; ++i) {
14178         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
14179           continue;
14180         break;
14181       }
14182       for (j = i; j != NumElts; ++j) {
14183         SDValue Arg = Amt.getOperand(j);
14184         if (Arg.getOpcode() == ISD::UNDEF) continue;
14185         if (Arg != Amt.getOperand(i))
14186           break;
14187       }
14188       if (i != NumElts && j == NumElts)
14189         BaseShAmt = Amt.getOperand(i);
14190     } else {
14191       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14192         Amt = Amt.getOperand(0);
14193       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
14194                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
14195         SDValue InVec = Amt.getOperand(0);
14196         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14197           unsigned NumElts = InVec.getValueType().getVectorNumElements();
14198           unsigned i = 0;
14199           for (; i != NumElts; ++i) {
14200             SDValue Arg = InVec.getOperand(i);
14201             if (Arg.getOpcode() == ISD::UNDEF) continue;
14202             BaseShAmt = Arg;
14203             break;
14204           }
14205         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14206            if (ConstantSDNode *C =
14207                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14208              unsigned SplatIdx =
14209                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
14210              if (C->getZExtValue() == SplatIdx)
14211                BaseShAmt = InVec.getOperand(1);
14212            }
14213         }
14214         if (!BaseShAmt.getNode())
14215           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
14216                                   DAG.getIntPtrConstant(0));
14217       }
14218     }
14219
14220     if (BaseShAmt.getNode()) {
14221       if (EltVT.bitsGT(MVT::i32))
14222         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
14223       else if (EltVT.bitsLT(MVT::i32))
14224         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
14225
14226       switch (Op.getOpcode()) {
14227       default:
14228         llvm_unreachable("Unknown shift opcode!");
14229       case ISD::SHL:
14230         switch (VT.SimpleTy) {
14231         default: return SDValue();
14232         case MVT::v2i64:
14233         case MVT::v4i32:
14234         case MVT::v8i16:
14235         case MVT::v4i64:
14236         case MVT::v8i32:
14237         case MVT::v16i16:
14238         case MVT::v16i32:
14239         case MVT::v8i64:
14240           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
14241         }
14242       case ISD::SRA:
14243         switch (VT.SimpleTy) {
14244         default: return SDValue();
14245         case MVT::v4i32:
14246         case MVT::v8i16:
14247         case MVT::v8i32:
14248         case MVT::v16i16:
14249         case MVT::v16i32:
14250         case MVT::v8i64:
14251           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
14252         }
14253       case ISD::SRL:
14254         switch (VT.SimpleTy) {
14255         default: return SDValue();
14256         case MVT::v2i64:
14257         case MVT::v4i32:
14258         case MVT::v8i16:
14259         case MVT::v4i64:
14260         case MVT::v8i32:
14261         case MVT::v16i16:
14262         case MVT::v16i32:
14263         case MVT::v8i64:
14264           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
14265         }
14266       }
14267     }
14268   }
14269
14270   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14271   if (!Subtarget->is64Bit() &&
14272       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
14273       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
14274       Amt.getOpcode() == ISD::BITCAST &&
14275       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14276     Amt = Amt.getOperand(0);
14277     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14278                      VT.getVectorNumElements();
14279     std::vector<SDValue> Vals(Ratio);
14280     for (unsigned i = 0; i != Ratio; ++i)
14281       Vals[i] = Amt.getOperand(i);
14282     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14283       for (unsigned j = 0; j != Ratio; ++j)
14284         if (Vals[j] != Amt.getOperand(i + j))
14285           return SDValue();
14286     }
14287     switch (Op.getOpcode()) {
14288     default:
14289       llvm_unreachable("Unknown shift opcode!");
14290     case ISD::SHL:
14291       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14292     case ISD::SRL:
14293       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14294     case ISD::SRA:
14295       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14296     }
14297   }
14298
14299   return SDValue();
14300 }
14301
14302 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14303                           SelectionDAG &DAG) {
14304
14305   MVT VT = Op.getSimpleValueType();
14306   SDLoc dl(Op);
14307   SDValue R = Op.getOperand(0);
14308   SDValue Amt = Op.getOperand(1);
14309   SDValue V;
14310
14311   if (!Subtarget->hasSSE2())
14312     return SDValue();
14313
14314   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14315   if (V.getNode())
14316     return V;
14317
14318   V = LowerScalarVariableShift(Op, DAG, Subtarget);
14319   if (V.getNode())
14320       return V;
14321
14322   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14323     return Op;
14324   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14325   if (Subtarget->hasInt256()) {
14326     if (Op.getOpcode() == ISD::SRL &&
14327         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14328          VT == MVT::v4i64 || VT == MVT::v8i32))
14329       return Op;
14330     if (Op.getOpcode() == ISD::SHL &&
14331         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14332          VT == MVT::v4i64 || VT == MVT::v8i32))
14333       return Op;
14334     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14335       return Op;
14336   }
14337
14338   // If possible, lower this packed shift into a vector multiply instead of
14339   // expanding it into a sequence of scalar shifts.
14340   // Do this only if the vector shift count is a constant build_vector.
14341   if (Op.getOpcode() == ISD::SHL && 
14342       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14343        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14344       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14345     SmallVector<SDValue, 8> Elts;
14346     EVT SVT = VT.getScalarType();
14347     unsigned SVTBits = SVT.getSizeInBits();
14348     const APInt &One = APInt(SVTBits, 1);
14349     unsigned NumElems = VT.getVectorNumElements();
14350
14351     for (unsigned i=0; i !=NumElems; ++i) {
14352       SDValue Op = Amt->getOperand(i);
14353       if (Op->getOpcode() == ISD::UNDEF) {
14354         Elts.push_back(Op);
14355         continue;
14356       }
14357
14358       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14359       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14360       uint64_t ShAmt = C.getZExtValue();
14361       if (ShAmt >= SVTBits) {
14362         Elts.push_back(DAG.getUNDEF(SVT));
14363         continue;
14364       }
14365       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14366     }
14367     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14368     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14369   }
14370
14371   // Lower SHL with variable shift amount.
14372   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14373     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14374
14375     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14376     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14377     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14378     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14379   }
14380
14381   // If possible, lower this shift as a sequence of two shifts by
14382   // constant plus a MOVSS/MOVSD instead of scalarizing it.
14383   // Example:
14384   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14385   //
14386   // Could be rewritten as:
14387   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14388   //
14389   // The advantage is that the two shifts from the example would be
14390   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14391   // the vector shift into four scalar shifts plus four pairs of vector
14392   // insert/extract.
14393   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14394       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14395     unsigned TargetOpcode = X86ISD::MOVSS;
14396     bool CanBeSimplified;
14397     // The splat value for the first packed shift (the 'X' from the example).
14398     SDValue Amt1 = Amt->getOperand(0);
14399     // The splat value for the second packed shift (the 'Y' from the example).
14400     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14401                                         Amt->getOperand(2);
14402
14403     // See if it is possible to replace this node with a sequence of
14404     // two shifts followed by a MOVSS/MOVSD
14405     if (VT == MVT::v4i32) {
14406       // Check if it is legal to use a MOVSS.
14407       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14408                         Amt2 == Amt->getOperand(3);
14409       if (!CanBeSimplified) {
14410         // Otherwise, check if we can still simplify this node using a MOVSD.
14411         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14412                           Amt->getOperand(2) == Amt->getOperand(3);
14413         TargetOpcode = X86ISD::MOVSD;
14414         Amt2 = Amt->getOperand(2);
14415       }
14416     } else {
14417       // Do similar checks for the case where the machine value type
14418       // is MVT::v8i16.
14419       CanBeSimplified = Amt1 == Amt->getOperand(1);
14420       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14421         CanBeSimplified = Amt2 == Amt->getOperand(i);
14422
14423       if (!CanBeSimplified) {
14424         TargetOpcode = X86ISD::MOVSD;
14425         CanBeSimplified = true;
14426         Amt2 = Amt->getOperand(4);
14427         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14428           CanBeSimplified = Amt1 == Amt->getOperand(i);
14429         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14430           CanBeSimplified = Amt2 == Amt->getOperand(j);
14431       }
14432     }
14433     
14434     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14435         isa<ConstantSDNode>(Amt2)) {
14436       // Replace this node with two shifts followed by a MOVSS/MOVSD.
14437       EVT CastVT = MVT::v4i32;
14438       SDValue Splat1 = 
14439         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14440       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14441       SDValue Splat2 = 
14442         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14443       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14444       if (TargetOpcode == X86ISD::MOVSD)
14445         CastVT = MVT::v2i64;
14446       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14447       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14448       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14449                                             BitCast1, DAG);
14450       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14451     }
14452   }
14453
14454   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14455     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14456
14457     // a = a << 5;
14458     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14459     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14460
14461     // Turn 'a' into a mask suitable for VSELECT
14462     SDValue VSelM = DAG.getConstant(0x80, VT);
14463     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14464     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14465
14466     SDValue CM1 = DAG.getConstant(0x0f, VT);
14467     SDValue CM2 = DAG.getConstant(0x3f, VT);
14468
14469     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14470     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14471     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14472     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14473     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14474
14475     // a += a
14476     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14477     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14478     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14479
14480     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14481     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14482     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14483     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14484     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14485
14486     // a += a
14487     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14488     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14489     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14490
14491     // return VSELECT(r, r+r, a);
14492     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14493                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14494     return R;
14495   }
14496
14497   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14498   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14499   // solution better.
14500   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14501     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14502     unsigned ExtOpc =
14503         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14504     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14505     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14506     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14507                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14508     }
14509
14510   // Decompose 256-bit shifts into smaller 128-bit shifts.
14511   if (VT.is256BitVector()) {
14512     unsigned NumElems = VT.getVectorNumElements();
14513     MVT EltVT = VT.getVectorElementType();
14514     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14515
14516     // Extract the two vectors
14517     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14518     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14519
14520     // Recreate the shift amount vectors
14521     SDValue Amt1, Amt2;
14522     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14523       // Constant shift amount
14524       SmallVector<SDValue, 4> Amt1Csts;
14525       SmallVector<SDValue, 4> Amt2Csts;
14526       for (unsigned i = 0; i != NumElems/2; ++i)
14527         Amt1Csts.push_back(Amt->getOperand(i));
14528       for (unsigned i = NumElems/2; i != NumElems; ++i)
14529         Amt2Csts.push_back(Amt->getOperand(i));
14530
14531       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14532       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14533     } else {
14534       // Variable shift amount
14535       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14536       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14537     }
14538
14539     // Issue new vector shifts for the smaller types
14540     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14541     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14542
14543     // Concatenate the result back
14544     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14545   }
14546
14547   return SDValue();
14548 }
14549
14550 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14551   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14552   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14553   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14554   // has only one use.
14555   SDNode *N = Op.getNode();
14556   SDValue LHS = N->getOperand(0);
14557   SDValue RHS = N->getOperand(1);
14558   unsigned BaseOp = 0;
14559   unsigned Cond = 0;
14560   SDLoc DL(Op);
14561   switch (Op.getOpcode()) {
14562   default: llvm_unreachable("Unknown ovf instruction!");
14563   case ISD::SADDO:
14564     // A subtract of one will be selected as a INC. Note that INC doesn't
14565     // set CF, so we can't do this for UADDO.
14566     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14567       if (C->isOne()) {
14568         BaseOp = X86ISD::INC;
14569         Cond = X86::COND_O;
14570         break;
14571       }
14572     BaseOp = X86ISD::ADD;
14573     Cond = X86::COND_O;
14574     break;
14575   case ISD::UADDO:
14576     BaseOp = X86ISD::ADD;
14577     Cond = X86::COND_B;
14578     break;
14579   case ISD::SSUBO:
14580     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14581     // set CF, so we can't do this for USUBO.
14582     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14583       if (C->isOne()) {
14584         BaseOp = X86ISD::DEC;
14585         Cond = X86::COND_O;
14586         break;
14587       }
14588     BaseOp = X86ISD::SUB;
14589     Cond = X86::COND_O;
14590     break;
14591   case ISD::USUBO:
14592     BaseOp = X86ISD::SUB;
14593     Cond = X86::COND_B;
14594     break;
14595   case ISD::SMULO:
14596     BaseOp = X86ISD::SMUL;
14597     Cond = X86::COND_O;
14598     break;
14599   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14600     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14601                                  MVT::i32);
14602     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14603
14604     SDValue SetCC =
14605       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14606                   DAG.getConstant(X86::COND_O, MVT::i32),
14607                   SDValue(Sum.getNode(), 2));
14608
14609     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14610   }
14611   }
14612
14613   // Also sets EFLAGS.
14614   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14615   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14616
14617   SDValue SetCC =
14618     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14619                 DAG.getConstant(Cond, MVT::i32),
14620                 SDValue(Sum.getNode(), 1));
14621
14622   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14623 }
14624
14625 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14626                                                   SelectionDAG &DAG) const {
14627   SDLoc dl(Op);
14628   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14629   MVT VT = Op.getSimpleValueType();
14630
14631   if (!Subtarget->hasSSE2() || !VT.isVector())
14632     return SDValue();
14633
14634   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14635                       ExtraVT.getScalarType().getSizeInBits();
14636
14637   switch (VT.SimpleTy) {
14638     default: return SDValue();
14639     case MVT::v8i32:
14640     case MVT::v16i16:
14641       if (!Subtarget->hasFp256())
14642         return SDValue();
14643       if (!Subtarget->hasInt256()) {
14644         // needs to be split
14645         unsigned NumElems = VT.getVectorNumElements();
14646
14647         // Extract the LHS vectors
14648         SDValue LHS = Op.getOperand(0);
14649         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14650         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14651
14652         MVT EltVT = VT.getVectorElementType();
14653         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14654
14655         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14656         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14657         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14658                                    ExtraNumElems/2);
14659         SDValue Extra = DAG.getValueType(ExtraVT);
14660
14661         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14662         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14663
14664         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14665       }
14666       // fall through
14667     case MVT::v4i32:
14668     case MVT::v8i16: {
14669       SDValue Op0 = Op.getOperand(0);
14670       SDValue Op00 = Op0.getOperand(0);
14671       SDValue Tmp1;
14672       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14673       if (Op0.getOpcode() == ISD::BITCAST &&
14674           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14675         // (sext (vzext x)) -> (vsext x)
14676         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14677         if (Tmp1.getNode()) {
14678           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14679           // This folding is only valid when the in-reg type is a vector of i8,
14680           // i16, or i32.
14681           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14682               ExtraEltVT == MVT::i32) {
14683             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14684             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14685                    "This optimization is invalid without a VZEXT.");
14686             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14687           }
14688           Op0 = Tmp1;
14689         }
14690       }
14691
14692       // If the above didn't work, then just use Shift-Left + Shift-Right.
14693       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14694                                         DAG);
14695       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14696                                         DAG);
14697     }
14698   }
14699 }
14700
14701 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14702                                  SelectionDAG &DAG) {
14703   SDLoc dl(Op);
14704   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14705     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14706   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14707     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14708
14709   // The only fence that needs an instruction is a sequentially-consistent
14710   // cross-thread fence.
14711   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14712     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14713     // no-sse2). There isn't any reason to disable it if the target processor
14714     // supports it.
14715     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14716       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14717
14718     SDValue Chain = Op.getOperand(0);
14719     SDValue Zero = DAG.getConstant(0, MVT::i32);
14720     SDValue Ops[] = {
14721       DAG.getRegister(X86::ESP, MVT::i32), // Base
14722       DAG.getTargetConstant(1, MVT::i8),   // Scale
14723       DAG.getRegister(0, MVT::i32),        // Index
14724       DAG.getTargetConstant(0, MVT::i32),  // Disp
14725       DAG.getRegister(0, MVT::i32),        // Segment.
14726       Zero,
14727       Chain
14728     };
14729     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14730     return SDValue(Res, 0);
14731   }
14732
14733   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14734   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14735 }
14736
14737 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14738                              SelectionDAG &DAG) {
14739   MVT T = Op.getSimpleValueType();
14740   SDLoc DL(Op);
14741   unsigned Reg = 0;
14742   unsigned size = 0;
14743   switch(T.SimpleTy) {
14744   default: llvm_unreachable("Invalid value type!");
14745   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14746   case MVT::i16: Reg = X86::AX;  size = 2; break;
14747   case MVT::i32: Reg = X86::EAX; size = 4; break;
14748   case MVT::i64:
14749     assert(Subtarget->is64Bit() && "Node not type legal!");
14750     Reg = X86::RAX; size = 8;
14751     break;
14752   }
14753   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14754                                   Op.getOperand(2), SDValue());
14755   SDValue Ops[] = { cpIn.getValue(0),
14756                     Op.getOperand(1),
14757                     Op.getOperand(3),
14758                     DAG.getTargetConstant(size, MVT::i8),
14759                     cpIn.getValue(1) };
14760   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14761   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14762   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14763                                            Ops, T, MMO);
14764
14765   SDValue cpOut =
14766     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14767   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
14768                                       MVT::i32, cpOut.getValue(2));
14769   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
14770                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
14771
14772   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
14773   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
14774   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
14775   return SDValue();
14776 }
14777
14778 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14779                             SelectionDAG &DAG) {
14780   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14781   MVT DstVT = Op.getSimpleValueType();
14782
14783   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14784     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14785     if (DstVT != MVT::f64)
14786       // This conversion needs to be expanded.
14787       return SDValue();
14788
14789     SDValue InVec = Op->getOperand(0);
14790     SDLoc dl(Op);
14791     unsigned NumElts = SrcVT.getVectorNumElements();
14792     EVT SVT = SrcVT.getVectorElementType();
14793
14794     // Widen the vector in input in the case of MVT::v2i32.
14795     // Example: from MVT::v2i32 to MVT::v4i32.
14796     SmallVector<SDValue, 16> Elts;
14797     for (unsigned i = 0, e = NumElts; i != e; ++i)
14798       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14799                                  DAG.getIntPtrConstant(i)));
14800
14801     // Explicitly mark the extra elements as Undef.
14802     SDValue Undef = DAG.getUNDEF(SVT);
14803     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14804       Elts.push_back(Undef);
14805
14806     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14807     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14808     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14809     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14810                        DAG.getIntPtrConstant(0));
14811   }
14812
14813   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14814          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14815   assert((DstVT == MVT::i64 ||
14816           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14817          "Unexpected custom BITCAST");
14818   // i64 <=> MMX conversions are Legal.
14819   if (SrcVT==MVT::i64 && DstVT.isVector())
14820     return Op;
14821   if (DstVT==MVT::i64 && SrcVT.isVector())
14822     return Op;
14823   // MMX <=> MMX conversions are Legal.
14824   if (SrcVT.isVector() && DstVT.isVector())
14825     return Op;
14826   // All other conversions need to be expanded.
14827   return SDValue();
14828 }
14829
14830 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14831   SDNode *Node = Op.getNode();
14832   SDLoc dl(Node);
14833   EVT T = Node->getValueType(0);
14834   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14835                               DAG.getConstant(0, T), Node->getOperand(2));
14836   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14837                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14838                        Node->getOperand(0),
14839                        Node->getOperand(1), negOp,
14840                        cast<AtomicSDNode>(Node)->getMemOperand(),
14841                        cast<AtomicSDNode>(Node)->getOrdering(),
14842                        cast<AtomicSDNode>(Node)->getSynchScope());
14843 }
14844
14845 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14846   SDNode *Node = Op.getNode();
14847   SDLoc dl(Node);
14848   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14849
14850   // Convert seq_cst store -> xchg
14851   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14852   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14853   //        (The only way to get a 16-byte store is cmpxchg16b)
14854   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14855   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14856       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14857     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14858                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14859                                  Node->getOperand(0),
14860                                  Node->getOperand(1), Node->getOperand(2),
14861                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14862                                  cast<AtomicSDNode>(Node)->getOrdering(),
14863                                  cast<AtomicSDNode>(Node)->getSynchScope());
14864     return Swap.getValue(1);
14865   }
14866   // Other atomic stores have a simple pattern.
14867   return Op;
14868 }
14869
14870 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14871   EVT VT = Op.getNode()->getSimpleValueType(0);
14872
14873   // Let legalize expand this if it isn't a legal type yet.
14874   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14875     return SDValue();
14876
14877   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14878
14879   unsigned Opc;
14880   bool ExtraOp = false;
14881   switch (Op.getOpcode()) {
14882   default: llvm_unreachable("Invalid code");
14883   case ISD::ADDC: Opc = X86ISD::ADD; break;
14884   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14885   case ISD::SUBC: Opc = X86ISD::SUB; break;
14886   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14887   }
14888
14889   if (!ExtraOp)
14890     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14891                        Op.getOperand(1));
14892   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14893                      Op.getOperand(1), Op.getOperand(2));
14894 }
14895
14896 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14897                             SelectionDAG &DAG) {
14898   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14899
14900   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14901   // which returns the values as { float, float } (in XMM0) or
14902   // { double, double } (which is returned in XMM0, XMM1).
14903   SDLoc dl(Op);
14904   SDValue Arg = Op.getOperand(0);
14905   EVT ArgVT = Arg.getValueType();
14906   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14907
14908   TargetLowering::ArgListTy Args;
14909   TargetLowering::ArgListEntry Entry;
14910
14911   Entry.Node = Arg;
14912   Entry.Ty = ArgTy;
14913   Entry.isSExt = false;
14914   Entry.isZExt = false;
14915   Args.push_back(Entry);
14916
14917   bool isF64 = ArgVT == MVT::f64;
14918   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14919   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14920   // the results are returned via SRet in memory.
14921   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14922   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14923   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14924
14925   Type *RetTy = isF64
14926     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14927     : (Type*)VectorType::get(ArgTy, 4);
14928
14929   TargetLowering::CallLoweringInfo CLI(DAG);
14930   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14931     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14932
14933   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14934
14935   if (isF64)
14936     // Returned in xmm0 and xmm1.
14937     return CallResult.first;
14938
14939   // Returned in bits 0:31 and 32:64 xmm0.
14940   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14941                                CallResult.first, DAG.getIntPtrConstant(0));
14942   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14943                                CallResult.first, DAG.getIntPtrConstant(1));
14944   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14945   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14946 }
14947
14948 /// LowerOperation - Provide custom lowering hooks for some operations.
14949 ///
14950 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14951   switch (Op.getOpcode()) {
14952   default: llvm_unreachable("Should not custom lower this!");
14953   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14954   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14955   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
14956     return LowerCMP_SWAP(Op, Subtarget, DAG);
14957   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14958   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14959   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14960   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14961   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14962   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14963   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14964   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14965   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14966   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14967   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14968   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14969   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14970   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14971   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14972   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14973   case ISD::SHL_PARTS:
14974   case ISD::SRA_PARTS:
14975   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14976   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14977   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14978   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14979   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14980   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14981   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14982   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14983   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14984   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14985   case ISD::FABS:               return LowerFABS(Op, DAG);
14986   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14987   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14988   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14989   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14990   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14991   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14992   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14993   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14994   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14995   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14996   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14997   case ISD::INTRINSIC_VOID:
14998   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14999   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
15000   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
15001   case ISD::FRAME_TO_ARGS_OFFSET:
15002                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
15003   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
15004   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
15005   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
15006   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
15007   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
15008   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
15009   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
15010   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
15011   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
15012   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
15013   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
15014   case ISD::UMUL_LOHI:
15015   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
15016   case ISD::SRA:
15017   case ISD::SRL:
15018   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
15019   case ISD::SADDO:
15020   case ISD::UADDO:
15021   case ISD::SSUBO:
15022   case ISD::USUBO:
15023   case ISD::SMULO:
15024   case ISD::UMULO:              return LowerXALUO(Op, DAG);
15025   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
15026   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
15027   case ISD::ADDC:
15028   case ISD::ADDE:
15029   case ISD::SUBC:
15030   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
15031   case ISD::ADD:                return LowerADD(Op, DAG);
15032   case ISD::SUB:                return LowerSUB(Op, DAG);
15033   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
15034   }
15035 }
15036
15037 static void ReplaceATOMIC_LOAD(SDNode *Node,
15038                                SmallVectorImpl<SDValue> &Results,
15039                                SelectionDAG &DAG) {
15040   SDLoc dl(Node);
15041   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
15042
15043   // Convert wide load -> cmpxchg8b/cmpxchg16b
15044   // FIXME: On 32-bit, load -> fild or movq would be more efficient
15045   //        (The only way to get a 16-byte load is cmpxchg16b)
15046   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
15047   SDValue Zero = DAG.getConstant(0, VT);
15048   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
15049   SDValue Swap =
15050       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
15051                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
15052                            cast<AtomicSDNode>(Node)->getMemOperand(),
15053                            cast<AtomicSDNode>(Node)->getOrdering(),
15054                            cast<AtomicSDNode>(Node)->getOrdering(),
15055                            cast<AtomicSDNode>(Node)->getSynchScope());
15056   Results.push_back(Swap.getValue(0));
15057   Results.push_back(Swap.getValue(2));
15058 }
15059
15060 static void
15061 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
15062                         SelectionDAG &DAG, unsigned NewOp) {
15063   SDLoc dl(Node);
15064   assert (Node->getValueType(0) == MVT::i64 &&
15065           "Only know how to expand i64 atomics");
15066
15067   SDValue Chain = Node->getOperand(0);
15068   SDValue In1 = Node->getOperand(1);
15069   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
15070                              Node->getOperand(2), DAG.getIntPtrConstant(0));
15071   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
15072                              Node->getOperand(2), DAG.getIntPtrConstant(1));
15073   SDValue Ops[] = { Chain, In1, In2L, In2H };
15074   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
15075   SDValue Result =
15076     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
15077                             cast<MemSDNode>(Node)->getMemOperand());
15078   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
15079   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
15080   Results.push_back(Result.getValue(2));
15081 }
15082
15083 /// ReplaceNodeResults - Replace a node with an illegal result type
15084 /// with a new node built out of custom code.
15085 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
15086                                            SmallVectorImpl<SDValue>&Results,
15087                                            SelectionDAG &DAG) const {
15088   SDLoc dl(N);
15089   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15090   switch (N->getOpcode()) {
15091   default:
15092     llvm_unreachable("Do not know how to custom type legalize this operation!");
15093   case ISD::SIGN_EXTEND_INREG:
15094   case ISD::ADDC:
15095   case ISD::ADDE:
15096   case ISD::SUBC:
15097   case ISD::SUBE:
15098     // We don't want to expand or promote these.
15099     return;
15100   case ISD::SDIV:
15101   case ISD::UDIV:
15102   case ISD::SREM:
15103   case ISD::UREM:
15104   case ISD::SDIVREM:
15105   case ISD::UDIVREM: {
15106     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
15107     Results.push_back(V);
15108     return;
15109   }
15110   case ISD::FP_TO_SINT:
15111   case ISD::FP_TO_UINT: {
15112     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
15113
15114     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
15115       return;
15116
15117     std::pair<SDValue,SDValue> Vals =
15118         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
15119     SDValue FIST = Vals.first, StackSlot = Vals.second;
15120     if (FIST.getNode()) {
15121       EVT VT = N->getValueType(0);
15122       // Return a load from the stack slot.
15123       if (StackSlot.getNode())
15124         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
15125                                       MachinePointerInfo(),
15126                                       false, false, false, 0));
15127       else
15128         Results.push_back(FIST);
15129     }
15130     return;
15131   }
15132   case ISD::UINT_TO_FP: {
15133     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15134     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
15135         N->getValueType(0) != MVT::v2f32)
15136       return;
15137     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
15138                                  N->getOperand(0));
15139     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
15140                                      MVT::f64);
15141     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
15142     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
15143                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
15144     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
15145     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
15146     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
15147     return;
15148   }
15149   case ISD::FP_ROUND: {
15150     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
15151         return;
15152     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
15153     Results.push_back(V);
15154     return;
15155   }
15156   case ISD::INTRINSIC_W_CHAIN: {
15157     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15158     switch (IntNo) {
15159     default : llvm_unreachable("Do not know how to custom type "
15160                                "legalize this intrinsic operation!");
15161     case Intrinsic::x86_rdtsc:
15162       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15163                                      Results);
15164     case Intrinsic::x86_rdtscp:
15165       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
15166                                      Results);
15167     }
15168   }
15169   case ISD::READCYCLECOUNTER: {
15170     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15171                                    Results);
15172   }
15173   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
15174     EVT T = N->getValueType(0);
15175     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
15176     bool Regs64bit = T == MVT::i128;
15177     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
15178     SDValue cpInL, cpInH;
15179     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15180                         DAG.getConstant(0, HalfT));
15181     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15182                         DAG.getConstant(1, HalfT));
15183     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
15184                              Regs64bit ? X86::RAX : X86::EAX,
15185                              cpInL, SDValue());
15186     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
15187                              Regs64bit ? X86::RDX : X86::EDX,
15188                              cpInH, cpInL.getValue(1));
15189     SDValue swapInL, swapInH;
15190     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15191                           DAG.getConstant(0, HalfT));
15192     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15193                           DAG.getConstant(1, HalfT));
15194     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
15195                                Regs64bit ? X86::RBX : X86::EBX,
15196                                swapInL, cpInH.getValue(1));
15197     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
15198                                Regs64bit ? X86::RCX : X86::ECX,
15199                                swapInH, swapInL.getValue(1));
15200     SDValue Ops[] = { swapInH.getValue(0),
15201                       N->getOperand(1),
15202                       swapInH.getValue(1) };
15203     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15204     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
15205     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
15206                                   X86ISD::LCMPXCHG8_DAG;
15207     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
15208     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
15209                                         Regs64bit ? X86::RAX : X86::EAX,
15210                                         HalfT, Result.getValue(1));
15211     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
15212                                         Regs64bit ? X86::RDX : X86::EDX,
15213                                         HalfT, cpOutL.getValue(2));
15214     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
15215
15216     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
15217                                         MVT::i32, cpOutH.getValue(2));
15218     SDValue Success =
15219         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15220                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15221     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
15222
15223     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
15224     Results.push_back(Success);
15225     Results.push_back(EFLAGS.getValue(1));
15226     return;
15227   }
15228   case ISD::ATOMIC_LOAD_ADD:
15229   case ISD::ATOMIC_LOAD_AND:
15230   case ISD::ATOMIC_LOAD_NAND:
15231   case ISD::ATOMIC_LOAD_OR:
15232   case ISD::ATOMIC_LOAD_SUB:
15233   case ISD::ATOMIC_LOAD_XOR:
15234   case ISD::ATOMIC_LOAD_MAX:
15235   case ISD::ATOMIC_LOAD_MIN:
15236   case ISD::ATOMIC_LOAD_UMAX:
15237   case ISD::ATOMIC_LOAD_UMIN:
15238   case ISD::ATOMIC_SWAP: {
15239     unsigned Opc;
15240     switch (N->getOpcode()) {
15241     default: llvm_unreachable("Unexpected opcode");
15242     case ISD::ATOMIC_LOAD_ADD:
15243       Opc = X86ISD::ATOMADD64_DAG;
15244       break;
15245     case ISD::ATOMIC_LOAD_AND:
15246       Opc = X86ISD::ATOMAND64_DAG;
15247       break;
15248     case ISD::ATOMIC_LOAD_NAND:
15249       Opc = X86ISD::ATOMNAND64_DAG;
15250       break;
15251     case ISD::ATOMIC_LOAD_OR:
15252       Opc = X86ISD::ATOMOR64_DAG;
15253       break;
15254     case ISD::ATOMIC_LOAD_SUB:
15255       Opc = X86ISD::ATOMSUB64_DAG;
15256       break;
15257     case ISD::ATOMIC_LOAD_XOR:
15258       Opc = X86ISD::ATOMXOR64_DAG;
15259       break;
15260     case ISD::ATOMIC_LOAD_MAX:
15261       Opc = X86ISD::ATOMMAX64_DAG;
15262       break;
15263     case ISD::ATOMIC_LOAD_MIN:
15264       Opc = X86ISD::ATOMMIN64_DAG;
15265       break;
15266     case ISD::ATOMIC_LOAD_UMAX:
15267       Opc = X86ISD::ATOMUMAX64_DAG;
15268       break;
15269     case ISD::ATOMIC_LOAD_UMIN:
15270       Opc = X86ISD::ATOMUMIN64_DAG;
15271       break;
15272     case ISD::ATOMIC_SWAP:
15273       Opc = X86ISD::ATOMSWAP64_DAG;
15274       break;
15275     }
15276     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
15277     return;
15278   }
15279   case ISD::ATOMIC_LOAD: {
15280     ReplaceATOMIC_LOAD(N, Results, DAG);
15281     return;
15282   }
15283   case ISD::BITCAST: {
15284     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15285     EVT DstVT = N->getValueType(0);
15286     EVT SrcVT = N->getOperand(0)->getValueType(0);
15287
15288     if (SrcVT != MVT::f64 ||
15289         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
15290       return;
15291
15292     unsigned NumElts = DstVT.getVectorNumElements();
15293     EVT SVT = DstVT.getVectorElementType();
15294     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15295     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
15296                                    MVT::v2f64, N->getOperand(0));
15297     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
15298
15299     SmallVector<SDValue, 8> Elts;
15300     for (unsigned i = 0, e = NumElts; i != e; ++i)
15301       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
15302                                    ToVecInt, DAG.getIntPtrConstant(i)));
15303
15304     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
15305   }
15306   }
15307 }
15308
15309 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
15310   switch (Opcode) {
15311   default: return nullptr;
15312   case X86ISD::BSF:                return "X86ISD::BSF";
15313   case X86ISD::BSR:                return "X86ISD::BSR";
15314   case X86ISD::SHLD:               return "X86ISD::SHLD";
15315   case X86ISD::SHRD:               return "X86ISD::SHRD";
15316   case X86ISD::FAND:               return "X86ISD::FAND";
15317   case X86ISD::FANDN:              return "X86ISD::FANDN";
15318   case X86ISD::FOR:                return "X86ISD::FOR";
15319   case X86ISD::FXOR:               return "X86ISD::FXOR";
15320   case X86ISD::FSRL:               return "X86ISD::FSRL";
15321   case X86ISD::FILD:               return "X86ISD::FILD";
15322   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
15323   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
15324   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
15325   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
15326   case X86ISD::FLD:                return "X86ISD::FLD";
15327   case X86ISD::FST:                return "X86ISD::FST";
15328   case X86ISD::CALL:               return "X86ISD::CALL";
15329   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
15330   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
15331   case X86ISD::BT:                 return "X86ISD::BT";
15332   case X86ISD::CMP:                return "X86ISD::CMP";
15333   case X86ISD::COMI:               return "X86ISD::COMI";
15334   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
15335   case X86ISD::CMPM:               return "X86ISD::CMPM";
15336   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
15337   case X86ISD::SETCC:              return "X86ISD::SETCC";
15338   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
15339   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
15340   case X86ISD::CMOV:               return "X86ISD::CMOV";
15341   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
15342   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
15343   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
15344   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
15345   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
15346   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
15347   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
15348   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
15349   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
15350   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
15351   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
15352   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
15353   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
15354   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
15355   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
15356   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
15357   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
15358   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
15359   case X86ISD::HADD:               return "X86ISD::HADD";
15360   case X86ISD::HSUB:               return "X86ISD::HSUB";
15361   case X86ISD::FHADD:              return "X86ISD::FHADD";
15362   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
15363   case X86ISD::UMAX:               return "X86ISD::UMAX";
15364   case X86ISD::UMIN:               return "X86ISD::UMIN";
15365   case X86ISD::SMAX:               return "X86ISD::SMAX";
15366   case X86ISD::SMIN:               return "X86ISD::SMIN";
15367   case X86ISD::FMAX:               return "X86ISD::FMAX";
15368   case X86ISD::FMIN:               return "X86ISD::FMIN";
15369   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
15370   case X86ISD::FMINC:              return "X86ISD::FMINC";
15371   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
15372   case X86ISD::FRCP:               return "X86ISD::FRCP";
15373   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
15374   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
15375   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
15376   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
15377   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
15378   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
15379   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
15380   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
15381   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
15382   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
15383   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
15384   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
15385   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
15386   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
15387   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
15388   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
15389   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
15390   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
15391   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
15392   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
15393   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
15394   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
15395   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
15396   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
15397   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
15398   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
15399   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
15400   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
15401   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
15402   case X86ISD::VSHL:               return "X86ISD::VSHL";
15403   case X86ISD::VSRL:               return "X86ISD::VSRL";
15404   case X86ISD::VSRA:               return "X86ISD::VSRA";
15405   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
15406   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
15407   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
15408   case X86ISD::CMPP:               return "X86ISD::CMPP";
15409   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
15410   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
15411   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
15412   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
15413   case X86ISD::ADD:                return "X86ISD::ADD";
15414   case X86ISD::SUB:                return "X86ISD::SUB";
15415   case X86ISD::ADC:                return "X86ISD::ADC";
15416   case X86ISD::SBB:                return "X86ISD::SBB";
15417   case X86ISD::SMUL:               return "X86ISD::SMUL";
15418   case X86ISD::UMUL:               return "X86ISD::UMUL";
15419   case X86ISD::INC:                return "X86ISD::INC";
15420   case X86ISD::DEC:                return "X86ISD::DEC";
15421   case X86ISD::OR:                 return "X86ISD::OR";
15422   case X86ISD::XOR:                return "X86ISD::XOR";
15423   case X86ISD::AND:                return "X86ISD::AND";
15424   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
15425   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
15426   case X86ISD::PTEST:              return "X86ISD::PTEST";
15427   case X86ISD::TESTP:              return "X86ISD::TESTP";
15428   case X86ISD::TESTM:              return "X86ISD::TESTM";
15429   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
15430   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
15431   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
15432   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
15433   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
15434   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
15435   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
15436   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
15437   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
15438   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
15439   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
15440   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
15441   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
15442   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
15443   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
15444   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
15445   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
15446   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
15447   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
15448   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
15449   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
15450   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
15451   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
15452   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
15453   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
15454   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
15455   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
15456   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
15457   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
15458   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
15459   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
15460   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
15461   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15462   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
15463   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
15464   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
15465   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
15466   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
15467   case X86ISD::SAHF:               return "X86ISD::SAHF";
15468   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
15469   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
15470   case X86ISD::FMADD:              return "X86ISD::FMADD";
15471   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
15472   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
15473   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
15474   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
15475   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
15476   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
15477   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
15478   case X86ISD::XTEST:              return "X86ISD::XTEST";
15479   }
15480 }
15481
15482 // isLegalAddressingMode - Return true if the addressing mode represented
15483 // by AM is legal for this target, for a load/store of the specified type.
15484 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15485                                               Type *Ty) const {
15486   // X86 supports extremely general addressing modes.
15487   CodeModel::Model M = getTargetMachine().getCodeModel();
15488   Reloc::Model R = getTargetMachine().getRelocationModel();
15489
15490   // X86 allows a sign-extended 32-bit immediate field as a displacement.
15491   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15492     return false;
15493
15494   if (AM.BaseGV) {
15495     unsigned GVFlags =
15496       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15497
15498     // If a reference to this global requires an extra load, we can't fold it.
15499     if (isGlobalStubReference(GVFlags))
15500       return false;
15501
15502     // If BaseGV requires a register for the PIC base, we cannot also have a
15503     // BaseReg specified.
15504     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15505       return false;
15506
15507     // If lower 4G is not available, then we must use rip-relative addressing.
15508     if ((M != CodeModel::Small || R != Reloc::Static) &&
15509         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15510       return false;
15511   }
15512
15513   switch (AM.Scale) {
15514   case 0:
15515   case 1:
15516   case 2:
15517   case 4:
15518   case 8:
15519     // These scales always work.
15520     break;
15521   case 3:
15522   case 5:
15523   case 9:
15524     // These scales are formed with basereg+scalereg.  Only accept if there is
15525     // no basereg yet.
15526     if (AM.HasBaseReg)
15527       return false;
15528     break;
15529   default:  // Other stuff never works.
15530     return false;
15531   }
15532
15533   return true;
15534 }
15535
15536 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15537   unsigned Bits = Ty->getScalarSizeInBits();
15538
15539   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15540   // particularly cheaper than those without.
15541   if (Bits == 8)
15542     return false;
15543
15544   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15545   // variable shifts just as cheap as scalar ones.
15546   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15547     return false;
15548
15549   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15550   // fully general vector.
15551   return true;
15552 }
15553
15554 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15555   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15556     return false;
15557   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15558   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15559   return NumBits1 > NumBits2;
15560 }
15561
15562 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15563   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15564     return false;
15565
15566   if (!isTypeLegal(EVT::getEVT(Ty1)))
15567     return false;
15568
15569   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15570
15571   // Assuming the caller doesn't have a zeroext or signext return parameter,
15572   // truncation all the way down to i1 is valid.
15573   return true;
15574 }
15575
15576 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15577   return isInt<32>(Imm);
15578 }
15579
15580 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15581   // Can also use sub to handle negated immediates.
15582   return isInt<32>(Imm);
15583 }
15584
15585 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15586   if (!VT1.isInteger() || !VT2.isInteger())
15587     return false;
15588   unsigned NumBits1 = VT1.getSizeInBits();
15589   unsigned NumBits2 = VT2.getSizeInBits();
15590   return NumBits1 > NumBits2;
15591 }
15592
15593 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15594   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15595   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15596 }
15597
15598 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15599   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15600   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15601 }
15602
15603 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15604   EVT VT1 = Val.getValueType();
15605   if (isZExtFree(VT1, VT2))
15606     return true;
15607
15608   if (Val.getOpcode() != ISD::LOAD)
15609     return false;
15610
15611   if (!VT1.isSimple() || !VT1.isInteger() ||
15612       !VT2.isSimple() || !VT2.isInteger())
15613     return false;
15614
15615   switch (VT1.getSimpleVT().SimpleTy) {
15616   default: break;
15617   case MVT::i8:
15618   case MVT::i16:
15619   case MVT::i32:
15620     // X86 has 8, 16, and 32-bit zero-extending loads.
15621     return true;
15622   }
15623
15624   return false;
15625 }
15626
15627 bool
15628 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15629   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15630     return false;
15631
15632   VT = VT.getScalarType();
15633
15634   if (!VT.isSimple())
15635     return false;
15636
15637   switch (VT.getSimpleVT().SimpleTy) {
15638   case MVT::f32:
15639   case MVT::f64:
15640     return true;
15641   default:
15642     break;
15643   }
15644
15645   return false;
15646 }
15647
15648 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15649   // i16 instructions are longer (0x66 prefix) and potentially slower.
15650   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15651 }
15652
15653 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15654 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15655 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15656 /// are assumed to be legal.
15657 bool
15658 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15659                                       EVT VT) const {
15660   if (!VT.isSimple())
15661     return false;
15662
15663   MVT SVT = VT.getSimpleVT();
15664
15665   // Very little shuffling can be done for 64-bit vectors right now.
15666   if (VT.getSizeInBits() == 64)
15667     return false;
15668
15669   // If this is a single-input shuffle with no 128 bit lane crossings we can
15670   // lower it into pshufb.
15671   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15672       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15673     bool isLegal = true;
15674     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15675       if (M[I] >= (int)SVT.getVectorNumElements() ||
15676           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15677         isLegal = false;
15678         break;
15679       }
15680     }
15681     if (isLegal)
15682       return true;
15683   }
15684
15685   // FIXME: blends, shifts.
15686   return (SVT.getVectorNumElements() == 2 ||
15687           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15688           isMOVLMask(M, SVT) ||
15689           isSHUFPMask(M, SVT) ||
15690           isPSHUFDMask(M, SVT) ||
15691           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15692           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15693           isPALIGNRMask(M, SVT, Subtarget) ||
15694           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15695           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15696           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15697           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15698           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15699 }
15700
15701 bool
15702 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15703                                           EVT VT) const {
15704   if (!VT.isSimple())
15705     return false;
15706
15707   MVT SVT = VT.getSimpleVT();
15708   unsigned NumElts = SVT.getVectorNumElements();
15709   // FIXME: This collection of masks seems suspect.
15710   if (NumElts == 2)
15711     return true;
15712   if (NumElts == 4 && SVT.is128BitVector()) {
15713     return (isMOVLMask(Mask, SVT)  ||
15714             isCommutedMOVLMask(Mask, SVT, true) ||
15715             isSHUFPMask(Mask, SVT) ||
15716             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15717   }
15718   return false;
15719 }
15720
15721 //===----------------------------------------------------------------------===//
15722 //                           X86 Scheduler Hooks
15723 //===----------------------------------------------------------------------===//
15724
15725 /// Utility function to emit xbegin specifying the start of an RTM region.
15726 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15727                                      const TargetInstrInfo *TII) {
15728   DebugLoc DL = MI->getDebugLoc();
15729
15730   const BasicBlock *BB = MBB->getBasicBlock();
15731   MachineFunction::iterator I = MBB;
15732   ++I;
15733
15734   // For the v = xbegin(), we generate
15735   //
15736   // thisMBB:
15737   //  xbegin sinkMBB
15738   //
15739   // mainMBB:
15740   //  eax = -1
15741   //
15742   // sinkMBB:
15743   //  v = eax
15744
15745   MachineBasicBlock *thisMBB = MBB;
15746   MachineFunction *MF = MBB->getParent();
15747   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15748   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15749   MF->insert(I, mainMBB);
15750   MF->insert(I, sinkMBB);
15751
15752   // Transfer the remainder of BB and its successor edges to sinkMBB.
15753   sinkMBB->splice(sinkMBB->begin(), MBB,
15754                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15755   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15756
15757   // thisMBB:
15758   //  xbegin sinkMBB
15759   //  # fallthrough to mainMBB
15760   //  # abortion to sinkMBB
15761   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15762   thisMBB->addSuccessor(mainMBB);
15763   thisMBB->addSuccessor(sinkMBB);
15764
15765   // mainMBB:
15766   //  EAX = -1
15767   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15768   mainMBB->addSuccessor(sinkMBB);
15769
15770   // sinkMBB:
15771   // EAX is live into the sinkMBB
15772   sinkMBB->addLiveIn(X86::EAX);
15773   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15774           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15775     .addReg(X86::EAX);
15776
15777   MI->eraseFromParent();
15778   return sinkMBB;
15779 }
15780
15781 // Get CMPXCHG opcode for the specified data type.
15782 static unsigned getCmpXChgOpcode(EVT VT) {
15783   switch (VT.getSimpleVT().SimpleTy) {
15784   case MVT::i8:  return X86::LCMPXCHG8;
15785   case MVT::i16: return X86::LCMPXCHG16;
15786   case MVT::i32: return X86::LCMPXCHG32;
15787   case MVT::i64: return X86::LCMPXCHG64;
15788   default:
15789     break;
15790   }
15791   llvm_unreachable("Invalid operand size!");
15792 }
15793
15794 // Get LOAD opcode for the specified data type.
15795 static unsigned getLoadOpcode(EVT VT) {
15796   switch (VT.getSimpleVT().SimpleTy) {
15797   case MVT::i8:  return X86::MOV8rm;
15798   case MVT::i16: return X86::MOV16rm;
15799   case MVT::i32: return X86::MOV32rm;
15800   case MVT::i64: return X86::MOV64rm;
15801   default:
15802     break;
15803   }
15804   llvm_unreachable("Invalid operand size!");
15805 }
15806
15807 // Get opcode of the non-atomic one from the specified atomic instruction.
15808 static unsigned getNonAtomicOpcode(unsigned Opc) {
15809   switch (Opc) {
15810   case X86::ATOMAND8:  return X86::AND8rr;
15811   case X86::ATOMAND16: return X86::AND16rr;
15812   case X86::ATOMAND32: return X86::AND32rr;
15813   case X86::ATOMAND64: return X86::AND64rr;
15814   case X86::ATOMOR8:   return X86::OR8rr;
15815   case X86::ATOMOR16:  return X86::OR16rr;
15816   case X86::ATOMOR32:  return X86::OR32rr;
15817   case X86::ATOMOR64:  return X86::OR64rr;
15818   case X86::ATOMXOR8:  return X86::XOR8rr;
15819   case X86::ATOMXOR16: return X86::XOR16rr;
15820   case X86::ATOMXOR32: return X86::XOR32rr;
15821   case X86::ATOMXOR64: return X86::XOR64rr;
15822   }
15823   llvm_unreachable("Unhandled atomic-load-op opcode!");
15824 }
15825
15826 // Get opcode of the non-atomic one from the specified atomic instruction with
15827 // extra opcode.
15828 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15829                                                unsigned &ExtraOpc) {
15830   switch (Opc) {
15831   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15832   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15833   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15834   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15835   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15836   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15837   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15838   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15839   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15840   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15841   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15842   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15843   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15844   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15845   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15846   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15847   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15848   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15849   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15850   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15851   }
15852   llvm_unreachable("Unhandled atomic-load-op opcode!");
15853 }
15854
15855 // Get opcode of the non-atomic one from the specified atomic instruction for
15856 // 64-bit data type on 32-bit target.
15857 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15858   switch (Opc) {
15859   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15860   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15861   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15862   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15863   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15864   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15865   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15866   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15867   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15868   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15869   }
15870   llvm_unreachable("Unhandled atomic-load-op opcode!");
15871 }
15872
15873 // Get opcode of the non-atomic one from the specified atomic instruction for
15874 // 64-bit data type on 32-bit target with extra opcode.
15875 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15876                                                    unsigned &HiOpc,
15877                                                    unsigned &ExtraOpc) {
15878   switch (Opc) {
15879   case X86::ATOMNAND6432:
15880     ExtraOpc = X86::NOT32r;
15881     HiOpc = X86::AND32rr;
15882     return X86::AND32rr;
15883   }
15884   llvm_unreachable("Unhandled atomic-load-op opcode!");
15885 }
15886
15887 // Get pseudo CMOV opcode from the specified data type.
15888 static unsigned getPseudoCMOVOpc(EVT VT) {
15889   switch (VT.getSimpleVT().SimpleTy) {
15890   case MVT::i8:  return X86::CMOV_GR8;
15891   case MVT::i16: return X86::CMOV_GR16;
15892   case MVT::i32: return X86::CMOV_GR32;
15893   default:
15894     break;
15895   }
15896   llvm_unreachable("Unknown CMOV opcode!");
15897 }
15898
15899 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15900 // They will be translated into a spin-loop or compare-exchange loop from
15901 //
15902 //    ...
15903 //    dst = atomic-fetch-op MI.addr, MI.val
15904 //    ...
15905 //
15906 // to
15907 //
15908 //    ...
15909 //    t1 = LOAD MI.addr
15910 // loop:
15911 //    t4 = phi(t1, t3 / loop)
15912 //    t2 = OP MI.val, t4
15913 //    EAX = t4
15914 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15915 //    t3 = EAX
15916 //    JNE loop
15917 // sink:
15918 //    dst = t3
15919 //    ...
15920 MachineBasicBlock *
15921 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15922                                        MachineBasicBlock *MBB) const {
15923   MachineFunction *MF = MBB->getParent();
15924   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15925   DebugLoc DL = MI->getDebugLoc();
15926
15927   MachineRegisterInfo &MRI = MF->getRegInfo();
15928
15929   const BasicBlock *BB = MBB->getBasicBlock();
15930   MachineFunction::iterator I = MBB;
15931   ++I;
15932
15933   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15934          "Unexpected number of operands");
15935
15936   assert(MI->hasOneMemOperand() &&
15937          "Expected atomic-load-op to have one memoperand");
15938
15939   // Memory Reference
15940   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15941   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15942
15943   unsigned DstReg, SrcReg;
15944   unsigned MemOpndSlot;
15945
15946   unsigned CurOp = 0;
15947
15948   DstReg = MI->getOperand(CurOp++).getReg();
15949   MemOpndSlot = CurOp;
15950   CurOp += X86::AddrNumOperands;
15951   SrcReg = MI->getOperand(CurOp++).getReg();
15952
15953   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15954   MVT::SimpleValueType VT = *RC->vt_begin();
15955   unsigned t1 = MRI.createVirtualRegister(RC);
15956   unsigned t2 = MRI.createVirtualRegister(RC);
15957   unsigned t3 = MRI.createVirtualRegister(RC);
15958   unsigned t4 = MRI.createVirtualRegister(RC);
15959   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15960
15961   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15962   unsigned LOADOpc = getLoadOpcode(VT);
15963
15964   // For the atomic load-arith operator, we generate
15965   //
15966   //  thisMBB:
15967   //    t1 = LOAD [MI.addr]
15968   //  mainMBB:
15969   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15970   //    t1 = OP MI.val, EAX
15971   //    EAX = t4
15972   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15973   //    t3 = EAX
15974   //    JNE mainMBB
15975   //  sinkMBB:
15976   //    dst = t3
15977
15978   MachineBasicBlock *thisMBB = MBB;
15979   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15980   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15981   MF->insert(I, mainMBB);
15982   MF->insert(I, sinkMBB);
15983
15984   MachineInstrBuilder MIB;
15985
15986   // Transfer the remainder of BB and its successor edges to sinkMBB.
15987   sinkMBB->splice(sinkMBB->begin(), MBB,
15988                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15989   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15990
15991   // thisMBB:
15992   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15993   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15994     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15995     if (NewMO.isReg())
15996       NewMO.setIsKill(false);
15997     MIB.addOperand(NewMO);
15998   }
15999   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16000     unsigned flags = (*MMOI)->getFlags();
16001     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16002     MachineMemOperand *MMO =
16003       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16004                                (*MMOI)->getSize(),
16005                                (*MMOI)->getBaseAlignment(),
16006                                (*MMOI)->getTBAAInfo(),
16007                                (*MMOI)->getRanges());
16008     MIB.addMemOperand(MMO);
16009   }
16010
16011   thisMBB->addSuccessor(mainMBB);
16012
16013   // mainMBB:
16014   MachineBasicBlock *origMainMBB = mainMBB;
16015
16016   // Add a PHI.
16017   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
16018                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
16019
16020   unsigned Opc = MI->getOpcode();
16021   switch (Opc) {
16022   default:
16023     llvm_unreachable("Unhandled atomic-load-op opcode!");
16024   case X86::ATOMAND8:
16025   case X86::ATOMAND16:
16026   case X86::ATOMAND32:
16027   case X86::ATOMAND64:
16028   case X86::ATOMOR8:
16029   case X86::ATOMOR16:
16030   case X86::ATOMOR32:
16031   case X86::ATOMOR64:
16032   case X86::ATOMXOR8:
16033   case X86::ATOMXOR16:
16034   case X86::ATOMXOR32:
16035   case X86::ATOMXOR64: {
16036     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
16037     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
16038       .addReg(t4);
16039     break;
16040   }
16041   case X86::ATOMNAND8:
16042   case X86::ATOMNAND16:
16043   case X86::ATOMNAND32:
16044   case X86::ATOMNAND64: {
16045     unsigned Tmp = MRI.createVirtualRegister(RC);
16046     unsigned NOTOpc;
16047     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
16048     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
16049       .addReg(t4);
16050     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
16051     break;
16052   }
16053   case X86::ATOMMAX8:
16054   case X86::ATOMMAX16:
16055   case X86::ATOMMAX32:
16056   case X86::ATOMMAX64:
16057   case X86::ATOMMIN8:
16058   case X86::ATOMMIN16:
16059   case X86::ATOMMIN32:
16060   case X86::ATOMMIN64:
16061   case X86::ATOMUMAX8:
16062   case X86::ATOMUMAX16:
16063   case X86::ATOMUMAX32:
16064   case X86::ATOMUMAX64:
16065   case X86::ATOMUMIN8:
16066   case X86::ATOMUMIN16:
16067   case X86::ATOMUMIN32:
16068   case X86::ATOMUMIN64: {
16069     unsigned CMPOpc;
16070     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
16071
16072     BuildMI(mainMBB, DL, TII->get(CMPOpc))
16073       .addReg(SrcReg)
16074       .addReg(t4);
16075
16076     if (Subtarget->hasCMov()) {
16077       if (VT != MVT::i8) {
16078         // Native support
16079         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
16080           .addReg(SrcReg)
16081           .addReg(t4);
16082       } else {
16083         // Promote i8 to i32 to use CMOV32
16084         const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
16085         const TargetRegisterClass *RC32 =
16086           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
16087         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
16088         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
16089         unsigned Tmp = MRI.createVirtualRegister(RC32);
16090
16091         unsigned Undef = MRI.createVirtualRegister(RC32);
16092         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
16093
16094         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
16095           .addReg(Undef)
16096           .addReg(SrcReg)
16097           .addImm(X86::sub_8bit);
16098         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
16099           .addReg(Undef)
16100           .addReg(t4)
16101           .addImm(X86::sub_8bit);
16102
16103         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
16104           .addReg(SrcReg32)
16105           .addReg(AccReg32);
16106
16107         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
16108           .addReg(Tmp, 0, X86::sub_8bit);
16109       }
16110     } else {
16111       // Use pseudo select and lower them.
16112       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
16113              "Invalid atomic-load-op transformation!");
16114       unsigned SelOpc = getPseudoCMOVOpc(VT);
16115       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
16116       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
16117       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
16118               .addReg(SrcReg).addReg(t4)
16119               .addImm(CC);
16120       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16121       // Replace the original PHI node as mainMBB is changed after CMOV
16122       // lowering.
16123       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
16124         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
16125       Phi->eraseFromParent();
16126     }
16127     break;
16128   }
16129   }
16130
16131   // Copy PhyReg back from virtual register.
16132   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
16133     .addReg(t4);
16134
16135   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16136   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16137     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16138     if (NewMO.isReg())
16139       NewMO.setIsKill(false);
16140     MIB.addOperand(NewMO);
16141   }
16142   MIB.addReg(t2);
16143   MIB.setMemRefs(MMOBegin, MMOEnd);
16144
16145   // Copy PhyReg back to virtual register.
16146   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
16147     .addReg(PhyReg);
16148
16149   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16150
16151   mainMBB->addSuccessor(origMainMBB);
16152   mainMBB->addSuccessor(sinkMBB);
16153
16154   // sinkMBB:
16155   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16156           TII->get(TargetOpcode::COPY), DstReg)
16157     .addReg(t3);
16158
16159   MI->eraseFromParent();
16160   return sinkMBB;
16161 }
16162
16163 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
16164 // instructions. They will be translated into a spin-loop or compare-exchange
16165 // loop from
16166 //
16167 //    ...
16168 //    dst = atomic-fetch-op MI.addr, MI.val
16169 //    ...
16170 //
16171 // to
16172 //
16173 //    ...
16174 //    t1L = LOAD [MI.addr + 0]
16175 //    t1H = LOAD [MI.addr + 4]
16176 // loop:
16177 //    t4L = phi(t1L, t3L / loop)
16178 //    t4H = phi(t1H, t3H / loop)
16179 //    t2L = OP MI.val.lo, t4L
16180 //    t2H = OP MI.val.hi, t4H
16181 //    EAX = t4L
16182 //    EDX = t4H
16183 //    EBX = t2L
16184 //    ECX = t2H
16185 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16186 //    t3L = EAX
16187 //    t3H = EDX
16188 //    JNE loop
16189 // sink:
16190 //    dstL = t3L
16191 //    dstH = t3H
16192 //    ...
16193 MachineBasicBlock *
16194 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
16195                                            MachineBasicBlock *MBB) const {
16196   MachineFunction *MF = MBB->getParent();
16197   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16198   DebugLoc DL = MI->getDebugLoc();
16199
16200   MachineRegisterInfo &MRI = MF->getRegInfo();
16201
16202   const BasicBlock *BB = MBB->getBasicBlock();
16203   MachineFunction::iterator I = MBB;
16204   ++I;
16205
16206   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
16207          "Unexpected number of operands");
16208
16209   assert(MI->hasOneMemOperand() &&
16210          "Expected atomic-load-op32 to have one memoperand");
16211
16212   // Memory Reference
16213   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16214   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16215
16216   unsigned DstLoReg, DstHiReg;
16217   unsigned SrcLoReg, SrcHiReg;
16218   unsigned MemOpndSlot;
16219
16220   unsigned CurOp = 0;
16221
16222   DstLoReg = MI->getOperand(CurOp++).getReg();
16223   DstHiReg = MI->getOperand(CurOp++).getReg();
16224   MemOpndSlot = CurOp;
16225   CurOp += X86::AddrNumOperands;
16226   SrcLoReg = MI->getOperand(CurOp++).getReg();
16227   SrcHiReg = MI->getOperand(CurOp++).getReg();
16228
16229   const TargetRegisterClass *RC = &X86::GR32RegClass;
16230   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
16231
16232   unsigned t1L = MRI.createVirtualRegister(RC);
16233   unsigned t1H = MRI.createVirtualRegister(RC);
16234   unsigned t2L = MRI.createVirtualRegister(RC);
16235   unsigned t2H = MRI.createVirtualRegister(RC);
16236   unsigned t3L = MRI.createVirtualRegister(RC);
16237   unsigned t3H = MRI.createVirtualRegister(RC);
16238   unsigned t4L = MRI.createVirtualRegister(RC);
16239   unsigned t4H = MRI.createVirtualRegister(RC);
16240
16241   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
16242   unsigned LOADOpc = X86::MOV32rm;
16243
16244   // For the atomic load-arith operator, we generate
16245   //
16246   //  thisMBB:
16247   //    t1L = LOAD [MI.addr + 0]
16248   //    t1H = LOAD [MI.addr + 4]
16249   //  mainMBB:
16250   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
16251   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
16252   //    t2L = OP MI.val.lo, t4L
16253   //    t2H = OP MI.val.hi, t4H
16254   //    EBX = t2L
16255   //    ECX = t2H
16256   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16257   //    t3L = EAX
16258   //    t3H = EDX
16259   //    JNE loop
16260   //  sinkMBB:
16261   //    dstL = t3L
16262   //    dstH = t3H
16263
16264   MachineBasicBlock *thisMBB = MBB;
16265   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16266   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16267   MF->insert(I, mainMBB);
16268   MF->insert(I, sinkMBB);
16269
16270   MachineInstrBuilder MIB;
16271
16272   // Transfer the remainder of BB and its successor edges to sinkMBB.
16273   sinkMBB->splice(sinkMBB->begin(), MBB,
16274                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16275   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16276
16277   // thisMBB:
16278   // Lo
16279   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
16280   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16281     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16282     if (NewMO.isReg())
16283       NewMO.setIsKill(false);
16284     MIB.addOperand(NewMO);
16285   }
16286   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16287     unsigned flags = (*MMOI)->getFlags();
16288     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16289     MachineMemOperand *MMO =
16290       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16291                                (*MMOI)->getSize(),
16292                                (*MMOI)->getBaseAlignment(),
16293                                (*MMOI)->getTBAAInfo(),
16294                                (*MMOI)->getRanges());
16295     MIB.addMemOperand(MMO);
16296   };
16297   MachineInstr *LowMI = MIB;
16298
16299   // Hi
16300   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
16301   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16302     if (i == X86::AddrDisp) {
16303       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
16304     } else {
16305       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16306       if (NewMO.isReg())
16307         NewMO.setIsKill(false);
16308       MIB.addOperand(NewMO);
16309     }
16310   }
16311   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
16312
16313   thisMBB->addSuccessor(mainMBB);
16314
16315   // mainMBB:
16316   MachineBasicBlock *origMainMBB = mainMBB;
16317
16318   // Add PHIs.
16319   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
16320                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16321   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
16322                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16323
16324   unsigned Opc = MI->getOpcode();
16325   switch (Opc) {
16326   default:
16327     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
16328   case X86::ATOMAND6432:
16329   case X86::ATOMOR6432:
16330   case X86::ATOMXOR6432:
16331   case X86::ATOMADD6432:
16332   case X86::ATOMSUB6432: {
16333     unsigned HiOpc;
16334     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16335     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
16336       .addReg(SrcLoReg);
16337     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16338       .addReg(SrcHiReg);
16339     break;
16340   }
16341   case X86::ATOMNAND6432: {
16342     unsigned HiOpc, NOTOpc;
16343     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16344     unsigned TmpL = MRI.createVirtualRegister(RC);
16345     unsigned TmpH = MRI.createVirtualRegister(RC);
16346     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16347       .addReg(t4L);
16348     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16349       .addReg(t4H);
16350     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16351     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16352     break;
16353   }
16354   case X86::ATOMMAX6432:
16355   case X86::ATOMMIN6432:
16356   case X86::ATOMUMAX6432:
16357   case X86::ATOMUMIN6432: {
16358     unsigned HiOpc;
16359     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16360     unsigned cL = MRI.createVirtualRegister(RC8);
16361     unsigned cH = MRI.createVirtualRegister(RC8);
16362     unsigned cL32 = MRI.createVirtualRegister(RC);
16363     unsigned cH32 = MRI.createVirtualRegister(RC);
16364     unsigned cc = MRI.createVirtualRegister(RC);
16365     // cl := cmp src_lo, lo
16366     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16367       .addReg(SrcLoReg).addReg(t4L);
16368     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16369     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16370     // ch := cmp src_hi, hi
16371     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16372       .addReg(SrcHiReg).addReg(t4H);
16373     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16374     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16375     // cc := if (src_hi == hi) ? cl : ch;
16376     if (Subtarget->hasCMov()) {
16377       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16378         .addReg(cH32).addReg(cL32);
16379     } else {
16380       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16381               .addReg(cH32).addReg(cL32)
16382               .addImm(X86::COND_E);
16383       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16384     }
16385     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16386     if (Subtarget->hasCMov()) {
16387       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16388         .addReg(SrcLoReg).addReg(t4L);
16389       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16390         .addReg(SrcHiReg).addReg(t4H);
16391     } else {
16392       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16393               .addReg(SrcLoReg).addReg(t4L)
16394               .addImm(X86::COND_NE);
16395       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16396       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16397       // 2nd CMOV lowering.
16398       mainMBB->addLiveIn(X86::EFLAGS);
16399       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16400               .addReg(SrcHiReg).addReg(t4H)
16401               .addImm(X86::COND_NE);
16402       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16403       // Replace the original PHI node as mainMBB is changed after CMOV
16404       // lowering.
16405       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16406         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16407       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16408         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16409       PhiL->eraseFromParent();
16410       PhiH->eraseFromParent();
16411     }
16412     break;
16413   }
16414   case X86::ATOMSWAP6432: {
16415     unsigned HiOpc;
16416     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16417     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16418     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16419     break;
16420   }
16421   }
16422
16423   // Copy EDX:EAX back from HiReg:LoReg
16424   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16425   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16426   // Copy ECX:EBX from t1H:t1L
16427   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16428   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16429
16430   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16431   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16432     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16433     if (NewMO.isReg())
16434       NewMO.setIsKill(false);
16435     MIB.addOperand(NewMO);
16436   }
16437   MIB.setMemRefs(MMOBegin, MMOEnd);
16438
16439   // Copy EDX:EAX back to t3H:t3L
16440   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16441   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16442
16443   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16444
16445   mainMBB->addSuccessor(origMainMBB);
16446   mainMBB->addSuccessor(sinkMBB);
16447
16448   // sinkMBB:
16449   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16450           TII->get(TargetOpcode::COPY), DstLoReg)
16451     .addReg(t3L);
16452   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16453           TII->get(TargetOpcode::COPY), DstHiReg)
16454     .addReg(t3H);
16455
16456   MI->eraseFromParent();
16457   return sinkMBB;
16458 }
16459
16460 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16461 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16462 // in the .td file.
16463 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16464                                        const TargetInstrInfo *TII) {
16465   unsigned Opc;
16466   switch (MI->getOpcode()) {
16467   default: llvm_unreachable("illegal opcode!");
16468   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16469   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16470   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16471   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16472   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16473   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16474   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16475   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16476   }
16477
16478   DebugLoc dl = MI->getDebugLoc();
16479   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16480
16481   unsigned NumArgs = MI->getNumOperands();
16482   for (unsigned i = 1; i < NumArgs; ++i) {
16483     MachineOperand &Op = MI->getOperand(i);
16484     if (!(Op.isReg() && Op.isImplicit()))
16485       MIB.addOperand(Op);
16486   }
16487   if (MI->hasOneMemOperand())
16488     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16489
16490   BuildMI(*BB, MI, dl,
16491     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16492     .addReg(X86::XMM0);
16493
16494   MI->eraseFromParent();
16495   return BB;
16496 }
16497
16498 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16499 // defs in an instruction pattern
16500 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16501                                        const TargetInstrInfo *TII) {
16502   unsigned Opc;
16503   switch (MI->getOpcode()) {
16504   default: llvm_unreachable("illegal opcode!");
16505   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16506   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16507   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16508   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16509   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16510   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16511   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16512   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16513   }
16514
16515   DebugLoc dl = MI->getDebugLoc();
16516   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16517
16518   unsigned NumArgs = MI->getNumOperands(); // remove the results
16519   for (unsigned i = 1; i < NumArgs; ++i) {
16520     MachineOperand &Op = MI->getOperand(i);
16521     if (!(Op.isReg() && Op.isImplicit()))
16522       MIB.addOperand(Op);
16523   }
16524   if (MI->hasOneMemOperand())
16525     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16526
16527   BuildMI(*BB, MI, dl,
16528     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16529     .addReg(X86::ECX);
16530
16531   MI->eraseFromParent();
16532   return BB;
16533 }
16534
16535 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16536                                        const TargetInstrInfo *TII,
16537                                        const X86Subtarget* Subtarget) {
16538   DebugLoc dl = MI->getDebugLoc();
16539
16540   // Address into RAX/EAX, other two args into ECX, EDX.
16541   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16542   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16543   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16544   for (int i = 0; i < X86::AddrNumOperands; ++i)
16545     MIB.addOperand(MI->getOperand(i));
16546
16547   unsigned ValOps = X86::AddrNumOperands;
16548   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16549     .addReg(MI->getOperand(ValOps).getReg());
16550   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16551     .addReg(MI->getOperand(ValOps+1).getReg());
16552
16553   // The instruction doesn't actually take any operands though.
16554   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16555
16556   MI->eraseFromParent(); // The pseudo is gone now.
16557   return BB;
16558 }
16559
16560 MachineBasicBlock *
16561 X86TargetLowering::EmitVAARG64WithCustomInserter(
16562                    MachineInstr *MI,
16563                    MachineBasicBlock *MBB) const {
16564   // Emit va_arg instruction on X86-64.
16565
16566   // Operands to this pseudo-instruction:
16567   // 0  ) Output        : destination address (reg)
16568   // 1-5) Input         : va_list address (addr, i64mem)
16569   // 6  ) ArgSize       : Size (in bytes) of vararg type
16570   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16571   // 8  ) Align         : Alignment of type
16572   // 9  ) EFLAGS (implicit-def)
16573
16574   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16575   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16576
16577   unsigned DestReg = MI->getOperand(0).getReg();
16578   MachineOperand &Base = MI->getOperand(1);
16579   MachineOperand &Scale = MI->getOperand(2);
16580   MachineOperand &Index = MI->getOperand(3);
16581   MachineOperand &Disp = MI->getOperand(4);
16582   MachineOperand &Segment = MI->getOperand(5);
16583   unsigned ArgSize = MI->getOperand(6).getImm();
16584   unsigned ArgMode = MI->getOperand(7).getImm();
16585   unsigned Align = MI->getOperand(8).getImm();
16586
16587   // Memory Reference
16588   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16589   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16590   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16591
16592   // Machine Information
16593   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16594   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16595   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16596   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16597   DebugLoc DL = MI->getDebugLoc();
16598
16599   // struct va_list {
16600   //   i32   gp_offset
16601   //   i32   fp_offset
16602   //   i64   overflow_area (address)
16603   //   i64   reg_save_area (address)
16604   // }
16605   // sizeof(va_list) = 24
16606   // alignment(va_list) = 8
16607
16608   unsigned TotalNumIntRegs = 6;
16609   unsigned TotalNumXMMRegs = 8;
16610   bool UseGPOffset = (ArgMode == 1);
16611   bool UseFPOffset = (ArgMode == 2);
16612   unsigned MaxOffset = TotalNumIntRegs * 8 +
16613                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16614
16615   /* Align ArgSize to a multiple of 8 */
16616   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16617   bool NeedsAlign = (Align > 8);
16618
16619   MachineBasicBlock *thisMBB = MBB;
16620   MachineBasicBlock *overflowMBB;
16621   MachineBasicBlock *offsetMBB;
16622   MachineBasicBlock *endMBB;
16623
16624   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16625   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16626   unsigned OffsetReg = 0;
16627
16628   if (!UseGPOffset && !UseFPOffset) {
16629     // If we only pull from the overflow region, we don't create a branch.
16630     // We don't need to alter control flow.
16631     OffsetDestReg = 0; // unused
16632     OverflowDestReg = DestReg;
16633
16634     offsetMBB = nullptr;
16635     overflowMBB = thisMBB;
16636     endMBB = thisMBB;
16637   } else {
16638     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16639     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16640     // If not, pull from overflow_area. (branch to overflowMBB)
16641     //
16642     //       thisMBB
16643     //         |     .
16644     //         |        .
16645     //     offsetMBB   overflowMBB
16646     //         |        .
16647     //         |     .
16648     //        endMBB
16649
16650     // Registers for the PHI in endMBB
16651     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16652     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16653
16654     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16655     MachineFunction *MF = MBB->getParent();
16656     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16657     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16658     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16659
16660     MachineFunction::iterator MBBIter = MBB;
16661     ++MBBIter;
16662
16663     // Insert the new basic blocks
16664     MF->insert(MBBIter, offsetMBB);
16665     MF->insert(MBBIter, overflowMBB);
16666     MF->insert(MBBIter, endMBB);
16667
16668     // Transfer the remainder of MBB and its successor edges to endMBB.
16669     endMBB->splice(endMBB->begin(), thisMBB,
16670                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16671     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16672
16673     // Make offsetMBB and overflowMBB successors of thisMBB
16674     thisMBB->addSuccessor(offsetMBB);
16675     thisMBB->addSuccessor(overflowMBB);
16676
16677     // endMBB is a successor of both offsetMBB and overflowMBB
16678     offsetMBB->addSuccessor(endMBB);
16679     overflowMBB->addSuccessor(endMBB);
16680
16681     // Load the offset value into a register
16682     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16683     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16684       .addOperand(Base)
16685       .addOperand(Scale)
16686       .addOperand(Index)
16687       .addDisp(Disp, UseFPOffset ? 4 : 0)
16688       .addOperand(Segment)
16689       .setMemRefs(MMOBegin, MMOEnd);
16690
16691     // Check if there is enough room left to pull this argument.
16692     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16693       .addReg(OffsetReg)
16694       .addImm(MaxOffset + 8 - ArgSizeA8);
16695
16696     // Branch to "overflowMBB" if offset >= max
16697     // Fall through to "offsetMBB" otherwise
16698     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16699       .addMBB(overflowMBB);
16700   }
16701
16702   // In offsetMBB, emit code to use the reg_save_area.
16703   if (offsetMBB) {
16704     assert(OffsetReg != 0);
16705
16706     // Read the reg_save_area address.
16707     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16708     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16709       .addOperand(Base)
16710       .addOperand(Scale)
16711       .addOperand(Index)
16712       .addDisp(Disp, 16)
16713       .addOperand(Segment)
16714       .setMemRefs(MMOBegin, MMOEnd);
16715
16716     // Zero-extend the offset
16717     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16718       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16719         .addImm(0)
16720         .addReg(OffsetReg)
16721         .addImm(X86::sub_32bit);
16722
16723     // Add the offset to the reg_save_area to get the final address.
16724     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16725       .addReg(OffsetReg64)
16726       .addReg(RegSaveReg);
16727
16728     // Compute the offset for the next argument
16729     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16730     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16731       .addReg(OffsetReg)
16732       .addImm(UseFPOffset ? 16 : 8);
16733
16734     // Store it back into the va_list.
16735     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16736       .addOperand(Base)
16737       .addOperand(Scale)
16738       .addOperand(Index)
16739       .addDisp(Disp, UseFPOffset ? 4 : 0)
16740       .addOperand(Segment)
16741       .addReg(NextOffsetReg)
16742       .setMemRefs(MMOBegin, MMOEnd);
16743
16744     // Jump to endMBB
16745     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16746       .addMBB(endMBB);
16747   }
16748
16749   //
16750   // Emit code to use overflow area
16751   //
16752
16753   // Load the overflow_area address into a register.
16754   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16755   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16756     .addOperand(Base)
16757     .addOperand(Scale)
16758     .addOperand(Index)
16759     .addDisp(Disp, 8)
16760     .addOperand(Segment)
16761     .setMemRefs(MMOBegin, MMOEnd);
16762
16763   // If we need to align it, do so. Otherwise, just copy the address
16764   // to OverflowDestReg.
16765   if (NeedsAlign) {
16766     // Align the overflow address
16767     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16768     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16769
16770     // aligned_addr = (addr + (align-1)) & ~(align-1)
16771     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16772       .addReg(OverflowAddrReg)
16773       .addImm(Align-1);
16774
16775     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16776       .addReg(TmpReg)
16777       .addImm(~(uint64_t)(Align-1));
16778   } else {
16779     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16780       .addReg(OverflowAddrReg);
16781   }
16782
16783   // Compute the next overflow address after this argument.
16784   // (the overflow address should be kept 8-byte aligned)
16785   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16786   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16787     .addReg(OverflowDestReg)
16788     .addImm(ArgSizeA8);
16789
16790   // Store the new overflow address.
16791   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16792     .addOperand(Base)
16793     .addOperand(Scale)
16794     .addOperand(Index)
16795     .addDisp(Disp, 8)
16796     .addOperand(Segment)
16797     .addReg(NextAddrReg)
16798     .setMemRefs(MMOBegin, MMOEnd);
16799
16800   // If we branched, emit the PHI to the front of endMBB.
16801   if (offsetMBB) {
16802     BuildMI(*endMBB, endMBB->begin(), DL,
16803             TII->get(X86::PHI), DestReg)
16804       .addReg(OffsetDestReg).addMBB(offsetMBB)
16805       .addReg(OverflowDestReg).addMBB(overflowMBB);
16806   }
16807
16808   // Erase the pseudo instruction
16809   MI->eraseFromParent();
16810
16811   return endMBB;
16812 }
16813
16814 MachineBasicBlock *
16815 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16816                                                  MachineInstr *MI,
16817                                                  MachineBasicBlock *MBB) const {
16818   // Emit code to save XMM registers to the stack. The ABI says that the
16819   // number of registers to save is given in %al, so it's theoretically
16820   // possible to do an indirect jump trick to avoid saving all of them,
16821   // however this code takes a simpler approach and just executes all
16822   // of the stores if %al is non-zero. It's less code, and it's probably
16823   // easier on the hardware branch predictor, and stores aren't all that
16824   // expensive anyway.
16825
16826   // Create the new basic blocks. One block contains all the XMM stores,
16827   // and one block is the final destination regardless of whether any
16828   // stores were performed.
16829   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16830   MachineFunction *F = MBB->getParent();
16831   MachineFunction::iterator MBBIter = MBB;
16832   ++MBBIter;
16833   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16834   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16835   F->insert(MBBIter, XMMSaveMBB);
16836   F->insert(MBBIter, EndMBB);
16837
16838   // Transfer the remainder of MBB and its successor edges to EndMBB.
16839   EndMBB->splice(EndMBB->begin(), MBB,
16840                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16841   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16842
16843   // The original block will now fall through to the XMM save block.
16844   MBB->addSuccessor(XMMSaveMBB);
16845   // The XMMSaveMBB will fall through to the end block.
16846   XMMSaveMBB->addSuccessor(EndMBB);
16847
16848   // Now add the instructions.
16849   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16850   DebugLoc DL = MI->getDebugLoc();
16851
16852   unsigned CountReg = MI->getOperand(0).getReg();
16853   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16854   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16855
16856   if (!Subtarget->isTargetWin64()) {
16857     // If %al is 0, branch around the XMM save block.
16858     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16859     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16860     MBB->addSuccessor(EndMBB);
16861   }
16862
16863   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16864   // that was just emitted, but clearly shouldn't be "saved".
16865   assert((MI->getNumOperands() <= 3 ||
16866           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16867           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16868          && "Expected last argument to be EFLAGS");
16869   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16870   // In the XMM save block, save all the XMM argument registers.
16871   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16872     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16873     MachineMemOperand *MMO =
16874       F->getMachineMemOperand(
16875           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16876         MachineMemOperand::MOStore,
16877         /*Size=*/16, /*Align=*/16);
16878     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16879       .addFrameIndex(RegSaveFrameIndex)
16880       .addImm(/*Scale=*/1)
16881       .addReg(/*IndexReg=*/0)
16882       .addImm(/*Disp=*/Offset)
16883       .addReg(/*Segment=*/0)
16884       .addReg(MI->getOperand(i).getReg())
16885       .addMemOperand(MMO);
16886   }
16887
16888   MI->eraseFromParent();   // The pseudo instruction is gone now.
16889
16890   return EndMBB;
16891 }
16892
16893 // The EFLAGS operand of SelectItr might be missing a kill marker
16894 // because there were multiple uses of EFLAGS, and ISel didn't know
16895 // which to mark. Figure out whether SelectItr should have had a
16896 // kill marker, and set it if it should. Returns the correct kill
16897 // marker value.
16898 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16899                                      MachineBasicBlock* BB,
16900                                      const TargetRegisterInfo* TRI) {
16901   // Scan forward through BB for a use/def of EFLAGS.
16902   MachineBasicBlock::iterator miI(std::next(SelectItr));
16903   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16904     const MachineInstr& mi = *miI;
16905     if (mi.readsRegister(X86::EFLAGS))
16906       return false;
16907     if (mi.definesRegister(X86::EFLAGS))
16908       break; // Should have kill-flag - update below.
16909   }
16910
16911   // If we hit the end of the block, check whether EFLAGS is live into a
16912   // successor.
16913   if (miI == BB->end()) {
16914     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16915                                           sEnd = BB->succ_end();
16916          sItr != sEnd; ++sItr) {
16917       MachineBasicBlock* succ = *sItr;
16918       if (succ->isLiveIn(X86::EFLAGS))
16919         return false;
16920     }
16921   }
16922
16923   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16924   // out. SelectMI should have a kill flag on EFLAGS.
16925   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16926   return true;
16927 }
16928
16929 MachineBasicBlock *
16930 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16931                                      MachineBasicBlock *BB) const {
16932   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16933   DebugLoc DL = MI->getDebugLoc();
16934
16935   // To "insert" a SELECT_CC instruction, we actually have to insert the
16936   // diamond control-flow pattern.  The incoming instruction knows the
16937   // destination vreg to set, the condition code register to branch on, the
16938   // true/false values to select between, and a branch opcode to use.
16939   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16940   MachineFunction::iterator It = BB;
16941   ++It;
16942
16943   //  thisMBB:
16944   //  ...
16945   //   TrueVal = ...
16946   //   cmpTY ccX, r1, r2
16947   //   bCC copy1MBB
16948   //   fallthrough --> copy0MBB
16949   MachineBasicBlock *thisMBB = BB;
16950   MachineFunction *F = BB->getParent();
16951   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16952   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16953   F->insert(It, copy0MBB);
16954   F->insert(It, sinkMBB);
16955
16956   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16957   // live into the sink and copy blocks.
16958   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16959   if (!MI->killsRegister(X86::EFLAGS) &&
16960       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16961     copy0MBB->addLiveIn(X86::EFLAGS);
16962     sinkMBB->addLiveIn(X86::EFLAGS);
16963   }
16964
16965   // Transfer the remainder of BB and its successor edges to sinkMBB.
16966   sinkMBB->splice(sinkMBB->begin(), BB,
16967                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16968   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16969
16970   // Add the true and fallthrough blocks as its successors.
16971   BB->addSuccessor(copy0MBB);
16972   BB->addSuccessor(sinkMBB);
16973
16974   // Create the conditional branch instruction.
16975   unsigned Opc =
16976     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16977   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16978
16979   //  copy0MBB:
16980   //   %FalseValue = ...
16981   //   # fallthrough to sinkMBB
16982   copy0MBB->addSuccessor(sinkMBB);
16983
16984   //  sinkMBB:
16985   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16986   //  ...
16987   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16988           TII->get(X86::PHI), MI->getOperand(0).getReg())
16989     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16990     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16991
16992   MI->eraseFromParent();   // The pseudo instruction is gone now.
16993   return sinkMBB;
16994 }
16995
16996 MachineBasicBlock *
16997 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16998                                         bool Is64Bit) const {
16999   MachineFunction *MF = BB->getParent();
17000   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17001   DebugLoc DL = MI->getDebugLoc();
17002   const BasicBlock *LLVM_BB = BB->getBasicBlock();
17003
17004   assert(MF->shouldSplitStack());
17005
17006   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
17007   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
17008
17009   // BB:
17010   //  ... [Till the alloca]
17011   // If stacklet is not large enough, jump to mallocMBB
17012   //
17013   // bumpMBB:
17014   //  Allocate by subtracting from RSP
17015   //  Jump to continueMBB
17016   //
17017   // mallocMBB:
17018   //  Allocate by call to runtime
17019   //
17020   // continueMBB:
17021   //  ...
17022   //  [rest of original BB]
17023   //
17024
17025   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17026   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17027   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
17028
17029   MachineRegisterInfo &MRI = MF->getRegInfo();
17030   const TargetRegisterClass *AddrRegClass =
17031     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
17032
17033   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17034     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
17035     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
17036     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
17037     sizeVReg = MI->getOperand(1).getReg(),
17038     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
17039
17040   MachineFunction::iterator MBBIter = BB;
17041   ++MBBIter;
17042
17043   MF->insert(MBBIter, bumpMBB);
17044   MF->insert(MBBIter, mallocMBB);
17045   MF->insert(MBBIter, continueMBB);
17046
17047   continueMBB->splice(continueMBB->begin(), BB,
17048                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
17049   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
17050
17051   // Add code to the main basic block to check if the stack limit has been hit,
17052   // and if so, jump to mallocMBB otherwise to bumpMBB.
17053   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
17054   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
17055     .addReg(tmpSPVReg).addReg(sizeVReg);
17056   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
17057     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
17058     .addReg(SPLimitVReg);
17059   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
17060
17061   // bumpMBB simply decreases the stack pointer, since we know the current
17062   // stacklet has enough space.
17063   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
17064     .addReg(SPLimitVReg);
17065   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
17066     .addReg(SPLimitVReg);
17067   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17068
17069   // Calls into a routine in libgcc to allocate more space from the heap.
17070   const uint32_t *RegMask =
17071     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17072   if (Is64Bit) {
17073     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
17074       .addReg(sizeVReg);
17075     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
17076       .addExternalSymbol("__morestack_allocate_stack_space")
17077       .addRegMask(RegMask)
17078       .addReg(X86::RDI, RegState::Implicit)
17079       .addReg(X86::RAX, RegState::ImplicitDefine);
17080   } else {
17081     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
17082       .addImm(12);
17083     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
17084     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
17085       .addExternalSymbol("__morestack_allocate_stack_space")
17086       .addRegMask(RegMask)
17087       .addReg(X86::EAX, RegState::ImplicitDefine);
17088   }
17089
17090   if (!Is64Bit)
17091     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
17092       .addImm(16);
17093
17094   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
17095     .addReg(Is64Bit ? X86::RAX : X86::EAX);
17096   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
17097
17098   // Set up the CFG correctly.
17099   BB->addSuccessor(bumpMBB);
17100   BB->addSuccessor(mallocMBB);
17101   mallocMBB->addSuccessor(continueMBB);
17102   bumpMBB->addSuccessor(continueMBB);
17103
17104   // Take care of the PHI nodes.
17105   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
17106           MI->getOperand(0).getReg())
17107     .addReg(mallocPtrVReg).addMBB(mallocMBB)
17108     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
17109
17110   // Delete the original pseudo instruction.
17111   MI->eraseFromParent();
17112
17113   // And we're done.
17114   return continueMBB;
17115 }
17116
17117 MachineBasicBlock *
17118 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
17119                                         MachineBasicBlock *BB) const {
17120   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
17121   DebugLoc DL = MI->getDebugLoc();
17122
17123   assert(!Subtarget->isTargetMacho());
17124
17125   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
17126   // non-trivial part is impdef of ESP.
17127
17128   if (Subtarget->isTargetWin64()) {
17129     if (Subtarget->isTargetCygMing()) {
17130       // ___chkstk(Mingw64):
17131       // Clobbers R10, R11, RAX and EFLAGS.
17132       // Updates RSP.
17133       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17134         .addExternalSymbol("___chkstk")
17135         .addReg(X86::RAX, RegState::Implicit)
17136         .addReg(X86::RSP, RegState::Implicit)
17137         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
17138         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
17139         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17140     } else {
17141       // __chkstk(MSVCRT): does not update stack pointer.
17142       // Clobbers R10, R11 and EFLAGS.
17143       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17144         .addExternalSymbol("__chkstk")
17145         .addReg(X86::RAX, RegState::Implicit)
17146         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17147       // RAX has the offset to be subtracted from RSP.
17148       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17149         .addReg(X86::RSP)
17150         .addReg(X86::RAX);
17151     }
17152   } else {
17153     const char *StackProbeSymbol =
17154       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17155
17156     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17157       .addExternalSymbol(StackProbeSymbol)
17158       .addReg(X86::EAX, RegState::Implicit)
17159       .addReg(X86::ESP, RegState::Implicit)
17160       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17161       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17162       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17163   }
17164
17165   MI->eraseFromParent();   // The pseudo instruction is gone now.
17166   return BB;
17167 }
17168
17169 MachineBasicBlock *
17170 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17171                                       MachineBasicBlock *BB) const {
17172   // This is pretty easy.  We're taking the value that we received from
17173   // our load from the relocation, sticking it in either RDI (x86-64)
17174   // or EAX and doing an indirect call.  The return value will then
17175   // be in the normal return register.
17176   MachineFunction *F = BB->getParent();
17177   const X86InstrInfo *TII
17178     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17179   DebugLoc DL = MI->getDebugLoc();
17180
17181   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17182   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17183
17184   // Get a register mask for the lowered call.
17185   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17186   // proper register mask.
17187   const uint32_t *RegMask =
17188     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17189   if (Subtarget->is64Bit()) {
17190     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17191                                       TII->get(X86::MOV64rm), X86::RDI)
17192     .addReg(X86::RIP)
17193     .addImm(0).addReg(0)
17194     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17195                       MI->getOperand(3).getTargetFlags())
17196     .addReg(0);
17197     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17198     addDirectMem(MIB, X86::RDI);
17199     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17200   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17201     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17202                                       TII->get(X86::MOV32rm), X86::EAX)
17203     .addReg(0)
17204     .addImm(0).addReg(0)
17205     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17206                       MI->getOperand(3).getTargetFlags())
17207     .addReg(0);
17208     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17209     addDirectMem(MIB, X86::EAX);
17210     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17211   } else {
17212     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17213                                       TII->get(X86::MOV32rm), X86::EAX)
17214     .addReg(TII->getGlobalBaseReg(F))
17215     .addImm(0).addReg(0)
17216     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17217                       MI->getOperand(3).getTargetFlags())
17218     .addReg(0);
17219     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17220     addDirectMem(MIB, X86::EAX);
17221     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17222   }
17223
17224   MI->eraseFromParent(); // The pseudo instruction is gone now.
17225   return BB;
17226 }
17227
17228 MachineBasicBlock *
17229 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17230                                     MachineBasicBlock *MBB) const {
17231   DebugLoc DL = MI->getDebugLoc();
17232   MachineFunction *MF = MBB->getParent();
17233   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17234   MachineRegisterInfo &MRI = MF->getRegInfo();
17235
17236   const BasicBlock *BB = MBB->getBasicBlock();
17237   MachineFunction::iterator I = MBB;
17238   ++I;
17239
17240   // Memory Reference
17241   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17242   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17243
17244   unsigned DstReg;
17245   unsigned MemOpndSlot = 0;
17246
17247   unsigned CurOp = 0;
17248
17249   DstReg = MI->getOperand(CurOp++).getReg();
17250   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17251   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17252   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17253   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17254
17255   MemOpndSlot = CurOp;
17256
17257   MVT PVT = getPointerTy();
17258   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17259          "Invalid Pointer Size!");
17260
17261   // For v = setjmp(buf), we generate
17262   //
17263   // thisMBB:
17264   //  buf[LabelOffset] = restoreMBB
17265   //  SjLjSetup restoreMBB
17266   //
17267   // mainMBB:
17268   //  v_main = 0
17269   //
17270   // sinkMBB:
17271   //  v = phi(main, restore)
17272   //
17273   // restoreMBB:
17274   //  v_restore = 1
17275
17276   MachineBasicBlock *thisMBB = MBB;
17277   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17278   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17279   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17280   MF->insert(I, mainMBB);
17281   MF->insert(I, sinkMBB);
17282   MF->push_back(restoreMBB);
17283
17284   MachineInstrBuilder MIB;
17285
17286   // Transfer the remainder of BB and its successor edges to sinkMBB.
17287   sinkMBB->splice(sinkMBB->begin(), MBB,
17288                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17289   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17290
17291   // thisMBB:
17292   unsigned PtrStoreOpc = 0;
17293   unsigned LabelReg = 0;
17294   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17295   Reloc::Model RM = MF->getTarget().getRelocationModel();
17296   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17297                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17298
17299   // Prepare IP either in reg or imm.
17300   if (!UseImmLabel) {
17301     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17302     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17303     LabelReg = MRI.createVirtualRegister(PtrRC);
17304     if (Subtarget->is64Bit()) {
17305       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17306               .addReg(X86::RIP)
17307               .addImm(0)
17308               .addReg(0)
17309               .addMBB(restoreMBB)
17310               .addReg(0);
17311     } else {
17312       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17313       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17314               .addReg(XII->getGlobalBaseReg(MF))
17315               .addImm(0)
17316               .addReg(0)
17317               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17318               .addReg(0);
17319     }
17320   } else
17321     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17322   // Store IP
17323   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17324   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17325     if (i == X86::AddrDisp)
17326       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17327     else
17328       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17329   }
17330   if (!UseImmLabel)
17331     MIB.addReg(LabelReg);
17332   else
17333     MIB.addMBB(restoreMBB);
17334   MIB.setMemRefs(MMOBegin, MMOEnd);
17335   // Setup
17336   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17337           .addMBB(restoreMBB);
17338
17339   const X86RegisterInfo *RegInfo =
17340     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17341   MIB.addRegMask(RegInfo->getNoPreservedMask());
17342   thisMBB->addSuccessor(mainMBB);
17343   thisMBB->addSuccessor(restoreMBB);
17344
17345   // mainMBB:
17346   //  EAX = 0
17347   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17348   mainMBB->addSuccessor(sinkMBB);
17349
17350   // sinkMBB:
17351   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17352           TII->get(X86::PHI), DstReg)
17353     .addReg(mainDstReg).addMBB(mainMBB)
17354     .addReg(restoreDstReg).addMBB(restoreMBB);
17355
17356   // restoreMBB:
17357   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17358   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17359   restoreMBB->addSuccessor(sinkMBB);
17360
17361   MI->eraseFromParent();
17362   return sinkMBB;
17363 }
17364
17365 MachineBasicBlock *
17366 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17367                                      MachineBasicBlock *MBB) const {
17368   DebugLoc DL = MI->getDebugLoc();
17369   MachineFunction *MF = MBB->getParent();
17370   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17371   MachineRegisterInfo &MRI = MF->getRegInfo();
17372
17373   // Memory Reference
17374   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17375   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17376
17377   MVT PVT = getPointerTy();
17378   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17379          "Invalid Pointer Size!");
17380
17381   const TargetRegisterClass *RC =
17382     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17383   unsigned Tmp = MRI.createVirtualRegister(RC);
17384   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17385   const X86RegisterInfo *RegInfo =
17386     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17387   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17388   unsigned SP = RegInfo->getStackRegister();
17389
17390   MachineInstrBuilder MIB;
17391
17392   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17393   const int64_t SPOffset = 2 * PVT.getStoreSize();
17394
17395   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17396   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17397
17398   // Reload FP
17399   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17400   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17401     MIB.addOperand(MI->getOperand(i));
17402   MIB.setMemRefs(MMOBegin, MMOEnd);
17403   // Reload IP
17404   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17405   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17406     if (i == X86::AddrDisp)
17407       MIB.addDisp(MI->getOperand(i), LabelOffset);
17408     else
17409       MIB.addOperand(MI->getOperand(i));
17410   }
17411   MIB.setMemRefs(MMOBegin, MMOEnd);
17412   // Reload SP
17413   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17414   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17415     if (i == X86::AddrDisp)
17416       MIB.addDisp(MI->getOperand(i), SPOffset);
17417     else
17418       MIB.addOperand(MI->getOperand(i));
17419   }
17420   MIB.setMemRefs(MMOBegin, MMOEnd);
17421   // Jump
17422   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17423
17424   MI->eraseFromParent();
17425   return MBB;
17426 }
17427
17428 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17429 // accumulator loops. Writing back to the accumulator allows the coalescer
17430 // to remove extra copies in the loop.   
17431 MachineBasicBlock *
17432 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17433                                  MachineBasicBlock *MBB) const {
17434   MachineOperand &AddendOp = MI->getOperand(3);
17435
17436   // Bail out early if the addend isn't a register - we can't switch these.
17437   if (!AddendOp.isReg())
17438     return MBB;
17439
17440   MachineFunction &MF = *MBB->getParent();
17441   MachineRegisterInfo &MRI = MF.getRegInfo();
17442
17443   // Check whether the addend is defined by a PHI:
17444   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17445   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17446   if (!AddendDef.isPHI())
17447     return MBB;
17448
17449   // Look for the following pattern:
17450   // loop:
17451   //   %addend = phi [%entry, 0], [%loop, %result]
17452   //   ...
17453   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17454
17455   // Replace with:
17456   //   loop:
17457   //   %addend = phi [%entry, 0], [%loop, %result]
17458   //   ...
17459   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17460
17461   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17462     assert(AddendDef.getOperand(i).isReg());
17463     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17464     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17465     if (&PHISrcInst == MI) {
17466       // Found a matching instruction.
17467       unsigned NewFMAOpc = 0;
17468       switch (MI->getOpcode()) {
17469         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17470         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17471         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17472         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17473         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17474         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17475         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17476         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17477         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17478         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17479         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17480         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17481         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17482         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17483         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17484         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17485         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17486         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17487         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17488         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17489         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17490         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17491         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17492         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17493         default: llvm_unreachable("Unrecognized FMA variant.");
17494       }
17495
17496       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17497       MachineInstrBuilder MIB =
17498         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17499         .addOperand(MI->getOperand(0))
17500         .addOperand(MI->getOperand(3))
17501         .addOperand(MI->getOperand(2))
17502         .addOperand(MI->getOperand(1));
17503       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17504       MI->eraseFromParent();
17505     }
17506   }
17507
17508   return MBB;
17509 }
17510
17511 MachineBasicBlock *
17512 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17513                                                MachineBasicBlock *BB) const {
17514   switch (MI->getOpcode()) {
17515   default: llvm_unreachable("Unexpected instr type to insert");
17516   case X86::TAILJMPd64:
17517   case X86::TAILJMPr64:
17518   case X86::TAILJMPm64:
17519     llvm_unreachable("TAILJMP64 would not be touched here.");
17520   case X86::TCRETURNdi64:
17521   case X86::TCRETURNri64:
17522   case X86::TCRETURNmi64:
17523     return BB;
17524   case X86::WIN_ALLOCA:
17525     return EmitLoweredWinAlloca(MI, BB);
17526   case X86::SEG_ALLOCA_32:
17527     return EmitLoweredSegAlloca(MI, BB, false);
17528   case X86::SEG_ALLOCA_64:
17529     return EmitLoweredSegAlloca(MI, BB, true);
17530   case X86::TLSCall_32:
17531   case X86::TLSCall_64:
17532     return EmitLoweredTLSCall(MI, BB);
17533   case X86::CMOV_GR8:
17534   case X86::CMOV_FR32:
17535   case X86::CMOV_FR64:
17536   case X86::CMOV_V4F32:
17537   case X86::CMOV_V2F64:
17538   case X86::CMOV_V2I64:
17539   case X86::CMOV_V8F32:
17540   case X86::CMOV_V4F64:
17541   case X86::CMOV_V4I64:
17542   case X86::CMOV_V16F32:
17543   case X86::CMOV_V8F64:
17544   case X86::CMOV_V8I64:
17545   case X86::CMOV_GR16:
17546   case X86::CMOV_GR32:
17547   case X86::CMOV_RFP32:
17548   case X86::CMOV_RFP64:
17549   case X86::CMOV_RFP80:
17550     return EmitLoweredSelect(MI, BB);
17551
17552   case X86::FP32_TO_INT16_IN_MEM:
17553   case X86::FP32_TO_INT32_IN_MEM:
17554   case X86::FP32_TO_INT64_IN_MEM:
17555   case X86::FP64_TO_INT16_IN_MEM:
17556   case X86::FP64_TO_INT32_IN_MEM:
17557   case X86::FP64_TO_INT64_IN_MEM:
17558   case X86::FP80_TO_INT16_IN_MEM:
17559   case X86::FP80_TO_INT32_IN_MEM:
17560   case X86::FP80_TO_INT64_IN_MEM: {
17561     MachineFunction *F = BB->getParent();
17562     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17563     DebugLoc DL = MI->getDebugLoc();
17564
17565     // Change the floating point control register to use "round towards zero"
17566     // mode when truncating to an integer value.
17567     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17568     addFrameReference(BuildMI(*BB, MI, DL,
17569                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17570
17571     // Load the old value of the high byte of the control word...
17572     unsigned OldCW =
17573       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17574     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17575                       CWFrameIdx);
17576
17577     // Set the high part to be round to zero...
17578     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17579       .addImm(0xC7F);
17580
17581     // Reload the modified control word now...
17582     addFrameReference(BuildMI(*BB, MI, DL,
17583                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17584
17585     // Restore the memory image of control word to original value
17586     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17587       .addReg(OldCW);
17588
17589     // Get the X86 opcode to use.
17590     unsigned Opc;
17591     switch (MI->getOpcode()) {
17592     default: llvm_unreachable("illegal opcode!");
17593     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17594     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17595     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17596     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17597     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17598     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17599     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17600     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17601     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17602     }
17603
17604     X86AddressMode AM;
17605     MachineOperand &Op = MI->getOperand(0);
17606     if (Op.isReg()) {
17607       AM.BaseType = X86AddressMode::RegBase;
17608       AM.Base.Reg = Op.getReg();
17609     } else {
17610       AM.BaseType = X86AddressMode::FrameIndexBase;
17611       AM.Base.FrameIndex = Op.getIndex();
17612     }
17613     Op = MI->getOperand(1);
17614     if (Op.isImm())
17615       AM.Scale = Op.getImm();
17616     Op = MI->getOperand(2);
17617     if (Op.isImm())
17618       AM.IndexReg = Op.getImm();
17619     Op = MI->getOperand(3);
17620     if (Op.isGlobal()) {
17621       AM.GV = Op.getGlobal();
17622     } else {
17623       AM.Disp = Op.getImm();
17624     }
17625     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17626                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17627
17628     // Reload the original control word now.
17629     addFrameReference(BuildMI(*BB, MI, DL,
17630                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17631
17632     MI->eraseFromParent();   // The pseudo instruction is gone now.
17633     return BB;
17634   }
17635     // String/text processing lowering.
17636   case X86::PCMPISTRM128REG:
17637   case X86::VPCMPISTRM128REG:
17638   case X86::PCMPISTRM128MEM:
17639   case X86::VPCMPISTRM128MEM:
17640   case X86::PCMPESTRM128REG:
17641   case X86::VPCMPESTRM128REG:
17642   case X86::PCMPESTRM128MEM:
17643   case X86::VPCMPESTRM128MEM:
17644     assert(Subtarget->hasSSE42() &&
17645            "Target must have SSE4.2 or AVX features enabled");
17646     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17647
17648   // String/text processing lowering.
17649   case X86::PCMPISTRIREG:
17650   case X86::VPCMPISTRIREG:
17651   case X86::PCMPISTRIMEM:
17652   case X86::VPCMPISTRIMEM:
17653   case X86::PCMPESTRIREG:
17654   case X86::VPCMPESTRIREG:
17655   case X86::PCMPESTRIMEM:
17656   case X86::VPCMPESTRIMEM:
17657     assert(Subtarget->hasSSE42() &&
17658            "Target must have SSE4.2 or AVX features enabled");
17659     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17660
17661   // Thread synchronization.
17662   case X86::MONITOR:
17663     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17664
17665   // xbegin
17666   case X86::XBEGIN:
17667     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17668
17669   // Atomic Lowering.
17670   case X86::ATOMAND8:
17671   case X86::ATOMAND16:
17672   case X86::ATOMAND32:
17673   case X86::ATOMAND64:
17674     // Fall through
17675   case X86::ATOMOR8:
17676   case X86::ATOMOR16:
17677   case X86::ATOMOR32:
17678   case X86::ATOMOR64:
17679     // Fall through
17680   case X86::ATOMXOR16:
17681   case X86::ATOMXOR8:
17682   case X86::ATOMXOR32:
17683   case X86::ATOMXOR64:
17684     // Fall through
17685   case X86::ATOMNAND8:
17686   case X86::ATOMNAND16:
17687   case X86::ATOMNAND32:
17688   case X86::ATOMNAND64:
17689     // Fall through
17690   case X86::ATOMMAX8:
17691   case X86::ATOMMAX16:
17692   case X86::ATOMMAX32:
17693   case X86::ATOMMAX64:
17694     // Fall through
17695   case X86::ATOMMIN8:
17696   case X86::ATOMMIN16:
17697   case X86::ATOMMIN32:
17698   case X86::ATOMMIN64:
17699     // Fall through
17700   case X86::ATOMUMAX8:
17701   case X86::ATOMUMAX16:
17702   case X86::ATOMUMAX32:
17703   case X86::ATOMUMAX64:
17704     // Fall through
17705   case X86::ATOMUMIN8:
17706   case X86::ATOMUMIN16:
17707   case X86::ATOMUMIN32:
17708   case X86::ATOMUMIN64:
17709     return EmitAtomicLoadArith(MI, BB);
17710
17711   // This group does 64-bit operations on a 32-bit host.
17712   case X86::ATOMAND6432:
17713   case X86::ATOMOR6432:
17714   case X86::ATOMXOR6432:
17715   case X86::ATOMNAND6432:
17716   case X86::ATOMADD6432:
17717   case X86::ATOMSUB6432:
17718   case X86::ATOMMAX6432:
17719   case X86::ATOMMIN6432:
17720   case X86::ATOMUMAX6432:
17721   case X86::ATOMUMIN6432:
17722   case X86::ATOMSWAP6432:
17723     return EmitAtomicLoadArith6432(MI, BB);
17724
17725   case X86::VASTART_SAVE_XMM_REGS:
17726     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17727
17728   case X86::VAARG_64:
17729     return EmitVAARG64WithCustomInserter(MI, BB);
17730
17731   case X86::EH_SjLj_SetJmp32:
17732   case X86::EH_SjLj_SetJmp64:
17733     return emitEHSjLjSetJmp(MI, BB);
17734
17735   case X86::EH_SjLj_LongJmp32:
17736   case X86::EH_SjLj_LongJmp64:
17737     return emitEHSjLjLongJmp(MI, BB);
17738
17739   case TargetOpcode::STACKMAP:
17740   case TargetOpcode::PATCHPOINT:
17741     return emitPatchPoint(MI, BB);
17742
17743   case X86::VFMADDPDr213r:
17744   case X86::VFMADDPSr213r:
17745   case X86::VFMADDSDr213r:
17746   case X86::VFMADDSSr213r:
17747   case X86::VFMSUBPDr213r:
17748   case X86::VFMSUBPSr213r:
17749   case X86::VFMSUBSDr213r:
17750   case X86::VFMSUBSSr213r:
17751   case X86::VFNMADDPDr213r:
17752   case X86::VFNMADDPSr213r:
17753   case X86::VFNMADDSDr213r:
17754   case X86::VFNMADDSSr213r:
17755   case X86::VFNMSUBPDr213r:
17756   case X86::VFNMSUBPSr213r:
17757   case X86::VFNMSUBSDr213r:
17758   case X86::VFNMSUBSSr213r:
17759   case X86::VFMADDPDr213rY:
17760   case X86::VFMADDPSr213rY:
17761   case X86::VFMSUBPDr213rY:
17762   case X86::VFMSUBPSr213rY:
17763   case X86::VFNMADDPDr213rY:
17764   case X86::VFNMADDPSr213rY:
17765   case X86::VFNMSUBPDr213rY:
17766   case X86::VFNMSUBPSr213rY:
17767     return emitFMA3Instr(MI, BB);
17768   }
17769 }
17770
17771 //===----------------------------------------------------------------------===//
17772 //                           X86 Optimization Hooks
17773 //===----------------------------------------------------------------------===//
17774
17775 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17776                                                       APInt &KnownZero,
17777                                                       APInt &KnownOne,
17778                                                       const SelectionDAG &DAG,
17779                                                       unsigned Depth) const {
17780   unsigned BitWidth = KnownZero.getBitWidth();
17781   unsigned Opc = Op.getOpcode();
17782   assert((Opc >= ISD::BUILTIN_OP_END ||
17783           Opc == ISD::INTRINSIC_WO_CHAIN ||
17784           Opc == ISD::INTRINSIC_W_CHAIN ||
17785           Opc == ISD::INTRINSIC_VOID) &&
17786          "Should use MaskedValueIsZero if you don't know whether Op"
17787          " is a target node!");
17788
17789   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17790   switch (Opc) {
17791   default: break;
17792   case X86ISD::ADD:
17793   case X86ISD::SUB:
17794   case X86ISD::ADC:
17795   case X86ISD::SBB:
17796   case X86ISD::SMUL:
17797   case X86ISD::UMUL:
17798   case X86ISD::INC:
17799   case X86ISD::DEC:
17800   case X86ISD::OR:
17801   case X86ISD::XOR:
17802   case X86ISD::AND:
17803     // These nodes' second result is a boolean.
17804     if (Op.getResNo() == 0)
17805       break;
17806     // Fallthrough
17807   case X86ISD::SETCC:
17808     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17809     break;
17810   case ISD::INTRINSIC_WO_CHAIN: {
17811     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17812     unsigned NumLoBits = 0;
17813     switch (IntId) {
17814     default: break;
17815     case Intrinsic::x86_sse_movmsk_ps:
17816     case Intrinsic::x86_avx_movmsk_ps_256:
17817     case Intrinsic::x86_sse2_movmsk_pd:
17818     case Intrinsic::x86_avx_movmsk_pd_256:
17819     case Intrinsic::x86_mmx_pmovmskb:
17820     case Intrinsic::x86_sse2_pmovmskb_128:
17821     case Intrinsic::x86_avx2_pmovmskb: {
17822       // High bits of movmskp{s|d}, pmovmskb are known zero.
17823       switch (IntId) {
17824         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17825         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17826         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17827         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17828         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17829         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17830         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17831         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17832       }
17833       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17834       break;
17835     }
17836     }
17837     break;
17838   }
17839   }
17840 }
17841
17842 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17843   SDValue Op,
17844   const SelectionDAG &,
17845   unsigned Depth) const {
17846   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17847   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17848     return Op.getValueType().getScalarType().getSizeInBits();
17849
17850   // Fallback case.
17851   return 1;
17852 }
17853
17854 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17855 /// node is a GlobalAddress + offset.
17856 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17857                                        const GlobalValue* &GA,
17858                                        int64_t &Offset) const {
17859   if (N->getOpcode() == X86ISD::Wrapper) {
17860     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17861       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17862       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17863       return true;
17864     }
17865   }
17866   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17867 }
17868
17869 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17870 /// same as extracting the high 128-bit part of 256-bit vector and then
17871 /// inserting the result into the low part of a new 256-bit vector
17872 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17873   EVT VT = SVOp->getValueType(0);
17874   unsigned NumElems = VT.getVectorNumElements();
17875
17876   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17877   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17878     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17879         SVOp->getMaskElt(j) >= 0)
17880       return false;
17881
17882   return true;
17883 }
17884
17885 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17886 /// same as extracting the low 128-bit part of 256-bit vector and then
17887 /// inserting the result into the high part of a new 256-bit vector
17888 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17889   EVT VT = SVOp->getValueType(0);
17890   unsigned NumElems = VT.getVectorNumElements();
17891
17892   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17893   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17894     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17895         SVOp->getMaskElt(j) >= 0)
17896       return false;
17897
17898   return true;
17899 }
17900
17901 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17902 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17903                                         TargetLowering::DAGCombinerInfo &DCI,
17904                                         const X86Subtarget* Subtarget) {
17905   SDLoc dl(N);
17906   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17907   SDValue V1 = SVOp->getOperand(0);
17908   SDValue V2 = SVOp->getOperand(1);
17909   EVT VT = SVOp->getValueType(0);
17910   unsigned NumElems = VT.getVectorNumElements();
17911
17912   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17913       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17914     //
17915     //                   0,0,0,...
17916     //                      |
17917     //    V      UNDEF    BUILD_VECTOR    UNDEF
17918     //     \      /           \           /
17919     //  CONCAT_VECTOR         CONCAT_VECTOR
17920     //         \                  /
17921     //          \                /
17922     //          RESULT: V + zero extended
17923     //
17924     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17925         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17926         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17927       return SDValue();
17928
17929     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17930       return SDValue();
17931
17932     // To match the shuffle mask, the first half of the mask should
17933     // be exactly the first vector, and all the rest a splat with the
17934     // first element of the second one.
17935     for (unsigned i = 0; i != NumElems/2; ++i)
17936       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17937           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17938         return SDValue();
17939
17940     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17941     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17942       if (Ld->hasNUsesOfValue(1, 0)) {
17943         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17944         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17945         SDValue ResNode =
17946           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17947                                   Ld->getMemoryVT(),
17948                                   Ld->getPointerInfo(),
17949                                   Ld->getAlignment(),
17950                                   false/*isVolatile*/, true/*ReadMem*/,
17951                                   false/*WriteMem*/);
17952
17953         // Make sure the newly-created LOAD is in the same position as Ld in
17954         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17955         // and update uses of Ld's output chain to use the TokenFactor.
17956         if (Ld->hasAnyUseOfValue(1)) {
17957           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17958                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17959           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17960           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17961                                  SDValue(ResNode.getNode(), 1));
17962         }
17963
17964         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17965       }
17966     }
17967
17968     // Emit a zeroed vector and insert the desired subvector on its
17969     // first half.
17970     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17971     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17972     return DCI.CombineTo(N, InsV);
17973   }
17974
17975   //===--------------------------------------------------------------------===//
17976   // Combine some shuffles into subvector extracts and inserts:
17977   //
17978
17979   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17980   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17981     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17982     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17983     return DCI.CombineTo(N, InsV);
17984   }
17985
17986   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17987   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17988     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17989     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17990     return DCI.CombineTo(N, InsV);
17991   }
17992
17993   return SDValue();
17994 }
17995
17996 /// PerformShuffleCombine - Performs several different shuffle combines.
17997 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17998                                      TargetLowering::DAGCombinerInfo &DCI,
17999                                      const X86Subtarget *Subtarget) {
18000   SDLoc dl(N);
18001   SDValue N0 = N->getOperand(0);
18002   SDValue N1 = N->getOperand(1);
18003   EVT VT = N->getValueType(0);
18004
18005   // Don't create instructions with illegal types after legalize types has run.
18006   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18007   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
18008     return SDValue();
18009
18010   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
18011   if (Subtarget->hasFp256() && VT.is256BitVector() &&
18012       N->getOpcode() == ISD::VECTOR_SHUFFLE)
18013     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
18014
18015   // During Type Legalization, when promoting illegal vector types,
18016   // the backend might introduce new shuffle dag nodes and bitcasts.
18017   //
18018   // This code performs the following transformation:
18019   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
18020   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
18021   //
18022   // We do this only if both the bitcast and the BINOP dag nodes have
18023   // one use. Also, perform this transformation only if the new binary
18024   // operation is legal. This is to avoid introducing dag nodes that
18025   // potentially need to be further expanded (or custom lowered) into a
18026   // less optimal sequence of dag nodes.
18027   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
18028       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
18029       N0.getOpcode() == ISD::BITCAST) {
18030     SDValue BC0 = N0.getOperand(0);
18031     EVT SVT = BC0.getValueType();
18032     unsigned Opcode = BC0.getOpcode();
18033     unsigned NumElts = VT.getVectorNumElements();
18034     
18035     if (BC0.hasOneUse() && SVT.isVector() &&
18036         SVT.getVectorNumElements() * 2 == NumElts &&
18037         TLI.isOperationLegal(Opcode, VT)) {
18038       bool CanFold = false;
18039       switch (Opcode) {
18040       default : break;
18041       case ISD::ADD :
18042       case ISD::FADD :
18043       case ISD::SUB :
18044       case ISD::FSUB :
18045       case ISD::MUL :
18046       case ISD::FMUL :
18047         CanFold = true;
18048       }
18049
18050       unsigned SVTNumElts = SVT.getVectorNumElements();
18051       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
18052       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
18053         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
18054       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
18055         CanFold = SVOp->getMaskElt(i) < 0;
18056
18057       if (CanFold) {
18058         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
18059         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
18060         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
18061         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
18062       }
18063     }
18064   }
18065
18066   // Only handle 128 wide vector from here on.
18067   if (!VT.is128BitVector())
18068     return SDValue();
18069
18070   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
18071   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
18072   // consecutive, non-overlapping, and in the right order.
18073   SmallVector<SDValue, 16> Elts;
18074   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
18075     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
18076
18077   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
18078 }
18079
18080 /// PerformTruncateCombine - Converts truncate operation to
18081 /// a sequence of vector shuffle operations.
18082 /// It is possible when we truncate 256-bit vector to 128-bit vector
18083 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
18084                                       TargetLowering::DAGCombinerInfo &DCI,
18085                                       const X86Subtarget *Subtarget)  {
18086   return SDValue();
18087 }
18088
18089 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
18090 /// specific shuffle of a load can be folded into a single element load.
18091 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
18092 /// shuffles have been customed lowered so we need to handle those here.
18093 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
18094                                          TargetLowering::DAGCombinerInfo &DCI) {
18095   if (DCI.isBeforeLegalizeOps())
18096     return SDValue();
18097
18098   SDValue InVec = N->getOperand(0);
18099   SDValue EltNo = N->getOperand(1);
18100
18101   if (!isa<ConstantSDNode>(EltNo))
18102     return SDValue();
18103
18104   EVT VT = InVec.getValueType();
18105
18106   bool HasShuffleIntoBitcast = false;
18107   if (InVec.getOpcode() == ISD::BITCAST) {
18108     // Don't duplicate a load with other uses.
18109     if (!InVec.hasOneUse())
18110       return SDValue();
18111     EVT BCVT = InVec.getOperand(0).getValueType();
18112     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
18113       return SDValue();
18114     InVec = InVec.getOperand(0);
18115     HasShuffleIntoBitcast = true;
18116   }
18117
18118   if (!isTargetShuffle(InVec.getOpcode()))
18119     return SDValue();
18120
18121   // Don't duplicate a load with other uses.
18122   if (!InVec.hasOneUse())
18123     return SDValue();
18124
18125   SmallVector<int, 16> ShuffleMask;
18126   bool UnaryShuffle;
18127   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
18128                             UnaryShuffle))
18129     return SDValue();
18130
18131   // Select the input vector, guarding against out of range extract vector.
18132   unsigned NumElems = VT.getVectorNumElements();
18133   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
18134   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
18135   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
18136                                          : InVec.getOperand(1);
18137
18138   // If inputs to shuffle are the same for both ops, then allow 2 uses
18139   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
18140
18141   if (LdNode.getOpcode() == ISD::BITCAST) {
18142     // Don't duplicate a load with other uses.
18143     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18144       return SDValue();
18145
18146     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18147     LdNode = LdNode.getOperand(0);
18148   }
18149
18150   if (!ISD::isNormalLoad(LdNode.getNode()))
18151     return SDValue();
18152
18153   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18154
18155   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18156     return SDValue();
18157
18158   if (HasShuffleIntoBitcast) {
18159     // If there's a bitcast before the shuffle, check if the load type and
18160     // alignment is valid.
18161     unsigned Align = LN0->getAlignment();
18162     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18163     unsigned NewAlign = TLI.getDataLayout()->
18164       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18165
18166     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18167       return SDValue();
18168   }
18169
18170   // All checks match so transform back to vector_shuffle so that DAG combiner
18171   // can finish the job
18172   SDLoc dl(N);
18173
18174   // Create shuffle node taking into account the case that its a unary shuffle
18175   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18176   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18177                                  InVec.getOperand(0), Shuffle,
18178                                  &ShuffleMask[0]);
18179   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18180   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18181                      EltNo);
18182 }
18183
18184 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18185 /// generation and convert it from being a bunch of shuffles and extracts
18186 /// to a simple store and scalar loads to extract the elements.
18187 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18188                                          TargetLowering::DAGCombinerInfo &DCI) {
18189   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18190   if (NewOp.getNode())
18191     return NewOp;
18192
18193   SDValue InputVector = N->getOperand(0);
18194
18195   // Detect whether we are trying to convert from mmx to i32 and the bitcast
18196   // from mmx to v2i32 has a single usage.
18197   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18198       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18199       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18200     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18201                        N->getValueType(0),
18202                        InputVector.getNode()->getOperand(0));
18203
18204   // Only operate on vectors of 4 elements, where the alternative shuffling
18205   // gets to be more expensive.
18206   if (InputVector.getValueType() != MVT::v4i32)
18207     return SDValue();
18208
18209   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18210   // single use which is a sign-extend or zero-extend, and all elements are
18211   // used.
18212   SmallVector<SDNode *, 4> Uses;
18213   unsigned ExtractedElements = 0;
18214   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18215        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18216     if (UI.getUse().getResNo() != InputVector.getResNo())
18217       return SDValue();
18218
18219     SDNode *Extract = *UI;
18220     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18221       return SDValue();
18222
18223     if (Extract->getValueType(0) != MVT::i32)
18224       return SDValue();
18225     if (!Extract->hasOneUse())
18226       return SDValue();
18227     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18228         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18229       return SDValue();
18230     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18231       return SDValue();
18232
18233     // Record which element was extracted.
18234     ExtractedElements |=
18235       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18236
18237     Uses.push_back(Extract);
18238   }
18239
18240   // If not all the elements were used, this may not be worthwhile.
18241   if (ExtractedElements != 15)
18242     return SDValue();
18243
18244   // Ok, we've now decided to do the transformation.
18245   SDLoc dl(InputVector);
18246
18247   // Store the value to a temporary stack slot.
18248   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18249   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18250                             MachinePointerInfo(), false, false, 0);
18251
18252   // Replace each use (extract) with a load of the appropriate element.
18253   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18254        UE = Uses.end(); UI != UE; ++UI) {
18255     SDNode *Extract = *UI;
18256
18257     // cOMpute the element's address.
18258     SDValue Idx = Extract->getOperand(1);
18259     unsigned EltSize =
18260         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18261     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18262     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18263     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18264
18265     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18266                                      StackPtr, OffsetVal);
18267
18268     // Load the scalar.
18269     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18270                                      ScalarAddr, MachinePointerInfo(),
18271                                      false, false, false, 0);
18272
18273     // Replace the exact with the load.
18274     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18275   }
18276
18277   // The replacement was made in place; don't return anything.
18278   return SDValue();
18279 }
18280
18281 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18282 static std::pair<unsigned, bool>
18283 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18284                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18285   if (!VT.isVector())
18286     return std::make_pair(0, false);
18287
18288   bool NeedSplit = false;
18289   switch (VT.getSimpleVT().SimpleTy) {
18290   default: return std::make_pair(0, false);
18291   case MVT::v32i8:
18292   case MVT::v16i16:
18293   case MVT::v8i32:
18294     if (!Subtarget->hasAVX2())
18295       NeedSplit = true;
18296     if (!Subtarget->hasAVX())
18297       return std::make_pair(0, false);
18298     break;
18299   case MVT::v16i8:
18300   case MVT::v8i16:
18301   case MVT::v4i32:
18302     if (!Subtarget->hasSSE2())
18303       return std::make_pair(0, false);
18304   }
18305
18306   // SSE2 has only a small subset of the operations.
18307   bool hasUnsigned = Subtarget->hasSSE41() ||
18308                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
18309   bool hasSigned = Subtarget->hasSSE41() ||
18310                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
18311
18312   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18313
18314   unsigned Opc = 0;
18315   // Check for x CC y ? x : y.
18316   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18317       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18318     switch (CC) {
18319     default: break;
18320     case ISD::SETULT:
18321     case ISD::SETULE:
18322       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18323     case ISD::SETUGT:
18324     case ISD::SETUGE:
18325       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18326     case ISD::SETLT:
18327     case ISD::SETLE:
18328       Opc = hasSigned ? X86ISD::SMIN : 0; break;
18329     case ISD::SETGT:
18330     case ISD::SETGE:
18331       Opc = hasSigned ? X86ISD::SMAX : 0; break;
18332     }
18333   // Check for x CC y ? y : x -- a min/max with reversed arms.
18334   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18335              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18336     switch (CC) {
18337     default: break;
18338     case ISD::SETULT:
18339     case ISD::SETULE:
18340       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18341     case ISD::SETUGT:
18342     case ISD::SETUGE:
18343       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18344     case ISD::SETLT:
18345     case ISD::SETLE:
18346       Opc = hasSigned ? X86ISD::SMAX : 0; break;
18347     case ISD::SETGT:
18348     case ISD::SETGE:
18349       Opc = hasSigned ? X86ISD::SMIN : 0; break;
18350     }
18351   }
18352
18353   return std::make_pair(Opc, NeedSplit);
18354 }
18355
18356 static SDValue
18357 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18358                                       const X86Subtarget *Subtarget) {
18359   SDLoc dl(N);
18360   SDValue Cond = N->getOperand(0);
18361   SDValue LHS = N->getOperand(1);
18362   SDValue RHS = N->getOperand(2);
18363
18364   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18365     SDValue CondSrc = Cond->getOperand(0);
18366     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18367       Cond = CondSrc->getOperand(0);
18368   }
18369
18370   MVT VT = N->getSimpleValueType(0);
18371   MVT EltVT = VT.getVectorElementType();
18372   unsigned NumElems = VT.getVectorNumElements();
18373   // There is no blend with immediate in AVX-512.
18374   if (VT.is512BitVector())
18375     return SDValue();
18376
18377   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18378     return SDValue();
18379   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18380     return SDValue();
18381
18382   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18383     return SDValue();
18384
18385   unsigned MaskValue = 0;
18386   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18387     return SDValue();
18388
18389   SmallVector<int, 8> ShuffleMask(NumElems, -1);
18390   for (unsigned i = 0; i < NumElems; ++i) {
18391     // Be sure we emit undef where we can.
18392     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18393       ShuffleMask[i] = -1;
18394     else
18395       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18396   }
18397
18398   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18399 }
18400
18401 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18402 /// nodes.
18403 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18404                                     TargetLowering::DAGCombinerInfo &DCI,
18405                                     const X86Subtarget *Subtarget) {
18406   SDLoc DL(N);
18407   SDValue Cond = N->getOperand(0);
18408   // Get the LHS/RHS of the select.
18409   SDValue LHS = N->getOperand(1);
18410   SDValue RHS = N->getOperand(2);
18411   EVT VT = LHS.getValueType();
18412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18413
18414   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18415   // instructions match the semantics of the common C idiom x<y?x:y but not
18416   // x<=y?x:y, because of how they handle negative zero (which can be
18417   // ignored in unsafe-math mode).
18418   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18419       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18420       (Subtarget->hasSSE2() ||
18421        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18422     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18423
18424     unsigned Opcode = 0;
18425     // Check for x CC y ? x : y.
18426     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18427         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18428       switch (CC) {
18429       default: break;
18430       case ISD::SETULT:
18431         // Converting this to a min would handle NaNs incorrectly, and swapping
18432         // the operands would cause it to handle comparisons between positive
18433         // and negative zero incorrectly.
18434         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18435           if (!DAG.getTarget().Options.UnsafeFPMath &&
18436               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18437             break;
18438           std::swap(LHS, RHS);
18439         }
18440         Opcode = X86ISD::FMIN;
18441         break;
18442       case ISD::SETOLE:
18443         // Converting this to a min would handle comparisons between positive
18444         // and negative zero incorrectly.
18445         if (!DAG.getTarget().Options.UnsafeFPMath &&
18446             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18447           break;
18448         Opcode = X86ISD::FMIN;
18449         break;
18450       case ISD::SETULE:
18451         // Converting this to a min would handle both negative zeros and NaNs
18452         // incorrectly, but we can swap the operands to fix both.
18453         std::swap(LHS, RHS);
18454       case ISD::SETOLT:
18455       case ISD::SETLT:
18456       case ISD::SETLE:
18457         Opcode = X86ISD::FMIN;
18458         break;
18459
18460       case ISD::SETOGE:
18461         // Converting this to a max would handle comparisons between positive
18462         // and negative zero incorrectly.
18463         if (!DAG.getTarget().Options.UnsafeFPMath &&
18464             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18465           break;
18466         Opcode = X86ISD::FMAX;
18467         break;
18468       case ISD::SETUGT:
18469         // Converting this to a max would handle NaNs incorrectly, and swapping
18470         // the operands would cause it to handle comparisons between positive
18471         // and negative zero incorrectly.
18472         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18473           if (!DAG.getTarget().Options.UnsafeFPMath &&
18474               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18475             break;
18476           std::swap(LHS, RHS);
18477         }
18478         Opcode = X86ISD::FMAX;
18479         break;
18480       case ISD::SETUGE:
18481         // Converting this to a max would handle both negative zeros and NaNs
18482         // incorrectly, but we can swap the operands to fix both.
18483         std::swap(LHS, RHS);
18484       case ISD::SETOGT:
18485       case ISD::SETGT:
18486       case ISD::SETGE:
18487         Opcode = X86ISD::FMAX;
18488         break;
18489       }
18490     // Check for x CC y ? y : x -- a min/max with reversed arms.
18491     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18492                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18493       switch (CC) {
18494       default: break;
18495       case ISD::SETOGE:
18496         // Converting this to a min would handle comparisons between positive
18497         // and negative zero incorrectly, and swapping the operands would
18498         // cause it to handle NaNs incorrectly.
18499         if (!DAG.getTarget().Options.UnsafeFPMath &&
18500             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18501           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18502             break;
18503           std::swap(LHS, RHS);
18504         }
18505         Opcode = X86ISD::FMIN;
18506         break;
18507       case ISD::SETUGT:
18508         // Converting this to a min would handle NaNs incorrectly.
18509         if (!DAG.getTarget().Options.UnsafeFPMath &&
18510             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18511           break;
18512         Opcode = X86ISD::FMIN;
18513         break;
18514       case ISD::SETUGE:
18515         // Converting this to a min would handle both negative zeros and NaNs
18516         // incorrectly, but we can swap the operands to fix both.
18517         std::swap(LHS, RHS);
18518       case ISD::SETOGT:
18519       case ISD::SETGT:
18520       case ISD::SETGE:
18521         Opcode = X86ISD::FMIN;
18522         break;
18523
18524       case ISD::SETULT:
18525         // Converting this to a max would handle NaNs incorrectly.
18526         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18527           break;
18528         Opcode = X86ISD::FMAX;
18529         break;
18530       case ISD::SETOLE:
18531         // Converting this to a max would handle comparisons between positive
18532         // and negative zero incorrectly, and swapping the operands would
18533         // cause it to handle NaNs incorrectly.
18534         if (!DAG.getTarget().Options.UnsafeFPMath &&
18535             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18536           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18537             break;
18538           std::swap(LHS, RHS);
18539         }
18540         Opcode = X86ISD::FMAX;
18541         break;
18542       case ISD::SETULE:
18543         // Converting this to a max would handle both negative zeros and NaNs
18544         // incorrectly, but we can swap the operands to fix both.
18545         std::swap(LHS, RHS);
18546       case ISD::SETOLT:
18547       case ISD::SETLT:
18548       case ISD::SETLE:
18549         Opcode = X86ISD::FMAX;
18550         break;
18551       }
18552     }
18553
18554     if (Opcode)
18555       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18556   }
18557
18558   EVT CondVT = Cond.getValueType();
18559   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18560       CondVT.getVectorElementType() == MVT::i1) {
18561     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18562     // lowering on AVX-512. In this case we convert it to
18563     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18564     // The same situation for all 128 and 256-bit vectors of i8 and i16
18565     EVT OpVT = LHS.getValueType();
18566     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18567         (OpVT.getVectorElementType() == MVT::i8 ||
18568          OpVT.getVectorElementType() == MVT::i16)) {
18569       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18570       DCI.AddToWorklist(Cond.getNode());
18571       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18572     }
18573   }
18574   // If this is a select between two integer constants, try to do some
18575   // optimizations.
18576   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18577     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18578       // Don't do this for crazy integer types.
18579       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18580         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18581         // so that TrueC (the true value) is larger than FalseC.
18582         bool NeedsCondInvert = false;
18583
18584         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18585             // Efficiently invertible.
18586             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18587              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18588               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18589           NeedsCondInvert = true;
18590           std::swap(TrueC, FalseC);
18591         }
18592
18593         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18594         if (FalseC->getAPIntValue() == 0 &&
18595             TrueC->getAPIntValue().isPowerOf2()) {
18596           if (NeedsCondInvert) // Invert the condition if needed.
18597             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18598                                DAG.getConstant(1, Cond.getValueType()));
18599
18600           // Zero extend the condition if needed.
18601           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18602
18603           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18604           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18605                              DAG.getConstant(ShAmt, MVT::i8));
18606         }
18607
18608         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18609         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18610           if (NeedsCondInvert) // Invert the condition if needed.
18611             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18612                                DAG.getConstant(1, Cond.getValueType()));
18613
18614           // Zero extend the condition if needed.
18615           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18616                              FalseC->getValueType(0), Cond);
18617           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18618                              SDValue(FalseC, 0));
18619         }
18620
18621         // Optimize cases that will turn into an LEA instruction.  This requires
18622         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18623         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18624           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18625           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18626
18627           bool isFastMultiplier = false;
18628           if (Diff < 10) {
18629             switch ((unsigned char)Diff) {
18630               default: break;
18631               case 1:  // result = add base, cond
18632               case 2:  // result = lea base(    , cond*2)
18633               case 3:  // result = lea base(cond, cond*2)
18634               case 4:  // result = lea base(    , cond*4)
18635               case 5:  // result = lea base(cond, cond*4)
18636               case 8:  // result = lea base(    , cond*8)
18637               case 9:  // result = lea base(cond, cond*8)
18638                 isFastMultiplier = true;
18639                 break;
18640             }
18641           }
18642
18643           if (isFastMultiplier) {
18644             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18645             if (NeedsCondInvert) // Invert the condition if needed.
18646               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18647                                  DAG.getConstant(1, Cond.getValueType()));
18648
18649             // Zero extend the condition if needed.
18650             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18651                                Cond);
18652             // Scale the condition by the difference.
18653             if (Diff != 1)
18654               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18655                                  DAG.getConstant(Diff, Cond.getValueType()));
18656
18657             // Add the base if non-zero.
18658             if (FalseC->getAPIntValue() != 0)
18659               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18660                                  SDValue(FalseC, 0));
18661             return Cond;
18662           }
18663         }
18664       }
18665   }
18666
18667   // Canonicalize max and min:
18668   // (x > y) ? x : y -> (x >= y) ? x : y
18669   // (x < y) ? x : y -> (x <= y) ? x : y
18670   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18671   // the need for an extra compare
18672   // against zero. e.g.
18673   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18674   // subl   %esi, %edi
18675   // testl  %edi, %edi
18676   // movl   $0, %eax
18677   // cmovgl %edi, %eax
18678   // =>
18679   // xorl   %eax, %eax
18680   // subl   %esi, $edi
18681   // cmovsl %eax, %edi
18682   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18683       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18684       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18685     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18686     switch (CC) {
18687     default: break;
18688     case ISD::SETLT:
18689     case ISD::SETGT: {
18690       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18691       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18692                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18693       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18694     }
18695     }
18696   }
18697
18698   // Early exit check
18699   if (!TLI.isTypeLegal(VT))
18700     return SDValue();
18701
18702   // Match VSELECTs into subs with unsigned saturation.
18703   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18704       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18705       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18706        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18707     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18708
18709     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18710     // left side invert the predicate to simplify logic below.
18711     SDValue Other;
18712     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18713       Other = RHS;
18714       CC = ISD::getSetCCInverse(CC, true);
18715     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18716       Other = LHS;
18717     }
18718
18719     if (Other.getNode() && Other->getNumOperands() == 2 &&
18720         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18721       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18722       SDValue CondRHS = Cond->getOperand(1);
18723
18724       // Look for a general sub with unsigned saturation first.
18725       // x >= y ? x-y : 0 --> subus x, y
18726       // x >  y ? x-y : 0 --> subus x, y
18727       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18728           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18729         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18730
18731       // If the RHS is a constant we have to reverse the const canonicalization.
18732       // x > C-1 ? x+-C : 0 --> subus x, C
18733       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18734           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18735         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18736         if (CondRHS.getConstantOperandVal(0) == -A-1)
18737           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18738                              DAG.getConstant(-A, VT));
18739       }
18740
18741       // Another special case: If C was a sign bit, the sub has been
18742       // canonicalized into a xor.
18743       // FIXME: Would it be better to use computeKnownBits to determine whether
18744       //        it's safe to decanonicalize the xor?
18745       // x s< 0 ? x^C : 0 --> subus x, C
18746       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18747           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18748           isSplatVector(OpRHS.getNode())) {
18749         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18750         if (A.isSignBit())
18751           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18752       }
18753     }
18754   }
18755
18756   // Try to match a min/max vector operation.
18757   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18758     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18759     unsigned Opc = ret.first;
18760     bool NeedSplit = ret.second;
18761
18762     if (Opc && NeedSplit) {
18763       unsigned NumElems = VT.getVectorNumElements();
18764       // Extract the LHS vectors
18765       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18766       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18767
18768       // Extract the RHS vectors
18769       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18770       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18771
18772       // Create min/max for each subvector
18773       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18774       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18775
18776       // Merge the result
18777       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18778     } else if (Opc)
18779       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18780   }
18781
18782   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18783   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18784       // Check if SETCC has already been promoted
18785       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18786       // Check that condition value type matches vselect operand type
18787       CondVT == VT) { 
18788
18789     assert(Cond.getValueType().isVector() &&
18790            "vector select expects a vector selector!");
18791
18792     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18793     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18794
18795     if (!TValIsAllOnes && !FValIsAllZeros) {
18796       // Try invert the condition if true value is not all 1s and false value
18797       // is not all 0s.
18798       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18799       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18800
18801       if (TValIsAllZeros || FValIsAllOnes) {
18802         SDValue CC = Cond.getOperand(2);
18803         ISD::CondCode NewCC =
18804           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18805                                Cond.getOperand(0).getValueType().isInteger());
18806         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18807         std::swap(LHS, RHS);
18808         TValIsAllOnes = FValIsAllOnes;
18809         FValIsAllZeros = TValIsAllZeros;
18810       }
18811     }
18812
18813     if (TValIsAllOnes || FValIsAllZeros) {
18814       SDValue Ret;
18815
18816       if (TValIsAllOnes && FValIsAllZeros)
18817         Ret = Cond;
18818       else if (TValIsAllOnes)
18819         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18820                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18821       else if (FValIsAllZeros)
18822         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18823                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18824
18825       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18826     }
18827   }
18828
18829   // Try to fold this VSELECT into a MOVSS/MOVSD
18830   if (N->getOpcode() == ISD::VSELECT &&
18831       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18832     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18833         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18834       bool CanFold = false;
18835       unsigned NumElems = Cond.getNumOperands();
18836       SDValue A = LHS;
18837       SDValue B = RHS;
18838       
18839       if (isZero(Cond.getOperand(0))) {
18840         CanFold = true;
18841
18842         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18843         // fold (vselect <0,-1> -> (movsd A, B)
18844         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18845           CanFold = isAllOnes(Cond.getOperand(i));
18846       } else if (isAllOnes(Cond.getOperand(0))) {
18847         CanFold = true;
18848         std::swap(A, B);
18849
18850         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18851         // fold (vselect <-1,0> -> (movsd B, A)
18852         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18853           CanFold = isZero(Cond.getOperand(i));
18854       }
18855
18856       if (CanFold) {
18857         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18858           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18859         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18860       }
18861
18862       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18863         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18864         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18865         //                             (v2i64 (bitcast B)))))
18866         //
18867         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18868         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18869         //                             (v2f64 (bitcast B)))))
18870         //
18871         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18872         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18873         //                             (v2i64 (bitcast A)))))
18874         //
18875         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18876         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18877         //                             (v2f64 (bitcast A)))))
18878
18879         CanFold = (isZero(Cond.getOperand(0)) &&
18880                    isZero(Cond.getOperand(1)) &&
18881                    isAllOnes(Cond.getOperand(2)) &&
18882                    isAllOnes(Cond.getOperand(3)));
18883
18884         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18885             isAllOnes(Cond.getOperand(1)) &&
18886             isZero(Cond.getOperand(2)) &&
18887             isZero(Cond.getOperand(3))) {
18888           CanFold = true;
18889           std::swap(LHS, RHS);
18890         }
18891
18892         if (CanFold) {
18893           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18894           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18895           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18896           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18897                                                 NewB, DAG);
18898           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18899         }
18900       }
18901     }
18902   }
18903
18904   // If we know that this node is legal then we know that it is going to be
18905   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18906   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18907   // to simplify previous instructions.
18908   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18909       !DCI.isBeforeLegalize() &&
18910       // We explicitly check against v8i16 and v16i16 because, although
18911       // they're marked as Custom, they might only be legal when Cond is a
18912       // build_vector of constants. This will be taken care in a later
18913       // condition.
18914       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18915        VT != MVT::v8i16)) {
18916     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18917
18918     // Don't optimize vector selects that map to mask-registers.
18919     if (BitWidth == 1)
18920       return SDValue();
18921
18922     // Check all uses of that condition operand to check whether it will be
18923     // consumed by non-BLEND instructions, which may depend on all bits are set
18924     // properly.
18925     for (SDNode::use_iterator I = Cond->use_begin(),
18926                               E = Cond->use_end(); I != E; ++I)
18927       if (I->getOpcode() != ISD::VSELECT)
18928         // TODO: Add other opcodes eventually lowered into BLEND.
18929         return SDValue();
18930
18931     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18932     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18933
18934     APInt KnownZero, KnownOne;
18935     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18936                                           DCI.isBeforeLegalizeOps());
18937     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18938         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18939       DCI.CommitTargetLoweringOpt(TLO);
18940   }
18941
18942   // We should generate an X86ISD::BLENDI from a vselect if its argument
18943   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18944   // constants. This specific pattern gets generated when we split a
18945   // selector for a 512 bit vector in a machine without AVX512 (but with
18946   // 256-bit vectors), during legalization:
18947   //
18948   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18949   //
18950   // Iff we find this pattern and the build_vectors are built from
18951   // constants, we translate the vselect into a shuffle_vector that we
18952   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18953   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18954     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18955     if (Shuffle.getNode())
18956       return Shuffle;
18957   }
18958
18959   return SDValue();
18960 }
18961
18962 // Check whether a boolean test is testing a boolean value generated by
18963 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18964 // code.
18965 //
18966 // Simplify the following patterns:
18967 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18968 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18969 // to (Op EFLAGS Cond)
18970 //
18971 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18972 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18973 // to (Op EFLAGS !Cond)
18974 //
18975 // where Op could be BRCOND or CMOV.
18976 //
18977 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18978   // Quit if not CMP and SUB with its value result used.
18979   if (Cmp.getOpcode() != X86ISD::CMP &&
18980       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18981       return SDValue();
18982
18983   // Quit if not used as a boolean value.
18984   if (CC != X86::COND_E && CC != X86::COND_NE)
18985     return SDValue();
18986
18987   // Check CMP operands. One of them should be 0 or 1 and the other should be
18988   // an SetCC or extended from it.
18989   SDValue Op1 = Cmp.getOperand(0);
18990   SDValue Op2 = Cmp.getOperand(1);
18991
18992   SDValue SetCC;
18993   const ConstantSDNode* C = nullptr;
18994   bool needOppositeCond = (CC == X86::COND_E);
18995   bool checkAgainstTrue = false; // Is it a comparison against 1?
18996
18997   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18998     SetCC = Op2;
18999   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
19000     SetCC = Op1;
19001   else // Quit if all operands are not constants.
19002     return SDValue();
19003
19004   if (C->getZExtValue() == 1) {
19005     needOppositeCond = !needOppositeCond;
19006     checkAgainstTrue = true;
19007   } else if (C->getZExtValue() != 0)
19008     // Quit if the constant is neither 0 or 1.
19009     return SDValue();
19010
19011   bool truncatedToBoolWithAnd = false;
19012   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
19013   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
19014          SetCC.getOpcode() == ISD::TRUNCATE ||
19015          SetCC.getOpcode() == ISD::AND) {
19016     if (SetCC.getOpcode() == ISD::AND) {
19017       int OpIdx = -1;
19018       ConstantSDNode *CS;
19019       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
19020           CS->getZExtValue() == 1)
19021         OpIdx = 1;
19022       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
19023           CS->getZExtValue() == 1)
19024         OpIdx = 0;
19025       if (OpIdx == -1)
19026         break;
19027       SetCC = SetCC.getOperand(OpIdx);
19028       truncatedToBoolWithAnd = true;
19029     } else
19030       SetCC = SetCC.getOperand(0);
19031   }
19032
19033   switch (SetCC.getOpcode()) {
19034   case X86ISD::SETCC_CARRY:
19035     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
19036     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
19037     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
19038     // truncated to i1 using 'and'.
19039     if (checkAgainstTrue && !truncatedToBoolWithAnd)
19040       break;
19041     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
19042            "Invalid use of SETCC_CARRY!");
19043     // FALL THROUGH
19044   case X86ISD::SETCC:
19045     // Set the condition code or opposite one if necessary.
19046     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
19047     if (needOppositeCond)
19048       CC = X86::GetOppositeBranchCondition(CC);
19049     return SetCC.getOperand(1);
19050   case X86ISD::CMOV: {
19051     // Check whether false/true value has canonical one, i.e. 0 or 1.
19052     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
19053     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
19054     // Quit if true value is not a constant.
19055     if (!TVal)
19056       return SDValue();
19057     // Quit if false value is not a constant.
19058     if (!FVal) {
19059       SDValue Op = SetCC.getOperand(0);
19060       // Skip 'zext' or 'trunc' node.
19061       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
19062           Op.getOpcode() == ISD::TRUNCATE)
19063         Op = Op.getOperand(0);
19064       // A special case for rdrand/rdseed, where 0 is set if false cond is
19065       // found.
19066       if ((Op.getOpcode() != X86ISD::RDRAND &&
19067            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
19068         return SDValue();
19069     }
19070     // Quit if false value is not the constant 0 or 1.
19071     bool FValIsFalse = true;
19072     if (FVal && FVal->getZExtValue() != 0) {
19073       if (FVal->getZExtValue() != 1)
19074         return SDValue();
19075       // If FVal is 1, opposite cond is needed.
19076       needOppositeCond = !needOppositeCond;
19077       FValIsFalse = false;
19078     }
19079     // Quit if TVal is not the constant opposite of FVal.
19080     if (FValIsFalse && TVal->getZExtValue() != 1)
19081       return SDValue();
19082     if (!FValIsFalse && TVal->getZExtValue() != 0)
19083       return SDValue();
19084     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
19085     if (needOppositeCond)
19086       CC = X86::GetOppositeBranchCondition(CC);
19087     return SetCC.getOperand(3);
19088   }
19089   }
19090
19091   return SDValue();
19092 }
19093
19094 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
19095 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
19096                                   TargetLowering::DAGCombinerInfo &DCI,
19097                                   const X86Subtarget *Subtarget) {
19098   SDLoc DL(N);
19099
19100   // If the flag operand isn't dead, don't touch this CMOV.
19101   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
19102     return SDValue();
19103
19104   SDValue FalseOp = N->getOperand(0);
19105   SDValue TrueOp = N->getOperand(1);
19106   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
19107   SDValue Cond = N->getOperand(3);
19108
19109   if (CC == X86::COND_E || CC == X86::COND_NE) {
19110     switch (Cond.getOpcode()) {
19111     default: break;
19112     case X86ISD::BSR:
19113     case X86ISD::BSF:
19114       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
19115       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
19116         return (CC == X86::COND_E) ? FalseOp : TrueOp;
19117     }
19118   }
19119
19120   SDValue Flags;
19121
19122   Flags = checkBoolTestSetCCCombine(Cond, CC);
19123   if (Flags.getNode() &&
19124       // Extra check as FCMOV only supports a subset of X86 cond.
19125       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
19126     SDValue Ops[] = { FalseOp, TrueOp,
19127                       DAG.getConstant(CC, MVT::i8), Flags };
19128     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
19129   }
19130
19131   // If this is a select between two integer constants, try to do some
19132   // optimizations.  Note that the operands are ordered the opposite of SELECT
19133   // operands.
19134   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
19135     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
19136       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
19137       // larger than FalseC (the false value).
19138       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
19139         CC = X86::GetOppositeBranchCondition(CC);
19140         std::swap(TrueC, FalseC);
19141         std::swap(TrueOp, FalseOp);
19142       }
19143
19144       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19145       // This is efficient for any integer data type (including i8/i16) and
19146       // shift amount.
19147       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19148         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19149                            DAG.getConstant(CC, MVT::i8), Cond);
19150
19151         // Zero extend the condition if needed.
19152         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19153
19154         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19155         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19156                            DAG.getConstant(ShAmt, MVT::i8));
19157         if (N->getNumValues() == 2)  // Dead flag value?
19158           return DCI.CombineTo(N, Cond, SDValue());
19159         return Cond;
19160       }
19161
19162       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
19163       // for any integer data type, including i8/i16.
19164       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19165         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19166                            DAG.getConstant(CC, MVT::i8), Cond);
19167
19168         // Zero extend the condition if needed.
19169         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19170                            FalseC->getValueType(0), Cond);
19171         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19172                            SDValue(FalseC, 0));
19173
19174         if (N->getNumValues() == 2)  // Dead flag value?
19175           return DCI.CombineTo(N, Cond, SDValue());
19176         return Cond;
19177       }
19178
19179       // Optimize cases that will turn into an LEA instruction.  This requires
19180       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19181       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19182         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19183         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19184
19185         bool isFastMultiplier = false;
19186         if (Diff < 10) {
19187           switch ((unsigned char)Diff) {
19188           default: break;
19189           case 1:  // result = add base, cond
19190           case 2:  // result = lea base(    , cond*2)
19191           case 3:  // result = lea base(cond, cond*2)
19192           case 4:  // result = lea base(    , cond*4)
19193           case 5:  // result = lea base(cond, cond*4)
19194           case 8:  // result = lea base(    , cond*8)
19195           case 9:  // result = lea base(cond, cond*8)
19196             isFastMultiplier = true;
19197             break;
19198           }
19199         }
19200
19201         if (isFastMultiplier) {
19202           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19203           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19204                              DAG.getConstant(CC, MVT::i8), Cond);
19205           // Zero extend the condition if needed.
19206           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19207                              Cond);
19208           // Scale the condition by the difference.
19209           if (Diff != 1)
19210             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19211                                DAG.getConstant(Diff, Cond.getValueType()));
19212
19213           // Add the base if non-zero.
19214           if (FalseC->getAPIntValue() != 0)
19215             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19216                                SDValue(FalseC, 0));
19217           if (N->getNumValues() == 2)  // Dead flag value?
19218             return DCI.CombineTo(N, Cond, SDValue());
19219           return Cond;
19220         }
19221       }
19222     }
19223   }
19224
19225   // Handle these cases:
19226   //   (select (x != c), e, c) -> select (x != c), e, x),
19227   //   (select (x == c), c, e) -> select (x == c), x, e)
19228   // where the c is an integer constant, and the "select" is the combination
19229   // of CMOV and CMP.
19230   //
19231   // The rationale for this change is that the conditional-move from a constant
19232   // needs two instructions, however, conditional-move from a register needs
19233   // only one instruction.
19234   //
19235   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19236   //  some instruction-combining opportunities. This opt needs to be
19237   //  postponed as late as possible.
19238   //
19239   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19240     // the DCI.xxxx conditions are provided to postpone the optimization as
19241     // late as possible.
19242
19243     ConstantSDNode *CmpAgainst = nullptr;
19244     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19245         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19246         !isa<ConstantSDNode>(Cond.getOperand(0))) {
19247
19248       if (CC == X86::COND_NE &&
19249           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19250         CC = X86::GetOppositeBranchCondition(CC);
19251         std::swap(TrueOp, FalseOp);
19252       }
19253
19254       if (CC == X86::COND_E &&
19255           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19256         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19257                           DAG.getConstant(CC, MVT::i8), Cond };
19258         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19259       }
19260     }
19261   }
19262
19263   return SDValue();
19264 }
19265
19266 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19267                                                 const X86Subtarget *Subtarget) {
19268   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19269   switch (IntNo) {
19270   default: return SDValue();
19271   // SSE/AVX/AVX2 blend intrinsics.
19272   case Intrinsic::x86_avx2_pblendvb:
19273   case Intrinsic::x86_avx2_pblendw:
19274   case Intrinsic::x86_avx2_pblendd_128:
19275   case Intrinsic::x86_avx2_pblendd_256:
19276     // Don't try to simplify this intrinsic if we don't have AVX2.
19277     if (!Subtarget->hasAVX2())
19278       return SDValue();
19279     // FALL-THROUGH
19280   case Intrinsic::x86_avx_blend_pd_256:
19281   case Intrinsic::x86_avx_blend_ps_256:
19282   case Intrinsic::x86_avx_blendv_pd_256:
19283   case Intrinsic::x86_avx_blendv_ps_256:
19284     // Don't try to simplify this intrinsic if we don't have AVX.
19285     if (!Subtarget->hasAVX())
19286       return SDValue();
19287     // FALL-THROUGH
19288   case Intrinsic::x86_sse41_pblendw:
19289   case Intrinsic::x86_sse41_blendpd:
19290   case Intrinsic::x86_sse41_blendps:
19291   case Intrinsic::x86_sse41_blendvps:
19292   case Intrinsic::x86_sse41_blendvpd:
19293   case Intrinsic::x86_sse41_pblendvb: {
19294     SDValue Op0 = N->getOperand(1);
19295     SDValue Op1 = N->getOperand(2);
19296     SDValue Mask = N->getOperand(3);
19297
19298     // Don't try to simplify this intrinsic if we don't have SSE4.1.
19299     if (!Subtarget->hasSSE41())
19300       return SDValue();
19301
19302     // fold (blend A, A, Mask) -> A
19303     if (Op0 == Op1)
19304       return Op0;
19305     // fold (blend A, B, allZeros) -> A
19306     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19307       return Op0;
19308     // fold (blend A, B, allOnes) -> B
19309     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19310       return Op1;
19311     
19312     // Simplify the case where the mask is a constant i32 value.
19313     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19314       if (C->isNullValue())
19315         return Op0;
19316       if (C->isAllOnesValue())
19317         return Op1;
19318     }
19319
19320     return SDValue();
19321   }
19322
19323   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19324   case Intrinsic::x86_sse2_psrai_w:
19325   case Intrinsic::x86_sse2_psrai_d:
19326   case Intrinsic::x86_avx2_psrai_w:
19327   case Intrinsic::x86_avx2_psrai_d:
19328   case Intrinsic::x86_sse2_psra_w:
19329   case Intrinsic::x86_sse2_psra_d:
19330   case Intrinsic::x86_avx2_psra_w:
19331   case Intrinsic::x86_avx2_psra_d: {
19332     SDValue Op0 = N->getOperand(1);
19333     SDValue Op1 = N->getOperand(2);
19334     EVT VT = Op0.getValueType();
19335     assert(VT.isVector() && "Expected a vector type!");
19336
19337     if (isa<BuildVectorSDNode>(Op1))
19338       Op1 = Op1.getOperand(0);
19339
19340     if (!isa<ConstantSDNode>(Op1))
19341       return SDValue();
19342
19343     EVT SVT = VT.getVectorElementType();
19344     unsigned SVTBits = SVT.getSizeInBits();
19345
19346     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19347     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19348     uint64_t ShAmt = C.getZExtValue();
19349
19350     // Don't try to convert this shift into a ISD::SRA if the shift
19351     // count is bigger than or equal to the element size.
19352     if (ShAmt >= SVTBits)
19353       return SDValue();
19354
19355     // Trivial case: if the shift count is zero, then fold this
19356     // into the first operand.
19357     if (ShAmt == 0)
19358       return Op0;
19359
19360     // Replace this packed shift intrinsic with a target independent
19361     // shift dag node.
19362     SDValue Splat = DAG.getConstant(C, VT);
19363     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19364   }
19365   }
19366 }
19367
19368 /// PerformMulCombine - Optimize a single multiply with constant into two
19369 /// in order to implement it with two cheaper instructions, e.g.
19370 /// LEA + SHL, LEA + LEA.
19371 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19372                                  TargetLowering::DAGCombinerInfo &DCI) {
19373   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19374     return SDValue();
19375
19376   EVT VT = N->getValueType(0);
19377   if (VT != MVT::i64)
19378     return SDValue();
19379
19380   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19381   if (!C)
19382     return SDValue();
19383   uint64_t MulAmt = C->getZExtValue();
19384   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19385     return SDValue();
19386
19387   uint64_t MulAmt1 = 0;
19388   uint64_t MulAmt2 = 0;
19389   if ((MulAmt % 9) == 0) {
19390     MulAmt1 = 9;
19391     MulAmt2 = MulAmt / 9;
19392   } else if ((MulAmt % 5) == 0) {
19393     MulAmt1 = 5;
19394     MulAmt2 = MulAmt / 5;
19395   } else if ((MulAmt % 3) == 0) {
19396     MulAmt1 = 3;
19397     MulAmt2 = MulAmt / 3;
19398   }
19399   if (MulAmt2 &&
19400       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19401     SDLoc DL(N);
19402
19403     if (isPowerOf2_64(MulAmt2) &&
19404         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19405       // If second multiplifer is pow2, issue it first. We want the multiply by
19406       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19407       // is an add.
19408       std::swap(MulAmt1, MulAmt2);
19409
19410     SDValue NewMul;
19411     if (isPowerOf2_64(MulAmt1))
19412       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19413                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19414     else
19415       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19416                            DAG.getConstant(MulAmt1, VT));
19417
19418     if (isPowerOf2_64(MulAmt2))
19419       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19420                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19421     else
19422       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19423                            DAG.getConstant(MulAmt2, VT));
19424
19425     // Do not add new nodes to DAG combiner worklist.
19426     DCI.CombineTo(N, NewMul, false);
19427   }
19428   return SDValue();
19429 }
19430
19431 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19432   SDValue N0 = N->getOperand(0);
19433   SDValue N1 = N->getOperand(1);
19434   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19435   EVT VT = N0.getValueType();
19436
19437   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19438   // since the result of setcc_c is all zero's or all ones.
19439   if (VT.isInteger() && !VT.isVector() &&
19440       N1C && N0.getOpcode() == ISD::AND &&
19441       N0.getOperand(1).getOpcode() == ISD::Constant) {
19442     SDValue N00 = N0.getOperand(0);
19443     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19444         ((N00.getOpcode() == ISD::ANY_EXTEND ||
19445           N00.getOpcode() == ISD::ZERO_EXTEND) &&
19446          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19447       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19448       APInt ShAmt = N1C->getAPIntValue();
19449       Mask = Mask.shl(ShAmt);
19450       if (Mask != 0)
19451         return DAG.getNode(ISD::AND, SDLoc(N), VT,
19452                            N00, DAG.getConstant(Mask, VT));
19453     }
19454   }
19455
19456   // Hardware support for vector shifts is sparse which makes us scalarize the
19457   // vector operations in many cases. Also, on sandybridge ADD is faster than
19458   // shl.
19459   // (shl V, 1) -> add V,V
19460   if (isSplatVector(N1.getNode())) {
19461     assert(N0.getValueType().isVector() && "Invalid vector shift type");
19462     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19463     // We shift all of the values by one. In many cases we do not have
19464     // hardware support for this operation. This is better expressed as an ADD
19465     // of two values.
19466     if (N1C && (1 == N1C->getZExtValue())) {
19467       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19468     }
19469   }
19470
19471   return SDValue();
19472 }
19473
19474 /// \brief Returns a vector of 0s if the node in input is a vector logical
19475 /// shift by a constant amount which is known to be bigger than or equal
19476 /// to the vector element size in bits.
19477 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19478                                       const X86Subtarget *Subtarget) {
19479   EVT VT = N->getValueType(0);
19480
19481   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19482       (!Subtarget->hasInt256() ||
19483        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19484     return SDValue();
19485
19486   SDValue Amt = N->getOperand(1);
19487   SDLoc DL(N);
19488   if (isSplatVector(Amt.getNode())) {
19489     SDValue SclrAmt = Amt->getOperand(0);
19490     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19491       APInt ShiftAmt = C->getAPIntValue();
19492       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19493
19494       // SSE2/AVX2 logical shifts always return a vector of 0s
19495       // if the shift amount is bigger than or equal to
19496       // the element size. The constant shift amount will be
19497       // encoded as a 8-bit immediate.
19498       if (ShiftAmt.trunc(8).uge(MaxAmount))
19499         return getZeroVector(VT, Subtarget, DAG, DL);
19500     }
19501   }
19502
19503   return SDValue();
19504 }
19505
19506 /// PerformShiftCombine - Combine shifts.
19507 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19508                                    TargetLowering::DAGCombinerInfo &DCI,
19509                                    const X86Subtarget *Subtarget) {
19510   if (N->getOpcode() == ISD::SHL) {
19511     SDValue V = PerformSHLCombine(N, DAG);
19512     if (V.getNode()) return V;
19513   }
19514
19515   if (N->getOpcode() != ISD::SRA) {
19516     // Try to fold this logical shift into a zero vector.
19517     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19518     if (V.getNode()) return V;
19519   }
19520
19521   return SDValue();
19522 }
19523
19524 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
19525 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19526 // and friends.  Likewise for OR -> CMPNEQSS.
19527 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19528                             TargetLowering::DAGCombinerInfo &DCI,
19529                             const X86Subtarget *Subtarget) {
19530   unsigned opcode;
19531
19532   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19533   // we're requiring SSE2 for both.
19534   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19535     SDValue N0 = N->getOperand(0);
19536     SDValue N1 = N->getOperand(1);
19537     SDValue CMP0 = N0->getOperand(1);
19538     SDValue CMP1 = N1->getOperand(1);
19539     SDLoc DL(N);
19540
19541     // The SETCCs should both refer to the same CMP.
19542     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19543       return SDValue();
19544
19545     SDValue CMP00 = CMP0->getOperand(0);
19546     SDValue CMP01 = CMP0->getOperand(1);
19547     EVT     VT    = CMP00.getValueType();
19548
19549     if (VT == MVT::f32 || VT == MVT::f64) {
19550       bool ExpectingFlags = false;
19551       // Check for any users that want flags:
19552       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19553            !ExpectingFlags && UI != UE; ++UI)
19554         switch (UI->getOpcode()) {
19555         default:
19556         case ISD::BR_CC:
19557         case ISD::BRCOND:
19558         case ISD::SELECT:
19559           ExpectingFlags = true;
19560           break;
19561         case ISD::CopyToReg:
19562         case ISD::SIGN_EXTEND:
19563         case ISD::ZERO_EXTEND:
19564         case ISD::ANY_EXTEND:
19565           break;
19566         }
19567
19568       if (!ExpectingFlags) {
19569         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19570         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19571
19572         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19573           X86::CondCode tmp = cc0;
19574           cc0 = cc1;
19575           cc1 = tmp;
19576         }
19577
19578         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19579             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19580           // FIXME: need symbolic constants for these magic numbers.
19581           // See X86ATTInstPrinter.cpp:printSSECC().
19582           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19583           if (Subtarget->hasAVX512()) {
19584             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19585                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19586             if (N->getValueType(0) != MVT::i1)
19587               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19588                                  FSetCC);
19589             return FSetCC;
19590           }
19591           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19592                                               CMP00.getValueType(), CMP00, CMP01,
19593                                               DAG.getConstant(x86cc, MVT::i8));
19594
19595           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19596           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19597
19598           if (is64BitFP && !Subtarget->is64Bit()) {
19599             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19600             // 64-bit integer, since that's not a legal type. Since
19601             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19602             // bits, but can do this little dance to extract the lowest 32 bits
19603             // and work with those going forward.
19604             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19605                                            OnesOrZeroesF);
19606             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19607                                            Vector64);
19608             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19609                                         Vector32, DAG.getIntPtrConstant(0));
19610             IntVT = MVT::i32;
19611           }
19612
19613           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19614           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19615                                       DAG.getConstant(1, IntVT));
19616           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19617           return OneBitOfTruth;
19618         }
19619       }
19620     }
19621   }
19622   return SDValue();
19623 }
19624
19625 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19626 /// so it can be folded inside ANDNP.
19627 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19628   EVT VT = N->getValueType(0);
19629
19630   // Match direct AllOnes for 128 and 256-bit vectors
19631   if (ISD::isBuildVectorAllOnes(N))
19632     return true;
19633
19634   // Look through a bit convert.
19635   if (N->getOpcode() == ISD::BITCAST)
19636     N = N->getOperand(0).getNode();
19637
19638   // Sometimes the operand may come from a insert_subvector building a 256-bit
19639   // allones vector
19640   if (VT.is256BitVector() &&
19641       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19642     SDValue V1 = N->getOperand(0);
19643     SDValue V2 = N->getOperand(1);
19644
19645     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19646         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19647         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19648         ISD::isBuildVectorAllOnes(V2.getNode()))
19649       return true;
19650   }
19651
19652   return false;
19653 }
19654
19655 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19656 // register. In most cases we actually compare or select YMM-sized registers
19657 // and mixing the two types creates horrible code. This method optimizes
19658 // some of the transition sequences.
19659 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19660                                  TargetLowering::DAGCombinerInfo &DCI,
19661                                  const X86Subtarget *Subtarget) {
19662   EVT VT = N->getValueType(0);
19663   if (!VT.is256BitVector())
19664     return SDValue();
19665
19666   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19667           N->getOpcode() == ISD::ZERO_EXTEND ||
19668           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19669
19670   SDValue Narrow = N->getOperand(0);
19671   EVT NarrowVT = Narrow->getValueType(0);
19672   if (!NarrowVT.is128BitVector())
19673     return SDValue();
19674
19675   if (Narrow->getOpcode() != ISD::XOR &&
19676       Narrow->getOpcode() != ISD::AND &&
19677       Narrow->getOpcode() != ISD::OR)
19678     return SDValue();
19679
19680   SDValue N0  = Narrow->getOperand(0);
19681   SDValue N1  = Narrow->getOperand(1);
19682   SDLoc DL(Narrow);
19683
19684   // The Left side has to be a trunc.
19685   if (N0.getOpcode() != ISD::TRUNCATE)
19686     return SDValue();
19687
19688   // The type of the truncated inputs.
19689   EVT WideVT = N0->getOperand(0)->getValueType(0);
19690   if (WideVT != VT)
19691     return SDValue();
19692
19693   // The right side has to be a 'trunc' or a constant vector.
19694   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19695   bool RHSConst = (isSplatVector(N1.getNode()) &&
19696                    isa<ConstantSDNode>(N1->getOperand(0)));
19697   if (!RHSTrunc && !RHSConst)
19698     return SDValue();
19699
19700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19701
19702   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19703     return SDValue();
19704
19705   // Set N0 and N1 to hold the inputs to the new wide operation.
19706   N0 = N0->getOperand(0);
19707   if (RHSConst) {
19708     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19709                      N1->getOperand(0));
19710     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19711     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19712   } else if (RHSTrunc) {
19713     N1 = N1->getOperand(0);
19714   }
19715
19716   // Generate the wide operation.
19717   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19718   unsigned Opcode = N->getOpcode();
19719   switch (Opcode) {
19720   case ISD::ANY_EXTEND:
19721     return Op;
19722   case ISD::ZERO_EXTEND: {
19723     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19724     APInt Mask = APInt::getAllOnesValue(InBits);
19725     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19726     return DAG.getNode(ISD::AND, DL, VT,
19727                        Op, DAG.getConstant(Mask, VT));
19728   }
19729   case ISD::SIGN_EXTEND:
19730     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19731                        Op, DAG.getValueType(NarrowVT));
19732   default:
19733     llvm_unreachable("Unexpected opcode");
19734   }
19735 }
19736
19737 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19738                                  TargetLowering::DAGCombinerInfo &DCI,
19739                                  const X86Subtarget *Subtarget) {
19740   EVT VT = N->getValueType(0);
19741   if (DCI.isBeforeLegalizeOps())
19742     return SDValue();
19743
19744   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19745   if (R.getNode())
19746     return R;
19747
19748   // Create BEXTR instructions
19749   // BEXTR is ((X >> imm) & (2**size-1))
19750   if (VT == MVT::i32 || VT == MVT::i64) {
19751     SDValue N0 = N->getOperand(0);
19752     SDValue N1 = N->getOperand(1);
19753     SDLoc DL(N);
19754
19755     // Check for BEXTR.
19756     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19757         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19758       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19759       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19760       if (MaskNode && ShiftNode) {
19761         uint64_t Mask = MaskNode->getZExtValue();
19762         uint64_t Shift = ShiftNode->getZExtValue();
19763         if (isMask_64(Mask)) {
19764           uint64_t MaskSize = CountPopulation_64(Mask);
19765           if (Shift + MaskSize <= VT.getSizeInBits())
19766             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19767                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19768         }
19769       }
19770     } // BEXTR
19771
19772     return SDValue();
19773   }
19774
19775   // Want to form ANDNP nodes:
19776   // 1) In the hopes of then easily combining them with OR and AND nodes
19777   //    to form PBLEND/PSIGN.
19778   // 2) To match ANDN packed intrinsics
19779   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19780     return SDValue();
19781
19782   SDValue N0 = N->getOperand(0);
19783   SDValue N1 = N->getOperand(1);
19784   SDLoc DL(N);
19785
19786   // Check LHS for vnot
19787   if (N0.getOpcode() == ISD::XOR &&
19788       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19789       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19790     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19791
19792   // Check RHS for vnot
19793   if (N1.getOpcode() == ISD::XOR &&
19794       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19795       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19796     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19797
19798   return SDValue();
19799 }
19800
19801 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19802                                 TargetLowering::DAGCombinerInfo &DCI,
19803                                 const X86Subtarget *Subtarget) {
19804   if (DCI.isBeforeLegalizeOps())
19805     return SDValue();
19806
19807   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19808   if (R.getNode())
19809     return R;
19810
19811   SDValue N0 = N->getOperand(0);
19812   SDValue N1 = N->getOperand(1);
19813   EVT VT = N->getValueType(0);
19814
19815   // look for psign/blend
19816   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19817     if (!Subtarget->hasSSSE3() ||
19818         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19819       return SDValue();
19820
19821     // Canonicalize pandn to RHS
19822     if (N0.getOpcode() == X86ISD::ANDNP)
19823       std::swap(N0, N1);
19824     // or (and (m, y), (pandn m, x))
19825     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19826       SDValue Mask = N1.getOperand(0);
19827       SDValue X    = N1.getOperand(1);
19828       SDValue Y;
19829       if (N0.getOperand(0) == Mask)
19830         Y = N0.getOperand(1);
19831       if (N0.getOperand(1) == Mask)
19832         Y = N0.getOperand(0);
19833
19834       // Check to see if the mask appeared in both the AND and ANDNP and
19835       if (!Y.getNode())
19836         return SDValue();
19837
19838       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19839       // Look through mask bitcast.
19840       if (Mask.getOpcode() == ISD::BITCAST)
19841         Mask = Mask.getOperand(0);
19842       if (X.getOpcode() == ISD::BITCAST)
19843         X = X.getOperand(0);
19844       if (Y.getOpcode() == ISD::BITCAST)
19845         Y = Y.getOperand(0);
19846
19847       EVT MaskVT = Mask.getValueType();
19848
19849       // Validate that the Mask operand is a vector sra node.
19850       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19851       // there is no psrai.b
19852       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19853       unsigned SraAmt = ~0;
19854       if (Mask.getOpcode() == ISD::SRA) {
19855         SDValue Amt = Mask.getOperand(1);
19856         if (isSplatVector(Amt.getNode())) {
19857           SDValue SclrAmt = Amt->getOperand(0);
19858           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19859             SraAmt = C->getZExtValue();
19860         }
19861       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19862         SDValue SraC = Mask.getOperand(1);
19863         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19864       }
19865       if ((SraAmt + 1) != EltBits)
19866         return SDValue();
19867
19868       SDLoc DL(N);
19869
19870       // Now we know we at least have a plendvb with the mask val.  See if
19871       // we can form a psignb/w/d.
19872       // psign = x.type == y.type == mask.type && y = sub(0, x);
19873       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19874           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19875           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19876         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19877                "Unsupported VT for PSIGN");
19878         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19879         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19880       }
19881       // PBLENDVB only available on SSE 4.1
19882       if (!Subtarget->hasSSE41())
19883         return SDValue();
19884
19885       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19886
19887       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19888       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19889       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19890       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19891       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19892     }
19893   }
19894
19895   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19896     return SDValue();
19897
19898   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19899   MachineFunction &MF = DAG.getMachineFunction();
19900   bool OptForSize = MF.getFunction()->getAttributes().
19901     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19902
19903   // SHLD/SHRD instructions have lower register pressure, but on some
19904   // platforms they have higher latency than the equivalent
19905   // series of shifts/or that would otherwise be generated.
19906   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19907   // have higher latencies and we are not optimizing for size.
19908   if (!OptForSize && Subtarget->isSHLDSlow())
19909     return SDValue();
19910
19911   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19912     std::swap(N0, N1);
19913   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19914     return SDValue();
19915   if (!N0.hasOneUse() || !N1.hasOneUse())
19916     return SDValue();
19917
19918   SDValue ShAmt0 = N0.getOperand(1);
19919   if (ShAmt0.getValueType() != MVT::i8)
19920     return SDValue();
19921   SDValue ShAmt1 = N1.getOperand(1);
19922   if (ShAmt1.getValueType() != MVT::i8)
19923     return SDValue();
19924   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19925     ShAmt0 = ShAmt0.getOperand(0);
19926   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19927     ShAmt1 = ShAmt1.getOperand(0);
19928
19929   SDLoc DL(N);
19930   unsigned Opc = X86ISD::SHLD;
19931   SDValue Op0 = N0.getOperand(0);
19932   SDValue Op1 = N1.getOperand(0);
19933   if (ShAmt0.getOpcode() == ISD::SUB) {
19934     Opc = X86ISD::SHRD;
19935     std::swap(Op0, Op1);
19936     std::swap(ShAmt0, ShAmt1);
19937   }
19938
19939   unsigned Bits = VT.getSizeInBits();
19940   if (ShAmt1.getOpcode() == ISD::SUB) {
19941     SDValue Sum = ShAmt1.getOperand(0);
19942     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19943       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19944       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19945         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19946       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19947         return DAG.getNode(Opc, DL, VT,
19948                            Op0, Op1,
19949                            DAG.getNode(ISD::TRUNCATE, DL,
19950                                        MVT::i8, ShAmt0));
19951     }
19952   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19953     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19954     if (ShAmt0C &&
19955         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19956       return DAG.getNode(Opc, DL, VT,
19957                          N0.getOperand(0), N1.getOperand(0),
19958                          DAG.getNode(ISD::TRUNCATE, DL,
19959                                        MVT::i8, ShAmt0));
19960   }
19961
19962   return SDValue();
19963 }
19964
19965 // Generate NEG and CMOV for integer abs.
19966 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19967   EVT VT = N->getValueType(0);
19968
19969   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19970   // 8-bit integer abs to NEG and CMOV.
19971   if (VT.isInteger() && VT.getSizeInBits() == 8)
19972     return SDValue();
19973
19974   SDValue N0 = N->getOperand(0);
19975   SDValue N1 = N->getOperand(1);
19976   SDLoc DL(N);
19977
19978   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19979   // and change it to SUB and CMOV.
19980   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19981       N0.getOpcode() == ISD::ADD &&
19982       N0.getOperand(1) == N1 &&
19983       N1.getOpcode() == ISD::SRA &&
19984       N1.getOperand(0) == N0.getOperand(0))
19985     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19986       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19987         // Generate SUB & CMOV.
19988         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19989                                   DAG.getConstant(0, VT), N0.getOperand(0));
19990
19991         SDValue Ops[] = { N0.getOperand(0), Neg,
19992                           DAG.getConstant(X86::COND_GE, MVT::i8),
19993                           SDValue(Neg.getNode(), 1) };
19994         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19995       }
19996   return SDValue();
19997 }
19998
19999 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
20000 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
20001                                  TargetLowering::DAGCombinerInfo &DCI,
20002                                  const X86Subtarget *Subtarget) {
20003   if (DCI.isBeforeLegalizeOps())
20004     return SDValue();
20005
20006   if (Subtarget->hasCMov()) {
20007     SDValue RV = performIntegerAbsCombine(N, DAG);
20008     if (RV.getNode())
20009       return RV;
20010   }
20011
20012   return SDValue();
20013 }
20014
20015 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
20016 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
20017                                   TargetLowering::DAGCombinerInfo &DCI,
20018                                   const X86Subtarget *Subtarget) {
20019   LoadSDNode *Ld = cast<LoadSDNode>(N);
20020   EVT RegVT = Ld->getValueType(0);
20021   EVT MemVT = Ld->getMemoryVT();
20022   SDLoc dl(Ld);
20023   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20024   unsigned RegSz = RegVT.getSizeInBits();
20025
20026   // On Sandybridge unaligned 256bit loads are inefficient.
20027   ISD::LoadExtType Ext = Ld->getExtensionType();
20028   unsigned Alignment = Ld->getAlignment();
20029   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
20030   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
20031       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
20032     unsigned NumElems = RegVT.getVectorNumElements();
20033     if (NumElems < 2)
20034       return SDValue();
20035
20036     SDValue Ptr = Ld->getBasePtr();
20037     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
20038
20039     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20040                                   NumElems/2);
20041     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20042                                 Ld->getPointerInfo(), Ld->isVolatile(),
20043                                 Ld->isNonTemporal(), Ld->isInvariant(),
20044                                 Alignment);
20045     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20046     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
20047                                 Ld->getPointerInfo(), Ld->isVolatile(),
20048                                 Ld->isNonTemporal(), Ld->isInvariant(),
20049                                 std::min(16U, Alignment));
20050     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20051                              Load1.getValue(1),
20052                              Load2.getValue(1));
20053
20054     SDValue NewVec = DAG.getUNDEF(RegVT);
20055     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
20056     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
20057     return DCI.CombineTo(N, NewVec, TF, true);
20058   }
20059
20060   // If this is a vector EXT Load then attempt to optimize it using a
20061   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
20062   // expansion is still better than scalar code.
20063   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
20064   // emit a shuffle and a arithmetic shift.
20065   // TODO: It is possible to support ZExt by zeroing the undef values
20066   // during the shuffle phase or after the shuffle.
20067   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
20068       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
20069     assert(MemVT != RegVT && "Cannot extend to the same type");
20070     assert(MemVT.isVector() && "Must load a vector from memory");
20071
20072     unsigned NumElems = RegVT.getVectorNumElements();
20073     unsigned MemSz = MemVT.getSizeInBits();
20074     assert(RegSz > MemSz && "Register size must be greater than the mem size");
20075
20076     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
20077       return SDValue();
20078
20079     // All sizes must be a power of two.
20080     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
20081       return SDValue();
20082
20083     // Attempt to load the original value using scalar loads.
20084     // Find the largest scalar type that divides the total loaded size.
20085     MVT SclrLoadTy = MVT::i8;
20086     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20087          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20088       MVT Tp = (MVT::SimpleValueType)tp;
20089       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
20090         SclrLoadTy = Tp;
20091       }
20092     }
20093
20094     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20095     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
20096         (64 <= MemSz))
20097       SclrLoadTy = MVT::f64;
20098
20099     // Calculate the number of scalar loads that we need to perform
20100     // in order to load our vector from memory.
20101     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
20102     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
20103       return SDValue();
20104
20105     unsigned loadRegZize = RegSz;
20106     if (Ext == ISD::SEXTLOAD && RegSz == 256)
20107       loadRegZize /= 2;
20108
20109     // Represent our vector as a sequence of elements which are the
20110     // largest scalar that we can load.
20111     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
20112       loadRegZize/SclrLoadTy.getSizeInBits());
20113
20114     // Represent the data using the same element type that is stored in
20115     // memory. In practice, we ''widen'' MemVT.
20116     EVT WideVecVT =
20117           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
20118                        loadRegZize/MemVT.getScalarType().getSizeInBits());
20119
20120     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
20121       "Invalid vector type");
20122
20123     // We can't shuffle using an illegal type.
20124     if (!TLI.isTypeLegal(WideVecVT))
20125       return SDValue();
20126
20127     SmallVector<SDValue, 8> Chains;
20128     SDValue Ptr = Ld->getBasePtr();
20129     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
20130                                         TLI.getPointerTy());
20131     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
20132
20133     for (unsigned i = 0; i < NumLoads; ++i) {
20134       // Perform a single load.
20135       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
20136                                        Ptr, Ld->getPointerInfo(),
20137                                        Ld->isVolatile(), Ld->isNonTemporal(),
20138                                        Ld->isInvariant(), Ld->getAlignment());
20139       Chains.push_back(ScalarLoad.getValue(1));
20140       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
20141       // another round of DAGCombining.
20142       if (i == 0)
20143         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
20144       else
20145         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20146                           ScalarLoad, DAG.getIntPtrConstant(i));
20147
20148       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20149     }
20150
20151     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20152
20153     // Bitcast the loaded value to a vector of the original element type, in
20154     // the size of the target vector type.
20155     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20156     unsigned SizeRatio = RegSz/MemSz;
20157
20158     if (Ext == ISD::SEXTLOAD) {
20159       // If we have SSE4.1 we can directly emit a VSEXT node.
20160       if (Subtarget->hasSSE41()) {
20161         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20162         return DCI.CombineTo(N, Sext, TF, true);
20163       }
20164
20165       // Otherwise we'll shuffle the small elements in the high bits of the
20166       // larger type and perform an arithmetic shift. If the shift is not legal
20167       // it's better to scalarize.
20168       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20169         return SDValue();
20170
20171       // Redistribute the loaded elements into the different locations.
20172       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20173       for (unsigned i = 0; i != NumElems; ++i)
20174         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20175
20176       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20177                                            DAG.getUNDEF(WideVecVT),
20178                                            &ShuffleVec[0]);
20179
20180       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20181
20182       // Build the arithmetic shift.
20183       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20184                      MemVT.getVectorElementType().getSizeInBits();
20185       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20186                           DAG.getConstant(Amt, RegVT));
20187
20188       return DCI.CombineTo(N, Shuff, TF, true);
20189     }
20190
20191     // Redistribute the loaded elements into the different locations.
20192     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20193     for (unsigned i = 0; i != NumElems; ++i)
20194       ShuffleVec[i*SizeRatio] = i;
20195
20196     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20197                                          DAG.getUNDEF(WideVecVT),
20198                                          &ShuffleVec[0]);
20199
20200     // Bitcast to the requested type.
20201     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20202     // Replace the original load with the new sequence
20203     // and return the new chain.
20204     return DCI.CombineTo(N, Shuff, TF, true);
20205   }
20206
20207   return SDValue();
20208 }
20209
20210 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20211 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20212                                    const X86Subtarget *Subtarget) {
20213   StoreSDNode *St = cast<StoreSDNode>(N);
20214   EVT VT = St->getValue().getValueType();
20215   EVT StVT = St->getMemoryVT();
20216   SDLoc dl(St);
20217   SDValue StoredVal = St->getOperand(1);
20218   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20219
20220   // If we are saving a concatenation of two XMM registers, perform two stores.
20221   // On Sandy Bridge, 256-bit memory operations are executed by two
20222   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20223   // memory  operation.
20224   unsigned Alignment = St->getAlignment();
20225   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20226   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20227       StVT == VT && !IsAligned) {
20228     unsigned NumElems = VT.getVectorNumElements();
20229     if (NumElems < 2)
20230       return SDValue();
20231
20232     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20233     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20234
20235     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20236     SDValue Ptr0 = St->getBasePtr();
20237     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20238
20239     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20240                                 St->getPointerInfo(), St->isVolatile(),
20241                                 St->isNonTemporal(), Alignment);
20242     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20243                                 St->getPointerInfo(), St->isVolatile(),
20244                                 St->isNonTemporal(),
20245                                 std::min(16U, Alignment));
20246     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20247   }
20248
20249   // Optimize trunc store (of multiple scalars) to shuffle and store.
20250   // First, pack all of the elements in one place. Next, store to memory
20251   // in fewer chunks.
20252   if (St->isTruncatingStore() && VT.isVector()) {
20253     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20254     unsigned NumElems = VT.getVectorNumElements();
20255     assert(StVT != VT && "Cannot truncate to the same type");
20256     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20257     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20258
20259     // From, To sizes and ElemCount must be pow of two
20260     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20261     // We are going to use the original vector elt for storing.
20262     // Accumulated smaller vector elements must be a multiple of the store size.
20263     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20264
20265     unsigned SizeRatio  = FromSz / ToSz;
20266
20267     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20268
20269     // Create a type on which we perform the shuffle
20270     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20271             StVT.getScalarType(), NumElems*SizeRatio);
20272
20273     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20274
20275     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20276     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20277     for (unsigned i = 0; i != NumElems; ++i)
20278       ShuffleVec[i] = i * SizeRatio;
20279
20280     // Can't shuffle using an illegal type.
20281     if (!TLI.isTypeLegal(WideVecVT))
20282       return SDValue();
20283
20284     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20285                                          DAG.getUNDEF(WideVecVT),
20286                                          &ShuffleVec[0]);
20287     // At this point all of the data is stored at the bottom of the
20288     // register. We now need to save it to mem.
20289
20290     // Find the largest store unit
20291     MVT StoreType = MVT::i8;
20292     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20293          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20294       MVT Tp = (MVT::SimpleValueType)tp;
20295       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20296         StoreType = Tp;
20297     }
20298
20299     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20300     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20301         (64 <= NumElems * ToSz))
20302       StoreType = MVT::f64;
20303
20304     // Bitcast the original vector into a vector of store-size units
20305     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20306             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20307     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20308     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20309     SmallVector<SDValue, 8> Chains;
20310     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20311                                         TLI.getPointerTy());
20312     SDValue Ptr = St->getBasePtr();
20313
20314     // Perform one or more big stores into memory.
20315     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20316       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20317                                    StoreType, ShuffWide,
20318                                    DAG.getIntPtrConstant(i));
20319       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20320                                 St->getPointerInfo(), St->isVolatile(),
20321                                 St->isNonTemporal(), St->getAlignment());
20322       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20323       Chains.push_back(Ch);
20324     }
20325
20326     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20327   }
20328
20329   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
20330   // the FP state in cases where an emms may be missing.
20331   // A preferable solution to the general problem is to figure out the right
20332   // places to insert EMMS.  This qualifies as a quick hack.
20333
20334   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20335   if (VT.getSizeInBits() != 64)
20336     return SDValue();
20337
20338   const Function *F = DAG.getMachineFunction().getFunction();
20339   bool NoImplicitFloatOps = F->getAttributes().
20340     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20341   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20342                      && Subtarget->hasSSE2();
20343   if ((VT.isVector() ||
20344        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20345       isa<LoadSDNode>(St->getValue()) &&
20346       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20347       St->getChain().hasOneUse() && !St->isVolatile()) {
20348     SDNode* LdVal = St->getValue().getNode();
20349     LoadSDNode *Ld = nullptr;
20350     int TokenFactorIndex = -1;
20351     SmallVector<SDValue, 8> Ops;
20352     SDNode* ChainVal = St->getChain().getNode();
20353     // Must be a store of a load.  We currently handle two cases:  the load
20354     // is a direct child, and it's under an intervening TokenFactor.  It is
20355     // possible to dig deeper under nested TokenFactors.
20356     if (ChainVal == LdVal)
20357       Ld = cast<LoadSDNode>(St->getChain());
20358     else if (St->getValue().hasOneUse() &&
20359              ChainVal->getOpcode() == ISD::TokenFactor) {
20360       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20361         if (ChainVal->getOperand(i).getNode() == LdVal) {
20362           TokenFactorIndex = i;
20363           Ld = cast<LoadSDNode>(St->getValue());
20364         } else
20365           Ops.push_back(ChainVal->getOperand(i));
20366       }
20367     }
20368
20369     if (!Ld || !ISD::isNormalLoad(Ld))
20370       return SDValue();
20371
20372     // If this is not the MMX case, i.e. we are just turning i64 load/store
20373     // into f64 load/store, avoid the transformation if there are multiple
20374     // uses of the loaded value.
20375     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20376       return SDValue();
20377
20378     SDLoc LdDL(Ld);
20379     SDLoc StDL(N);
20380     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20381     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20382     // pair instead.
20383     if (Subtarget->is64Bit() || F64IsLegal) {
20384       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20385       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20386                                   Ld->getPointerInfo(), Ld->isVolatile(),
20387                                   Ld->isNonTemporal(), Ld->isInvariant(),
20388                                   Ld->getAlignment());
20389       SDValue NewChain = NewLd.getValue(1);
20390       if (TokenFactorIndex != -1) {
20391         Ops.push_back(NewChain);
20392         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20393       }
20394       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20395                           St->getPointerInfo(),
20396                           St->isVolatile(), St->isNonTemporal(),
20397                           St->getAlignment());
20398     }
20399
20400     // Otherwise, lower to two pairs of 32-bit loads / stores.
20401     SDValue LoAddr = Ld->getBasePtr();
20402     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20403                                  DAG.getConstant(4, MVT::i32));
20404
20405     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20406                                Ld->getPointerInfo(),
20407                                Ld->isVolatile(), Ld->isNonTemporal(),
20408                                Ld->isInvariant(), Ld->getAlignment());
20409     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20410                                Ld->getPointerInfo().getWithOffset(4),
20411                                Ld->isVolatile(), Ld->isNonTemporal(),
20412                                Ld->isInvariant(),
20413                                MinAlign(Ld->getAlignment(), 4));
20414
20415     SDValue NewChain = LoLd.getValue(1);
20416     if (TokenFactorIndex != -1) {
20417       Ops.push_back(LoLd);
20418       Ops.push_back(HiLd);
20419       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20420     }
20421
20422     LoAddr = St->getBasePtr();
20423     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20424                          DAG.getConstant(4, MVT::i32));
20425
20426     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20427                                 St->getPointerInfo(),
20428                                 St->isVolatile(), St->isNonTemporal(),
20429                                 St->getAlignment());
20430     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20431                                 St->getPointerInfo().getWithOffset(4),
20432                                 St->isVolatile(),
20433                                 St->isNonTemporal(),
20434                                 MinAlign(St->getAlignment(), 4));
20435     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20436   }
20437   return SDValue();
20438 }
20439
20440 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20441 /// and return the operands for the horizontal operation in LHS and RHS.  A
20442 /// horizontal operation performs the binary operation on successive elements
20443 /// of its first operand, then on successive elements of its second operand,
20444 /// returning the resulting values in a vector.  For example, if
20445 ///   A = < float a0, float a1, float a2, float a3 >
20446 /// and
20447 ///   B = < float b0, float b1, float b2, float b3 >
20448 /// then the result of doing a horizontal operation on A and B is
20449 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20450 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20451 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20452 /// set to A, RHS to B, and the routine returns 'true'.
20453 /// Note that the binary operation should have the property that if one of the
20454 /// operands is UNDEF then the result is UNDEF.
20455 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20456   // Look for the following pattern: if
20457   //   A = < float a0, float a1, float a2, float a3 >
20458   //   B = < float b0, float b1, float b2, float b3 >
20459   // and
20460   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20461   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20462   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20463   // which is A horizontal-op B.
20464
20465   // At least one of the operands should be a vector shuffle.
20466   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20467       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20468     return false;
20469
20470   MVT VT = LHS.getSimpleValueType();
20471
20472   assert((VT.is128BitVector() || VT.is256BitVector()) &&
20473          "Unsupported vector type for horizontal add/sub");
20474
20475   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20476   // operate independently on 128-bit lanes.
20477   unsigned NumElts = VT.getVectorNumElements();
20478   unsigned NumLanes = VT.getSizeInBits()/128;
20479   unsigned NumLaneElts = NumElts / NumLanes;
20480   assert((NumLaneElts % 2 == 0) &&
20481          "Vector type should have an even number of elements in each lane");
20482   unsigned HalfLaneElts = NumLaneElts/2;
20483
20484   // View LHS in the form
20485   //   LHS = VECTOR_SHUFFLE A, B, LMask
20486   // If LHS is not a shuffle then pretend it is the shuffle
20487   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20488   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20489   // type VT.
20490   SDValue A, B;
20491   SmallVector<int, 16> LMask(NumElts);
20492   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20493     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20494       A = LHS.getOperand(0);
20495     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20496       B = LHS.getOperand(1);
20497     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20498     std::copy(Mask.begin(), Mask.end(), LMask.begin());
20499   } else {
20500     if (LHS.getOpcode() != ISD::UNDEF)
20501       A = LHS;
20502     for (unsigned i = 0; i != NumElts; ++i)
20503       LMask[i] = i;
20504   }
20505
20506   // Likewise, view RHS in the form
20507   //   RHS = VECTOR_SHUFFLE C, D, RMask
20508   SDValue C, D;
20509   SmallVector<int, 16> RMask(NumElts);
20510   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20511     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20512       C = RHS.getOperand(0);
20513     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20514       D = RHS.getOperand(1);
20515     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20516     std::copy(Mask.begin(), Mask.end(), RMask.begin());
20517   } else {
20518     if (RHS.getOpcode() != ISD::UNDEF)
20519       C = RHS;
20520     for (unsigned i = 0; i != NumElts; ++i)
20521       RMask[i] = i;
20522   }
20523
20524   // Check that the shuffles are both shuffling the same vectors.
20525   if (!(A == C && B == D) && !(A == D && B == C))
20526     return false;
20527
20528   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20529   if (!A.getNode() && !B.getNode())
20530     return false;
20531
20532   // If A and B occur in reverse order in RHS, then "swap" them (which means
20533   // rewriting the mask).
20534   if (A != C)
20535     CommuteVectorShuffleMask(RMask, NumElts);
20536
20537   // At this point LHS and RHS are equivalent to
20538   //   LHS = VECTOR_SHUFFLE A, B, LMask
20539   //   RHS = VECTOR_SHUFFLE A, B, RMask
20540   // Check that the masks correspond to performing a horizontal operation.
20541   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20542     for (unsigned i = 0; i != NumLaneElts; ++i) {
20543       int LIdx = LMask[i+l], RIdx = RMask[i+l];
20544
20545       // Ignore any UNDEF components.
20546       if (LIdx < 0 || RIdx < 0 ||
20547           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20548           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20549         continue;
20550
20551       // Check that successive elements are being operated on.  If not, this is
20552       // not a horizontal operation.
20553       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20554       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20555       if (!(LIdx == Index && RIdx == Index + 1) &&
20556           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20557         return false;
20558     }
20559   }
20560
20561   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20562   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20563   return true;
20564 }
20565
20566 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20567 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20568                                   const X86Subtarget *Subtarget) {
20569   EVT VT = N->getValueType(0);
20570   SDValue LHS = N->getOperand(0);
20571   SDValue RHS = N->getOperand(1);
20572
20573   // Try to synthesize horizontal adds from adds of shuffles.
20574   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20575        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20576       isHorizontalBinOp(LHS, RHS, true))
20577     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20578   return SDValue();
20579 }
20580
20581 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20582 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20583                                   const X86Subtarget *Subtarget) {
20584   EVT VT = N->getValueType(0);
20585   SDValue LHS = N->getOperand(0);
20586   SDValue RHS = N->getOperand(1);
20587
20588   // Try to synthesize horizontal subs from subs of shuffles.
20589   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20590        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20591       isHorizontalBinOp(LHS, RHS, false))
20592     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20593   return SDValue();
20594 }
20595
20596 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20597 /// X86ISD::FXOR nodes.
20598 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20599   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20600   // F[X]OR(0.0, x) -> x
20601   // F[X]OR(x, 0.0) -> x
20602   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20603     if (C->getValueAPF().isPosZero())
20604       return N->getOperand(1);
20605   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20606     if (C->getValueAPF().isPosZero())
20607       return N->getOperand(0);
20608   return SDValue();
20609 }
20610
20611 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20612 /// X86ISD::FMAX nodes.
20613 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20614   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20615
20616   // Only perform optimizations if UnsafeMath is used.
20617   if (!DAG.getTarget().Options.UnsafeFPMath)
20618     return SDValue();
20619
20620   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20621   // into FMINC and FMAXC, which are Commutative operations.
20622   unsigned NewOp = 0;
20623   switch (N->getOpcode()) {
20624     default: llvm_unreachable("unknown opcode");
20625     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20626     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20627   }
20628
20629   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20630                      N->getOperand(0), N->getOperand(1));
20631 }
20632
20633 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20634 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20635   // FAND(0.0, x) -> 0.0
20636   // FAND(x, 0.0) -> 0.0
20637   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20638     if (C->getValueAPF().isPosZero())
20639       return N->getOperand(0);
20640   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20641     if (C->getValueAPF().isPosZero())
20642       return N->getOperand(1);
20643   return SDValue();
20644 }
20645
20646 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20647 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20648   // FANDN(x, 0.0) -> 0.0
20649   // FANDN(0.0, x) -> x
20650   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20651     if (C->getValueAPF().isPosZero())
20652       return N->getOperand(1);
20653   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20654     if (C->getValueAPF().isPosZero())
20655       return N->getOperand(1);
20656   return SDValue();
20657 }
20658
20659 static SDValue PerformBTCombine(SDNode *N,
20660                                 SelectionDAG &DAG,
20661                                 TargetLowering::DAGCombinerInfo &DCI) {
20662   // BT ignores high bits in the bit index operand.
20663   SDValue Op1 = N->getOperand(1);
20664   if (Op1.hasOneUse()) {
20665     unsigned BitWidth = Op1.getValueSizeInBits();
20666     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20667     APInt KnownZero, KnownOne;
20668     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20669                                           !DCI.isBeforeLegalizeOps());
20670     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20671     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20672         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20673       DCI.CommitTargetLoweringOpt(TLO);
20674   }
20675   return SDValue();
20676 }
20677
20678 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20679   SDValue Op = N->getOperand(0);
20680   if (Op.getOpcode() == ISD::BITCAST)
20681     Op = Op.getOperand(0);
20682   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20683   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20684       VT.getVectorElementType().getSizeInBits() ==
20685       OpVT.getVectorElementType().getSizeInBits()) {
20686     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20687   }
20688   return SDValue();
20689 }
20690
20691 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20692                                                const X86Subtarget *Subtarget) {
20693   EVT VT = N->getValueType(0);
20694   if (!VT.isVector())
20695     return SDValue();
20696
20697   SDValue N0 = N->getOperand(0);
20698   SDValue N1 = N->getOperand(1);
20699   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20700   SDLoc dl(N);
20701
20702   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20703   // both SSE and AVX2 since there is no sign-extended shift right
20704   // operation on a vector with 64-bit elements.
20705   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20706   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20707   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20708       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20709     SDValue N00 = N0.getOperand(0);
20710
20711     // EXTLOAD has a better solution on AVX2,
20712     // it may be replaced with X86ISD::VSEXT node.
20713     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20714       if (!ISD::isNormalLoad(N00.getNode()))
20715         return SDValue();
20716
20717     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20718         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20719                                   N00, N1);
20720       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20721     }
20722   }
20723   return SDValue();
20724 }
20725
20726 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20727                                   TargetLowering::DAGCombinerInfo &DCI,
20728                                   const X86Subtarget *Subtarget) {
20729   if (!DCI.isBeforeLegalizeOps())
20730     return SDValue();
20731
20732   if (!Subtarget->hasFp256())
20733     return SDValue();
20734
20735   EVT VT = N->getValueType(0);
20736   if (VT.isVector() && VT.getSizeInBits() == 256) {
20737     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20738     if (R.getNode())
20739       return R;
20740   }
20741
20742   return SDValue();
20743 }
20744
20745 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20746                                  const X86Subtarget* Subtarget) {
20747   SDLoc dl(N);
20748   EVT VT = N->getValueType(0);
20749
20750   // Let legalize expand this if it isn't a legal type yet.
20751   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20752     return SDValue();
20753
20754   EVT ScalarVT = VT.getScalarType();
20755   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20756       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20757     return SDValue();
20758
20759   SDValue A = N->getOperand(0);
20760   SDValue B = N->getOperand(1);
20761   SDValue C = N->getOperand(2);
20762
20763   bool NegA = (A.getOpcode() == ISD::FNEG);
20764   bool NegB = (B.getOpcode() == ISD::FNEG);
20765   bool NegC = (C.getOpcode() == ISD::FNEG);
20766
20767   // Negative multiplication when NegA xor NegB
20768   bool NegMul = (NegA != NegB);
20769   if (NegA)
20770     A = A.getOperand(0);
20771   if (NegB)
20772     B = B.getOperand(0);
20773   if (NegC)
20774     C = C.getOperand(0);
20775
20776   unsigned Opcode;
20777   if (!NegMul)
20778     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20779   else
20780     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20781
20782   return DAG.getNode(Opcode, dl, VT, A, B, C);
20783 }
20784
20785 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20786                                   TargetLowering::DAGCombinerInfo &DCI,
20787                                   const X86Subtarget *Subtarget) {
20788   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20789   //           (and (i32 x86isd::setcc_carry), 1)
20790   // This eliminates the zext. This transformation is necessary because
20791   // ISD::SETCC is always legalized to i8.
20792   SDLoc dl(N);
20793   SDValue N0 = N->getOperand(0);
20794   EVT VT = N->getValueType(0);
20795
20796   if (N0.getOpcode() == ISD::AND &&
20797       N0.hasOneUse() &&
20798       N0.getOperand(0).hasOneUse()) {
20799     SDValue N00 = N0.getOperand(0);
20800     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20801       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20802       if (!C || C->getZExtValue() != 1)
20803         return SDValue();
20804       return DAG.getNode(ISD::AND, dl, VT,
20805                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20806                                      N00.getOperand(0), N00.getOperand(1)),
20807                          DAG.getConstant(1, VT));
20808     }
20809   }
20810
20811   if (N0.getOpcode() == ISD::TRUNCATE &&
20812       N0.hasOneUse() &&
20813       N0.getOperand(0).hasOneUse()) {
20814     SDValue N00 = N0.getOperand(0);
20815     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20816       return DAG.getNode(ISD::AND, dl, VT,
20817                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20818                                      N00.getOperand(0), N00.getOperand(1)),
20819                          DAG.getConstant(1, VT));
20820     }
20821   }
20822   if (VT.is256BitVector()) {
20823     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20824     if (R.getNode())
20825       return R;
20826   }
20827
20828   return SDValue();
20829 }
20830
20831 // Optimize x == -y --> x+y == 0
20832 //          x != -y --> x+y != 0
20833 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20834                                       const X86Subtarget* Subtarget) {
20835   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20836   SDValue LHS = N->getOperand(0);
20837   SDValue RHS = N->getOperand(1);
20838   EVT VT = N->getValueType(0);
20839   SDLoc DL(N);
20840
20841   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20842     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20843       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20844         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20845                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20846         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20847                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20848       }
20849   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20850     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20851       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20852         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20853                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20854         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20855                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20856       }
20857
20858   if (VT.getScalarType() == MVT::i1) {
20859     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20860       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20861     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20862     if (!IsSEXT0 && !IsVZero0)
20863       return SDValue();
20864     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20865       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20866     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20867
20868     if (!IsSEXT1 && !IsVZero1)
20869       return SDValue();
20870
20871     if (IsSEXT0 && IsVZero1) {
20872       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20873       if (CC == ISD::SETEQ)
20874         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20875       return LHS.getOperand(0);
20876     }
20877     if (IsSEXT1 && IsVZero0) {
20878       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20879       if (CC == ISD::SETEQ)
20880         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20881       return RHS.getOperand(0);
20882     }
20883   }
20884
20885   return SDValue();
20886 }
20887
20888 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20889                                       const X86Subtarget *Subtarget) {
20890   SDLoc dl(N);
20891   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20892   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20893          "X86insertps is only defined for v4x32");
20894
20895   SDValue Ld = N->getOperand(1);
20896   if (MayFoldLoad(Ld)) {
20897     // Extract the countS bits from the immediate so we can get the proper
20898     // address when narrowing the vector load to a specific element.
20899     // When the second source op is a memory address, interps doesn't use
20900     // countS and just gets an f32 from that address.
20901     unsigned DestIndex =
20902         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20903     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20904   } else
20905     return SDValue();
20906
20907   // Create this as a scalar to vector to match the instruction pattern.
20908   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20909   // countS bits are ignored when loading from memory on insertps, which
20910   // means we don't need to explicitly set them to 0.
20911   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20912                      LoadScalarToVector, N->getOperand(2));
20913 }
20914
20915 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20916 // as "sbb reg,reg", since it can be extended without zext and produces
20917 // an all-ones bit which is more useful than 0/1 in some cases.
20918 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20919                                MVT VT) {
20920   if (VT == MVT::i8)
20921     return DAG.getNode(ISD::AND, DL, VT,
20922                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20923                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20924                        DAG.getConstant(1, VT));
20925   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20926   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20927                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20928                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20929 }
20930
20931 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20932 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20933                                    TargetLowering::DAGCombinerInfo &DCI,
20934                                    const X86Subtarget *Subtarget) {
20935   SDLoc DL(N);
20936   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20937   SDValue EFLAGS = N->getOperand(1);
20938
20939   if (CC == X86::COND_A) {
20940     // Try to convert COND_A into COND_B in an attempt to facilitate
20941     // materializing "setb reg".
20942     //
20943     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20944     // cannot take an immediate as its first operand.
20945     //
20946     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20947         EFLAGS.getValueType().isInteger() &&
20948         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20949       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20950                                    EFLAGS.getNode()->getVTList(),
20951                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20952       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20953       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20954     }
20955   }
20956
20957   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20958   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20959   // cases.
20960   if (CC == X86::COND_B)
20961     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20962
20963   SDValue Flags;
20964
20965   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20966   if (Flags.getNode()) {
20967     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20968     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20969   }
20970
20971   return SDValue();
20972 }
20973
20974 // Optimize branch condition evaluation.
20975 //
20976 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20977                                     TargetLowering::DAGCombinerInfo &DCI,
20978                                     const X86Subtarget *Subtarget) {
20979   SDLoc DL(N);
20980   SDValue Chain = N->getOperand(0);
20981   SDValue Dest = N->getOperand(1);
20982   SDValue EFLAGS = N->getOperand(3);
20983   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20984
20985   SDValue Flags;
20986
20987   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20988   if (Flags.getNode()) {
20989     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20990     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20991                        Flags);
20992   }
20993
20994   return SDValue();
20995 }
20996
20997 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20998                                         const X86TargetLowering *XTLI) {
20999   SDValue Op0 = N->getOperand(0);
21000   EVT InVT = Op0->getValueType(0);
21001
21002   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
21003   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
21004     SDLoc dl(N);
21005     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
21006     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
21007     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
21008   }
21009
21010   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
21011   // a 32-bit target where SSE doesn't support i64->FP operations.
21012   if (Op0.getOpcode() == ISD::LOAD) {
21013     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
21014     EVT VT = Ld->getValueType(0);
21015     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
21016         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
21017         !XTLI->getSubtarget()->is64Bit() &&
21018         VT == MVT::i64) {
21019       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
21020                                           Ld->getChain(), Op0, DAG);
21021       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
21022       return FILDChain;
21023     }
21024   }
21025   return SDValue();
21026 }
21027
21028 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
21029 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
21030                                  X86TargetLowering::DAGCombinerInfo &DCI) {
21031   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
21032   // the result is either zero or one (depending on the input carry bit).
21033   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
21034   if (X86::isZeroNode(N->getOperand(0)) &&
21035       X86::isZeroNode(N->getOperand(1)) &&
21036       // We don't have a good way to replace an EFLAGS use, so only do this when
21037       // dead right now.
21038       SDValue(N, 1).use_empty()) {
21039     SDLoc DL(N);
21040     EVT VT = N->getValueType(0);
21041     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
21042     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
21043                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
21044                                            DAG.getConstant(X86::COND_B,MVT::i8),
21045                                            N->getOperand(2)),
21046                                DAG.getConstant(1, VT));
21047     return DCI.CombineTo(N, Res1, CarryOut);
21048   }
21049
21050   return SDValue();
21051 }
21052
21053 // fold (add Y, (sete  X, 0)) -> adc  0, Y
21054 //      (add Y, (setne X, 0)) -> sbb -1, Y
21055 //      (sub (sete  X, 0), Y) -> sbb  0, Y
21056 //      (sub (setne X, 0), Y) -> adc -1, Y
21057 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
21058   SDLoc DL(N);
21059
21060   // Look through ZExts.
21061   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
21062   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
21063     return SDValue();
21064
21065   SDValue SetCC = Ext.getOperand(0);
21066   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
21067     return SDValue();
21068
21069   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
21070   if (CC != X86::COND_E && CC != X86::COND_NE)
21071     return SDValue();
21072
21073   SDValue Cmp = SetCC.getOperand(1);
21074   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
21075       !X86::isZeroNode(Cmp.getOperand(1)) ||
21076       !Cmp.getOperand(0).getValueType().isInteger())
21077     return SDValue();
21078
21079   SDValue CmpOp0 = Cmp.getOperand(0);
21080   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
21081                                DAG.getConstant(1, CmpOp0.getValueType()));
21082
21083   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
21084   if (CC == X86::COND_NE)
21085     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
21086                        DL, OtherVal.getValueType(), OtherVal,
21087                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
21088   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
21089                      DL, OtherVal.getValueType(), OtherVal,
21090                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
21091 }
21092
21093 /// PerformADDCombine - Do target-specific dag combines on integer adds.
21094 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
21095                                  const X86Subtarget *Subtarget) {
21096   EVT VT = N->getValueType(0);
21097   SDValue Op0 = N->getOperand(0);
21098   SDValue Op1 = N->getOperand(1);
21099
21100   // Try to synthesize horizontal adds from adds of shuffles.
21101   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21102        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21103       isHorizontalBinOp(Op0, Op1, true))
21104     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
21105
21106   return OptimizeConditionalInDecrement(N, DAG);
21107 }
21108
21109 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
21110                                  const X86Subtarget *Subtarget) {
21111   SDValue Op0 = N->getOperand(0);
21112   SDValue Op1 = N->getOperand(1);
21113
21114   // X86 can't encode an immediate LHS of a sub. See if we can push the
21115   // negation into a preceding instruction.
21116   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
21117     // If the RHS of the sub is a XOR with one use and a constant, invert the
21118     // immediate. Then add one to the LHS of the sub so we can turn
21119     // X-Y -> X+~Y+1, saving one register.
21120     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
21121         isa<ConstantSDNode>(Op1.getOperand(1))) {
21122       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
21123       EVT VT = Op0.getValueType();
21124       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
21125                                    Op1.getOperand(0),
21126                                    DAG.getConstant(~XorC, VT));
21127       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
21128                          DAG.getConstant(C->getAPIntValue()+1, VT));
21129     }
21130   }
21131
21132   // Try to synthesize horizontal adds from adds of shuffles.
21133   EVT VT = N->getValueType(0);
21134   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
21135        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
21136       isHorizontalBinOp(Op0, Op1, true))
21137     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
21138
21139   return OptimizeConditionalInDecrement(N, DAG);
21140 }
21141
21142 /// performVZEXTCombine - Performs build vector combines
21143 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
21144                                         TargetLowering::DAGCombinerInfo &DCI,
21145                                         const X86Subtarget *Subtarget) {
21146   // (vzext (bitcast (vzext (x)) -> (vzext x)
21147   SDValue In = N->getOperand(0);
21148   while (In.getOpcode() == ISD::BITCAST)
21149     In = In.getOperand(0);
21150
21151   if (In.getOpcode() != X86ISD::VZEXT)
21152     return SDValue();
21153
21154   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21155                      In.getOperand(0));
21156 }
21157
21158 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21159                                              DAGCombinerInfo &DCI) const {
21160   SelectionDAG &DAG = DCI.DAG;
21161   switch (N->getOpcode()) {
21162   default: break;
21163   case ISD::EXTRACT_VECTOR_ELT:
21164     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21165   case ISD::VSELECT:
21166   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21167   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21168   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
21169   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
21170   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
21171   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
21172   case ISD::SHL:
21173   case ISD::SRA:
21174   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
21175   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
21176   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
21177   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
21178   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
21179   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
21180   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
21181   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
21182   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
21183   case X86ISD::FXOR:
21184   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
21185   case X86ISD::FMIN:
21186   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
21187   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
21188   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
21189   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
21190   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
21191   case ISD::ANY_EXTEND:
21192   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
21193   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
21194   case ISD::SIGN_EXTEND_INREG:
21195     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21196   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21197   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
21198   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21199   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21200   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
21201   case X86ISD::SHUFP:       // Handle all target specific shuffles
21202   case X86ISD::PALIGNR:
21203   case X86ISD::UNPCKH:
21204   case X86ISD::UNPCKL:
21205   case X86ISD::MOVHLPS:
21206   case X86ISD::MOVLHPS:
21207   case X86ISD::PSHUFD:
21208   case X86ISD::PSHUFHW:
21209   case X86ISD::PSHUFLW:
21210   case X86ISD::MOVSS:
21211   case X86ISD::MOVSD:
21212   case X86ISD::VPERMILP:
21213   case X86ISD::VPERM2X128:
21214   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21215   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
21216   case ISD::INTRINSIC_WO_CHAIN:
21217     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21218   case X86ISD::INSERTPS:
21219     return PerformINSERTPSCombine(N, DAG, Subtarget);
21220   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21221   }
21222
21223   return SDValue();
21224 }
21225
21226 /// isTypeDesirableForOp - Return true if the target has native support for
21227 /// the specified value type and it is 'desirable' to use the type for the
21228 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21229 /// instruction encodings are longer and some i16 instructions are slow.
21230 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21231   if (!isTypeLegal(VT))
21232     return false;
21233   if (VT != MVT::i16)
21234     return true;
21235
21236   switch (Opc) {
21237   default:
21238     return true;
21239   case ISD::LOAD:
21240   case ISD::SIGN_EXTEND:
21241   case ISD::ZERO_EXTEND:
21242   case ISD::ANY_EXTEND:
21243   case ISD::SHL:
21244   case ISD::SRL:
21245   case ISD::SUB:
21246   case ISD::ADD:
21247   case ISD::MUL:
21248   case ISD::AND:
21249   case ISD::OR:
21250   case ISD::XOR:
21251     return false;
21252   }
21253 }
21254
21255 /// IsDesirableToPromoteOp - This method query the target whether it is
21256 /// beneficial for dag combiner to promote the specified node. If true, it
21257 /// should return the desired promotion type by reference.
21258 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21259   EVT VT = Op.getValueType();
21260   if (VT != MVT::i16)
21261     return false;
21262
21263   bool Promote = false;
21264   bool Commute = false;
21265   switch (Op.getOpcode()) {
21266   default: break;
21267   case ISD::LOAD: {
21268     LoadSDNode *LD = cast<LoadSDNode>(Op);
21269     // If the non-extending load has a single use and it's not live out, then it
21270     // might be folded.
21271     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21272                                                      Op.hasOneUse()*/) {
21273       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21274              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21275         // The only case where we'd want to promote LOAD (rather then it being
21276         // promoted as an operand is when it's only use is liveout.
21277         if (UI->getOpcode() != ISD::CopyToReg)
21278           return false;
21279       }
21280     }
21281     Promote = true;
21282     break;
21283   }
21284   case ISD::SIGN_EXTEND:
21285   case ISD::ZERO_EXTEND:
21286   case ISD::ANY_EXTEND:
21287     Promote = true;
21288     break;
21289   case ISD::SHL:
21290   case ISD::SRL: {
21291     SDValue N0 = Op.getOperand(0);
21292     // Look out for (store (shl (load), x)).
21293     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21294       return false;
21295     Promote = true;
21296     break;
21297   }
21298   case ISD::ADD:
21299   case ISD::MUL:
21300   case ISD::AND:
21301   case ISD::OR:
21302   case ISD::XOR:
21303     Commute = true;
21304     // fallthrough
21305   case ISD::SUB: {
21306     SDValue N0 = Op.getOperand(0);
21307     SDValue N1 = Op.getOperand(1);
21308     if (!Commute && MayFoldLoad(N1))
21309       return false;
21310     // Avoid disabling potential load folding opportunities.
21311     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21312       return false;
21313     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21314       return false;
21315     Promote = true;
21316   }
21317   }
21318
21319   PVT = MVT::i32;
21320   return Promote;
21321 }
21322
21323 //===----------------------------------------------------------------------===//
21324 //                           X86 Inline Assembly Support
21325 //===----------------------------------------------------------------------===//
21326
21327 namespace {
21328   // Helper to match a string separated by whitespace.
21329   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21330     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21331
21332     for (unsigned i = 0, e = args.size(); i != e; ++i) {
21333       StringRef piece(*args[i]);
21334       if (!s.startswith(piece)) // Check if the piece matches.
21335         return false;
21336
21337       s = s.substr(piece.size());
21338       StringRef::size_type pos = s.find_first_not_of(" \t");
21339       if (pos == 0) // We matched a prefix.
21340         return false;
21341
21342       s = s.substr(pos);
21343     }
21344
21345     return s.empty();
21346   }
21347   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21348 }
21349
21350 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21351
21352   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21353     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21354         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21355         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21356
21357       if (AsmPieces.size() == 3)
21358         return true;
21359       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21360         return true;
21361     }
21362   }
21363   return false;
21364 }
21365
21366 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21367   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21368
21369   std::string AsmStr = IA->getAsmString();
21370
21371   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21372   if (!Ty || Ty->getBitWidth() % 16 != 0)
21373     return false;
21374
21375   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21376   SmallVector<StringRef, 4> AsmPieces;
21377   SplitString(AsmStr, AsmPieces, ";\n");
21378
21379   switch (AsmPieces.size()) {
21380   default: return false;
21381   case 1:
21382     // FIXME: this should verify that we are targeting a 486 or better.  If not,
21383     // we will turn this bswap into something that will be lowered to logical
21384     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
21385     // lower so don't worry about this.
21386     // bswap $0
21387     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21388         matchAsm(AsmPieces[0], "bswapl", "$0") ||
21389         matchAsm(AsmPieces[0], "bswapq", "$0") ||
21390         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21391         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21392         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21393       // No need to check constraints, nothing other than the equivalent of
21394       // "=r,0" would be valid here.
21395       return IntrinsicLowering::LowerToByteSwap(CI);
21396     }
21397
21398     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
21399     if (CI->getType()->isIntegerTy(16) &&
21400         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21401         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21402          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21403       AsmPieces.clear();
21404       const std::string &ConstraintsStr = IA->getConstraintString();
21405       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21406       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21407       if (clobbersFlagRegisters(AsmPieces))
21408         return IntrinsicLowering::LowerToByteSwap(CI);
21409     }
21410     break;
21411   case 3:
21412     if (CI->getType()->isIntegerTy(32) &&
21413         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21414         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21415         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21416         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21417       AsmPieces.clear();
21418       const std::string &ConstraintsStr = IA->getConstraintString();
21419       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21420       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21421       if (clobbersFlagRegisters(AsmPieces))
21422         return IntrinsicLowering::LowerToByteSwap(CI);
21423     }
21424
21425     if (CI->getType()->isIntegerTy(64)) {
21426       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21427       if (Constraints.size() >= 2 &&
21428           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21429           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21430         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
21431         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21432             matchAsm(AsmPieces[1], "bswap", "%edx") &&
21433             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21434           return IntrinsicLowering::LowerToByteSwap(CI);
21435       }
21436     }
21437     break;
21438   }
21439   return false;
21440 }
21441
21442 /// getConstraintType - Given a constraint letter, return the type of
21443 /// constraint it is for this target.
21444 X86TargetLowering::ConstraintType
21445 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21446   if (Constraint.size() == 1) {
21447     switch (Constraint[0]) {
21448     case 'R':
21449     case 'q':
21450     case 'Q':
21451     case 'f':
21452     case 't':
21453     case 'u':
21454     case 'y':
21455     case 'x':
21456     case 'Y':
21457     case 'l':
21458       return C_RegisterClass;
21459     case 'a':
21460     case 'b':
21461     case 'c':
21462     case 'd':
21463     case 'S':
21464     case 'D':
21465     case 'A':
21466       return C_Register;
21467     case 'I':
21468     case 'J':
21469     case 'K':
21470     case 'L':
21471     case 'M':
21472     case 'N':
21473     case 'G':
21474     case 'C':
21475     case 'e':
21476     case 'Z':
21477       return C_Other;
21478     default:
21479       break;
21480     }
21481   }
21482   return TargetLowering::getConstraintType(Constraint);
21483 }
21484
21485 /// Examine constraint type and operand type and determine a weight value.
21486 /// This object must already have been set up with the operand type
21487 /// and the current alternative constraint selected.
21488 TargetLowering::ConstraintWeight
21489   X86TargetLowering::getSingleConstraintMatchWeight(
21490     AsmOperandInfo &info, const char *constraint) const {
21491   ConstraintWeight weight = CW_Invalid;
21492   Value *CallOperandVal = info.CallOperandVal;
21493     // If we don't have a value, we can't do a match,
21494     // but allow it at the lowest weight.
21495   if (!CallOperandVal)
21496     return CW_Default;
21497   Type *type = CallOperandVal->getType();
21498   // Look at the constraint type.
21499   switch (*constraint) {
21500   default:
21501     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21502   case 'R':
21503   case 'q':
21504   case 'Q':
21505   case 'a':
21506   case 'b':
21507   case 'c':
21508   case 'd':
21509   case 'S':
21510   case 'D':
21511   case 'A':
21512     if (CallOperandVal->getType()->isIntegerTy())
21513       weight = CW_SpecificReg;
21514     break;
21515   case 'f':
21516   case 't':
21517   case 'u':
21518     if (type->isFloatingPointTy())
21519       weight = CW_SpecificReg;
21520     break;
21521   case 'y':
21522     if (type->isX86_MMXTy() && Subtarget->hasMMX())
21523       weight = CW_SpecificReg;
21524     break;
21525   case 'x':
21526   case 'Y':
21527     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21528         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21529       weight = CW_Register;
21530     break;
21531   case 'I':
21532     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21533       if (C->getZExtValue() <= 31)
21534         weight = CW_Constant;
21535     }
21536     break;
21537   case 'J':
21538     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21539       if (C->getZExtValue() <= 63)
21540         weight = CW_Constant;
21541     }
21542     break;
21543   case 'K':
21544     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21545       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21546         weight = CW_Constant;
21547     }
21548     break;
21549   case 'L':
21550     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21551       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21552         weight = CW_Constant;
21553     }
21554     break;
21555   case 'M':
21556     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21557       if (C->getZExtValue() <= 3)
21558         weight = CW_Constant;
21559     }
21560     break;
21561   case 'N':
21562     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21563       if (C->getZExtValue() <= 0xff)
21564         weight = CW_Constant;
21565     }
21566     break;
21567   case 'G':
21568   case 'C':
21569     if (dyn_cast<ConstantFP>(CallOperandVal)) {
21570       weight = CW_Constant;
21571     }
21572     break;
21573   case 'e':
21574     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21575       if ((C->getSExtValue() >= -0x80000000LL) &&
21576           (C->getSExtValue() <= 0x7fffffffLL))
21577         weight = CW_Constant;
21578     }
21579     break;
21580   case 'Z':
21581     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21582       if (C->getZExtValue() <= 0xffffffff)
21583         weight = CW_Constant;
21584     }
21585     break;
21586   }
21587   return weight;
21588 }
21589
21590 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21591 /// with another that has more specific requirements based on the type of the
21592 /// corresponding operand.
21593 const char *X86TargetLowering::
21594 LowerXConstraint(EVT ConstraintVT) const {
21595   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21596   // 'f' like normal targets.
21597   if (ConstraintVT.isFloatingPoint()) {
21598     if (Subtarget->hasSSE2())
21599       return "Y";
21600     if (Subtarget->hasSSE1())
21601       return "x";
21602   }
21603
21604   return TargetLowering::LowerXConstraint(ConstraintVT);
21605 }
21606
21607 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21608 /// vector.  If it is invalid, don't add anything to Ops.
21609 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21610                                                      std::string &Constraint,
21611                                                      std::vector<SDValue>&Ops,
21612                                                      SelectionDAG &DAG) const {
21613   SDValue Result;
21614
21615   // Only support length 1 constraints for now.
21616   if (Constraint.length() > 1) return;
21617
21618   char ConstraintLetter = Constraint[0];
21619   switch (ConstraintLetter) {
21620   default: break;
21621   case 'I':
21622     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21623       if (C->getZExtValue() <= 31) {
21624         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21625         break;
21626       }
21627     }
21628     return;
21629   case 'J':
21630     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21631       if (C->getZExtValue() <= 63) {
21632         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21633         break;
21634       }
21635     }
21636     return;
21637   case 'K':
21638     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21639       if (isInt<8>(C->getSExtValue())) {
21640         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21641         break;
21642       }
21643     }
21644     return;
21645   case 'N':
21646     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21647       if (C->getZExtValue() <= 255) {
21648         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21649         break;
21650       }
21651     }
21652     return;
21653   case 'e': {
21654     // 32-bit signed value
21655     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21656       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21657                                            C->getSExtValue())) {
21658         // Widen to 64 bits here to get it sign extended.
21659         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21660         break;
21661       }
21662     // FIXME gcc accepts some relocatable values here too, but only in certain
21663     // memory models; it's complicated.
21664     }
21665     return;
21666   }
21667   case 'Z': {
21668     // 32-bit unsigned value
21669     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21670       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21671                                            C->getZExtValue())) {
21672         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21673         break;
21674       }
21675     }
21676     // FIXME gcc accepts some relocatable values here too, but only in certain
21677     // memory models; it's complicated.
21678     return;
21679   }
21680   case 'i': {
21681     // Literal immediates are always ok.
21682     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21683       // Widen to 64 bits here to get it sign extended.
21684       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21685       break;
21686     }
21687
21688     // In any sort of PIC mode addresses need to be computed at runtime by
21689     // adding in a register or some sort of table lookup.  These can't
21690     // be used as immediates.
21691     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21692       return;
21693
21694     // If we are in non-pic codegen mode, we allow the address of a global (with
21695     // an optional displacement) to be used with 'i'.
21696     GlobalAddressSDNode *GA = nullptr;
21697     int64_t Offset = 0;
21698
21699     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21700     while (1) {
21701       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21702         Offset += GA->getOffset();
21703         break;
21704       } else if (Op.getOpcode() == ISD::ADD) {
21705         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21706           Offset += C->getZExtValue();
21707           Op = Op.getOperand(0);
21708           continue;
21709         }
21710       } else if (Op.getOpcode() == ISD::SUB) {
21711         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21712           Offset += -C->getZExtValue();
21713           Op = Op.getOperand(0);
21714           continue;
21715         }
21716       }
21717
21718       // Otherwise, this isn't something we can handle, reject it.
21719       return;
21720     }
21721
21722     const GlobalValue *GV = GA->getGlobal();
21723     // If we require an extra load to get this address, as in PIC mode, we
21724     // can't accept it.
21725     if (isGlobalStubReference(
21726             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21727       return;
21728
21729     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21730                                         GA->getValueType(0), Offset);
21731     break;
21732   }
21733   }
21734
21735   if (Result.getNode()) {
21736     Ops.push_back(Result);
21737     return;
21738   }
21739   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21740 }
21741
21742 std::pair<unsigned, const TargetRegisterClass*>
21743 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21744                                                 MVT VT) const {
21745   // First, see if this is a constraint that directly corresponds to an LLVM
21746   // register class.
21747   if (Constraint.size() == 1) {
21748     // GCC Constraint Letters
21749     switch (Constraint[0]) {
21750     default: break;
21751       // TODO: Slight differences here in allocation order and leaving
21752       // RIP in the class. Do they matter any more here than they do
21753       // in the normal allocation?
21754     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21755       if (Subtarget->is64Bit()) {
21756         if (VT == MVT::i32 || VT == MVT::f32)
21757           return std::make_pair(0U, &X86::GR32RegClass);
21758         if (VT == MVT::i16)
21759           return std::make_pair(0U, &X86::GR16RegClass);
21760         if (VT == MVT::i8 || VT == MVT::i1)
21761           return std::make_pair(0U, &X86::GR8RegClass);
21762         if (VT == MVT::i64 || VT == MVT::f64)
21763           return std::make_pair(0U, &X86::GR64RegClass);
21764         break;
21765       }
21766       // 32-bit fallthrough
21767     case 'Q':   // Q_REGS
21768       if (VT == MVT::i32 || VT == MVT::f32)
21769         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21770       if (VT == MVT::i16)
21771         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21772       if (VT == MVT::i8 || VT == MVT::i1)
21773         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21774       if (VT == MVT::i64)
21775         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21776       break;
21777     case 'r':   // GENERAL_REGS
21778     case 'l':   // INDEX_REGS
21779       if (VT == MVT::i8 || VT == MVT::i1)
21780         return std::make_pair(0U, &X86::GR8RegClass);
21781       if (VT == MVT::i16)
21782         return std::make_pair(0U, &X86::GR16RegClass);
21783       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21784         return std::make_pair(0U, &X86::GR32RegClass);
21785       return std::make_pair(0U, &X86::GR64RegClass);
21786     case 'R':   // LEGACY_REGS
21787       if (VT == MVT::i8 || VT == MVT::i1)
21788         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21789       if (VT == MVT::i16)
21790         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21791       if (VT == MVT::i32 || !Subtarget->is64Bit())
21792         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21793       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21794     case 'f':  // FP Stack registers.
21795       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21796       // value to the correct fpstack register class.
21797       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21798         return std::make_pair(0U, &X86::RFP32RegClass);
21799       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21800         return std::make_pair(0U, &X86::RFP64RegClass);
21801       return std::make_pair(0U, &X86::RFP80RegClass);
21802     case 'y':   // MMX_REGS if MMX allowed.
21803       if (!Subtarget->hasMMX()) break;
21804       return std::make_pair(0U, &X86::VR64RegClass);
21805     case 'Y':   // SSE_REGS if SSE2 allowed
21806       if (!Subtarget->hasSSE2()) break;
21807       // FALL THROUGH.
21808     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21809       if (!Subtarget->hasSSE1()) break;
21810
21811       switch (VT.SimpleTy) {
21812       default: break;
21813       // Scalar SSE types.
21814       case MVT::f32:
21815       case MVT::i32:
21816         return std::make_pair(0U, &X86::FR32RegClass);
21817       case MVT::f64:
21818       case MVT::i64:
21819         return std::make_pair(0U, &X86::FR64RegClass);
21820       // Vector types.
21821       case MVT::v16i8:
21822       case MVT::v8i16:
21823       case MVT::v4i32:
21824       case MVT::v2i64:
21825       case MVT::v4f32:
21826       case MVT::v2f64:
21827         return std::make_pair(0U, &X86::VR128RegClass);
21828       // AVX types.
21829       case MVT::v32i8:
21830       case MVT::v16i16:
21831       case MVT::v8i32:
21832       case MVT::v4i64:
21833       case MVT::v8f32:
21834       case MVT::v4f64:
21835         return std::make_pair(0U, &X86::VR256RegClass);
21836       case MVT::v8f64:
21837       case MVT::v16f32:
21838       case MVT::v16i32:
21839       case MVT::v8i64:
21840         return std::make_pair(0U, &X86::VR512RegClass);
21841       }
21842       break;
21843     }
21844   }
21845
21846   // Use the default implementation in TargetLowering to convert the register
21847   // constraint into a member of a register class.
21848   std::pair<unsigned, const TargetRegisterClass*> Res;
21849   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21850
21851   // Not found as a standard register?
21852   if (!Res.second) {
21853     // Map st(0) -> st(7) -> ST0
21854     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21855         tolower(Constraint[1]) == 's' &&
21856         tolower(Constraint[2]) == 't' &&
21857         Constraint[3] == '(' &&
21858         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21859         Constraint[5] == ')' &&
21860         Constraint[6] == '}') {
21861
21862       Res.first = X86::ST0+Constraint[4]-'0';
21863       Res.second = &X86::RFP80RegClass;
21864       return Res;
21865     }
21866
21867     // GCC allows "st(0)" to be called just plain "st".
21868     if (StringRef("{st}").equals_lower(Constraint)) {
21869       Res.first = X86::ST0;
21870       Res.second = &X86::RFP80RegClass;
21871       return Res;
21872     }
21873
21874     // flags -> EFLAGS
21875     if (StringRef("{flags}").equals_lower(Constraint)) {
21876       Res.first = X86::EFLAGS;
21877       Res.second = &X86::CCRRegClass;
21878       return Res;
21879     }
21880
21881     // 'A' means EAX + EDX.
21882     if (Constraint == "A") {
21883       Res.first = X86::EAX;
21884       Res.second = &X86::GR32_ADRegClass;
21885       return Res;
21886     }
21887     return Res;
21888   }
21889
21890   // Otherwise, check to see if this is a register class of the wrong value
21891   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21892   // turn into {ax},{dx}.
21893   if (Res.second->hasType(VT))
21894     return Res;   // Correct type already, nothing to do.
21895
21896   // All of the single-register GCC register classes map their values onto
21897   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21898   // really want an 8-bit or 32-bit register, map to the appropriate register
21899   // class and return the appropriate register.
21900   if (Res.second == &X86::GR16RegClass) {
21901     if (VT == MVT::i8 || VT == MVT::i1) {
21902       unsigned DestReg = 0;
21903       switch (Res.first) {
21904       default: break;
21905       case X86::AX: DestReg = X86::AL; break;
21906       case X86::DX: DestReg = X86::DL; break;
21907       case X86::CX: DestReg = X86::CL; break;
21908       case X86::BX: DestReg = X86::BL; break;
21909       }
21910       if (DestReg) {
21911         Res.first = DestReg;
21912         Res.second = &X86::GR8RegClass;
21913       }
21914     } else if (VT == MVT::i32 || VT == MVT::f32) {
21915       unsigned DestReg = 0;
21916       switch (Res.first) {
21917       default: break;
21918       case X86::AX: DestReg = X86::EAX; break;
21919       case X86::DX: DestReg = X86::EDX; break;
21920       case X86::CX: DestReg = X86::ECX; break;
21921       case X86::BX: DestReg = X86::EBX; break;
21922       case X86::SI: DestReg = X86::ESI; break;
21923       case X86::DI: DestReg = X86::EDI; break;
21924       case X86::BP: DestReg = X86::EBP; break;
21925       case X86::SP: DestReg = X86::ESP; break;
21926       }
21927       if (DestReg) {
21928         Res.first = DestReg;
21929         Res.second = &X86::GR32RegClass;
21930       }
21931     } else if (VT == MVT::i64 || VT == MVT::f64) {
21932       unsigned DestReg = 0;
21933       switch (Res.first) {
21934       default: break;
21935       case X86::AX: DestReg = X86::RAX; break;
21936       case X86::DX: DestReg = X86::RDX; break;
21937       case X86::CX: DestReg = X86::RCX; break;
21938       case X86::BX: DestReg = X86::RBX; break;
21939       case X86::SI: DestReg = X86::RSI; break;
21940       case X86::DI: DestReg = X86::RDI; break;
21941       case X86::BP: DestReg = X86::RBP; break;
21942       case X86::SP: DestReg = X86::RSP; break;
21943       }
21944       if (DestReg) {
21945         Res.first = DestReg;
21946         Res.second = &X86::GR64RegClass;
21947       }
21948     }
21949   } else if (Res.second == &X86::FR32RegClass ||
21950              Res.second == &X86::FR64RegClass ||
21951              Res.second == &X86::VR128RegClass ||
21952              Res.second == &X86::VR256RegClass ||
21953              Res.second == &X86::FR32XRegClass ||
21954              Res.second == &X86::FR64XRegClass ||
21955              Res.second == &X86::VR128XRegClass ||
21956              Res.second == &X86::VR256XRegClass ||
21957              Res.second == &X86::VR512RegClass) {
21958     // Handle references to XMM physical registers that got mapped into the
21959     // wrong class.  This can happen with constraints like {xmm0} where the
21960     // target independent register mapper will just pick the first match it can
21961     // find, ignoring the required type.
21962
21963     if (VT == MVT::f32 || VT == MVT::i32)
21964       Res.second = &X86::FR32RegClass;
21965     else if (VT == MVT::f64 || VT == MVT::i64)
21966       Res.second = &X86::FR64RegClass;
21967     else if (X86::VR128RegClass.hasType(VT))
21968       Res.second = &X86::VR128RegClass;
21969     else if (X86::VR256RegClass.hasType(VT))
21970       Res.second = &X86::VR256RegClass;
21971     else if (X86::VR512RegClass.hasType(VT))
21972       Res.second = &X86::VR512RegClass;
21973   }
21974
21975   return Res;
21976 }
21977
21978 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21979                                             Type *Ty) const {
21980   // Scaling factors are not free at all.
21981   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21982   // will take 2 allocations in the out of order engine instead of 1
21983   // for plain addressing mode, i.e. inst (reg1).
21984   // E.g.,
21985   // vaddps (%rsi,%drx), %ymm0, %ymm1
21986   // Requires two allocations (one for the load, one for the computation)
21987   // whereas:
21988   // vaddps (%rsi), %ymm0, %ymm1
21989   // Requires just 1 allocation, i.e., freeing allocations for other operations
21990   // and having less micro operations to execute.
21991   //
21992   // For some X86 architectures, this is even worse because for instance for
21993   // stores, the complex addressing mode forces the instruction to use the
21994   // "load" ports instead of the dedicated "store" port.
21995   // E.g., on Haswell:
21996   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21997   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21998   if (isLegalAddressingMode(AM, Ty))
21999     // Scale represents reg2 * scale, thus account for 1
22000     // as soon as we use a second register.
22001     return AM.Scale != 0;
22002   return -1;
22003 }
22004
22005 bool X86TargetLowering::isTargetFTOL() const {
22006   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
22007 }