a7b6e707816fdffbb95ad08ce0dc7c434bcf8a99
[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() &&
609       !Subtarget->isTargetELF() &&
610       !Subtarget->isTargetCygMing()) {
611     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
612   }
613
614   if (Subtarget->is64Bit()) {
615     setExceptionPointerRegister(X86::RAX);
616     setExceptionSelectorRegister(X86::RDX);
617   } else {
618     setExceptionPointerRegister(X86::EAX);
619     setExceptionSelectorRegister(X86::EDX);
620   }
621   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
622   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
623
624   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
625   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
626
627   setOperationAction(ISD::TRAP, MVT::Other, Legal);
628   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
629
630   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
631   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
632   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
633   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
634     // TargetInfo::X86_64ABIBuiltinVaList
635     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
636     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
637   } else {
638     // TargetInfo::CharPtrBuiltinVaList
639     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
640     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
641   }
642
643   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
644   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
645
646   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
647                      MVT::i64 : MVT::i32, Custom);
648
649   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
650     // f32 and f64 use SSE.
651     // Set up the FP register classes.
652     addRegisterClass(MVT::f32, &X86::FR32RegClass);
653     addRegisterClass(MVT::f64, &X86::FR64RegClass);
654
655     // Use ANDPD to simulate FABS.
656     setOperationAction(ISD::FABS , MVT::f64, Custom);
657     setOperationAction(ISD::FABS , MVT::f32, Custom);
658
659     // Use XORP to simulate FNEG.
660     setOperationAction(ISD::FNEG , MVT::f64, Custom);
661     setOperationAction(ISD::FNEG , MVT::f32, Custom);
662
663     // Use ANDPD and ORPD to simulate FCOPYSIGN.
664     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
665     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
666
667     // Lower this to FGETSIGNx86 plus an AND.
668     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
669     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
670
671     // We don't support sin/cos/fmod
672     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
673     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
674     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
675     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
676     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
677     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
678
679     // Expand FP immediates into loads from the stack, except for the special
680     // cases we handle.
681     addLegalFPImmediate(APFloat(+0.0)); // xorpd
682     addLegalFPImmediate(APFloat(+0.0f)); // xorps
683   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
684     // Use SSE for f32, x87 for f64.
685     // Set up the FP register classes.
686     addRegisterClass(MVT::f32, &X86::FR32RegClass);
687     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
688
689     // Use ANDPS to simulate FABS.
690     setOperationAction(ISD::FABS , MVT::f32, Custom);
691
692     // Use XORP to simulate FNEG.
693     setOperationAction(ISD::FNEG , MVT::f32, Custom);
694
695     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
696
697     // Use ANDPS and ORPS to simulate FCOPYSIGN.
698     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
699     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
700
701     // We don't support sin/cos/fmod
702     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
703     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
704     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
705
706     // Special cases we handle for FP constants.
707     addLegalFPImmediate(APFloat(+0.0f)); // xorps
708     addLegalFPImmediate(APFloat(+0.0)); // FLD0
709     addLegalFPImmediate(APFloat(+1.0)); // FLD1
710     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
711     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
712
713     if (!TM.Options.UnsafeFPMath) {
714       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
715       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
716       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
717     }
718   } else if (!TM.Options.UseSoftFloat) {
719     // f32 and f64 in x87.
720     // Set up the FP register classes.
721     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
722     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
723
724     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
725     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
726     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
727     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
728
729     if (!TM.Options.UnsafeFPMath) {
730       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
731       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
732       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
733       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
734       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
735       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
736     }
737     addLegalFPImmediate(APFloat(+0.0)); // FLD0
738     addLegalFPImmediate(APFloat(+1.0)); // FLD1
739     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
740     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
741     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
742     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
743     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
744     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
745   }
746
747   // We don't support FMA.
748   setOperationAction(ISD::FMA, MVT::f64, Expand);
749   setOperationAction(ISD::FMA, MVT::f32, Expand);
750
751   // Long double always uses X87.
752   if (!TM.Options.UseSoftFloat) {
753     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
754     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
755     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
756     {
757       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
758       addLegalFPImmediate(TmpFlt);  // FLD0
759       TmpFlt.changeSign();
760       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
761
762       bool ignored;
763       APFloat TmpFlt2(+1.0);
764       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
765                       &ignored);
766       addLegalFPImmediate(TmpFlt2);  // FLD1
767       TmpFlt2.changeSign();
768       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
769     }
770
771     if (!TM.Options.UnsafeFPMath) {
772       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
773       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
774       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
775     }
776
777     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
778     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
779     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
780     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
781     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
782     setOperationAction(ISD::FMA, MVT::f80, Expand);
783   }
784
785   // Always use a library call for pow.
786   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
787   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
788   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
789
790   setOperationAction(ISD::FLOG, MVT::f80, Expand);
791   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
792   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
793   setOperationAction(ISD::FEXP, MVT::f80, Expand);
794   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
795
796   // First set operation action for all vector types to either promote
797   // (for widening) or expand (for scalarization). Then we will selectively
798   // turn on ones that can be effectively codegen'd.
799   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
800            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
801     MVT VT = (MVT::SimpleValueType)i;
802     setOperationAction(ISD::ADD , VT, Expand);
803     setOperationAction(ISD::SUB , VT, Expand);
804     setOperationAction(ISD::FADD, VT, Expand);
805     setOperationAction(ISD::FNEG, VT, Expand);
806     setOperationAction(ISD::FSUB, VT, Expand);
807     setOperationAction(ISD::MUL , VT, Expand);
808     setOperationAction(ISD::FMUL, VT, Expand);
809     setOperationAction(ISD::SDIV, VT, Expand);
810     setOperationAction(ISD::UDIV, VT, Expand);
811     setOperationAction(ISD::FDIV, VT, Expand);
812     setOperationAction(ISD::SREM, VT, Expand);
813     setOperationAction(ISD::UREM, VT, Expand);
814     setOperationAction(ISD::LOAD, VT, Expand);
815     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
816     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
817     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
818     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
819     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
820     setOperationAction(ISD::FABS, VT, Expand);
821     setOperationAction(ISD::FSIN, VT, Expand);
822     setOperationAction(ISD::FSINCOS, VT, Expand);
823     setOperationAction(ISD::FCOS, VT, Expand);
824     setOperationAction(ISD::FSINCOS, VT, Expand);
825     setOperationAction(ISD::FREM, VT, Expand);
826     setOperationAction(ISD::FMA,  VT, Expand);
827     setOperationAction(ISD::FPOWI, VT, Expand);
828     setOperationAction(ISD::FSQRT, VT, Expand);
829     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
830     setOperationAction(ISD::FFLOOR, VT, Expand);
831     setOperationAction(ISD::FCEIL, VT, Expand);
832     setOperationAction(ISD::FTRUNC, VT, Expand);
833     setOperationAction(ISD::FRINT, VT, Expand);
834     setOperationAction(ISD::FNEARBYINT, VT, Expand);
835     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
836     setOperationAction(ISD::MULHS, VT, Expand);
837     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
838     setOperationAction(ISD::MULHU, VT, Expand);
839     setOperationAction(ISD::SDIVREM, VT, Expand);
840     setOperationAction(ISD::UDIVREM, VT, Expand);
841     setOperationAction(ISD::FPOW, VT, Expand);
842     setOperationAction(ISD::CTPOP, VT, Expand);
843     setOperationAction(ISD::CTTZ, VT, Expand);
844     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
845     setOperationAction(ISD::CTLZ, VT, Expand);
846     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
847     setOperationAction(ISD::SHL, VT, Expand);
848     setOperationAction(ISD::SRA, VT, Expand);
849     setOperationAction(ISD::SRL, VT, Expand);
850     setOperationAction(ISD::ROTL, VT, Expand);
851     setOperationAction(ISD::ROTR, VT, Expand);
852     setOperationAction(ISD::BSWAP, VT, Expand);
853     setOperationAction(ISD::SETCC, VT, Expand);
854     setOperationAction(ISD::FLOG, VT, Expand);
855     setOperationAction(ISD::FLOG2, VT, Expand);
856     setOperationAction(ISD::FLOG10, VT, Expand);
857     setOperationAction(ISD::FEXP, VT, Expand);
858     setOperationAction(ISD::FEXP2, VT, Expand);
859     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
860     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
861     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
862     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
863     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
864     setOperationAction(ISD::TRUNCATE, VT, Expand);
865     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
866     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
867     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
868     setOperationAction(ISD::VSELECT, VT, Expand);
869     setOperationAction(ISD::SELECT_CC, VT, Expand);
870     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
871              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
872       setTruncStoreAction(VT,
873                           (MVT::SimpleValueType)InnerVT, Expand);
874     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
875     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
876     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
877   }
878
879   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
880   // with -msoft-float, disable use of MMX as well.
881   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
882     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
883     // No operations on x86mmx supported, everything uses intrinsics.
884   }
885
886   // MMX-sized vectors (other than x86mmx) are expected to be expanded
887   // into smaller operations.
888   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
889   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
890   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
891   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
892   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
893   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
894   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
895   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
896   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
897   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
898   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
899   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
900   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
901   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
902   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
903   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
904   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
905   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
906   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
907   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
908   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
909   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
910   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
911   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
912   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
913   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
914   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
915   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
916   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
917
918   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
919     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
920
921     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
922     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
923     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
924     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
925     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
926     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
927     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
928     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
929     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
930     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
931     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
932     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
933   }
934
935   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
936     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
937
938     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
939     // registers cannot be used even for integer operations.
940     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
941     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
942     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
943     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
944
945     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
946     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
947     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
948     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
949     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
950     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
951     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
952     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
953     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
954     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
955     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
956     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
957     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
958     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
959     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
960     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
961     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
962     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
963     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
964     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
965     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
966     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
967
968     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
969     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
970     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
971     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
972
973     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
974     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
975     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
976     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
977     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
978
979     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
980     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
981       MVT VT = (MVT::SimpleValueType)i;
982       // Do not attempt to custom lower non-power-of-2 vectors
983       if (!isPowerOf2_32(VT.getVectorNumElements()))
984         continue;
985       // Do not attempt to custom lower non-128-bit vectors
986       if (!VT.is128BitVector())
987         continue;
988       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
989       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
990       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
991     }
992
993     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
994     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
995     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
996     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
998     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
999
1000     if (Subtarget->is64Bit()) {
1001       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1002       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1003     }
1004
1005     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
1006     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
1007       MVT VT = (MVT::SimpleValueType)i;
1008
1009       // Do not attempt to promote non-128-bit vectors
1010       if (!VT.is128BitVector())
1011         continue;
1012
1013       setOperationAction(ISD::AND,    VT, Promote);
1014       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1015       setOperationAction(ISD::OR,     VT, Promote);
1016       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1017       setOperationAction(ISD::XOR,    VT, Promote);
1018       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1019       setOperationAction(ISD::LOAD,   VT, Promote);
1020       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1021       setOperationAction(ISD::SELECT, VT, Promote);
1022       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1023     }
1024
1025     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1026
1027     // Custom lower v2i64 and v2f64 selects.
1028     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1029     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1030     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1031     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1032
1033     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1034     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1035
1036     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1037     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1038     // As there is no 64-bit GPR available, we need build a special custom
1039     // sequence to convert from v2i32 to v2f32.
1040     if (!Subtarget->is64Bit())
1041       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1042
1043     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1044     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1045
1046     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1047
1048     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1049     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1050     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1051   }
1052
1053   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1054     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1055     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1056     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1057     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1058     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1059     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1060     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1061     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1062     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1063     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1064
1065     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1066     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1067     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1068     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1069     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1070     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1071     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1072     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1073     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1074     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1075
1076     // FIXME: Do we need to handle scalar-to-vector here?
1077     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1078
1079     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1080     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1081     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1082     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1083     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1084     // There is no BLENDI for byte vectors. We don't need to custom lower
1085     // some vselects for now.
1086     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1087
1088     // i8 and i16 vectors are custom , because the source register and source
1089     // source memory operand types are not the same width.  f32 vectors are
1090     // custom since the immediate controlling the insert encodes additional
1091     // information.
1092     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1093     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1094     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1095     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1096
1097     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1098     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1099     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1100     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1101
1102     // FIXME: these should be Legal but thats only for the case where
1103     // the index is constant.  For now custom expand to deal with that.
1104     if (Subtarget->is64Bit()) {
1105       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1106       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1107     }
1108   }
1109
1110   if (Subtarget->hasSSE2()) {
1111     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1112     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1113
1114     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1115     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1116
1117     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1118     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1119
1120     // In the customized shift lowering, the legal cases in AVX2 will be
1121     // recognized.
1122     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1123     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1124
1125     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1126     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1127
1128     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1129   }
1130
1131   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1132     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1133     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1134     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1135     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1136     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1137     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1138
1139     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1140     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1141     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1142
1143     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1144     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1145     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1146     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1147     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1148     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1149     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1150     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1151     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1152     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1153     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1154     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1155
1156     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1157     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1158     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1159     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1160     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1161     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1162     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1163     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1164     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1165     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1166     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1167     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1168
1169     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1170     // even though v8i16 is a legal type.
1171     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1172     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1173     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1174
1175     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1176     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1177     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1178
1179     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1180     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1181
1182     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1183
1184     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1185     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1186
1187     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1188     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1189
1190     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1191     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1192
1193     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1194     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1195     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1196     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1197
1198     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1199     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1200     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1201
1202     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1203     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1204     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1205     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1206
1207     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1208     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1209     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1210     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1211     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1212     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1213     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1214     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1215     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1216     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1217     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1218     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1219
1220     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1221       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1222       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1223       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1224       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1225       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1226       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1227     }
1228
1229     if (Subtarget->hasInt256()) {
1230       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1231       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1232       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1233       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1234
1235       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1236       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1237       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1238       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1239
1240       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1241       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1242       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1243       // Don't lower v32i8 because there is no 128-bit byte mul
1244
1245       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1246       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1247       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1248       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1249
1250       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1251       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1252     } else {
1253       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1254       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1255       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1256       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1257
1258       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1259       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1260       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1261       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1262
1263       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1264       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1265       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1266       // Don't lower v32i8 because there is no 128-bit byte mul
1267     }
1268
1269     // In the customized shift lowering, the legal cases in AVX2 will be
1270     // recognized.
1271     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1272     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1273
1274     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1275     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1276
1277     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1278
1279     // Custom lower several nodes for 256-bit types.
1280     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1281              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1282       MVT VT = (MVT::SimpleValueType)i;
1283
1284       // Extract subvector is special because the value type
1285       // (result) is 128-bit but the source is 256-bit wide.
1286       if (VT.is128BitVector())
1287         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1288
1289       // Do not attempt to custom lower other non-256-bit vectors
1290       if (!VT.is256BitVector())
1291         continue;
1292
1293       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1294       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1295       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1296       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1297       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1298       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1299       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1300     }
1301
1302     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1303     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1304       MVT VT = (MVT::SimpleValueType)i;
1305
1306       // Do not attempt to promote non-256-bit vectors
1307       if (!VT.is256BitVector())
1308         continue;
1309
1310       setOperationAction(ISD::AND,    VT, Promote);
1311       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1312       setOperationAction(ISD::OR,     VT, Promote);
1313       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1314       setOperationAction(ISD::XOR,    VT, Promote);
1315       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1316       setOperationAction(ISD::LOAD,   VT, Promote);
1317       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1318       setOperationAction(ISD::SELECT, VT, Promote);
1319       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1320     }
1321   }
1322
1323   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1324     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1325     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1326     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1327     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1328
1329     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1330     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1331     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1332
1333     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1334     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1335     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1336     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1337     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1338     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1339     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1341     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1342     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1343     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1344
1345     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1346     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1347     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1348     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1349     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1350     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1351
1352     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1353     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1354     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1355     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1356     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1357     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1358     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1359     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1360
1361     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1362     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1363     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1364     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1365     if (Subtarget->is64Bit()) {
1366       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1367       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1368       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1369       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1370     }
1371     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1372     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1373     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1374     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1375     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1376     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1377     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1378     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1379     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1380     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1381
1382     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1383     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1386     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1387     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1388     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1389     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1390     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1391     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1392     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1393     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1394     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1395
1396     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1397     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1398     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1399     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1400     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1401     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1402
1403     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1404     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1405
1406     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1407
1408     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1409     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1410     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1411     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1412     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1413     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1414     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1415     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1416     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1417
1418     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1419     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1420
1421     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1422     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1423
1424     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1425
1426     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1427     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1428
1429     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1430     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1431
1432     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1433     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1434
1435     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1436     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1437     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1438     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1439     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1440     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1441
1442     if (Subtarget->hasCDI()) {
1443       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1444       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1445     }
1446
1447     // Custom lower several nodes.
1448     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1449              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1450       MVT VT = (MVT::SimpleValueType)i;
1451
1452       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453       // Extract subvector is special because the value type
1454       // (result) is 256/128-bit but the source is 512-bit wide.
1455       if (VT.is128BitVector() || VT.is256BitVector())
1456         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1457
1458       if (VT.getVectorElementType() == MVT::i1)
1459         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1460
1461       // Do not attempt to custom lower other non-512-bit vectors
1462       if (!VT.is512BitVector())
1463         continue;
1464
1465       if ( EltSize >= 32) {
1466         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1467         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1468         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1469         setOperationAction(ISD::VSELECT,             VT, Legal);
1470         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1471         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1472         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1473       }
1474     }
1475     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1476       MVT VT = (MVT::SimpleValueType)i;
1477
1478       // Do not attempt to promote non-256-bit vectors
1479       if (!VT.is512BitVector())
1480         continue;
1481
1482       setOperationAction(ISD::SELECT, VT, Promote);
1483       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1484     }
1485   }// has  AVX-512
1486
1487   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1488   // of this type with custom code.
1489   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1490            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1491     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1492                        Custom);
1493   }
1494
1495   // We want to custom lower some of our intrinsics.
1496   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1497   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1498   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1499   if (!Subtarget->is64Bit())
1500     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1501
1502   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1503   // handle type legalization for these operations here.
1504   //
1505   // FIXME: We really should do custom legalization for addition and
1506   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1507   // than generic legalization for 64-bit multiplication-with-overflow, though.
1508   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1509     // Add/Sub/Mul with overflow operations are custom lowered.
1510     MVT VT = IntVTs[i];
1511     setOperationAction(ISD::SADDO, VT, Custom);
1512     setOperationAction(ISD::UADDO, VT, Custom);
1513     setOperationAction(ISD::SSUBO, VT, Custom);
1514     setOperationAction(ISD::USUBO, VT, Custom);
1515     setOperationAction(ISD::SMULO, VT, Custom);
1516     setOperationAction(ISD::UMULO, VT, Custom);
1517   }
1518
1519   // There are no 8-bit 3-address imul/mul instructions
1520   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1521   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1522
1523   if (!Subtarget->is64Bit()) {
1524     // These libcalls are not available in 32-bit.
1525     setLibcallName(RTLIB::SHL_I128, nullptr);
1526     setLibcallName(RTLIB::SRL_I128, nullptr);
1527     setLibcallName(RTLIB::SRA_I128, nullptr);
1528   }
1529
1530   // Combine sin / cos into one node or libcall if possible.
1531   if (Subtarget->hasSinCos()) {
1532     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1533     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1534     if (Subtarget->isTargetDarwin()) {
1535       // For MacOSX, we don't want to the normal expansion of a libcall to
1536       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1537       // traffic.
1538       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1539       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1540     }
1541   }
1542
1543   if (Subtarget->isTargetWin64()) {
1544     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1545     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1546     setOperationAction(ISD::SREM, MVT::i128, Custom);
1547     setOperationAction(ISD::UREM, MVT::i128, Custom);
1548     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1549     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1550   }
1551
1552   // We have target-specific dag combine patterns for the following nodes:
1553   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1554   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1555   setTargetDAGCombine(ISD::VSELECT);
1556   setTargetDAGCombine(ISD::SELECT);
1557   setTargetDAGCombine(ISD::SHL);
1558   setTargetDAGCombine(ISD::SRA);
1559   setTargetDAGCombine(ISD::SRL);
1560   setTargetDAGCombine(ISD::OR);
1561   setTargetDAGCombine(ISD::AND);
1562   setTargetDAGCombine(ISD::ADD);
1563   setTargetDAGCombine(ISD::FADD);
1564   setTargetDAGCombine(ISD::FSUB);
1565   setTargetDAGCombine(ISD::FMA);
1566   setTargetDAGCombine(ISD::SUB);
1567   setTargetDAGCombine(ISD::LOAD);
1568   setTargetDAGCombine(ISD::STORE);
1569   setTargetDAGCombine(ISD::ZERO_EXTEND);
1570   setTargetDAGCombine(ISD::ANY_EXTEND);
1571   setTargetDAGCombine(ISD::SIGN_EXTEND);
1572   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1573   setTargetDAGCombine(ISD::TRUNCATE);
1574   setTargetDAGCombine(ISD::SINT_TO_FP);
1575   setTargetDAGCombine(ISD::SETCC);
1576   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1577   setTargetDAGCombine(ISD::BUILD_VECTOR);
1578   if (Subtarget->is64Bit())
1579     setTargetDAGCombine(ISD::MUL);
1580   setTargetDAGCombine(ISD::XOR);
1581
1582   computeRegisterProperties();
1583
1584   // On Darwin, -Os means optimize for size without hurting performance,
1585   // do not reduce the limit.
1586   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1587   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1588   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1589   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1590   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1591   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1592   setPrefLoopAlignment(4); // 2^4 bytes.
1593
1594   // Predictable cmov don't hurt on atom because it's in-order.
1595   PredictableSelectIsExpensive = !Subtarget->isAtom();
1596
1597   setPrefFunctionAlignment(4); // 2^4 bytes.
1598 }
1599
1600 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1601   if (!VT.isVector())
1602     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1603
1604   if (Subtarget->hasAVX512())
1605     switch(VT.getVectorNumElements()) {
1606     case  8: return MVT::v8i1;
1607     case 16: return MVT::v16i1;
1608   }
1609
1610   return VT.changeVectorElementTypeToInteger();
1611 }
1612
1613 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1614 /// the desired ByVal argument alignment.
1615 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1616   if (MaxAlign == 16)
1617     return;
1618   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1619     if (VTy->getBitWidth() == 128)
1620       MaxAlign = 16;
1621   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1622     unsigned EltAlign = 0;
1623     getMaxByValAlign(ATy->getElementType(), EltAlign);
1624     if (EltAlign > MaxAlign)
1625       MaxAlign = EltAlign;
1626   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1627     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1628       unsigned EltAlign = 0;
1629       getMaxByValAlign(STy->getElementType(i), EltAlign);
1630       if (EltAlign > MaxAlign)
1631         MaxAlign = EltAlign;
1632       if (MaxAlign == 16)
1633         break;
1634     }
1635   }
1636 }
1637
1638 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1639 /// function arguments in the caller parameter area. For X86, aggregates
1640 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1641 /// are at 4-byte boundaries.
1642 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1643   if (Subtarget->is64Bit()) {
1644     // Max of 8 and alignment of type.
1645     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1646     if (TyAlign > 8)
1647       return TyAlign;
1648     return 8;
1649   }
1650
1651   unsigned Align = 4;
1652   if (Subtarget->hasSSE1())
1653     getMaxByValAlign(Ty, Align);
1654   return Align;
1655 }
1656
1657 /// getOptimalMemOpType - Returns the target specific optimal type for load
1658 /// and store operations as a result of memset, memcpy, and memmove
1659 /// lowering. If DstAlign is zero that means it's safe to destination
1660 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1661 /// means there isn't a need to check it against alignment requirement,
1662 /// probably because the source does not need to be loaded. If 'IsMemset' is
1663 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1664 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1665 /// source is constant so it does not need to be loaded.
1666 /// It returns EVT::Other if the type should be determined using generic
1667 /// target-independent logic.
1668 EVT
1669 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1670                                        unsigned DstAlign, unsigned SrcAlign,
1671                                        bool IsMemset, bool ZeroMemset,
1672                                        bool MemcpyStrSrc,
1673                                        MachineFunction &MF) const {
1674   const Function *F = MF.getFunction();
1675   if ((!IsMemset || ZeroMemset) &&
1676       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1677                                        Attribute::NoImplicitFloat)) {
1678     if (Size >= 16 &&
1679         (Subtarget->isUnalignedMemAccessFast() ||
1680          ((DstAlign == 0 || DstAlign >= 16) &&
1681           (SrcAlign == 0 || SrcAlign >= 16)))) {
1682       if (Size >= 32) {
1683         if (Subtarget->hasInt256())
1684           return MVT::v8i32;
1685         if (Subtarget->hasFp256())
1686           return MVT::v8f32;
1687       }
1688       if (Subtarget->hasSSE2())
1689         return MVT::v4i32;
1690       if (Subtarget->hasSSE1())
1691         return MVT::v4f32;
1692     } else if (!MemcpyStrSrc && Size >= 8 &&
1693                !Subtarget->is64Bit() &&
1694                Subtarget->hasSSE2()) {
1695       // Do not use f64 to lower memcpy if source is string constant. It's
1696       // better to use i32 to avoid the loads.
1697       return MVT::f64;
1698     }
1699   }
1700   if (Subtarget->is64Bit() && Size >= 8)
1701     return MVT::i64;
1702   return MVT::i32;
1703 }
1704
1705 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1706   if (VT == MVT::f32)
1707     return X86ScalarSSEf32;
1708   else if (VT == MVT::f64)
1709     return X86ScalarSSEf64;
1710   return true;
1711 }
1712
1713 bool
1714 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1715                                                  unsigned,
1716                                                  bool *Fast) const {
1717   if (Fast)
1718     *Fast = Subtarget->isUnalignedMemAccessFast();
1719   return true;
1720 }
1721
1722 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1723 /// current function.  The returned value is a member of the
1724 /// MachineJumpTableInfo::JTEntryKind enum.
1725 unsigned X86TargetLowering::getJumpTableEncoding() const {
1726   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1727   // symbol.
1728   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1729       Subtarget->isPICStyleGOT())
1730     return MachineJumpTableInfo::EK_Custom32;
1731
1732   // Otherwise, use the normal jump table encoding heuristics.
1733   return TargetLowering::getJumpTableEncoding();
1734 }
1735
1736 const MCExpr *
1737 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1738                                              const MachineBasicBlock *MBB,
1739                                              unsigned uid,MCContext &Ctx) const{
1740   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1741          Subtarget->isPICStyleGOT());
1742   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1743   // entries.
1744   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1745                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1746 }
1747
1748 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1749 /// jumptable.
1750 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1751                                                     SelectionDAG &DAG) const {
1752   if (!Subtarget->is64Bit())
1753     // This doesn't have SDLoc associated with it, but is not really the
1754     // same as a Register.
1755     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1756   return Table;
1757 }
1758
1759 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1760 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1761 /// MCExpr.
1762 const MCExpr *X86TargetLowering::
1763 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1764                              MCContext &Ctx) const {
1765   // X86-64 uses RIP relative addressing based on the jump table label.
1766   if (Subtarget->isPICStyleRIPRel())
1767     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1768
1769   // Otherwise, the reference is relative to the PIC base.
1770   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1771 }
1772
1773 // FIXME: Why this routine is here? Move to RegInfo!
1774 std::pair<const TargetRegisterClass*, uint8_t>
1775 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1776   const TargetRegisterClass *RRC = nullptr;
1777   uint8_t Cost = 1;
1778   switch (VT.SimpleTy) {
1779   default:
1780     return TargetLowering::findRepresentativeClass(VT);
1781   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1782     RRC = Subtarget->is64Bit() ?
1783       (const TargetRegisterClass*)&X86::GR64RegClass :
1784       (const TargetRegisterClass*)&X86::GR32RegClass;
1785     break;
1786   case MVT::x86mmx:
1787     RRC = &X86::VR64RegClass;
1788     break;
1789   case MVT::f32: case MVT::f64:
1790   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1791   case MVT::v4f32: case MVT::v2f64:
1792   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1793   case MVT::v4f64:
1794     RRC = &X86::VR128RegClass;
1795     break;
1796   }
1797   return std::make_pair(RRC, Cost);
1798 }
1799
1800 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1801                                                unsigned &Offset) const {
1802   if (!Subtarget->isTargetLinux())
1803     return false;
1804
1805   if (Subtarget->is64Bit()) {
1806     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1807     Offset = 0x28;
1808     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1809       AddressSpace = 256;
1810     else
1811       AddressSpace = 257;
1812   } else {
1813     // %gs:0x14 on i386
1814     Offset = 0x14;
1815     AddressSpace = 256;
1816   }
1817   return true;
1818 }
1819
1820 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1821                                             unsigned DestAS) const {
1822   assert(SrcAS != DestAS && "Expected different address spaces!");
1823
1824   return SrcAS < 256 && DestAS < 256;
1825 }
1826
1827 //===----------------------------------------------------------------------===//
1828 //               Return Value Calling Convention Implementation
1829 //===----------------------------------------------------------------------===//
1830
1831 #include "X86GenCallingConv.inc"
1832
1833 bool
1834 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1835                                   MachineFunction &MF, bool isVarArg,
1836                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1837                         LLVMContext &Context) const {
1838   SmallVector<CCValAssign, 16> RVLocs;
1839   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
1840                  RVLocs, Context);
1841   return CCInfo.CheckReturn(Outs, RetCC_X86);
1842 }
1843
1844 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1845   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1846   return ScratchRegs;
1847 }
1848
1849 SDValue
1850 X86TargetLowering::LowerReturn(SDValue Chain,
1851                                CallingConv::ID CallConv, bool isVarArg,
1852                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1853                                const SmallVectorImpl<SDValue> &OutVals,
1854                                SDLoc dl, SelectionDAG &DAG) const {
1855   MachineFunction &MF = DAG.getMachineFunction();
1856   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1857
1858   SmallVector<CCValAssign, 16> RVLocs;
1859   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
1860                  RVLocs, *DAG.getContext());
1861   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1862
1863   SDValue Flag;
1864   SmallVector<SDValue, 6> RetOps;
1865   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1866   // Operand #1 = Bytes To Pop
1867   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1868                    MVT::i16));
1869
1870   // Copy the result values into the output registers.
1871   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1872     CCValAssign &VA = RVLocs[i];
1873     assert(VA.isRegLoc() && "Can only return in registers!");
1874     SDValue ValToCopy = OutVals[i];
1875     EVT ValVT = ValToCopy.getValueType();
1876
1877     // Promote values to the appropriate types
1878     if (VA.getLocInfo() == CCValAssign::SExt)
1879       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1880     else if (VA.getLocInfo() == CCValAssign::ZExt)
1881       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1882     else if (VA.getLocInfo() == CCValAssign::AExt)
1883       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1884     else if (VA.getLocInfo() == CCValAssign::BCvt)
1885       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1886
1887     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1888            "Unexpected FP-extend for return value.");  
1889
1890     // If this is x86-64, and we disabled SSE, we can't return FP values,
1891     // or SSE or MMX vectors.
1892     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1893          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1894           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1895       report_fatal_error("SSE register return with SSE disabled");
1896     }
1897     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1898     // llvm-gcc has never done it right and no one has noticed, so this
1899     // should be OK for now.
1900     if (ValVT == MVT::f64 &&
1901         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1902       report_fatal_error("SSE2 register return with SSE2 disabled");
1903
1904     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1905     // the RET instruction and handled by the FP Stackifier.
1906     if (VA.getLocReg() == X86::ST0 ||
1907         VA.getLocReg() == X86::ST1) {
1908       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1909       // change the value to the FP stack register class.
1910       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1911         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1912       RetOps.push_back(ValToCopy);
1913       // Don't emit a copytoreg.
1914       continue;
1915     }
1916
1917     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1918     // which is returned in RAX / RDX.
1919     if (Subtarget->is64Bit()) {
1920       if (ValVT == MVT::x86mmx) {
1921         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1922           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1923           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1924                                   ValToCopy);
1925           // If we don't have SSE2 available, convert to v4f32 so the generated
1926           // register is legal.
1927           if (!Subtarget->hasSSE2())
1928             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1929         }
1930       }
1931     }
1932
1933     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1934     Flag = Chain.getValue(1);
1935     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1936   }
1937
1938   // The x86-64 ABIs require that for returning structs by value we copy
1939   // the sret argument into %rax/%eax (depending on ABI) for the return.
1940   // Win32 requires us to put the sret argument to %eax as well.
1941   // We saved the argument into a virtual register in the entry block,
1942   // so now we copy the value out and into %rax/%eax.
1943   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1944       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1945     MachineFunction &MF = DAG.getMachineFunction();
1946     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1947     unsigned Reg = FuncInfo->getSRetReturnReg();
1948     assert(Reg &&
1949            "SRetReturnReg should have been set in LowerFormalArguments().");
1950     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1951
1952     unsigned RetValReg
1953         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1954           X86::RAX : X86::EAX;
1955     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1956     Flag = Chain.getValue(1);
1957
1958     // RAX/EAX now acts like a return value.
1959     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1960   }
1961
1962   RetOps[0] = Chain;  // Update chain.
1963
1964   // Add the flag if we have it.
1965   if (Flag.getNode())
1966     RetOps.push_back(Flag);
1967
1968   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1969 }
1970
1971 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1972   if (N->getNumValues() != 1)
1973     return false;
1974   if (!N->hasNUsesOfValue(1, 0))
1975     return false;
1976
1977   SDValue TCChain = Chain;
1978   SDNode *Copy = *N->use_begin();
1979   if (Copy->getOpcode() == ISD::CopyToReg) {
1980     // If the copy has a glue operand, we conservatively assume it isn't safe to
1981     // perform a tail call.
1982     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1983       return false;
1984     TCChain = Copy->getOperand(0);
1985   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1986     return false;
1987
1988   bool HasRet = false;
1989   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1990        UI != UE; ++UI) {
1991     if (UI->getOpcode() != X86ISD::RET_FLAG)
1992       return false;
1993     HasRet = true;
1994   }
1995
1996   if (!HasRet)
1997     return false;
1998
1999   Chain = TCChain;
2000   return true;
2001 }
2002
2003 MVT
2004 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
2005                                             ISD::NodeType ExtendKind) const {
2006   MVT ReturnMVT;
2007   // TODO: Is this also valid on 32-bit?
2008   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2009     ReturnMVT = MVT::i8;
2010   else
2011     ReturnMVT = MVT::i32;
2012
2013   MVT MinVT = getRegisterType(ReturnMVT);
2014   return VT.bitsLT(MinVT) ? MinVT : VT;
2015 }
2016
2017 /// LowerCallResult - Lower the result values of a call into the
2018 /// appropriate copies out of appropriate physical registers.
2019 ///
2020 SDValue
2021 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2022                                    CallingConv::ID CallConv, bool isVarArg,
2023                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2024                                    SDLoc dl, SelectionDAG &DAG,
2025                                    SmallVectorImpl<SDValue> &InVals) const {
2026
2027   // Assign locations to each value returned by this call.
2028   SmallVector<CCValAssign, 16> RVLocs;
2029   bool Is64Bit = Subtarget->is64Bit();
2030   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2031                  DAG.getTarget(), RVLocs, *DAG.getContext());
2032   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2033
2034   // Copy all of the result registers out of their specified physreg.
2035   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2036     CCValAssign &VA = RVLocs[i];
2037     EVT CopyVT = VA.getValVT();
2038
2039     // If this is x86-64, and we disabled SSE, we can't return FP values
2040     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2041         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2042       report_fatal_error("SSE register return with SSE disabled");
2043     }
2044
2045     SDValue Val;
2046
2047     // If this is a call to a function that returns an fp value on the floating
2048     // point stack, we must guarantee the value is popped from the stack, so
2049     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2050     // if the return value is not used. We use the FpPOP_RETVAL instruction
2051     // instead.
2052     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2053       // If we prefer to use the value in xmm registers, copy it out as f80 and
2054       // use a truncate to move it from fp stack reg to xmm reg.
2055       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2056       SDValue Ops[] = { Chain, InFlag };
2057       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2058                                          MVT::Other, MVT::Glue, Ops), 1);
2059       Val = Chain.getValue(0);
2060
2061       // Round the f80 to the right size, which also moves it to the appropriate
2062       // xmm register.
2063       if (CopyVT != VA.getValVT())
2064         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2065                           // This truncation won't change the value.
2066                           DAG.getIntPtrConstant(1));
2067     } else {
2068       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2069                                  CopyVT, InFlag).getValue(1);
2070       Val = Chain.getValue(0);
2071     }
2072     InFlag = Chain.getValue(2);
2073     InVals.push_back(Val);
2074   }
2075
2076   return Chain;
2077 }
2078
2079 //===----------------------------------------------------------------------===//
2080 //                C & StdCall & Fast Calling Convention implementation
2081 //===----------------------------------------------------------------------===//
2082 //  StdCall calling convention seems to be standard for many Windows' API
2083 //  routines and around. It differs from C calling convention just a little:
2084 //  callee should clean up the stack, not caller. Symbols should be also
2085 //  decorated in some fancy way :) It doesn't support any vector arguments.
2086 //  For info on fast calling convention see Fast Calling Convention (tail call)
2087 //  implementation LowerX86_32FastCCCallTo.
2088
2089 /// CallIsStructReturn - Determines whether a call uses struct return
2090 /// semantics.
2091 enum StructReturnType {
2092   NotStructReturn,
2093   RegStructReturn,
2094   StackStructReturn
2095 };
2096 static StructReturnType
2097 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2098   if (Outs.empty())
2099     return NotStructReturn;
2100
2101   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2102   if (!Flags.isSRet())
2103     return NotStructReturn;
2104   if (Flags.isInReg())
2105     return RegStructReturn;
2106   return StackStructReturn;
2107 }
2108
2109 /// ArgsAreStructReturn - Determines whether a function uses struct
2110 /// return semantics.
2111 static StructReturnType
2112 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2113   if (Ins.empty())
2114     return NotStructReturn;
2115
2116   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2117   if (!Flags.isSRet())
2118     return NotStructReturn;
2119   if (Flags.isInReg())
2120     return RegStructReturn;
2121   return StackStructReturn;
2122 }
2123
2124 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2125 /// by "Src" to address "Dst" with size and alignment information specified by
2126 /// the specific parameter attribute. The copy will be passed as a byval
2127 /// function parameter.
2128 static SDValue
2129 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2130                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2131                           SDLoc dl) {
2132   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2133
2134   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2135                        /*isVolatile*/false, /*AlwaysInline=*/true,
2136                        MachinePointerInfo(), MachinePointerInfo());
2137 }
2138
2139 /// IsTailCallConvention - Return true if the calling convention is one that
2140 /// supports tail call optimization.
2141 static bool IsTailCallConvention(CallingConv::ID CC) {
2142   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2143           CC == CallingConv::HiPE);
2144 }
2145
2146 /// \brief Return true if the calling convention is a C calling convention.
2147 static bool IsCCallConvention(CallingConv::ID CC) {
2148   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2149           CC == CallingConv::X86_64_SysV);
2150 }
2151
2152 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2153   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2154     return false;
2155
2156   CallSite CS(CI);
2157   CallingConv::ID CalleeCC = CS.getCallingConv();
2158   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2159     return false;
2160
2161   return true;
2162 }
2163
2164 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2165 /// a tailcall target by changing its ABI.
2166 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2167                                    bool GuaranteedTailCallOpt) {
2168   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2169 }
2170
2171 SDValue
2172 X86TargetLowering::LowerMemArgument(SDValue Chain,
2173                                     CallingConv::ID CallConv,
2174                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2175                                     SDLoc dl, SelectionDAG &DAG,
2176                                     const CCValAssign &VA,
2177                                     MachineFrameInfo *MFI,
2178                                     unsigned i) const {
2179   // Create the nodes corresponding to a load from this parameter slot.
2180   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2181   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2182       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2183   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2184   EVT ValVT;
2185
2186   // If value is passed by pointer we have address passed instead of the value
2187   // itself.
2188   if (VA.getLocInfo() == CCValAssign::Indirect)
2189     ValVT = VA.getLocVT();
2190   else
2191     ValVT = VA.getValVT();
2192
2193   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2194   // changed with more analysis.
2195   // In case of tail call optimization mark all arguments mutable. Since they
2196   // could be overwritten by lowering of arguments in case of a tail call.
2197   if (Flags.isByVal()) {
2198     unsigned Bytes = Flags.getByValSize();
2199     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2200     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2201     return DAG.getFrameIndex(FI, getPointerTy());
2202   } else {
2203     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2204                                     VA.getLocMemOffset(), isImmutable);
2205     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2206     return DAG.getLoad(ValVT, dl, Chain, FIN,
2207                        MachinePointerInfo::getFixedStack(FI),
2208                        false, false, false, 0);
2209   }
2210 }
2211
2212 SDValue
2213 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2214                                         CallingConv::ID CallConv,
2215                                         bool isVarArg,
2216                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2217                                         SDLoc dl,
2218                                         SelectionDAG &DAG,
2219                                         SmallVectorImpl<SDValue> &InVals)
2220                                           const {
2221   MachineFunction &MF = DAG.getMachineFunction();
2222   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2223
2224   const Function* Fn = MF.getFunction();
2225   if (Fn->hasExternalLinkage() &&
2226       Subtarget->isTargetCygMing() &&
2227       Fn->getName() == "main")
2228     FuncInfo->setForceFramePointer(true);
2229
2230   MachineFrameInfo *MFI = MF.getFrameInfo();
2231   bool Is64Bit = Subtarget->is64Bit();
2232   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2233
2234   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2235          "Var args not supported with calling convention fastcc, ghc or hipe");
2236
2237   // Assign locations to all of the incoming arguments.
2238   SmallVector<CCValAssign, 16> ArgLocs;
2239   CCState CCInfo(CallConv, isVarArg, MF, DAG.getTarget(),
2240                  ArgLocs, *DAG.getContext());
2241
2242   // Allocate shadow area for Win64
2243   if (IsWin64)
2244     CCInfo.AllocateStack(32, 8);
2245
2246   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2247
2248   unsigned LastVal = ~0U;
2249   SDValue ArgValue;
2250   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2251     CCValAssign &VA = ArgLocs[i];
2252     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2253     // places.
2254     assert(VA.getValNo() != LastVal &&
2255            "Don't support value assigned to multiple locs yet");
2256     (void)LastVal;
2257     LastVal = VA.getValNo();
2258
2259     if (VA.isRegLoc()) {
2260       EVT RegVT = VA.getLocVT();
2261       const TargetRegisterClass *RC;
2262       if (RegVT == MVT::i32)
2263         RC = &X86::GR32RegClass;
2264       else if (Is64Bit && RegVT == MVT::i64)
2265         RC = &X86::GR64RegClass;
2266       else if (RegVT == MVT::f32)
2267         RC = &X86::FR32RegClass;
2268       else if (RegVT == MVT::f64)
2269         RC = &X86::FR64RegClass;
2270       else if (RegVT.is512BitVector())
2271         RC = &X86::VR512RegClass;
2272       else if (RegVT.is256BitVector())
2273         RC = &X86::VR256RegClass;
2274       else if (RegVT.is128BitVector())
2275         RC = &X86::VR128RegClass;
2276       else if (RegVT == MVT::x86mmx)
2277         RC = &X86::VR64RegClass;
2278       else if (RegVT == MVT::i1)
2279         RC = &X86::VK1RegClass;
2280       else if (RegVT == MVT::v8i1)
2281         RC = &X86::VK8RegClass;
2282       else if (RegVT == MVT::v16i1)
2283         RC = &X86::VK16RegClass;
2284       else
2285         llvm_unreachable("Unknown argument type!");
2286
2287       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2288       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2289
2290       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2291       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2292       // right size.
2293       if (VA.getLocInfo() == CCValAssign::SExt)
2294         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2295                                DAG.getValueType(VA.getValVT()));
2296       else if (VA.getLocInfo() == CCValAssign::ZExt)
2297         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2298                                DAG.getValueType(VA.getValVT()));
2299       else if (VA.getLocInfo() == CCValAssign::BCvt)
2300         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2301
2302       if (VA.isExtInLoc()) {
2303         // Handle MMX values passed in XMM regs.
2304         if (RegVT.isVector())
2305           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2306         else
2307           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2308       }
2309     } else {
2310       assert(VA.isMemLoc());
2311       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2312     }
2313
2314     // If value is passed via pointer - do a load.
2315     if (VA.getLocInfo() == CCValAssign::Indirect)
2316       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2317                              MachinePointerInfo(), false, false, false, 0);
2318
2319     InVals.push_back(ArgValue);
2320   }
2321
2322   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2323     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2324       // The x86-64 ABIs require that for returning structs by value we copy
2325       // the sret argument into %rax/%eax (depending on ABI) for the return.
2326       // Win32 requires us to put the sret argument to %eax as well.
2327       // Save the argument into a virtual register so that we can access it
2328       // from the return points.
2329       if (Ins[i].Flags.isSRet()) {
2330         unsigned Reg = FuncInfo->getSRetReturnReg();
2331         if (!Reg) {
2332           MVT PtrTy = getPointerTy();
2333           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2334           FuncInfo->setSRetReturnReg(Reg);
2335         }
2336         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2337         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2338         break;
2339       }
2340     }
2341   }
2342
2343   unsigned StackSize = CCInfo.getNextStackOffset();
2344   // Align stack specially for tail calls.
2345   if (FuncIsMadeTailCallSafe(CallConv,
2346                              MF.getTarget().Options.GuaranteedTailCallOpt))
2347     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2348
2349   // If the function takes variable number of arguments, make a frame index for
2350   // the start of the first vararg value... for expansion of llvm.va_start.
2351   if (isVarArg) {
2352     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2353                     CallConv != CallingConv::X86_ThisCall)) {
2354       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2355     }
2356     if (Is64Bit) {
2357       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2358
2359       // FIXME: We should really autogenerate these arrays
2360       static const MCPhysReg GPR64ArgRegsWin64[] = {
2361         X86::RCX, X86::RDX, X86::R8,  X86::R9
2362       };
2363       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2364         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2365       };
2366       static const MCPhysReg XMMArgRegs64Bit[] = {
2367         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2368         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2369       };
2370       const MCPhysReg *GPR64ArgRegs;
2371       unsigned NumXMMRegs = 0;
2372
2373       if (IsWin64) {
2374         // The XMM registers which might contain var arg parameters are shadowed
2375         // in their paired GPR.  So we only need to save the GPR to their home
2376         // slots.
2377         TotalNumIntRegs = 4;
2378         GPR64ArgRegs = GPR64ArgRegsWin64;
2379       } else {
2380         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2381         GPR64ArgRegs = GPR64ArgRegs64Bit;
2382
2383         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2384                                                 TotalNumXMMRegs);
2385       }
2386       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2387                                                        TotalNumIntRegs);
2388
2389       bool NoImplicitFloatOps = Fn->getAttributes().
2390         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2391       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2392              "SSE register cannot be used when SSE is disabled!");
2393       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2394                NoImplicitFloatOps) &&
2395              "SSE register cannot be used when SSE is disabled!");
2396       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2397           !Subtarget->hasSSE1())
2398         // Kernel mode asks for SSE to be disabled, so don't push them
2399         // on the stack.
2400         TotalNumXMMRegs = 0;
2401
2402       if (IsWin64) {
2403         const TargetFrameLowering &TFI = *MF.getTarget().getFrameLowering();
2404         // Get to the caller-allocated home save location.  Add 8 to account
2405         // for the return address.
2406         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2407         FuncInfo->setRegSaveFrameIndex(
2408           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2409         // Fixup to set vararg frame on shadow area (4 x i64).
2410         if (NumIntRegs < 4)
2411           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2412       } else {
2413         // For X86-64, if there are vararg parameters that are passed via
2414         // registers, then we must store them to their spots on the stack so
2415         // they may be loaded by deferencing the result of va_next.
2416         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2417         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2418         FuncInfo->setRegSaveFrameIndex(
2419           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2420                                false));
2421       }
2422
2423       // Store the integer parameter registers.
2424       SmallVector<SDValue, 8> MemOps;
2425       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2426                                         getPointerTy());
2427       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2428       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2429         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2430                                   DAG.getIntPtrConstant(Offset));
2431         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2432                                      &X86::GR64RegClass);
2433         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2434         SDValue Store =
2435           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2436                        MachinePointerInfo::getFixedStack(
2437                          FuncInfo->getRegSaveFrameIndex(), Offset),
2438                        false, false, 0);
2439         MemOps.push_back(Store);
2440         Offset += 8;
2441       }
2442
2443       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2444         // Now store the XMM (fp + vector) parameter registers.
2445         SmallVector<SDValue, 11> SaveXMMOps;
2446         SaveXMMOps.push_back(Chain);
2447
2448         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2449         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2450         SaveXMMOps.push_back(ALVal);
2451
2452         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2453                                FuncInfo->getRegSaveFrameIndex()));
2454         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2455                                FuncInfo->getVarArgsFPOffset()));
2456
2457         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2458           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2459                                        &X86::VR128RegClass);
2460           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2461           SaveXMMOps.push_back(Val);
2462         }
2463         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2464                                      MVT::Other, SaveXMMOps));
2465       }
2466
2467       if (!MemOps.empty())
2468         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2469     }
2470   }
2471
2472   // Some CCs need callee pop.
2473   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2474                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2475     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2476   } else {
2477     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2478     // If this is an sret function, the return should pop the hidden pointer.
2479     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2480         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2481         argsAreStructReturn(Ins) == StackStructReturn)
2482       FuncInfo->setBytesToPopOnReturn(4);
2483   }
2484
2485   if (!Is64Bit) {
2486     // RegSaveFrameIndex is X86-64 only.
2487     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2488     if (CallConv == CallingConv::X86_FastCall ||
2489         CallConv == CallingConv::X86_ThisCall)
2490       // fastcc functions can't have varargs.
2491       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2492   }
2493
2494   FuncInfo->setArgumentStackSize(StackSize);
2495
2496   return Chain;
2497 }
2498
2499 SDValue
2500 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2501                                     SDValue StackPtr, SDValue Arg,
2502                                     SDLoc dl, SelectionDAG &DAG,
2503                                     const CCValAssign &VA,
2504                                     ISD::ArgFlagsTy Flags) const {
2505   unsigned LocMemOffset = VA.getLocMemOffset();
2506   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2507   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2508   if (Flags.isByVal())
2509     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2510
2511   return DAG.getStore(Chain, dl, Arg, PtrOff,
2512                       MachinePointerInfo::getStack(LocMemOffset),
2513                       false, false, 0);
2514 }
2515
2516 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2517 /// optimization is performed and it is required.
2518 SDValue
2519 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2520                                            SDValue &OutRetAddr, SDValue Chain,
2521                                            bool IsTailCall, bool Is64Bit,
2522                                            int FPDiff, SDLoc dl) const {
2523   // Adjust the Return address stack slot.
2524   EVT VT = getPointerTy();
2525   OutRetAddr = getReturnAddressFrameIndex(DAG);
2526
2527   // Load the "old" Return address.
2528   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2529                            false, false, false, 0);
2530   return SDValue(OutRetAddr.getNode(), 1);
2531 }
2532
2533 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2534 /// optimization is performed and it is required (FPDiff!=0).
2535 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2536                                         SDValue Chain, SDValue RetAddrFrIdx,
2537                                         EVT PtrVT, unsigned SlotSize,
2538                                         int FPDiff, SDLoc dl) {
2539   // Store the return address to the appropriate stack slot.
2540   if (!FPDiff) return Chain;
2541   // Calculate the new stack slot for the return address.
2542   int NewReturnAddrFI =
2543     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2544                                          false);
2545   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2546   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2547                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2548                        false, false, 0);
2549   return Chain;
2550 }
2551
2552 SDValue
2553 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2554                              SmallVectorImpl<SDValue> &InVals) const {
2555   SelectionDAG &DAG                     = CLI.DAG;
2556   SDLoc &dl                             = CLI.DL;
2557   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2558   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2559   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2560   SDValue Chain                         = CLI.Chain;
2561   SDValue Callee                        = CLI.Callee;
2562   CallingConv::ID CallConv              = CLI.CallConv;
2563   bool &isTailCall                      = CLI.IsTailCall;
2564   bool isVarArg                         = CLI.IsVarArg;
2565
2566   MachineFunction &MF = DAG.getMachineFunction();
2567   bool Is64Bit        = Subtarget->is64Bit();
2568   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2569   StructReturnType SR = callIsStructReturn(Outs);
2570   bool IsSibcall      = false;
2571
2572   if (MF.getTarget().Options.DisableTailCalls)
2573     isTailCall = false;
2574
2575   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2576   if (IsMustTail) {
2577     // Force this to be a tail call.  The verifier rules are enough to ensure
2578     // that we can lower this successfully without moving the return address
2579     // around.
2580     isTailCall = true;
2581   } else if (isTailCall) {
2582     // Check if it's really possible to do a tail call.
2583     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2584                     isVarArg, SR != NotStructReturn,
2585                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2586                     Outs, OutVals, Ins, DAG);
2587
2588     // Sibcalls are automatically detected tailcalls which do not require
2589     // ABI changes.
2590     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2591       IsSibcall = true;
2592
2593     if (isTailCall)
2594       ++NumTailCalls;
2595   }
2596
2597   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2598          "Var args not supported with calling convention fastcc, ghc or hipe");
2599
2600   // Analyze operands of the call, assigning locations to each operand.
2601   SmallVector<CCValAssign, 16> ArgLocs;
2602   CCState CCInfo(CallConv, isVarArg, MF, MF.getTarget(),
2603                  ArgLocs, *DAG.getContext());
2604
2605   // Allocate shadow area for Win64
2606   if (IsWin64)
2607     CCInfo.AllocateStack(32, 8);
2608
2609   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2610
2611   // Get a count of how many bytes are to be pushed on the stack.
2612   unsigned NumBytes = CCInfo.getNextStackOffset();
2613   if (IsSibcall)
2614     // This is a sibcall. The memory operands are available in caller's
2615     // own caller's stack.
2616     NumBytes = 0;
2617   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2618            IsTailCallConvention(CallConv))
2619     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2620
2621   int FPDiff = 0;
2622   if (isTailCall && !IsSibcall && !IsMustTail) {
2623     // Lower arguments at fp - stackoffset + fpdiff.
2624     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2625     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2626
2627     FPDiff = NumBytesCallerPushed - NumBytes;
2628
2629     // Set the delta of movement of the returnaddr stackslot.
2630     // But only set if delta is greater than previous delta.
2631     if (FPDiff < X86Info->getTCReturnAddrDelta())
2632       X86Info->setTCReturnAddrDelta(FPDiff);
2633   }
2634
2635   unsigned NumBytesToPush = NumBytes;
2636   unsigned NumBytesToPop = NumBytes;
2637
2638   // If we have an inalloca argument, all stack space has already been allocated
2639   // for us and be right at the top of the stack.  We don't support multiple
2640   // arguments passed in memory when using inalloca.
2641   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2642     NumBytesToPush = 0;
2643     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2644            "an inalloca argument must be the only memory argument");
2645   }
2646
2647   if (!IsSibcall)
2648     Chain = DAG.getCALLSEQ_START(
2649         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2650
2651   SDValue RetAddrFrIdx;
2652   // Load return address for tail calls.
2653   if (isTailCall && FPDiff)
2654     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2655                                     Is64Bit, FPDiff, dl);
2656
2657   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2658   SmallVector<SDValue, 8> MemOpChains;
2659   SDValue StackPtr;
2660
2661   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2662   // of tail call optimization arguments are handle later.
2663   const X86RegisterInfo *RegInfo =
2664     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
2665   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2666     // Skip inalloca arguments, they have already been written.
2667     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2668     if (Flags.isInAlloca())
2669       continue;
2670
2671     CCValAssign &VA = ArgLocs[i];
2672     EVT RegVT = VA.getLocVT();
2673     SDValue Arg = OutVals[i];
2674     bool isByVal = Flags.isByVal();
2675
2676     // Promote the value if needed.
2677     switch (VA.getLocInfo()) {
2678     default: llvm_unreachable("Unknown loc info!");
2679     case CCValAssign::Full: break;
2680     case CCValAssign::SExt:
2681       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2682       break;
2683     case CCValAssign::ZExt:
2684       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2685       break;
2686     case CCValAssign::AExt:
2687       if (RegVT.is128BitVector()) {
2688         // Special case: passing MMX values in XMM registers.
2689         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2690         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2691         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2692       } else
2693         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2694       break;
2695     case CCValAssign::BCvt:
2696       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2697       break;
2698     case CCValAssign::Indirect: {
2699       // Store the argument.
2700       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2701       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2702       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2703                            MachinePointerInfo::getFixedStack(FI),
2704                            false, false, 0);
2705       Arg = SpillSlot;
2706       break;
2707     }
2708     }
2709
2710     if (VA.isRegLoc()) {
2711       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2712       if (isVarArg && IsWin64) {
2713         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2714         // shadow reg if callee is a varargs function.
2715         unsigned ShadowReg = 0;
2716         switch (VA.getLocReg()) {
2717         case X86::XMM0: ShadowReg = X86::RCX; break;
2718         case X86::XMM1: ShadowReg = X86::RDX; break;
2719         case X86::XMM2: ShadowReg = X86::R8; break;
2720         case X86::XMM3: ShadowReg = X86::R9; break;
2721         }
2722         if (ShadowReg)
2723           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2724       }
2725     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2726       assert(VA.isMemLoc());
2727       if (!StackPtr.getNode())
2728         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2729                                       getPointerTy());
2730       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2731                                              dl, DAG, VA, Flags));
2732     }
2733   }
2734
2735   if (!MemOpChains.empty())
2736     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2737
2738   if (Subtarget->isPICStyleGOT()) {
2739     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2740     // GOT pointer.
2741     if (!isTailCall) {
2742       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2743                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2744     } else {
2745       // If we are tail calling and generating PIC/GOT style code load the
2746       // address of the callee into ECX. The value in ecx is used as target of
2747       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2748       // for tail calls on PIC/GOT architectures. Normally we would just put the
2749       // address of GOT into ebx and then call target@PLT. But for tail calls
2750       // ebx would be restored (since ebx is callee saved) before jumping to the
2751       // target@PLT.
2752
2753       // Note: The actual moving to ECX is done further down.
2754       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2755       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2756           !G->getGlobal()->hasProtectedVisibility())
2757         Callee = LowerGlobalAddress(Callee, DAG);
2758       else if (isa<ExternalSymbolSDNode>(Callee))
2759         Callee = LowerExternalSymbol(Callee, DAG);
2760     }
2761   }
2762
2763   if (Is64Bit && isVarArg && !IsWin64) {
2764     // From AMD64 ABI document:
2765     // For calls that may call functions that use varargs or stdargs
2766     // (prototype-less calls or calls to functions containing ellipsis (...) in
2767     // the declaration) %al is used as hidden argument to specify the number
2768     // of SSE registers used. The contents of %al do not need to match exactly
2769     // the number of registers, but must be an ubound on the number of SSE
2770     // registers used and is in the range 0 - 8 inclusive.
2771
2772     // Count the number of XMM registers allocated.
2773     static const MCPhysReg XMMArgRegs[] = {
2774       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2775       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2776     };
2777     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2778     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2779            && "SSE registers cannot be used when SSE is disabled");
2780
2781     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2782                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2783   }
2784
2785   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2786   // don't need this because the eligibility check rejects calls that require
2787   // shuffling arguments passed in memory.
2788   if (!IsSibcall && isTailCall) {
2789     // Force all the incoming stack arguments to be loaded from the stack
2790     // before any new outgoing arguments are stored to the stack, because the
2791     // outgoing stack slots may alias the incoming argument stack slots, and
2792     // the alias isn't otherwise explicit. This is slightly more conservative
2793     // than necessary, because it means that each store effectively depends
2794     // on every argument instead of just those arguments it would clobber.
2795     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2796
2797     SmallVector<SDValue, 8> MemOpChains2;
2798     SDValue FIN;
2799     int FI = 0;
2800     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2801       CCValAssign &VA = ArgLocs[i];
2802       if (VA.isRegLoc())
2803         continue;
2804       assert(VA.isMemLoc());
2805       SDValue Arg = OutVals[i];
2806       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2807       // Skip inalloca arguments.  They don't require any work.
2808       if (Flags.isInAlloca())
2809         continue;
2810       // Create frame index.
2811       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2812       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2813       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2814       FIN = DAG.getFrameIndex(FI, getPointerTy());
2815
2816       if (Flags.isByVal()) {
2817         // Copy relative to framepointer.
2818         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2819         if (!StackPtr.getNode())
2820           StackPtr = DAG.getCopyFromReg(Chain, dl,
2821                                         RegInfo->getStackRegister(),
2822                                         getPointerTy());
2823         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2824
2825         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2826                                                          ArgChain,
2827                                                          Flags, DAG, dl));
2828       } else {
2829         // Store relative to framepointer.
2830         MemOpChains2.push_back(
2831           DAG.getStore(ArgChain, dl, Arg, FIN,
2832                        MachinePointerInfo::getFixedStack(FI),
2833                        false, false, 0));
2834       }
2835     }
2836
2837     if (!MemOpChains2.empty())
2838       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2839
2840     // Store the return address to the appropriate stack slot.
2841     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2842                                      getPointerTy(), RegInfo->getSlotSize(),
2843                                      FPDiff, dl);
2844   }
2845
2846   // Build a sequence of copy-to-reg nodes chained together with token chain
2847   // and flag operands which copy the outgoing args into registers.
2848   SDValue InFlag;
2849   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2850     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2851                              RegsToPass[i].second, InFlag);
2852     InFlag = Chain.getValue(1);
2853   }
2854
2855   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
2856     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2857     // In the 64-bit large code model, we have to make all calls
2858     // through a register, since the call instruction's 32-bit
2859     // pc-relative offset may not be large enough to hold the whole
2860     // address.
2861   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2862     // If the callee is a GlobalAddress node (quite common, every direct call
2863     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2864     // it.
2865
2866     // We should use extra load for direct calls to dllimported functions in
2867     // non-JIT mode.
2868     const GlobalValue *GV = G->getGlobal();
2869     if (!GV->hasDLLImportStorageClass()) {
2870       unsigned char OpFlags = 0;
2871       bool ExtraLoad = false;
2872       unsigned WrapperKind = ISD::DELETED_NODE;
2873
2874       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2875       // external symbols most go through the PLT in PIC mode.  If the symbol
2876       // has hidden or protected visibility, or if it is static or local, then
2877       // we don't need to use the PLT - we can directly call it.
2878       if (Subtarget->isTargetELF() &&
2879           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
2880           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2881         OpFlags = X86II::MO_PLT;
2882       } else if (Subtarget->isPICStyleStubAny() &&
2883                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2884                  (!Subtarget->getTargetTriple().isMacOSX() ||
2885                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2886         // PC-relative references to external symbols should go through $stub,
2887         // unless we're building with the leopard linker or later, which
2888         // automatically synthesizes these stubs.
2889         OpFlags = X86II::MO_DARWIN_STUB;
2890       } else if (Subtarget->isPICStyleRIPRel() &&
2891                  isa<Function>(GV) &&
2892                  cast<Function>(GV)->getAttributes().
2893                    hasAttribute(AttributeSet::FunctionIndex,
2894                                 Attribute::NonLazyBind)) {
2895         // If the function is marked as non-lazy, generate an indirect call
2896         // which loads from the GOT directly. This avoids runtime overhead
2897         // at the cost of eager binding (and one extra byte of encoding).
2898         OpFlags = X86II::MO_GOTPCREL;
2899         WrapperKind = X86ISD::WrapperRIP;
2900         ExtraLoad = true;
2901       }
2902
2903       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2904                                           G->getOffset(), OpFlags);
2905
2906       // Add a wrapper if needed.
2907       if (WrapperKind != ISD::DELETED_NODE)
2908         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2909       // Add extra indirection if needed.
2910       if (ExtraLoad)
2911         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2912                              MachinePointerInfo::getGOT(),
2913                              false, false, false, 0);
2914     }
2915   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2916     unsigned char OpFlags = 0;
2917
2918     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2919     // external symbols should go through the PLT.
2920     if (Subtarget->isTargetELF() &&
2921         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
2922       OpFlags = X86II::MO_PLT;
2923     } else if (Subtarget->isPICStyleStubAny() &&
2924                (!Subtarget->getTargetTriple().isMacOSX() ||
2925                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2926       // PC-relative references to external symbols should go through $stub,
2927       // unless we're building with the leopard linker or later, which
2928       // automatically synthesizes these stubs.
2929       OpFlags = X86II::MO_DARWIN_STUB;
2930     }
2931
2932     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2933                                          OpFlags);
2934   }
2935
2936   // Returns a chain & a flag for retval copy to use.
2937   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2938   SmallVector<SDValue, 8> Ops;
2939
2940   if (!IsSibcall && isTailCall) {
2941     Chain = DAG.getCALLSEQ_END(Chain,
2942                                DAG.getIntPtrConstant(NumBytesToPop, true),
2943                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2944     InFlag = Chain.getValue(1);
2945   }
2946
2947   Ops.push_back(Chain);
2948   Ops.push_back(Callee);
2949
2950   if (isTailCall)
2951     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2952
2953   // Add argument registers to the end of the list so that they are known live
2954   // into the call.
2955   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2956     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2957                                   RegsToPass[i].second.getValueType()));
2958
2959   // Add a register mask operand representing the call-preserved registers.
2960   const TargetRegisterInfo *TRI = DAG.getTarget().getRegisterInfo();
2961   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2962   assert(Mask && "Missing call preserved mask for calling convention");
2963   Ops.push_back(DAG.getRegisterMask(Mask));
2964
2965   if (InFlag.getNode())
2966     Ops.push_back(InFlag);
2967
2968   if (isTailCall) {
2969     // We used to do:
2970     //// If this is the first return lowered for this function, add the regs
2971     //// to the liveout set for the function.
2972     // This isn't right, although it's probably harmless on x86; liveouts
2973     // should be computed from returns not tail calls.  Consider a void
2974     // function making a tail call to a function returning int.
2975     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2976   }
2977
2978   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2979   InFlag = Chain.getValue(1);
2980
2981   // Create the CALLSEQ_END node.
2982   unsigned NumBytesForCalleeToPop;
2983   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2984                        DAG.getTarget().Options.GuaranteedTailCallOpt))
2985     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2986   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2987            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2988            SR == StackStructReturn)
2989     // If this is a call to a struct-return function, the callee
2990     // pops the hidden struct pointer, so we have to push it back.
2991     // This is common for Darwin/X86, Linux & Mingw32 targets.
2992     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2993     NumBytesForCalleeToPop = 4;
2994   else
2995     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2996
2997   // Returns a flag for retval copy to use.
2998   if (!IsSibcall) {
2999     Chain = DAG.getCALLSEQ_END(Chain,
3000                                DAG.getIntPtrConstant(NumBytesToPop, true),
3001                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
3002                                                      true),
3003                                InFlag, dl);
3004     InFlag = Chain.getValue(1);
3005   }
3006
3007   // Handle result values, copying them out of physregs into vregs that we
3008   // return.
3009   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3010                          Ins, dl, DAG, InVals);
3011 }
3012
3013 //===----------------------------------------------------------------------===//
3014 //                Fast Calling Convention (tail call) implementation
3015 //===----------------------------------------------------------------------===//
3016
3017 //  Like std call, callee cleans arguments, convention except that ECX is
3018 //  reserved for storing the tail called function address. Only 2 registers are
3019 //  free for argument passing (inreg). Tail call optimization is performed
3020 //  provided:
3021 //                * tailcallopt is enabled
3022 //                * caller/callee are fastcc
3023 //  On X86_64 architecture with GOT-style position independent code only local
3024 //  (within module) calls are supported at the moment.
3025 //  To keep the stack aligned according to platform abi the function
3026 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3027 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3028 //  If a tail called function callee has more arguments than the caller the
3029 //  caller needs to make sure that there is room to move the RETADDR to. This is
3030 //  achieved by reserving an area the size of the argument delta right after the
3031 //  original REtADDR, but before the saved framepointer or the spilled registers
3032 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3033 //  stack layout:
3034 //    arg1
3035 //    arg2
3036 //    RETADDR
3037 //    [ new RETADDR
3038 //      move area ]
3039 //    (possible EBP)
3040 //    ESI
3041 //    EDI
3042 //    local1 ..
3043
3044 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3045 /// for a 16 byte align requirement.
3046 unsigned
3047 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3048                                                SelectionDAG& DAG) const {
3049   MachineFunction &MF = DAG.getMachineFunction();
3050   const TargetMachine &TM = MF.getTarget();
3051   const X86RegisterInfo *RegInfo =
3052     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3053   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3054   unsigned StackAlignment = TFI.getStackAlignment();
3055   uint64_t AlignMask = StackAlignment - 1;
3056   int64_t Offset = StackSize;
3057   unsigned SlotSize = RegInfo->getSlotSize();
3058   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3059     // Number smaller than 12 so just add the difference.
3060     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3061   } else {
3062     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3063     Offset = ((~AlignMask) & Offset) + StackAlignment +
3064       (StackAlignment-SlotSize);
3065   }
3066   return Offset;
3067 }
3068
3069 /// MatchingStackOffset - Return true if the given stack call argument is
3070 /// already available in the same position (relatively) of the caller's
3071 /// incoming argument stack.
3072 static
3073 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3074                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3075                          const X86InstrInfo *TII) {
3076   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3077   int FI = INT_MAX;
3078   if (Arg.getOpcode() == ISD::CopyFromReg) {
3079     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3080     if (!TargetRegisterInfo::isVirtualRegister(VR))
3081       return false;
3082     MachineInstr *Def = MRI->getVRegDef(VR);
3083     if (!Def)
3084       return false;
3085     if (!Flags.isByVal()) {
3086       if (!TII->isLoadFromStackSlot(Def, FI))
3087         return false;
3088     } else {
3089       unsigned Opcode = Def->getOpcode();
3090       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3091           Def->getOperand(1).isFI()) {
3092         FI = Def->getOperand(1).getIndex();
3093         Bytes = Flags.getByValSize();
3094       } else
3095         return false;
3096     }
3097   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3098     if (Flags.isByVal())
3099       // ByVal argument is passed in as a pointer but it's now being
3100       // dereferenced. e.g.
3101       // define @foo(%struct.X* %A) {
3102       //   tail call @bar(%struct.X* byval %A)
3103       // }
3104       return false;
3105     SDValue Ptr = Ld->getBasePtr();
3106     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3107     if (!FINode)
3108       return false;
3109     FI = FINode->getIndex();
3110   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3111     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3112     FI = FINode->getIndex();
3113     Bytes = Flags.getByValSize();
3114   } else
3115     return false;
3116
3117   assert(FI != INT_MAX);
3118   if (!MFI->isFixedObjectIndex(FI))
3119     return false;
3120   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3121 }
3122
3123 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3124 /// for tail call optimization. Targets which want to do tail call
3125 /// optimization should implement this function.
3126 bool
3127 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3128                                                      CallingConv::ID CalleeCC,
3129                                                      bool isVarArg,
3130                                                      bool isCalleeStructRet,
3131                                                      bool isCallerStructRet,
3132                                                      Type *RetTy,
3133                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3134                                     const SmallVectorImpl<SDValue> &OutVals,
3135                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3136                                                      SelectionDAG &DAG) const {
3137   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3138     return false;
3139
3140   // If -tailcallopt is specified, make fastcc functions tail-callable.
3141   const MachineFunction &MF = DAG.getMachineFunction();
3142   const Function *CallerF = MF.getFunction();
3143
3144   // If the function return type is x86_fp80 and the callee return type is not,
3145   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3146   // perform a tailcall optimization here.
3147   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3148     return false;
3149
3150   CallingConv::ID CallerCC = CallerF->getCallingConv();
3151   bool CCMatch = CallerCC == CalleeCC;
3152   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3153   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3154
3155   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3156     if (IsTailCallConvention(CalleeCC) && CCMatch)
3157       return true;
3158     return false;
3159   }
3160
3161   // Look for obvious safe cases to perform tail call optimization that do not
3162   // require ABI changes. This is what gcc calls sibcall.
3163
3164   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3165   // emit a special epilogue.
3166   const X86RegisterInfo *RegInfo =
3167     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3168   if (RegInfo->needsStackRealignment(MF))
3169     return false;
3170
3171   // Also avoid sibcall optimization if either caller or callee uses struct
3172   // return semantics.
3173   if (isCalleeStructRet || isCallerStructRet)
3174     return false;
3175
3176   // An stdcall/thiscall caller is expected to clean up its arguments; the
3177   // callee isn't going to do that.
3178   // FIXME: this is more restrictive than needed. We could produce a tailcall
3179   // when the stack adjustment matches. For example, with a thiscall that takes
3180   // only one argument.
3181   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3182                    CallerCC == CallingConv::X86_ThisCall))
3183     return false;
3184
3185   // Do not sibcall optimize vararg calls unless all arguments are passed via
3186   // registers.
3187   if (isVarArg && !Outs.empty()) {
3188
3189     // Optimizing for varargs on Win64 is unlikely to be safe without
3190     // additional testing.
3191     if (IsCalleeWin64 || IsCallerWin64)
3192       return false;
3193
3194     SmallVector<CCValAssign, 16> ArgLocs;
3195     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3196                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3197
3198     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3199     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3200       if (!ArgLocs[i].isRegLoc())
3201         return false;
3202   }
3203
3204   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3205   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3206   // this into a sibcall.
3207   bool Unused = false;
3208   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3209     if (!Ins[i].Used) {
3210       Unused = true;
3211       break;
3212     }
3213   }
3214   if (Unused) {
3215     SmallVector<CCValAssign, 16> RVLocs;
3216     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3217                    DAG.getTarget(), RVLocs, *DAG.getContext());
3218     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3219     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3220       CCValAssign &VA = RVLocs[i];
3221       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3222         return false;
3223     }
3224   }
3225
3226   // If the calling conventions do not match, then we'd better make sure the
3227   // results are returned in the same way as what the caller expects.
3228   if (!CCMatch) {
3229     SmallVector<CCValAssign, 16> RVLocs1;
3230     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3231                     DAG.getTarget(), RVLocs1, *DAG.getContext());
3232     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3233
3234     SmallVector<CCValAssign, 16> RVLocs2;
3235     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3236                     DAG.getTarget(), RVLocs2, *DAG.getContext());
3237     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3238
3239     if (RVLocs1.size() != RVLocs2.size())
3240       return false;
3241     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3242       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3243         return false;
3244       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3245         return false;
3246       if (RVLocs1[i].isRegLoc()) {
3247         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3248           return false;
3249       } else {
3250         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3251           return false;
3252       }
3253     }
3254   }
3255
3256   // If the callee takes no arguments then go on to check the results of the
3257   // call.
3258   if (!Outs.empty()) {
3259     // Check if stack adjustment is needed. For now, do not do this if any
3260     // argument is passed on the stack.
3261     SmallVector<CCValAssign, 16> ArgLocs;
3262     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3263                    DAG.getTarget(), ArgLocs, *DAG.getContext());
3264
3265     // Allocate shadow area for Win64
3266     if (IsCalleeWin64)
3267       CCInfo.AllocateStack(32, 8);
3268
3269     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3270     if (CCInfo.getNextStackOffset()) {
3271       MachineFunction &MF = DAG.getMachineFunction();
3272       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3273         return false;
3274
3275       // Check if the arguments are already laid out in the right way as
3276       // the caller's fixed stack objects.
3277       MachineFrameInfo *MFI = MF.getFrameInfo();
3278       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3279       const X86InstrInfo *TII =
3280           static_cast<const X86InstrInfo *>(DAG.getTarget().getInstrInfo());
3281       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3282         CCValAssign &VA = ArgLocs[i];
3283         SDValue Arg = OutVals[i];
3284         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3285         if (VA.getLocInfo() == CCValAssign::Indirect)
3286           return false;
3287         if (!VA.isRegLoc()) {
3288           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3289                                    MFI, MRI, TII))
3290             return false;
3291         }
3292       }
3293     }
3294
3295     // If the tailcall address may be in a register, then make sure it's
3296     // possible to register allocate for it. In 32-bit, the call address can
3297     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3298     // callee-saved registers are restored. These happen to be the same
3299     // registers used to pass 'inreg' arguments so watch out for those.
3300     if (!Subtarget->is64Bit() &&
3301         ((!isa<GlobalAddressSDNode>(Callee) &&
3302           !isa<ExternalSymbolSDNode>(Callee)) ||
3303          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3304       unsigned NumInRegs = 0;
3305       // In PIC we need an extra register to formulate the address computation
3306       // for the callee.
3307       unsigned MaxInRegs =
3308         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3309
3310       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3311         CCValAssign &VA = ArgLocs[i];
3312         if (!VA.isRegLoc())
3313           continue;
3314         unsigned Reg = VA.getLocReg();
3315         switch (Reg) {
3316         default: break;
3317         case X86::EAX: case X86::EDX: case X86::ECX:
3318           if (++NumInRegs == MaxInRegs)
3319             return false;
3320           break;
3321         }
3322       }
3323     }
3324   }
3325
3326   return true;
3327 }
3328
3329 FastISel *
3330 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3331                                   const TargetLibraryInfo *libInfo) const {
3332   return X86::createFastISel(funcInfo, libInfo);
3333 }
3334
3335 //===----------------------------------------------------------------------===//
3336 //                           Other Lowering Hooks
3337 //===----------------------------------------------------------------------===//
3338
3339 static bool MayFoldLoad(SDValue Op) {
3340   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3341 }
3342
3343 static bool MayFoldIntoStore(SDValue Op) {
3344   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3345 }
3346
3347 static bool isTargetShuffle(unsigned Opcode) {
3348   switch(Opcode) {
3349   default: return false;
3350   case X86ISD::PSHUFD:
3351   case X86ISD::PSHUFHW:
3352   case X86ISD::PSHUFLW:
3353   case X86ISD::SHUFP:
3354   case X86ISD::PALIGNR:
3355   case X86ISD::MOVLHPS:
3356   case X86ISD::MOVLHPD:
3357   case X86ISD::MOVHLPS:
3358   case X86ISD::MOVLPS:
3359   case X86ISD::MOVLPD:
3360   case X86ISD::MOVSHDUP:
3361   case X86ISD::MOVSLDUP:
3362   case X86ISD::MOVDDUP:
3363   case X86ISD::MOVSS:
3364   case X86ISD::MOVSD:
3365   case X86ISD::UNPCKL:
3366   case X86ISD::UNPCKH:
3367   case X86ISD::VPERMILP:
3368   case X86ISD::VPERM2X128:
3369   case X86ISD::VPERMI:
3370     return true;
3371   }
3372 }
3373
3374 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3375                                     SDValue V1, SelectionDAG &DAG) {
3376   switch(Opc) {
3377   default: llvm_unreachable("Unknown x86 shuffle node");
3378   case X86ISD::MOVSHDUP:
3379   case X86ISD::MOVSLDUP:
3380   case X86ISD::MOVDDUP:
3381     return DAG.getNode(Opc, dl, VT, V1);
3382   }
3383 }
3384
3385 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3386                                     SDValue V1, unsigned TargetMask,
3387                                     SelectionDAG &DAG) {
3388   switch(Opc) {
3389   default: llvm_unreachable("Unknown x86 shuffle node");
3390   case X86ISD::PSHUFD:
3391   case X86ISD::PSHUFHW:
3392   case X86ISD::PSHUFLW:
3393   case X86ISD::VPERMILP:
3394   case X86ISD::VPERMI:
3395     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3396   }
3397 }
3398
3399 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3400                                     SDValue V1, SDValue V2, unsigned TargetMask,
3401                                     SelectionDAG &DAG) {
3402   switch(Opc) {
3403   default: llvm_unreachable("Unknown x86 shuffle node");
3404   case X86ISD::PALIGNR:
3405   case X86ISD::SHUFP:
3406   case X86ISD::VPERM2X128:
3407     return DAG.getNode(Opc, dl, VT, V1, V2,
3408                        DAG.getConstant(TargetMask, MVT::i8));
3409   }
3410 }
3411
3412 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3413                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3414   switch(Opc) {
3415   default: llvm_unreachable("Unknown x86 shuffle node");
3416   case X86ISD::MOVLHPS:
3417   case X86ISD::MOVLHPD:
3418   case X86ISD::MOVHLPS:
3419   case X86ISD::MOVLPS:
3420   case X86ISD::MOVLPD:
3421   case X86ISD::MOVSS:
3422   case X86ISD::MOVSD:
3423   case X86ISD::UNPCKL:
3424   case X86ISD::UNPCKH:
3425     return DAG.getNode(Opc, dl, VT, V1, V2);
3426   }
3427 }
3428
3429 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3430   MachineFunction &MF = DAG.getMachineFunction();
3431   const X86RegisterInfo *RegInfo =
3432     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
3433   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3434   int ReturnAddrIndex = FuncInfo->getRAIndex();
3435
3436   if (ReturnAddrIndex == 0) {
3437     // Set up a frame object for the return address.
3438     unsigned SlotSize = RegInfo->getSlotSize();
3439     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3440                                                            -(int64_t)SlotSize,
3441                                                            false);
3442     FuncInfo->setRAIndex(ReturnAddrIndex);
3443   }
3444
3445   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3446 }
3447
3448 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3449                                        bool hasSymbolicDisplacement) {
3450   // Offset should fit into 32 bit immediate field.
3451   if (!isInt<32>(Offset))
3452     return false;
3453
3454   // If we don't have a symbolic displacement - we don't have any extra
3455   // restrictions.
3456   if (!hasSymbolicDisplacement)
3457     return true;
3458
3459   // FIXME: Some tweaks might be needed for medium code model.
3460   if (M != CodeModel::Small && M != CodeModel::Kernel)
3461     return false;
3462
3463   // For small code model we assume that latest object is 16MB before end of 31
3464   // bits boundary. We may also accept pretty large negative constants knowing
3465   // that all objects are in the positive half of address space.
3466   if (M == CodeModel::Small && Offset < 16*1024*1024)
3467     return true;
3468
3469   // For kernel code model we know that all object resist in the negative half
3470   // of 32bits address space. We may not accept negative offsets, since they may
3471   // be just off and we may accept pretty large positive ones.
3472   if (M == CodeModel::Kernel && Offset > 0)
3473     return true;
3474
3475   return false;
3476 }
3477
3478 /// isCalleePop - Determines whether the callee is required to pop its
3479 /// own arguments. Callee pop is necessary to support tail calls.
3480 bool X86::isCalleePop(CallingConv::ID CallingConv,
3481                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3482   if (IsVarArg)
3483     return false;
3484
3485   switch (CallingConv) {
3486   default:
3487     return false;
3488   case CallingConv::X86_StdCall:
3489     return !is64Bit;
3490   case CallingConv::X86_FastCall:
3491     return !is64Bit;
3492   case CallingConv::X86_ThisCall:
3493     return !is64Bit;
3494   case CallingConv::Fast:
3495     return TailCallOpt;
3496   case CallingConv::GHC:
3497     return TailCallOpt;
3498   case CallingConv::HiPE:
3499     return TailCallOpt;
3500   }
3501 }
3502
3503 /// \brief Return true if the condition is an unsigned comparison operation.
3504 static bool isX86CCUnsigned(unsigned X86CC) {
3505   switch (X86CC) {
3506   default: llvm_unreachable("Invalid integer condition!");
3507   case X86::COND_E:     return true;
3508   case X86::COND_G:     return false;
3509   case X86::COND_GE:    return false;
3510   case X86::COND_L:     return false;
3511   case X86::COND_LE:    return false;
3512   case X86::COND_NE:    return true;
3513   case X86::COND_B:     return true;
3514   case X86::COND_A:     return true;
3515   case X86::COND_BE:    return true;
3516   case X86::COND_AE:    return true;
3517   }
3518   llvm_unreachable("covered switch fell through?!");
3519 }
3520
3521 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3522 /// specific condition code, returning the condition code and the LHS/RHS of the
3523 /// comparison to make.
3524 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3525                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3526   if (!isFP) {
3527     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3528       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3529         // X > -1   -> X == 0, jump !sign.
3530         RHS = DAG.getConstant(0, RHS.getValueType());
3531         return X86::COND_NS;
3532       }
3533       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3534         // X < 0   -> X == 0, jump on sign.
3535         return X86::COND_S;
3536       }
3537       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3538         // X < 1   -> X <= 0
3539         RHS = DAG.getConstant(0, RHS.getValueType());
3540         return X86::COND_LE;
3541       }
3542     }
3543
3544     switch (SetCCOpcode) {
3545     default: llvm_unreachable("Invalid integer condition!");
3546     case ISD::SETEQ:  return X86::COND_E;
3547     case ISD::SETGT:  return X86::COND_G;
3548     case ISD::SETGE:  return X86::COND_GE;
3549     case ISD::SETLT:  return X86::COND_L;
3550     case ISD::SETLE:  return X86::COND_LE;
3551     case ISD::SETNE:  return X86::COND_NE;
3552     case ISD::SETULT: return X86::COND_B;
3553     case ISD::SETUGT: return X86::COND_A;
3554     case ISD::SETULE: return X86::COND_BE;
3555     case ISD::SETUGE: return X86::COND_AE;
3556     }
3557   }
3558
3559   // First determine if it is required or is profitable to flip the operands.
3560
3561   // If LHS is a foldable load, but RHS is not, flip the condition.
3562   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3563       !ISD::isNON_EXTLoad(RHS.getNode())) {
3564     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3565     std::swap(LHS, RHS);
3566   }
3567
3568   switch (SetCCOpcode) {
3569   default: break;
3570   case ISD::SETOLT:
3571   case ISD::SETOLE:
3572   case ISD::SETUGT:
3573   case ISD::SETUGE:
3574     std::swap(LHS, RHS);
3575     break;
3576   }
3577
3578   // On a floating point condition, the flags are set as follows:
3579   // ZF  PF  CF   op
3580   //  0 | 0 | 0 | X > Y
3581   //  0 | 0 | 1 | X < Y
3582   //  1 | 0 | 0 | X == Y
3583   //  1 | 1 | 1 | unordered
3584   switch (SetCCOpcode) {
3585   default: llvm_unreachable("Condcode should be pre-legalized away");
3586   case ISD::SETUEQ:
3587   case ISD::SETEQ:   return X86::COND_E;
3588   case ISD::SETOLT:              // flipped
3589   case ISD::SETOGT:
3590   case ISD::SETGT:   return X86::COND_A;
3591   case ISD::SETOLE:              // flipped
3592   case ISD::SETOGE:
3593   case ISD::SETGE:   return X86::COND_AE;
3594   case ISD::SETUGT:              // flipped
3595   case ISD::SETULT:
3596   case ISD::SETLT:   return X86::COND_B;
3597   case ISD::SETUGE:              // flipped
3598   case ISD::SETULE:
3599   case ISD::SETLE:   return X86::COND_BE;
3600   case ISD::SETONE:
3601   case ISD::SETNE:   return X86::COND_NE;
3602   case ISD::SETUO:   return X86::COND_P;
3603   case ISD::SETO:    return X86::COND_NP;
3604   case ISD::SETOEQ:
3605   case ISD::SETUNE:  return X86::COND_INVALID;
3606   }
3607 }
3608
3609 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3610 /// code. Current x86 isa includes the following FP cmov instructions:
3611 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3612 static bool hasFPCMov(unsigned X86CC) {
3613   switch (X86CC) {
3614   default:
3615     return false;
3616   case X86::COND_B:
3617   case X86::COND_BE:
3618   case X86::COND_E:
3619   case X86::COND_P:
3620   case X86::COND_A:
3621   case X86::COND_AE:
3622   case X86::COND_NE:
3623   case X86::COND_NP:
3624     return true;
3625   }
3626 }
3627
3628 /// isFPImmLegal - Returns true if the target can instruction select the
3629 /// specified FP immediate natively. If false, the legalizer will
3630 /// materialize the FP immediate as a load from a constant pool.
3631 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3632   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3633     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3634       return true;
3635   }
3636   return false;
3637 }
3638
3639 /// \brief Returns true if it is beneficial to convert a load of a constant
3640 /// to just the constant itself.
3641 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3642                                                           Type *Ty) const {
3643   assert(Ty->isIntegerTy());
3644
3645   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3646   if (BitSize == 0 || BitSize > 64)
3647     return false;
3648   return true;
3649 }
3650
3651 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3652 /// the specified range (L, H].
3653 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3654   return (Val < 0) || (Val >= Low && Val < Hi);
3655 }
3656
3657 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3658 /// specified value.
3659 static bool isUndefOrEqual(int Val, int CmpVal) {
3660   return (Val < 0 || Val == CmpVal);
3661 }
3662
3663 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3664 /// from position Pos and ending in Pos+Size, falls within the specified
3665 /// sequential range (L, L+Pos]. or is undef.
3666 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3667                                        unsigned Pos, unsigned Size, int Low) {
3668   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3669     if (!isUndefOrEqual(Mask[i], Low))
3670       return false;
3671   return true;
3672 }
3673
3674 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3675 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3676 /// the second operand.
3677 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3678   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3679     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3680   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3681     return (Mask[0] < 2 && Mask[1] < 2);
3682   return false;
3683 }
3684
3685 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3686 /// is suitable for input to PSHUFHW.
3687 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3688   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3689     return false;
3690
3691   // Lower quadword copied in order or undef.
3692   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3693     return false;
3694
3695   // Upper quadword shuffled.
3696   for (unsigned i = 4; i != 8; ++i)
3697     if (!isUndefOrInRange(Mask[i], 4, 8))
3698       return false;
3699
3700   if (VT == MVT::v16i16) {
3701     // Lower quadword copied in order or undef.
3702     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3703       return false;
3704
3705     // Upper quadword shuffled.
3706     for (unsigned i = 12; i != 16; ++i)
3707       if (!isUndefOrInRange(Mask[i], 12, 16))
3708         return false;
3709   }
3710
3711   return true;
3712 }
3713
3714 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3715 /// is suitable for input to PSHUFLW.
3716 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3717   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3718     return false;
3719
3720   // Upper quadword copied in order.
3721   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3722     return false;
3723
3724   // Lower quadword shuffled.
3725   for (unsigned i = 0; i != 4; ++i)
3726     if (!isUndefOrInRange(Mask[i], 0, 4))
3727       return false;
3728
3729   if (VT == MVT::v16i16) {
3730     // Upper quadword copied in order.
3731     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3732       return false;
3733
3734     // Lower quadword shuffled.
3735     for (unsigned i = 8; i != 12; ++i)
3736       if (!isUndefOrInRange(Mask[i], 8, 12))
3737         return false;
3738   }
3739
3740   return true;
3741 }
3742
3743 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3744 /// is suitable for input to PALIGNR.
3745 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3746                           const X86Subtarget *Subtarget) {
3747   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3748       (VT.is256BitVector() && !Subtarget->hasInt256()))
3749     return false;
3750
3751   unsigned NumElts = VT.getVectorNumElements();
3752   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3753   unsigned NumLaneElts = NumElts/NumLanes;
3754
3755   // Do not handle 64-bit element shuffles with palignr.
3756   if (NumLaneElts == 2)
3757     return false;
3758
3759   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3760     unsigned i;
3761     for (i = 0; i != NumLaneElts; ++i) {
3762       if (Mask[i+l] >= 0)
3763         break;
3764     }
3765
3766     // Lane is all undef, go to next lane
3767     if (i == NumLaneElts)
3768       continue;
3769
3770     int Start = Mask[i+l];
3771
3772     // Make sure its in this lane in one of the sources
3773     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3774         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3775       return false;
3776
3777     // If not lane 0, then we must match lane 0
3778     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3779       return false;
3780
3781     // Correct second source to be contiguous with first source
3782     if (Start >= (int)NumElts)
3783       Start -= NumElts - NumLaneElts;
3784
3785     // Make sure we're shifting in the right direction.
3786     if (Start <= (int)(i+l))
3787       return false;
3788
3789     Start -= i;
3790
3791     // Check the rest of the elements to see if they are consecutive.
3792     for (++i; i != NumLaneElts; ++i) {
3793       int Idx = Mask[i+l];
3794
3795       // Make sure its in this lane
3796       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3797           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3798         return false;
3799
3800       // If not lane 0, then we must match lane 0
3801       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3802         return false;
3803
3804       if (Idx >= (int)NumElts)
3805         Idx -= NumElts - NumLaneElts;
3806
3807       if (!isUndefOrEqual(Idx, Start+i))
3808         return false;
3809
3810     }
3811   }
3812
3813   return true;
3814 }
3815
3816 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3817 /// the two vector operands have swapped position.
3818 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3819                                      unsigned NumElems) {
3820   for (unsigned i = 0; i != NumElems; ++i) {
3821     int idx = Mask[i];
3822     if (idx < 0)
3823       continue;
3824     else if (idx < (int)NumElems)
3825       Mask[i] = idx + NumElems;
3826     else
3827       Mask[i] = idx - NumElems;
3828   }
3829 }
3830
3831 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3832 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3833 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3834 /// reverse of what x86 shuffles want.
3835 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3836
3837   unsigned NumElems = VT.getVectorNumElements();
3838   unsigned NumLanes = VT.getSizeInBits()/128;
3839   unsigned NumLaneElems = NumElems/NumLanes;
3840
3841   if (NumLaneElems != 2 && NumLaneElems != 4)
3842     return false;
3843
3844   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3845   bool symetricMaskRequired =
3846     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3847
3848   // VSHUFPSY divides the resulting vector into 4 chunks.
3849   // The sources are also splitted into 4 chunks, and each destination
3850   // chunk must come from a different source chunk.
3851   //
3852   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3853   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3854   //
3855   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3856   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3857   //
3858   // VSHUFPDY divides the resulting vector into 4 chunks.
3859   // The sources are also splitted into 4 chunks, and each destination
3860   // chunk must come from a different source chunk.
3861   //
3862   //  SRC1 =>      X3       X2       X1       X0
3863   //  SRC2 =>      Y3       Y2       Y1       Y0
3864   //
3865   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3866   //
3867   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3868   unsigned HalfLaneElems = NumLaneElems/2;
3869   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3870     for (unsigned i = 0; i != NumLaneElems; ++i) {
3871       int Idx = Mask[i+l];
3872       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3873       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3874         return false;
3875       // For VSHUFPSY, the mask of the second half must be the same as the
3876       // first but with the appropriate offsets. This works in the same way as
3877       // VPERMILPS works with masks.
3878       if (!symetricMaskRequired || Idx < 0)
3879         continue;
3880       if (MaskVal[i] < 0) {
3881         MaskVal[i] = Idx - l;
3882         continue;
3883       }
3884       if ((signed)(Idx - l) != MaskVal[i])
3885         return false;
3886     }
3887   }
3888
3889   return true;
3890 }
3891
3892 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3893 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3894 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3895   if (!VT.is128BitVector())
3896     return false;
3897
3898   unsigned NumElems = VT.getVectorNumElements();
3899
3900   if (NumElems != 4)
3901     return false;
3902
3903   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3904   return isUndefOrEqual(Mask[0], 6) &&
3905          isUndefOrEqual(Mask[1], 7) &&
3906          isUndefOrEqual(Mask[2], 2) &&
3907          isUndefOrEqual(Mask[3], 3);
3908 }
3909
3910 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3911 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3912 /// <2, 3, 2, 3>
3913 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3914   if (!VT.is128BitVector())
3915     return false;
3916
3917   unsigned NumElems = VT.getVectorNumElements();
3918
3919   if (NumElems != 4)
3920     return false;
3921
3922   return isUndefOrEqual(Mask[0], 2) &&
3923          isUndefOrEqual(Mask[1], 3) &&
3924          isUndefOrEqual(Mask[2], 2) &&
3925          isUndefOrEqual(Mask[3], 3);
3926 }
3927
3928 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3929 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3930 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3931   if (!VT.is128BitVector())
3932     return false;
3933
3934   unsigned NumElems = VT.getVectorNumElements();
3935
3936   if (NumElems != 2 && NumElems != 4)
3937     return false;
3938
3939   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3940     if (!isUndefOrEqual(Mask[i], i + NumElems))
3941       return false;
3942
3943   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3944     if (!isUndefOrEqual(Mask[i], i))
3945       return false;
3946
3947   return true;
3948 }
3949
3950 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3951 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3952 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3953   if (!VT.is128BitVector())
3954     return false;
3955
3956   unsigned NumElems = VT.getVectorNumElements();
3957
3958   if (NumElems != 2 && NumElems != 4)
3959     return false;
3960
3961   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3962     if (!isUndefOrEqual(Mask[i], i))
3963       return false;
3964
3965   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3966     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3967       return false;
3968
3969   return true;
3970 }
3971
3972 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3973 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3974 /// i. e: If all but one element come from the same vector.
3975 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3976   // TODO: Deal with AVX's VINSERTPS
3977   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3978     return false;
3979
3980   unsigned CorrectPosV1 = 0;
3981   unsigned CorrectPosV2 = 0;
3982   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i) {
3983     if (Mask[i] == -1) {
3984       ++CorrectPosV1;
3985       ++CorrectPosV2;
3986       continue;
3987     }
3988
3989     if (Mask[i] == i)
3990       ++CorrectPosV1;
3991     else if (Mask[i] == i + 4)
3992       ++CorrectPosV2;
3993   }
3994
3995   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3996     // We have 3 elements (undefs count as elements from any vector) from one
3997     // vector, and one from another.
3998     return true;
3999
4000   return false;
4001 }
4002
4003 //
4004 // Some special combinations that can be optimized.
4005 //
4006 static
4007 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
4008                                SelectionDAG &DAG) {
4009   MVT VT = SVOp->getSimpleValueType(0);
4010   SDLoc dl(SVOp);
4011
4012   if (VT != MVT::v8i32 && VT != MVT::v8f32)
4013     return SDValue();
4014
4015   ArrayRef<int> Mask = SVOp->getMask();
4016
4017   // These are the special masks that may be optimized.
4018   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
4019   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
4020   bool MatchEvenMask = true;
4021   bool MatchOddMask  = true;
4022   for (int i=0; i<8; ++i) {
4023     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4024       MatchEvenMask = false;
4025     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4026       MatchOddMask = false;
4027   }
4028
4029   if (!MatchEvenMask && !MatchOddMask)
4030     return SDValue();
4031
4032   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4033
4034   SDValue Op0 = SVOp->getOperand(0);
4035   SDValue Op1 = SVOp->getOperand(1);
4036
4037   if (MatchEvenMask) {
4038     // Shift the second operand right to 32 bits.
4039     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4040     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4041   } else {
4042     // Shift the first operand left to 32 bits.
4043     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4044     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4045   }
4046   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4047   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4048 }
4049
4050 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4051 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4052 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4053                          bool HasInt256, bool V2IsSplat = false) {
4054
4055   assert(VT.getSizeInBits() >= 128 &&
4056          "Unsupported vector type for unpckl");
4057
4058   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4059   unsigned NumLanes;
4060   unsigned NumOf256BitLanes;
4061   unsigned NumElts = VT.getVectorNumElements();
4062   if (VT.is256BitVector()) {
4063     if (NumElts != 4 && NumElts != 8 &&
4064         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4065     return false;
4066     NumLanes = 2;
4067     NumOf256BitLanes = 1;
4068   } else if (VT.is512BitVector()) {
4069     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4070            "Unsupported vector type for unpckh");
4071     NumLanes = 2;
4072     NumOf256BitLanes = 2;
4073   } else {
4074     NumLanes = 1;
4075     NumOf256BitLanes = 1;
4076   }
4077
4078   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4079   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4080
4081   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4082     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4083       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4084         int BitI  = Mask[l256*NumEltsInStride+l+i];
4085         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4086         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4087           return false;
4088         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4089           return false;
4090         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4091           return false;
4092       }
4093     }
4094   }
4095   return true;
4096 }
4097
4098 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4099 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4100 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4101                          bool HasInt256, bool V2IsSplat = false) {
4102   assert(VT.getSizeInBits() >= 128 &&
4103          "Unsupported vector type for unpckh");
4104
4105   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4106   unsigned NumLanes;
4107   unsigned NumOf256BitLanes;
4108   unsigned NumElts = VT.getVectorNumElements();
4109   if (VT.is256BitVector()) {
4110     if (NumElts != 4 && NumElts != 8 &&
4111         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4112     return false;
4113     NumLanes = 2;
4114     NumOf256BitLanes = 1;
4115   } else if (VT.is512BitVector()) {
4116     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4117            "Unsupported vector type for unpckh");
4118     NumLanes = 2;
4119     NumOf256BitLanes = 2;
4120   } else {
4121     NumLanes = 1;
4122     NumOf256BitLanes = 1;
4123   }
4124
4125   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4126   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4127
4128   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4129     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4130       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4131         int BitI  = Mask[l256*NumEltsInStride+l+i];
4132         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4133         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4134           return false;
4135         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4136           return false;
4137         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4138           return false;
4139       }
4140     }
4141   }
4142   return true;
4143 }
4144
4145 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4146 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4147 /// <0, 0, 1, 1>
4148 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4149   unsigned NumElts = VT.getVectorNumElements();
4150   bool Is256BitVec = VT.is256BitVector();
4151
4152   if (VT.is512BitVector())
4153     return false;
4154   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4155          "Unsupported vector type for unpckh");
4156
4157   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4158       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4159     return false;
4160
4161   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4162   // FIXME: Need a better way to get rid of this, there's no latency difference
4163   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4164   // the former later. We should also remove the "_undef" special mask.
4165   if (NumElts == 4 && Is256BitVec)
4166     return false;
4167
4168   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4169   // independently on 128-bit lanes.
4170   unsigned NumLanes = VT.getSizeInBits()/128;
4171   unsigned NumLaneElts = NumElts/NumLanes;
4172
4173   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4174     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4175       int BitI  = Mask[l+i];
4176       int BitI1 = Mask[l+i+1];
4177
4178       if (!isUndefOrEqual(BitI, j))
4179         return false;
4180       if (!isUndefOrEqual(BitI1, j))
4181         return false;
4182     }
4183   }
4184
4185   return true;
4186 }
4187
4188 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4189 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4190 /// <2, 2, 3, 3>
4191 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4192   unsigned NumElts = VT.getVectorNumElements();
4193
4194   if (VT.is512BitVector())
4195     return false;
4196
4197   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4198          "Unsupported vector type for unpckh");
4199
4200   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4201       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4202     return false;
4203
4204   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4205   // independently on 128-bit lanes.
4206   unsigned NumLanes = VT.getSizeInBits()/128;
4207   unsigned NumLaneElts = NumElts/NumLanes;
4208
4209   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4210     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4211       int BitI  = Mask[l+i];
4212       int BitI1 = Mask[l+i+1];
4213       if (!isUndefOrEqual(BitI, j))
4214         return false;
4215       if (!isUndefOrEqual(BitI1, j))
4216         return false;
4217     }
4218   }
4219   return true;
4220 }
4221
4222 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4223 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4224 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4225   if (!VT.is512BitVector())
4226     return false;
4227
4228   unsigned NumElts = VT.getVectorNumElements();
4229   unsigned HalfSize = NumElts/2;
4230   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4231     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4232       *Imm = 1;
4233       return true;
4234     }
4235   }
4236   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4237     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4238       *Imm = 0;
4239       return true;
4240     }
4241   }
4242   return false;
4243 }
4244
4245 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4246 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4247 /// MOVSD, and MOVD, i.e. setting the lowest element.
4248 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4249   if (VT.getVectorElementType().getSizeInBits() < 32)
4250     return false;
4251   if (!VT.is128BitVector())
4252     return false;
4253
4254   unsigned NumElts = VT.getVectorNumElements();
4255
4256   if (!isUndefOrEqual(Mask[0], NumElts))
4257     return false;
4258
4259   for (unsigned i = 1; i != NumElts; ++i)
4260     if (!isUndefOrEqual(Mask[i], i))
4261       return false;
4262
4263   return true;
4264 }
4265
4266 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4267 /// as permutations between 128-bit chunks or halves. As an example: this
4268 /// shuffle bellow:
4269 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4270 /// The first half comes from the second half of V1 and the second half from the
4271 /// the second half of V2.
4272 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4273   if (!HasFp256 || !VT.is256BitVector())
4274     return false;
4275
4276   // The shuffle result is divided into half A and half B. In total the two
4277   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4278   // B must come from C, D, E or F.
4279   unsigned HalfSize = VT.getVectorNumElements()/2;
4280   bool MatchA = false, MatchB = false;
4281
4282   // Check if A comes from one of C, D, E, F.
4283   for (unsigned Half = 0; Half != 4; ++Half) {
4284     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4285       MatchA = true;
4286       break;
4287     }
4288   }
4289
4290   // Check if B comes from one of C, D, E, F.
4291   for (unsigned Half = 0; Half != 4; ++Half) {
4292     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4293       MatchB = true;
4294       break;
4295     }
4296   }
4297
4298   return MatchA && MatchB;
4299 }
4300
4301 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4302 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4303 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4304   MVT VT = SVOp->getSimpleValueType(0);
4305
4306   unsigned HalfSize = VT.getVectorNumElements()/2;
4307
4308   unsigned FstHalf = 0, SndHalf = 0;
4309   for (unsigned i = 0; i < HalfSize; ++i) {
4310     if (SVOp->getMaskElt(i) > 0) {
4311       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4312       break;
4313     }
4314   }
4315   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4316     if (SVOp->getMaskElt(i) > 0) {
4317       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4318       break;
4319     }
4320   }
4321
4322   return (FstHalf | (SndHalf << 4));
4323 }
4324
4325 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4326 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4327   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4328   if (EltSize < 32)
4329     return false;
4330
4331   unsigned NumElts = VT.getVectorNumElements();
4332   Imm8 = 0;
4333   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4334     for (unsigned i = 0; i != NumElts; ++i) {
4335       if (Mask[i] < 0)
4336         continue;
4337       Imm8 |= Mask[i] << (i*2);
4338     }
4339     return true;
4340   }
4341
4342   unsigned LaneSize = 4;
4343   SmallVector<int, 4> MaskVal(LaneSize, -1);
4344
4345   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4346     for (unsigned i = 0; i != LaneSize; ++i) {
4347       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4348         return false;
4349       if (Mask[i+l] < 0)
4350         continue;
4351       if (MaskVal[i] < 0) {
4352         MaskVal[i] = Mask[i+l] - l;
4353         Imm8 |= MaskVal[i] << (i*2);
4354         continue;
4355       }
4356       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4357         return false;
4358     }
4359   }
4360   return true;
4361 }
4362
4363 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4364 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4365 /// Note that VPERMIL mask matching is different depending whether theunderlying
4366 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4367 /// to the same elements of the low, but to the higher half of the source.
4368 /// In VPERMILPD the two lanes could be shuffled independently of each other
4369 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4370 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4371   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4372   if (VT.getSizeInBits() < 256 || EltSize < 32)
4373     return false;
4374   bool symetricMaskRequired = (EltSize == 32);
4375   unsigned NumElts = VT.getVectorNumElements();
4376
4377   unsigned NumLanes = VT.getSizeInBits()/128;
4378   unsigned LaneSize = NumElts/NumLanes;
4379   // 2 or 4 elements in one lane
4380
4381   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4382   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4383     for (unsigned i = 0; i != LaneSize; ++i) {
4384       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4385         return false;
4386       if (symetricMaskRequired) {
4387         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4388           ExpectedMaskVal[i] = Mask[i+l] - l;
4389           continue;
4390         }
4391         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4392           return false;
4393       }
4394     }
4395   }
4396   return true;
4397 }
4398
4399 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4400 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4401 /// element of vector 2 and the other elements to come from vector 1 in order.
4402 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4403                                bool V2IsSplat = false, bool V2IsUndef = false) {
4404   if (!VT.is128BitVector())
4405     return false;
4406
4407   unsigned NumOps = VT.getVectorNumElements();
4408   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4409     return false;
4410
4411   if (!isUndefOrEqual(Mask[0], 0))
4412     return false;
4413
4414   for (unsigned i = 1; i != NumOps; ++i)
4415     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4416           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4417           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4418       return false;
4419
4420   return true;
4421 }
4422
4423 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4424 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4425 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4426 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4427                            const X86Subtarget *Subtarget) {
4428   if (!Subtarget->hasSSE3())
4429     return false;
4430
4431   unsigned NumElems = VT.getVectorNumElements();
4432
4433   if ((VT.is128BitVector() && NumElems != 4) ||
4434       (VT.is256BitVector() && NumElems != 8) ||
4435       (VT.is512BitVector() && NumElems != 16))
4436     return false;
4437
4438   // "i+1" is the value the indexed mask element must have
4439   for (unsigned i = 0; i != NumElems; i += 2)
4440     if (!isUndefOrEqual(Mask[i], i+1) ||
4441         !isUndefOrEqual(Mask[i+1], i+1))
4442       return false;
4443
4444   return true;
4445 }
4446
4447 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4448 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4449 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4450 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4451                            const X86Subtarget *Subtarget) {
4452   if (!Subtarget->hasSSE3())
4453     return false;
4454
4455   unsigned NumElems = VT.getVectorNumElements();
4456
4457   if ((VT.is128BitVector() && NumElems != 4) ||
4458       (VT.is256BitVector() && NumElems != 8) ||
4459       (VT.is512BitVector() && NumElems != 16))
4460     return false;
4461
4462   // "i" is the value the indexed mask element must have
4463   for (unsigned i = 0; i != NumElems; i += 2)
4464     if (!isUndefOrEqual(Mask[i], i) ||
4465         !isUndefOrEqual(Mask[i+1], i))
4466       return false;
4467
4468   return true;
4469 }
4470
4471 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4472 /// specifies a shuffle of elements that is suitable for input to 256-bit
4473 /// version of MOVDDUP.
4474 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4475   if (!HasFp256 || !VT.is256BitVector())
4476     return false;
4477
4478   unsigned NumElts = VT.getVectorNumElements();
4479   if (NumElts != 4)
4480     return false;
4481
4482   for (unsigned i = 0; i != NumElts/2; ++i)
4483     if (!isUndefOrEqual(Mask[i], 0))
4484       return false;
4485   for (unsigned i = NumElts/2; i != NumElts; ++i)
4486     if (!isUndefOrEqual(Mask[i], NumElts/2))
4487       return false;
4488   return true;
4489 }
4490
4491 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4492 /// specifies a shuffle of elements that is suitable for input to 128-bit
4493 /// version of MOVDDUP.
4494 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4495   if (!VT.is128BitVector())
4496     return false;
4497
4498   unsigned e = VT.getVectorNumElements() / 2;
4499   for (unsigned i = 0; i != e; ++i)
4500     if (!isUndefOrEqual(Mask[i], i))
4501       return false;
4502   for (unsigned i = 0; i != e; ++i)
4503     if (!isUndefOrEqual(Mask[e+i], i))
4504       return false;
4505   return true;
4506 }
4507
4508 /// isVEXTRACTIndex - Return true if the specified
4509 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4510 /// suitable for instruction that extract 128 or 256 bit vectors
4511 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4512   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4513   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4514     return false;
4515
4516   // The index should be aligned on a vecWidth-bit boundary.
4517   uint64_t Index =
4518     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4519
4520   MVT VT = N->getSimpleValueType(0);
4521   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4522   bool Result = (Index * ElSize) % vecWidth == 0;
4523
4524   return Result;
4525 }
4526
4527 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4528 /// operand specifies a subvector insert that is suitable for input to
4529 /// insertion of 128 or 256-bit subvectors
4530 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4531   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4532   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4533     return false;
4534   // The index should be aligned on a vecWidth-bit boundary.
4535   uint64_t Index =
4536     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4537
4538   MVT VT = N->getSimpleValueType(0);
4539   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4540   bool Result = (Index * ElSize) % vecWidth == 0;
4541
4542   return Result;
4543 }
4544
4545 bool X86::isVINSERT128Index(SDNode *N) {
4546   return isVINSERTIndex(N, 128);
4547 }
4548
4549 bool X86::isVINSERT256Index(SDNode *N) {
4550   return isVINSERTIndex(N, 256);
4551 }
4552
4553 bool X86::isVEXTRACT128Index(SDNode *N) {
4554   return isVEXTRACTIndex(N, 128);
4555 }
4556
4557 bool X86::isVEXTRACT256Index(SDNode *N) {
4558   return isVEXTRACTIndex(N, 256);
4559 }
4560
4561 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4562 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4563 /// Handles 128-bit and 256-bit.
4564 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4565   MVT VT = N->getSimpleValueType(0);
4566
4567   assert((VT.getSizeInBits() >= 128) &&
4568          "Unsupported vector type for PSHUF/SHUFP");
4569
4570   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4571   // independently on 128-bit lanes.
4572   unsigned NumElts = VT.getVectorNumElements();
4573   unsigned NumLanes = VT.getSizeInBits()/128;
4574   unsigned NumLaneElts = NumElts/NumLanes;
4575
4576   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4577          "Only supports 2, 4 or 8 elements per lane");
4578
4579   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4580   unsigned Mask = 0;
4581   for (unsigned i = 0; i != NumElts; ++i) {
4582     int Elt = N->getMaskElt(i);
4583     if (Elt < 0) continue;
4584     Elt &= NumLaneElts - 1;
4585     unsigned ShAmt = (i << Shift) % 8;
4586     Mask |= Elt << ShAmt;
4587   }
4588
4589   return Mask;
4590 }
4591
4592 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4593 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4594 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4595   MVT VT = N->getSimpleValueType(0);
4596
4597   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4598          "Unsupported vector type for PSHUFHW");
4599
4600   unsigned NumElts = VT.getVectorNumElements();
4601
4602   unsigned Mask = 0;
4603   for (unsigned l = 0; l != NumElts; l += 8) {
4604     // 8 nodes per lane, but we only care about the last 4.
4605     for (unsigned i = 0; i < 4; ++i) {
4606       int Elt = N->getMaskElt(l+i+4);
4607       if (Elt < 0) continue;
4608       Elt &= 0x3; // only 2-bits.
4609       Mask |= Elt << (i * 2);
4610     }
4611   }
4612
4613   return Mask;
4614 }
4615
4616 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4617 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4618 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4619   MVT VT = N->getSimpleValueType(0);
4620
4621   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4622          "Unsupported vector type for PSHUFHW");
4623
4624   unsigned NumElts = VT.getVectorNumElements();
4625
4626   unsigned Mask = 0;
4627   for (unsigned l = 0; l != NumElts; l += 8) {
4628     // 8 nodes per lane, but we only care about the first 4.
4629     for (unsigned i = 0; i < 4; ++i) {
4630       int Elt = N->getMaskElt(l+i);
4631       if (Elt < 0) continue;
4632       Elt &= 0x3; // only 2-bits
4633       Mask |= Elt << (i * 2);
4634     }
4635   }
4636
4637   return Mask;
4638 }
4639
4640 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4641 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4642 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4643   MVT VT = SVOp->getSimpleValueType(0);
4644   unsigned EltSize = VT.is512BitVector() ? 1 :
4645     VT.getVectorElementType().getSizeInBits() >> 3;
4646
4647   unsigned NumElts = VT.getVectorNumElements();
4648   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4649   unsigned NumLaneElts = NumElts/NumLanes;
4650
4651   int Val = 0;
4652   unsigned i;
4653   for (i = 0; i != NumElts; ++i) {
4654     Val = SVOp->getMaskElt(i);
4655     if (Val >= 0)
4656       break;
4657   }
4658   if (Val >= (int)NumElts)
4659     Val -= NumElts - NumLaneElts;
4660
4661   assert(Val - i > 0 && "PALIGNR imm should be positive");
4662   return (Val - i) * EltSize;
4663 }
4664
4665 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4666   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4667   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4668     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4669
4670   uint64_t Index =
4671     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4672
4673   MVT VecVT = N->getOperand(0).getSimpleValueType();
4674   MVT ElVT = VecVT.getVectorElementType();
4675
4676   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4677   return Index / NumElemsPerChunk;
4678 }
4679
4680 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4681   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4682   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4683     llvm_unreachable("Illegal insert subvector for VINSERT");
4684
4685   uint64_t Index =
4686     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4687
4688   MVT VecVT = N->getSimpleValueType(0);
4689   MVT ElVT = VecVT.getVectorElementType();
4690
4691   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4692   return Index / NumElemsPerChunk;
4693 }
4694
4695 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4696 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4697 /// and VINSERTI128 instructions.
4698 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4699   return getExtractVEXTRACTImmediate(N, 128);
4700 }
4701
4702 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4703 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4704 /// and VINSERTI64x4 instructions.
4705 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4706   return getExtractVEXTRACTImmediate(N, 256);
4707 }
4708
4709 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4710 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4711 /// and VINSERTI128 instructions.
4712 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4713   return getInsertVINSERTImmediate(N, 128);
4714 }
4715
4716 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4717 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4718 /// and VINSERTI64x4 instructions.
4719 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4720   return getInsertVINSERTImmediate(N, 256);
4721 }
4722
4723 /// isZero - Returns true if Elt is a constant integer zero
4724 static bool isZero(SDValue V) {
4725   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4726   return C && C->isNullValue();
4727 }
4728
4729 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4730 /// constant +0.0.
4731 bool X86::isZeroNode(SDValue Elt) {
4732   if (isZero(Elt))
4733     return true;
4734   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4735     return CFP->getValueAPF().isPosZero();
4736   return false;
4737 }
4738
4739 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4740 /// their permute mask.
4741 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4742                                     SelectionDAG &DAG) {
4743   MVT VT = SVOp->getSimpleValueType(0);
4744   unsigned NumElems = VT.getVectorNumElements();
4745   SmallVector<int, 8> MaskVec;
4746
4747   for (unsigned i = 0; i != NumElems; ++i) {
4748     int Idx = SVOp->getMaskElt(i);
4749     if (Idx >= 0) {
4750       if (Idx < (int)NumElems)
4751         Idx += NumElems;
4752       else
4753         Idx -= NumElems;
4754     }
4755     MaskVec.push_back(Idx);
4756   }
4757   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4758                               SVOp->getOperand(0), &MaskVec[0]);
4759 }
4760
4761 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4762 /// match movhlps. The lower half elements should come from upper half of
4763 /// V1 (and in order), and the upper half elements should come from the upper
4764 /// half of V2 (and in order).
4765 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4766   if (!VT.is128BitVector())
4767     return false;
4768   if (VT.getVectorNumElements() != 4)
4769     return false;
4770   for (unsigned i = 0, e = 2; i != e; ++i)
4771     if (!isUndefOrEqual(Mask[i], i+2))
4772       return false;
4773   for (unsigned i = 2; i != 4; ++i)
4774     if (!isUndefOrEqual(Mask[i], i+4))
4775       return false;
4776   return true;
4777 }
4778
4779 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4780 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4781 /// required.
4782 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4783   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4784     return false;
4785   N = N->getOperand(0).getNode();
4786   if (!ISD::isNON_EXTLoad(N))
4787     return false;
4788   if (LD)
4789     *LD = cast<LoadSDNode>(N);
4790   return true;
4791 }
4792
4793 // Test whether the given value is a vector value which will be legalized
4794 // into a load.
4795 static bool WillBeConstantPoolLoad(SDNode *N) {
4796   if (N->getOpcode() != ISD::BUILD_VECTOR)
4797     return false;
4798
4799   // Check for any non-constant elements.
4800   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4801     switch (N->getOperand(i).getNode()->getOpcode()) {
4802     case ISD::UNDEF:
4803     case ISD::ConstantFP:
4804     case ISD::Constant:
4805       break;
4806     default:
4807       return false;
4808     }
4809
4810   // Vectors of all-zeros and all-ones are materialized with special
4811   // instructions rather than being loaded.
4812   return !ISD::isBuildVectorAllZeros(N) &&
4813          !ISD::isBuildVectorAllOnes(N);
4814 }
4815
4816 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4817 /// match movlp{s|d}. The lower half elements should come from lower half of
4818 /// V1 (and in order), and the upper half elements should come from the upper
4819 /// half of V2 (and in order). And since V1 will become the source of the
4820 /// MOVLP, it must be either a vector load or a scalar load to vector.
4821 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4822                                ArrayRef<int> Mask, MVT VT) {
4823   if (!VT.is128BitVector())
4824     return false;
4825
4826   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4827     return false;
4828   // Is V2 is a vector load, don't do this transformation. We will try to use
4829   // load folding shufps op.
4830   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4831     return false;
4832
4833   unsigned NumElems = VT.getVectorNumElements();
4834
4835   if (NumElems != 2 && NumElems != 4)
4836     return false;
4837   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4838     if (!isUndefOrEqual(Mask[i], i))
4839       return false;
4840   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4841     if (!isUndefOrEqual(Mask[i], i+NumElems))
4842       return false;
4843   return true;
4844 }
4845
4846 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4847 /// all the same.
4848 static bool isSplatVector(SDNode *N) {
4849   if (N->getOpcode() != ISD::BUILD_VECTOR)
4850     return false;
4851
4852   SDValue SplatValue = N->getOperand(0);
4853   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4854     if (N->getOperand(i) != SplatValue)
4855       return false;
4856   return true;
4857 }
4858
4859 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4860 /// to an zero vector.
4861 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4862 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4863   SDValue V1 = N->getOperand(0);
4864   SDValue V2 = N->getOperand(1);
4865   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4866   for (unsigned i = 0; i != NumElems; ++i) {
4867     int Idx = N->getMaskElt(i);
4868     if (Idx >= (int)NumElems) {
4869       unsigned Opc = V2.getOpcode();
4870       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4871         continue;
4872       if (Opc != ISD::BUILD_VECTOR ||
4873           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4874         return false;
4875     } else if (Idx >= 0) {
4876       unsigned Opc = V1.getOpcode();
4877       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4878         continue;
4879       if (Opc != ISD::BUILD_VECTOR ||
4880           !X86::isZeroNode(V1.getOperand(Idx)))
4881         return false;
4882     }
4883   }
4884   return true;
4885 }
4886
4887 /// getZeroVector - Returns a vector of specified type with all zero elements.
4888 ///
4889 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4890                              SelectionDAG &DAG, SDLoc dl) {
4891   assert(VT.isVector() && "Expected a vector type");
4892
4893   // Always build SSE zero vectors as <4 x i32> bitcasted
4894   // to their dest type. This ensures they get CSE'd.
4895   SDValue Vec;
4896   if (VT.is128BitVector()) {  // SSE
4897     if (Subtarget->hasSSE2()) {  // SSE2
4898       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4899       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4900     } else { // SSE1
4901       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4902       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4903     }
4904   } else if (VT.is256BitVector()) { // AVX
4905     if (Subtarget->hasInt256()) { // AVX2
4906       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4907       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4908       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4909     } else {
4910       // 256-bit logic and arithmetic instructions in AVX are all
4911       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4912       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4913       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4914       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4915     }
4916   } else if (VT.is512BitVector()) { // AVX-512
4917       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4918       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4919                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4920       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4921   } else if (VT.getScalarType() == MVT::i1) {
4922     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4923     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4924     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4925     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4926   } else
4927     llvm_unreachable("Unexpected vector type");
4928
4929   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4930 }
4931
4932 /// getOnesVector - Returns a vector of specified type with all bits set.
4933 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4934 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4935 /// Then bitcast to their original type, ensuring they get CSE'd.
4936 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4937                              SDLoc dl) {
4938   assert(VT.isVector() && "Expected a vector type");
4939
4940   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4941   SDValue Vec;
4942   if (VT.is256BitVector()) {
4943     if (HasInt256) { // AVX2
4944       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4945       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4946     } else { // AVX
4947       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4948       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4949     }
4950   } else if (VT.is128BitVector()) {
4951     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4952   } else
4953     llvm_unreachable("Unexpected vector type");
4954
4955   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4956 }
4957
4958 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4959 /// that point to V2 points to its first element.
4960 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4961   for (unsigned i = 0; i != NumElems; ++i) {
4962     if (Mask[i] > (int)NumElems) {
4963       Mask[i] = NumElems;
4964     }
4965   }
4966 }
4967
4968 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4969 /// operation of specified width.
4970 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4971                        SDValue V2) {
4972   unsigned NumElems = VT.getVectorNumElements();
4973   SmallVector<int, 8> Mask;
4974   Mask.push_back(NumElems);
4975   for (unsigned i = 1; i != NumElems; ++i)
4976     Mask.push_back(i);
4977   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4978 }
4979
4980 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4981 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4982                           SDValue V2) {
4983   unsigned NumElems = VT.getVectorNumElements();
4984   SmallVector<int, 8> Mask;
4985   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4986     Mask.push_back(i);
4987     Mask.push_back(i + NumElems);
4988   }
4989   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4990 }
4991
4992 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4993 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4994                           SDValue V2) {
4995   unsigned NumElems = VT.getVectorNumElements();
4996   SmallVector<int, 8> Mask;
4997   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4998     Mask.push_back(i + Half);
4999     Mask.push_back(i + NumElems + Half);
5000   }
5001   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
5002 }
5003
5004 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
5005 // a generic shuffle instruction because the target has no such instructions.
5006 // Generate shuffles which repeat i16 and i8 several times until they can be
5007 // represented by v4f32 and then be manipulated by target suported shuffles.
5008 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
5009   MVT VT = V.getSimpleValueType();
5010   int NumElems = VT.getVectorNumElements();
5011   SDLoc dl(V);
5012
5013   while (NumElems > 4) {
5014     if (EltNo < NumElems/2) {
5015       V = getUnpackl(DAG, dl, VT, V, V);
5016     } else {
5017       V = getUnpackh(DAG, dl, VT, V, V);
5018       EltNo -= NumElems/2;
5019     }
5020     NumElems >>= 1;
5021   }
5022   return V;
5023 }
5024
5025 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5026 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5027   MVT VT = V.getSimpleValueType();
5028   SDLoc dl(V);
5029
5030   if (VT.is128BitVector()) {
5031     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5032     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5033     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5034                              &SplatMask[0]);
5035   } else if (VT.is256BitVector()) {
5036     // To use VPERMILPS to splat scalars, the second half of indicies must
5037     // refer to the higher part, which is a duplication of the lower one,
5038     // because VPERMILPS can only handle in-lane permutations.
5039     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5040                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5041
5042     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5043     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5044                              &SplatMask[0]);
5045   } else
5046     llvm_unreachable("Vector size not supported");
5047
5048   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5049 }
5050
5051 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5052 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5053   MVT SrcVT = SV->getSimpleValueType(0);
5054   SDValue V1 = SV->getOperand(0);
5055   SDLoc dl(SV);
5056
5057   int EltNo = SV->getSplatIndex();
5058   int NumElems = SrcVT.getVectorNumElements();
5059   bool Is256BitVec = SrcVT.is256BitVector();
5060
5061   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5062          "Unknown how to promote splat for type");
5063
5064   // Extract the 128-bit part containing the splat element and update
5065   // the splat element index when it refers to the higher register.
5066   if (Is256BitVec) {
5067     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5068     if (EltNo >= NumElems/2)
5069       EltNo -= NumElems/2;
5070   }
5071
5072   // All i16 and i8 vector types can't be used directly by a generic shuffle
5073   // instruction because the target has no such instruction. Generate shuffles
5074   // which repeat i16 and i8 several times until they fit in i32, and then can
5075   // be manipulated by target suported shuffles.
5076   MVT EltVT = SrcVT.getVectorElementType();
5077   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5078     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5079
5080   // Recreate the 256-bit vector and place the same 128-bit vector
5081   // into the low and high part. This is necessary because we want
5082   // to use VPERM* to shuffle the vectors
5083   if (Is256BitVec) {
5084     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5085   }
5086
5087   return getLegalSplat(DAG, V1, EltNo);
5088 }
5089
5090 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5091 /// vector of zero or undef vector.  This produces a shuffle where the low
5092 /// element of V2 is swizzled into the zero/undef vector, landing at element
5093 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5094 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5095                                            bool IsZero,
5096                                            const X86Subtarget *Subtarget,
5097                                            SelectionDAG &DAG) {
5098   MVT VT = V2.getSimpleValueType();
5099   SDValue V1 = IsZero
5100     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5101   unsigned NumElems = VT.getVectorNumElements();
5102   SmallVector<int, 16> MaskVec;
5103   for (unsigned i = 0; i != NumElems; ++i)
5104     // If this is the insertion idx, put the low elt of V2 here.
5105     MaskVec.push_back(i == Idx ? NumElems : i);
5106   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5107 }
5108
5109 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5110 /// target specific opcode. Returns true if the Mask could be calculated.
5111 /// Sets IsUnary to true if only uses one source.
5112 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5113                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5114   unsigned NumElems = VT.getVectorNumElements();
5115   SDValue ImmN;
5116
5117   IsUnary = false;
5118   switch(N->getOpcode()) {
5119   case X86ISD::SHUFP:
5120     ImmN = N->getOperand(N->getNumOperands()-1);
5121     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5122     break;
5123   case X86ISD::UNPCKH:
5124     DecodeUNPCKHMask(VT, Mask);
5125     break;
5126   case X86ISD::UNPCKL:
5127     DecodeUNPCKLMask(VT, Mask);
5128     break;
5129   case X86ISD::MOVHLPS:
5130     DecodeMOVHLPSMask(NumElems, Mask);
5131     break;
5132   case X86ISD::MOVLHPS:
5133     DecodeMOVLHPSMask(NumElems, Mask);
5134     break;
5135   case X86ISD::PALIGNR:
5136     ImmN = N->getOperand(N->getNumOperands()-1);
5137     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5138     break;
5139   case X86ISD::PSHUFD:
5140   case X86ISD::VPERMILP:
5141     ImmN = N->getOperand(N->getNumOperands()-1);
5142     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5143     IsUnary = true;
5144     break;
5145   case X86ISD::PSHUFHW:
5146     ImmN = N->getOperand(N->getNumOperands()-1);
5147     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5148     IsUnary = true;
5149     break;
5150   case X86ISD::PSHUFLW:
5151     ImmN = N->getOperand(N->getNumOperands()-1);
5152     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5153     IsUnary = true;
5154     break;
5155   case X86ISD::VPERMI:
5156     ImmN = N->getOperand(N->getNumOperands()-1);
5157     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5158     IsUnary = true;
5159     break;
5160   case X86ISD::MOVSS:
5161   case X86ISD::MOVSD: {
5162     // The index 0 always comes from the first element of the second source,
5163     // this is why MOVSS and MOVSD are used in the first place. The other
5164     // elements come from the other positions of the first source vector
5165     Mask.push_back(NumElems);
5166     for (unsigned i = 1; i != NumElems; ++i) {
5167       Mask.push_back(i);
5168     }
5169     break;
5170   }
5171   case X86ISD::VPERM2X128:
5172     ImmN = N->getOperand(N->getNumOperands()-1);
5173     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5174     if (Mask.empty()) return false;
5175     break;
5176   case X86ISD::MOVDDUP:
5177   case X86ISD::MOVLHPD:
5178   case X86ISD::MOVLPD:
5179   case X86ISD::MOVLPS:
5180   case X86ISD::MOVSHDUP:
5181   case X86ISD::MOVSLDUP:
5182     // Not yet implemented
5183     return false;
5184   default: llvm_unreachable("unknown target shuffle node");
5185   }
5186
5187   return true;
5188 }
5189
5190 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5191 /// element of the result of the vector shuffle.
5192 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5193                                    unsigned Depth) {
5194   if (Depth == 6)
5195     return SDValue();  // Limit search depth.
5196
5197   SDValue V = SDValue(N, 0);
5198   EVT VT = V.getValueType();
5199   unsigned Opcode = V.getOpcode();
5200
5201   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5202   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5203     int Elt = SV->getMaskElt(Index);
5204
5205     if (Elt < 0)
5206       return DAG.getUNDEF(VT.getVectorElementType());
5207
5208     unsigned NumElems = VT.getVectorNumElements();
5209     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5210                                          : SV->getOperand(1);
5211     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5212   }
5213
5214   // Recurse into target specific vector shuffles to find scalars.
5215   if (isTargetShuffle(Opcode)) {
5216     MVT ShufVT = V.getSimpleValueType();
5217     unsigned NumElems = ShufVT.getVectorNumElements();
5218     SmallVector<int, 16> ShuffleMask;
5219     bool IsUnary;
5220
5221     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5222       return SDValue();
5223
5224     int Elt = ShuffleMask[Index];
5225     if (Elt < 0)
5226       return DAG.getUNDEF(ShufVT.getVectorElementType());
5227
5228     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5229                                          : N->getOperand(1);
5230     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5231                                Depth+1);
5232   }
5233
5234   // Actual nodes that may contain scalar elements
5235   if (Opcode == ISD::BITCAST) {
5236     V = V.getOperand(0);
5237     EVT SrcVT = V.getValueType();
5238     unsigned NumElems = VT.getVectorNumElements();
5239
5240     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5241       return SDValue();
5242   }
5243
5244   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5245     return (Index == 0) ? V.getOperand(0)
5246                         : DAG.getUNDEF(VT.getVectorElementType());
5247
5248   if (V.getOpcode() == ISD::BUILD_VECTOR)
5249     return V.getOperand(Index);
5250
5251   return SDValue();
5252 }
5253
5254 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5255 /// shuffle operation which come from a consecutively from a zero. The
5256 /// search can start in two different directions, from left or right.
5257 /// We count undefs as zeros until PreferredNum is reached.
5258 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5259                                          unsigned NumElems, bool ZerosFromLeft,
5260                                          SelectionDAG &DAG,
5261                                          unsigned PreferredNum = -1U) {
5262   unsigned NumZeros = 0;
5263   for (unsigned i = 0; i != NumElems; ++i) {
5264     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5265     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5266     if (!Elt.getNode())
5267       break;
5268
5269     if (X86::isZeroNode(Elt))
5270       ++NumZeros;
5271     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5272       NumZeros = std::min(NumZeros + 1, PreferredNum);
5273     else
5274       break;
5275   }
5276
5277   return NumZeros;
5278 }
5279
5280 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5281 /// correspond consecutively to elements from one of the vector operands,
5282 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5283 static
5284 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5285                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5286                               unsigned NumElems, unsigned &OpNum) {
5287   bool SeenV1 = false;
5288   bool SeenV2 = false;
5289
5290   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5291     int Idx = SVOp->getMaskElt(i);
5292     // Ignore undef indicies
5293     if (Idx < 0)
5294       continue;
5295
5296     if (Idx < (int)NumElems)
5297       SeenV1 = true;
5298     else
5299       SeenV2 = true;
5300
5301     // Only accept consecutive elements from the same vector
5302     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5303       return false;
5304   }
5305
5306   OpNum = SeenV1 ? 0 : 1;
5307   return true;
5308 }
5309
5310 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5311 /// logical left shift of a vector.
5312 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5313                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5314   unsigned NumElems =
5315     SVOp->getSimpleValueType(0).getVectorNumElements();
5316   unsigned NumZeros = getNumOfConsecutiveZeros(
5317       SVOp, NumElems, false /* check zeros from right */, DAG,
5318       SVOp->getMaskElt(0));
5319   unsigned OpSrc;
5320
5321   if (!NumZeros)
5322     return false;
5323
5324   // Considering the elements in the mask that are not consecutive zeros,
5325   // check if they consecutively come from only one of the source vectors.
5326   //
5327   //               V1 = {X, A, B, C}     0
5328   //                         \  \  \    /
5329   //   vector_shuffle V1, V2 <1, 2, 3, X>
5330   //
5331   if (!isShuffleMaskConsecutive(SVOp,
5332             0,                   // Mask Start Index
5333             NumElems-NumZeros,   // Mask End Index(exclusive)
5334             NumZeros,            // Where to start looking in the src vector
5335             NumElems,            // Number of elements in vector
5336             OpSrc))              // Which source operand ?
5337     return false;
5338
5339   isLeft = false;
5340   ShAmt = NumZeros;
5341   ShVal = SVOp->getOperand(OpSrc);
5342   return true;
5343 }
5344
5345 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5346 /// logical left shift of a vector.
5347 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5348                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5349   unsigned NumElems =
5350     SVOp->getSimpleValueType(0).getVectorNumElements();
5351   unsigned NumZeros = getNumOfConsecutiveZeros(
5352       SVOp, NumElems, true /* check zeros from left */, DAG,
5353       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5354   unsigned OpSrc;
5355
5356   if (!NumZeros)
5357     return false;
5358
5359   // Considering the elements in the mask that are not consecutive zeros,
5360   // check if they consecutively come from only one of the source vectors.
5361   //
5362   //                           0    { A, B, X, X } = V2
5363   //                          / \    /  /
5364   //   vector_shuffle V1, V2 <X, X, 4, 5>
5365   //
5366   if (!isShuffleMaskConsecutive(SVOp,
5367             NumZeros,     // Mask Start Index
5368             NumElems,     // Mask End Index(exclusive)
5369             0,            // Where to start looking in the src vector
5370             NumElems,     // Number of elements in vector
5371             OpSrc))       // Which source operand ?
5372     return false;
5373
5374   isLeft = true;
5375   ShAmt = NumZeros;
5376   ShVal = SVOp->getOperand(OpSrc);
5377   return true;
5378 }
5379
5380 /// isVectorShift - Returns true if the shuffle can be implemented as a
5381 /// logical left or right shift of a vector.
5382 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5383                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5384   // Although the logic below support any bitwidth size, there are no
5385   // shift instructions which handle more than 128-bit vectors.
5386   if (!SVOp->getSimpleValueType(0).is128BitVector())
5387     return false;
5388
5389   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5390       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5391     return true;
5392
5393   return false;
5394 }
5395
5396 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5397 ///
5398 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5399                                        unsigned NumNonZero, unsigned NumZero,
5400                                        SelectionDAG &DAG,
5401                                        const X86Subtarget* Subtarget,
5402                                        const TargetLowering &TLI) {
5403   if (NumNonZero > 8)
5404     return SDValue();
5405
5406   SDLoc dl(Op);
5407   SDValue V;
5408   bool First = true;
5409   for (unsigned i = 0; i < 16; ++i) {
5410     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5411     if (ThisIsNonZero && First) {
5412       if (NumZero)
5413         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5414       else
5415         V = DAG.getUNDEF(MVT::v8i16);
5416       First = false;
5417     }
5418
5419     if ((i & 1) != 0) {
5420       SDValue ThisElt, LastElt;
5421       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5422       if (LastIsNonZero) {
5423         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5424                               MVT::i16, Op.getOperand(i-1));
5425       }
5426       if (ThisIsNonZero) {
5427         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5428         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5429                               ThisElt, DAG.getConstant(8, MVT::i8));
5430         if (LastIsNonZero)
5431           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5432       } else
5433         ThisElt = LastElt;
5434
5435       if (ThisElt.getNode())
5436         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5437                         DAG.getIntPtrConstant(i/2));
5438     }
5439   }
5440
5441   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5442 }
5443
5444 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5445 ///
5446 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5447                                      unsigned NumNonZero, unsigned NumZero,
5448                                      SelectionDAG &DAG,
5449                                      const X86Subtarget* Subtarget,
5450                                      const TargetLowering &TLI) {
5451   if (NumNonZero > 4)
5452     return SDValue();
5453
5454   SDLoc dl(Op);
5455   SDValue V;
5456   bool First = true;
5457   for (unsigned i = 0; i < 8; ++i) {
5458     bool isNonZero = (NonZeros & (1 << i)) != 0;
5459     if (isNonZero) {
5460       if (First) {
5461         if (NumZero)
5462           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5463         else
5464           V = DAG.getUNDEF(MVT::v8i16);
5465         First = false;
5466       }
5467       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5468                       MVT::v8i16, V, Op.getOperand(i),
5469                       DAG.getIntPtrConstant(i));
5470     }
5471   }
5472
5473   return V;
5474 }
5475
5476 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5477 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5478                                      unsigned NonZeros, unsigned NumNonZero,
5479                                      unsigned NumZero, SelectionDAG &DAG,
5480                                      const X86Subtarget *Subtarget,
5481                                      const TargetLowering &TLI) {
5482   // We know there's at least one non-zero element
5483   unsigned FirstNonZeroIdx = 0;
5484   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5485   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5486          X86::isZeroNode(FirstNonZero)) {
5487     ++FirstNonZeroIdx;
5488     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5489   }
5490
5491   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5492       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5493     return SDValue();
5494
5495   SDValue V = FirstNonZero.getOperand(0);
5496   MVT VVT = V.getSimpleValueType();
5497   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5498     return SDValue();
5499
5500   unsigned FirstNonZeroDst =
5501       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5502   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5503   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5504   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5505
5506   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5507     SDValue Elem = Op.getOperand(Idx);
5508     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5509       continue;
5510
5511     // TODO: What else can be here? Deal with it.
5512     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5513       return SDValue();
5514
5515     // TODO: Some optimizations are still possible here
5516     // ex: Getting one element from a vector, and the rest from another.
5517     if (Elem.getOperand(0) != V)
5518       return SDValue();
5519
5520     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5521     if (Dst == Idx)
5522       ++CorrectIdx;
5523     else if (IncorrectIdx == -1U) {
5524       IncorrectIdx = Idx;
5525       IncorrectDst = Dst;
5526     } else
5527       // There was already one element with an incorrect index.
5528       // We can't optimize this case to an insertps.
5529       return SDValue();
5530   }
5531
5532   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5533     SDLoc dl(Op);
5534     EVT VT = Op.getSimpleValueType();
5535     unsigned ElementMoveMask = 0;
5536     if (IncorrectIdx == -1U)
5537       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5538     else
5539       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5540
5541     SDValue InsertpsMask =
5542         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5543     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5544   }
5545
5546   return SDValue();
5547 }
5548
5549 /// getVShift - Return a vector logical shift node.
5550 ///
5551 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5552                          unsigned NumBits, SelectionDAG &DAG,
5553                          const TargetLowering &TLI, SDLoc dl) {
5554   assert(VT.is128BitVector() && "Unknown type for VShift");
5555   EVT ShVT = MVT::v2i64;
5556   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5557   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5558   return DAG.getNode(ISD::BITCAST, dl, VT,
5559                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5560                              DAG.getConstant(NumBits,
5561                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5562 }
5563
5564 static SDValue
5565 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5566
5567   // Check if the scalar load can be widened into a vector load. And if
5568   // the address is "base + cst" see if the cst can be "absorbed" into
5569   // the shuffle mask.
5570   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5571     SDValue Ptr = LD->getBasePtr();
5572     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5573       return SDValue();
5574     EVT PVT = LD->getValueType(0);
5575     if (PVT != MVT::i32 && PVT != MVT::f32)
5576       return SDValue();
5577
5578     int FI = -1;
5579     int64_t Offset = 0;
5580     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5581       FI = FINode->getIndex();
5582       Offset = 0;
5583     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5584                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5585       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5586       Offset = Ptr.getConstantOperandVal(1);
5587       Ptr = Ptr.getOperand(0);
5588     } else {
5589       return SDValue();
5590     }
5591
5592     // FIXME: 256-bit vector instructions don't require a strict alignment,
5593     // improve this code to support it better.
5594     unsigned RequiredAlign = VT.getSizeInBits()/8;
5595     SDValue Chain = LD->getChain();
5596     // Make sure the stack object alignment is at least 16 or 32.
5597     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5598     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5599       if (MFI->isFixedObjectIndex(FI)) {
5600         // Can't change the alignment. FIXME: It's possible to compute
5601         // the exact stack offset and reference FI + adjust offset instead.
5602         // If someone *really* cares about this. That's the way to implement it.
5603         return SDValue();
5604       } else {
5605         MFI->setObjectAlignment(FI, RequiredAlign);
5606       }
5607     }
5608
5609     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5610     // Ptr + (Offset & ~15).
5611     if (Offset < 0)
5612       return SDValue();
5613     if ((Offset % RequiredAlign) & 3)
5614       return SDValue();
5615     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5616     if (StartOffset)
5617       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5618                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5619
5620     int EltNo = (Offset - StartOffset) >> 2;
5621     unsigned NumElems = VT.getVectorNumElements();
5622
5623     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5624     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5625                              LD->getPointerInfo().getWithOffset(StartOffset),
5626                              false, false, false, 0);
5627
5628     SmallVector<int, 8> Mask;
5629     for (unsigned i = 0; i != NumElems; ++i)
5630       Mask.push_back(EltNo);
5631
5632     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5633   }
5634
5635   return SDValue();
5636 }
5637
5638 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5639 /// vector of type 'VT', see if the elements can be replaced by a single large
5640 /// load which has the same value as a build_vector whose operands are 'elts'.
5641 ///
5642 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5643 ///
5644 /// FIXME: we'd also like to handle the case where the last elements are zero
5645 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5646 /// There's even a handy isZeroNode for that purpose.
5647 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5648                                         SDLoc &DL, SelectionDAG &DAG,
5649                                         bool isAfterLegalize) {
5650   EVT EltVT = VT.getVectorElementType();
5651   unsigned NumElems = Elts.size();
5652
5653   LoadSDNode *LDBase = nullptr;
5654   unsigned LastLoadedElt = -1U;
5655
5656   // For each element in the initializer, see if we've found a load or an undef.
5657   // If we don't find an initial load element, or later load elements are
5658   // non-consecutive, bail out.
5659   for (unsigned i = 0; i < NumElems; ++i) {
5660     SDValue Elt = Elts[i];
5661
5662     if (!Elt.getNode() ||
5663         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5664       return SDValue();
5665     if (!LDBase) {
5666       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5667         return SDValue();
5668       LDBase = cast<LoadSDNode>(Elt.getNode());
5669       LastLoadedElt = i;
5670       continue;
5671     }
5672     if (Elt.getOpcode() == ISD::UNDEF)
5673       continue;
5674
5675     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5676     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5677       return SDValue();
5678     LastLoadedElt = i;
5679   }
5680
5681   // If we have found an entire vector of loads and undefs, then return a large
5682   // load of the entire vector width starting at the base pointer.  If we found
5683   // consecutive loads for the low half, generate a vzext_load node.
5684   if (LastLoadedElt == NumElems - 1) {
5685
5686     if (isAfterLegalize &&
5687         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5688       return SDValue();
5689
5690     SDValue NewLd = SDValue();
5691
5692     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5693       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5694                           LDBase->getPointerInfo(),
5695                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5696                           LDBase->isInvariant(), 0);
5697     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5698                         LDBase->getPointerInfo(),
5699                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5700                         LDBase->isInvariant(), LDBase->getAlignment());
5701
5702     if (LDBase->hasAnyUseOfValue(1)) {
5703       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5704                                      SDValue(LDBase, 1),
5705                                      SDValue(NewLd.getNode(), 1));
5706       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5707       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5708                              SDValue(NewLd.getNode(), 1));
5709     }
5710
5711     return NewLd;
5712   }
5713   if (NumElems == 4 && LastLoadedElt == 1 &&
5714       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5715     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5716     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5717     SDValue ResNode =
5718         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5719                                 LDBase->getPointerInfo(),
5720                                 LDBase->getAlignment(),
5721                                 false/*isVolatile*/, true/*ReadMem*/,
5722                                 false/*WriteMem*/);
5723
5724     // Make sure the newly-created LOAD is in the same position as LDBase in
5725     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5726     // update uses of LDBase's output chain to use the TokenFactor.
5727     if (LDBase->hasAnyUseOfValue(1)) {
5728       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5729                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5730       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5731       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5732                              SDValue(ResNode.getNode(), 1));
5733     }
5734
5735     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5736   }
5737   return SDValue();
5738 }
5739
5740 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5741 /// to generate a splat value for the following cases:
5742 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5743 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5744 /// a scalar load, or a constant.
5745 /// The VBROADCAST node is returned when a pattern is found,
5746 /// or SDValue() otherwise.
5747 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5748                                     SelectionDAG &DAG) {
5749   if (!Subtarget->hasFp256())
5750     return SDValue();
5751
5752   MVT VT = Op.getSimpleValueType();
5753   SDLoc dl(Op);
5754
5755   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5756          "Unsupported vector type for broadcast.");
5757
5758   SDValue Ld;
5759   bool ConstSplatVal;
5760
5761   switch (Op.getOpcode()) {
5762     default:
5763       // Unknown pattern found.
5764       return SDValue();
5765
5766     case ISD::BUILD_VECTOR: {
5767       // The BUILD_VECTOR node must be a splat.
5768       if (!isSplatVector(Op.getNode()))
5769         return SDValue();
5770
5771       Ld = Op.getOperand(0);
5772       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5773                      Ld.getOpcode() == ISD::ConstantFP);
5774
5775       // The suspected load node has several users. Make sure that all
5776       // of its users are from the BUILD_VECTOR node.
5777       // Constants may have multiple users.
5778       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5779         return SDValue();
5780       break;
5781     }
5782
5783     case ISD::VECTOR_SHUFFLE: {
5784       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5785
5786       // Shuffles must have a splat mask where the first element is
5787       // broadcasted.
5788       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5789         return SDValue();
5790
5791       SDValue Sc = Op.getOperand(0);
5792       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5793           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5794
5795         if (!Subtarget->hasInt256())
5796           return SDValue();
5797
5798         // Use the register form of the broadcast instruction available on AVX2.
5799         if (VT.getSizeInBits() >= 256)
5800           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5801         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5802       }
5803
5804       Ld = Sc.getOperand(0);
5805       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5806                        Ld.getOpcode() == ISD::ConstantFP);
5807
5808       // The scalar_to_vector node and the suspected
5809       // load node must have exactly one user.
5810       // Constants may have multiple users.
5811
5812       // AVX-512 has register version of the broadcast
5813       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5814         Ld.getValueType().getSizeInBits() >= 32;
5815       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5816           !hasRegVer))
5817         return SDValue();
5818       break;
5819     }
5820   }
5821
5822   bool IsGE256 = (VT.getSizeInBits() >= 256);
5823
5824   // Handle the broadcasting a single constant scalar from the constant pool
5825   // into a vector. On Sandybridge it is still better to load a constant vector
5826   // from the constant pool and not to broadcast it from a scalar.
5827   if (ConstSplatVal && Subtarget->hasInt256()) {
5828     EVT CVT = Ld.getValueType();
5829     assert(!CVT.isVector() && "Must not broadcast a vector type");
5830     unsigned ScalarSize = CVT.getSizeInBits();
5831
5832     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5833       const Constant *C = nullptr;
5834       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5835         C = CI->getConstantIntValue();
5836       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5837         C = CF->getConstantFPValue();
5838
5839       assert(C && "Invalid constant type");
5840
5841       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5842       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5843       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5844       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5845                        MachinePointerInfo::getConstantPool(),
5846                        false, false, false, Alignment);
5847
5848       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5849     }
5850   }
5851
5852   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5853   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5854
5855   // Handle AVX2 in-register broadcasts.
5856   if (!IsLoad && Subtarget->hasInt256() &&
5857       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5858     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5859
5860   // The scalar source must be a normal load.
5861   if (!IsLoad)
5862     return SDValue();
5863
5864   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5865     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5866
5867   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5868   // double since there is no vbroadcastsd xmm
5869   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5870     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5871       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5872   }
5873
5874   // Unsupported broadcast.
5875   return SDValue();
5876 }
5877
5878 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5879 /// underlying vector and index.
5880 ///
5881 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5882 /// index.
5883 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5884                                          SDValue ExtIdx) {
5885   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5886   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5887     return Idx;
5888
5889   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5890   // lowered this:
5891   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5892   // to:
5893   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5894   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5895   //                           undef)
5896   //                       Constant<0>)
5897   // In this case the vector is the extract_subvector expression and the index
5898   // is 2, as specified by the shuffle.
5899   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5900   SDValue ShuffleVec = SVOp->getOperand(0);
5901   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5902   assert(ShuffleVecVT.getVectorElementType() ==
5903          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5904
5905   int ShuffleIdx = SVOp->getMaskElt(Idx);
5906   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5907     ExtractedFromVec = ShuffleVec;
5908     return ShuffleIdx;
5909   }
5910   return Idx;
5911 }
5912
5913 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5914   MVT VT = Op.getSimpleValueType();
5915
5916   // Skip if insert_vec_elt is not supported.
5917   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5918   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5919     return SDValue();
5920
5921   SDLoc DL(Op);
5922   unsigned NumElems = Op.getNumOperands();
5923
5924   SDValue VecIn1;
5925   SDValue VecIn2;
5926   SmallVector<unsigned, 4> InsertIndices;
5927   SmallVector<int, 8> Mask(NumElems, -1);
5928
5929   for (unsigned i = 0; i != NumElems; ++i) {
5930     unsigned Opc = Op.getOperand(i).getOpcode();
5931
5932     if (Opc == ISD::UNDEF)
5933       continue;
5934
5935     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5936       // Quit if more than 1 elements need inserting.
5937       if (InsertIndices.size() > 1)
5938         return SDValue();
5939
5940       InsertIndices.push_back(i);
5941       continue;
5942     }
5943
5944     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5945     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5946     // Quit if non-constant index.
5947     if (!isa<ConstantSDNode>(ExtIdx))
5948       return SDValue();
5949     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5950
5951     // Quit if extracted from vector of different type.
5952     if (ExtractedFromVec.getValueType() != VT)
5953       return SDValue();
5954
5955     if (!VecIn1.getNode())
5956       VecIn1 = ExtractedFromVec;
5957     else if (VecIn1 != ExtractedFromVec) {
5958       if (!VecIn2.getNode())
5959         VecIn2 = ExtractedFromVec;
5960       else if (VecIn2 != ExtractedFromVec)
5961         // Quit if more than 2 vectors to shuffle
5962         return SDValue();
5963     }
5964
5965     if (ExtractedFromVec == VecIn1)
5966       Mask[i] = Idx;
5967     else if (ExtractedFromVec == VecIn2)
5968       Mask[i] = Idx + NumElems;
5969   }
5970
5971   if (!VecIn1.getNode())
5972     return SDValue();
5973
5974   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5975   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5976   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5977     unsigned Idx = InsertIndices[i];
5978     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5979                      DAG.getIntPtrConstant(Idx));
5980   }
5981
5982   return NV;
5983 }
5984
5985 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5986 SDValue
5987 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5988
5989   MVT VT = Op.getSimpleValueType();
5990   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5991          "Unexpected type in LowerBUILD_VECTORvXi1!");
5992
5993   SDLoc dl(Op);
5994   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5995     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5996     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5997     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5998   }
5999
6000   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
6001     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
6002     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
6003     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
6004   }
6005
6006   bool AllContants = true;
6007   uint64_t Immediate = 0;
6008   int NonConstIdx = -1;
6009   bool IsSplat = true;
6010   unsigned NumNonConsts = 0;
6011   unsigned NumConsts = 0;
6012   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
6013     SDValue In = Op.getOperand(idx);
6014     if (In.getOpcode() == ISD::UNDEF)
6015       continue;
6016     if (!isa<ConstantSDNode>(In)) {
6017       AllContants = false;
6018       NonConstIdx = idx;
6019       NumNonConsts++;
6020     }
6021     else {
6022       NumConsts++;
6023       if (cast<ConstantSDNode>(In)->getZExtValue())
6024       Immediate |= (1ULL << idx);
6025     }
6026     if (In != Op.getOperand(0))
6027       IsSplat = false;
6028   }
6029
6030   if (AllContants) {
6031     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6032       DAG.getConstant(Immediate, MVT::i16));
6033     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6034                        DAG.getIntPtrConstant(0));
6035   }
6036
6037   if (NumNonConsts == 1 && NonConstIdx != 0) {
6038     SDValue DstVec;
6039     if (NumConsts) {
6040       SDValue VecAsImm = DAG.getConstant(Immediate,
6041                                          MVT::getIntegerVT(VT.getSizeInBits()));
6042       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6043     }
6044     else 
6045       DstVec = DAG.getUNDEF(VT);
6046     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6047                        Op.getOperand(NonConstIdx),
6048                        DAG.getIntPtrConstant(NonConstIdx));
6049   }
6050   if (!IsSplat && (NonConstIdx != 0))
6051     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6052   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6053   SDValue Select;
6054   if (IsSplat)
6055     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6056                           DAG.getConstant(-1, SelectVT),
6057                           DAG.getConstant(0, SelectVT));
6058   else
6059     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6060                          DAG.getConstant((Immediate | 1), SelectVT),
6061                          DAG.getConstant(Immediate, SelectVT));
6062   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6063 }
6064
6065 /// \brief Return true if \p N implements a horizontal binop and return the
6066 /// operands for the horizontal binop into V0 and V1.
6067 /// 
6068 /// This is a helper function of PerformBUILD_VECTORCombine.
6069 /// This function checks that the build_vector \p N in input implements a
6070 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
6071 /// operation to match.
6072 /// For example, if \p Opcode is equal to ISD::ADD, then this function
6073 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
6074 /// is equal to ISD::SUB, then this function checks if this is a horizontal
6075 /// arithmetic sub.
6076 ///
6077 /// This function only analyzes elements of \p N whose indices are
6078 /// in range [BaseIdx, LastIdx).
6079 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
6080                               SelectionDAG &DAG,
6081                               unsigned BaseIdx, unsigned LastIdx,
6082                               SDValue &V0, SDValue &V1) {
6083   EVT VT = N->getValueType(0);
6084
6085   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
6086   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
6087          "Invalid Vector in input!");
6088   
6089   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
6090   bool CanFold = true;
6091   unsigned ExpectedVExtractIdx = BaseIdx;
6092   unsigned NumElts = LastIdx - BaseIdx;
6093   V0 = DAG.getUNDEF(VT);
6094   V1 = DAG.getUNDEF(VT);
6095
6096   // Check if N implements a horizontal binop.
6097   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
6098     SDValue Op = N->getOperand(i + BaseIdx);
6099
6100     // Skip UNDEFs.
6101     if (Op->getOpcode() == ISD::UNDEF) {
6102       // Update the expected vector extract index.
6103       if (i * 2 == NumElts)
6104         ExpectedVExtractIdx = BaseIdx;
6105       ExpectedVExtractIdx += 2;
6106       continue;
6107     }
6108
6109     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
6110
6111     if (!CanFold)
6112       break;
6113
6114     SDValue Op0 = Op.getOperand(0);
6115     SDValue Op1 = Op.getOperand(1);
6116
6117     // Try to match the following pattern:
6118     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
6119     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6120         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6121         Op0.getOperand(0) == Op1.getOperand(0) &&
6122         isa<ConstantSDNode>(Op0.getOperand(1)) &&
6123         isa<ConstantSDNode>(Op1.getOperand(1)));
6124     if (!CanFold)
6125       break;
6126
6127     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
6128     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
6129
6130     if (i * 2 < NumElts) {
6131       if (V0.getOpcode() == ISD::UNDEF)
6132         V0 = Op0.getOperand(0);
6133     } else {
6134       if (V1.getOpcode() == ISD::UNDEF)
6135         V1 = Op0.getOperand(0);
6136       if (i * 2 == NumElts)
6137         ExpectedVExtractIdx = BaseIdx;
6138     }
6139
6140     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
6141     if (I0 == ExpectedVExtractIdx)
6142       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
6143     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
6144       // Try to match the following dag sequence:
6145       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
6146       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
6147     } else
6148       CanFold = false;
6149
6150     ExpectedVExtractIdx += 2;
6151   }
6152
6153   return CanFold;
6154 }
6155
6156 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
6157 /// a concat_vector. 
6158 ///
6159 /// This is a helper function of PerformBUILD_VECTORCombine.
6160 /// This function expects two 256-bit vectors called V0 and V1.
6161 /// At first, each vector is split into two separate 128-bit vectors.
6162 /// Then, the resulting 128-bit vectors are used to implement two
6163 /// horizontal binary operations. 
6164 ///
6165 /// The kind of horizontal binary operation is defined by \p X86Opcode.
6166 ///
6167 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
6168 /// the two new horizontal binop.
6169 /// When Mode is set, the first horizontal binop dag node would take as input
6170 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
6171 /// horizontal binop dag node would take as input the lower 128-bit of V1
6172 /// and the upper 128-bit of V1.
6173 ///   Example:
6174 ///     HADD V0_LO, V0_HI
6175 ///     HADD V1_LO, V1_HI
6176 ///
6177 /// Otherwise, the first horizontal binop dag node takes as input the lower
6178 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
6179 /// dag node takes the the upper 128-bit of V0 and the upper 128-bit of V1.
6180 ///   Example:
6181 ///     HADD V0_LO, V1_LO
6182 ///     HADD V0_HI, V1_HI
6183 ///
6184 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
6185 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
6186 /// the upper 128-bits of the result.
6187 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
6188                                      SDLoc DL, SelectionDAG &DAG,
6189                                      unsigned X86Opcode, bool Mode,
6190                                      bool isUndefLO, bool isUndefHI) {
6191   EVT VT = V0.getValueType();
6192   assert(VT.is256BitVector() && VT == V1.getValueType() &&
6193          "Invalid nodes in input!");
6194
6195   unsigned NumElts = VT.getVectorNumElements();
6196   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
6197   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
6198   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
6199   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
6200   EVT NewVT = V0_LO.getValueType();
6201
6202   SDValue LO = DAG.getUNDEF(NewVT);
6203   SDValue HI = DAG.getUNDEF(NewVT);
6204
6205   if (Mode) {
6206     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6207     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
6208       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
6209     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
6210       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
6211   } else {
6212     // Don't emit a horizontal binop if the result is expected to be UNDEF.
6213     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
6214                        V1_LO->getOpcode() != ISD::UNDEF))
6215       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
6216
6217     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
6218                        V1_HI->getOpcode() != ISD::UNDEF))
6219       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
6220   }
6221
6222   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
6223 }
6224
6225 static SDValue PerformBUILD_VECTORCombine(SDNode *N, SelectionDAG &DAG,
6226                                           const X86Subtarget *Subtarget) {
6227   SDLoc DL(N);
6228   EVT VT = N->getValueType(0);
6229   unsigned NumElts = VT.getVectorNumElements();
6230   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N);
6231   SDValue InVec0, InVec1;
6232
6233   // Try to match horizontal ADD/SUB.
6234   unsigned NumUndefsLO = 0;
6235   unsigned NumUndefsHI = 0;
6236   unsigned Half = NumElts/2;
6237
6238   // Count the number of UNDEF operands in the build_vector in input.
6239   for (unsigned i = 0, e = Half; i != e; ++i)
6240     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6241       NumUndefsLO++;
6242
6243   for (unsigned i = Half, e = NumElts; i != e; ++i)
6244     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
6245       NumUndefsHI++;
6246
6247   // Early exit if this is either a build_vector of all UNDEFs or all the
6248   // operands but one are UNDEF.
6249   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
6250     return SDValue();
6251
6252   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
6253     // Try to match an SSE3 float HADD/HSUB.
6254     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6255       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6256     
6257     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6258       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6259   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
6260     // Try to match an SSSE3 integer HADD/HSUB.
6261     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6262       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
6263     
6264     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6265       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
6266   }
6267   
6268   if (!Subtarget->hasAVX())
6269     return SDValue();
6270
6271   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
6272     // Try to match an AVX horizontal add/sub of packed single/double
6273     // precision floating point values from 256-bit vectors.
6274     SDValue InVec2, InVec3;
6275     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
6276         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
6277         ((InVec0.getOpcode() == ISD::UNDEF ||
6278           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6279         ((InVec1.getOpcode() == ISD::UNDEF ||
6280           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6281       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
6282
6283     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
6284         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
6285         ((InVec0.getOpcode() == ISD::UNDEF ||
6286           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6287         ((InVec1.getOpcode() == ISD::UNDEF ||
6288           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6289       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
6290   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
6291     // Try to match an AVX2 horizontal add/sub of signed integers.
6292     SDValue InVec2, InVec3;
6293     unsigned X86Opcode;
6294     bool CanFold = true;
6295
6296     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
6297         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
6298         ((InVec0.getOpcode() == ISD::UNDEF ||
6299           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6300         ((InVec1.getOpcode() == ISD::UNDEF ||
6301           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6302       X86Opcode = X86ISD::HADD;
6303     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
6304         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
6305         ((InVec0.getOpcode() == ISD::UNDEF ||
6306           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
6307         ((InVec1.getOpcode() == ISD::UNDEF ||
6308           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
6309       X86Opcode = X86ISD::HSUB;
6310     else
6311       CanFold = false;
6312
6313     if (CanFold) {
6314       // Fold this build_vector into a single horizontal add/sub.
6315       // Do this only if the target has AVX2.
6316       if (Subtarget->hasAVX2())
6317         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
6318  
6319       // Do not try to expand this build_vector into a pair of horizontal
6320       // add/sub if we can emit a pair of scalar add/sub.
6321       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6322         return SDValue();
6323
6324       // Convert this build_vector into a pair of horizontal binop followed by
6325       // a concat vector.
6326       bool isUndefLO = NumUndefsLO == Half;
6327       bool isUndefHI = NumUndefsHI == Half;
6328       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
6329                                    isUndefLO, isUndefHI);
6330     }
6331   }
6332
6333   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
6334        VT == MVT::v16i16) && Subtarget->hasAVX()) {
6335     unsigned X86Opcode;
6336     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
6337       X86Opcode = X86ISD::HADD;
6338     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
6339       X86Opcode = X86ISD::HSUB;
6340     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
6341       X86Opcode = X86ISD::FHADD;
6342     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
6343       X86Opcode = X86ISD::FHSUB;
6344     else
6345       return SDValue();
6346
6347     // Don't try to expand this build_vector into a pair of horizontal add/sub
6348     // if we can simply emit a pair of scalar add/sub.
6349     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
6350       return SDValue();
6351
6352     // Convert this build_vector into two horizontal add/sub followed by
6353     // a concat vector.
6354     bool isUndefLO = NumUndefsLO == Half;
6355     bool isUndefHI = NumUndefsHI == Half;
6356     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
6357                                  isUndefLO, isUndefHI);
6358   }
6359
6360   return SDValue();
6361 }
6362
6363 SDValue
6364 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6365   SDLoc dl(Op);
6366
6367   MVT VT = Op.getSimpleValueType();
6368   MVT ExtVT = VT.getVectorElementType();
6369   unsigned NumElems = Op.getNumOperands();
6370
6371   // Generate vectors for predicate vectors.
6372   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6373     return LowerBUILD_VECTORvXi1(Op, DAG);
6374
6375   // Vectors containing all zeros can be matched by pxor and xorps later
6376   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6377     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6378     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6379     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6380       return Op;
6381
6382     return getZeroVector(VT, Subtarget, DAG, dl);
6383   }
6384
6385   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6386   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6387   // vpcmpeqd on 256-bit vectors.
6388   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6389     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6390       return Op;
6391
6392     if (!VT.is512BitVector())
6393       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6394   }
6395
6396   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6397   if (Broadcast.getNode())
6398     return Broadcast;
6399
6400   unsigned EVTBits = ExtVT.getSizeInBits();
6401
6402   unsigned NumZero  = 0;
6403   unsigned NumNonZero = 0;
6404   unsigned NonZeros = 0;
6405   bool IsAllConstants = true;
6406   SmallSet<SDValue, 8> Values;
6407   for (unsigned i = 0; i < NumElems; ++i) {
6408     SDValue Elt = Op.getOperand(i);
6409     if (Elt.getOpcode() == ISD::UNDEF)
6410       continue;
6411     Values.insert(Elt);
6412     if (Elt.getOpcode() != ISD::Constant &&
6413         Elt.getOpcode() != ISD::ConstantFP)
6414       IsAllConstants = false;
6415     if (X86::isZeroNode(Elt))
6416       NumZero++;
6417     else {
6418       NonZeros |= (1 << i);
6419       NumNonZero++;
6420     }
6421   }
6422
6423   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6424   if (NumNonZero == 0)
6425     return DAG.getUNDEF(VT);
6426
6427   // Special case for single non-zero, non-undef, element.
6428   if (NumNonZero == 1) {
6429     unsigned Idx = countTrailingZeros(NonZeros);
6430     SDValue Item = Op.getOperand(Idx);
6431
6432     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6433     // the value are obviously zero, truncate the value to i32 and do the
6434     // insertion that way.  Only do this if the value is non-constant or if the
6435     // value is a constant being inserted into element 0.  It is cheaper to do
6436     // a constant pool load than it is to do a movd + shuffle.
6437     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6438         (!IsAllConstants || Idx == 0)) {
6439       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6440         // Handle SSE only.
6441         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6442         EVT VecVT = MVT::v4i32;
6443         unsigned VecElts = 4;
6444
6445         // Truncate the value (which may itself be a constant) to i32, and
6446         // convert it to a vector with movd (S2V+shuffle to zero extend).
6447         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6448         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6449         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6450
6451         // Now we have our 32-bit value zero extended in the low element of
6452         // a vector.  If Idx != 0, swizzle it into place.
6453         if (Idx != 0) {
6454           SmallVector<int, 4> Mask;
6455           Mask.push_back(Idx);
6456           for (unsigned i = 1; i != VecElts; ++i)
6457             Mask.push_back(i);
6458           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6459                                       &Mask[0]);
6460         }
6461         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6462       }
6463     }
6464
6465     // If we have a constant or non-constant insertion into the low element of
6466     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6467     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6468     // depending on what the source datatype is.
6469     if (Idx == 0) {
6470       if (NumZero == 0)
6471         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6472
6473       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6474           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6475         if (VT.is256BitVector() || VT.is512BitVector()) {
6476           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6477           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6478                              Item, DAG.getIntPtrConstant(0));
6479         }
6480         assert(VT.is128BitVector() && "Expected an SSE value type!");
6481         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6482         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6483         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6484       }
6485
6486       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6487         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6488         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6489         if (VT.is256BitVector()) {
6490           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6491           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6492         } else {
6493           assert(VT.is128BitVector() && "Expected an SSE value type!");
6494           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6495         }
6496         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6497       }
6498     }
6499
6500     // Is it a vector logical left shift?
6501     if (NumElems == 2 && Idx == 1 &&
6502         X86::isZeroNode(Op.getOperand(0)) &&
6503         !X86::isZeroNode(Op.getOperand(1))) {
6504       unsigned NumBits = VT.getSizeInBits();
6505       return getVShift(true, VT,
6506                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6507                                    VT, Op.getOperand(1)),
6508                        NumBits/2, DAG, *this, dl);
6509     }
6510
6511     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6512       return SDValue();
6513
6514     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6515     // is a non-constant being inserted into an element other than the low one,
6516     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6517     // movd/movss) to move this into the low element, then shuffle it into
6518     // place.
6519     if (EVTBits == 32) {
6520       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6521
6522       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6523       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6524       SmallVector<int, 8> MaskVec;
6525       for (unsigned i = 0; i != NumElems; ++i)
6526         MaskVec.push_back(i == Idx ? 0 : 1);
6527       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6528     }
6529   }
6530
6531   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6532   if (Values.size() == 1) {
6533     if (EVTBits == 32) {
6534       // Instead of a shuffle like this:
6535       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6536       // Check if it's possible to issue this instead.
6537       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6538       unsigned Idx = countTrailingZeros(NonZeros);
6539       SDValue Item = Op.getOperand(Idx);
6540       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6541         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6542     }
6543     return SDValue();
6544   }
6545
6546   // A vector full of immediates; various special cases are already
6547   // handled, so this is best done with a single constant-pool load.
6548   if (IsAllConstants)
6549     return SDValue();
6550
6551   // For AVX-length vectors, build the individual 128-bit pieces and use
6552   // shuffles to put them in place.
6553   if (VT.is256BitVector() || VT.is512BitVector()) {
6554     SmallVector<SDValue, 64> V;
6555     for (unsigned i = 0; i != NumElems; ++i)
6556       V.push_back(Op.getOperand(i));
6557
6558     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6559
6560     // Build both the lower and upper subvector.
6561     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6562                                 makeArrayRef(&V[0], NumElems/2));
6563     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6564                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6565
6566     // Recreate the wider vector with the lower and upper part.
6567     if (VT.is256BitVector())
6568       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6569     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6570   }
6571
6572   // Let legalizer expand 2-wide build_vectors.
6573   if (EVTBits == 64) {
6574     if (NumNonZero == 1) {
6575       // One half is zero or undef.
6576       unsigned Idx = countTrailingZeros(NonZeros);
6577       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6578                                  Op.getOperand(Idx));
6579       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6580     }
6581     return SDValue();
6582   }
6583
6584   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6585   if (EVTBits == 8 && NumElems == 16) {
6586     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6587                                         Subtarget, *this);
6588     if (V.getNode()) return V;
6589   }
6590
6591   if (EVTBits == 16 && NumElems == 8) {
6592     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6593                                       Subtarget, *this);
6594     if (V.getNode()) return V;
6595   }
6596
6597   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6598   if (EVTBits == 32 && NumElems == 4) {
6599     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6600                                       NumZero, DAG, Subtarget, *this);
6601     if (V.getNode())
6602       return V;
6603   }
6604
6605   // If element VT is == 32 bits, turn it into a number of shuffles.
6606   SmallVector<SDValue, 8> V(NumElems);
6607   if (NumElems == 4 && NumZero > 0) {
6608     for (unsigned i = 0; i < 4; ++i) {
6609       bool isZero = !(NonZeros & (1 << i));
6610       if (isZero)
6611         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6612       else
6613         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6614     }
6615
6616     for (unsigned i = 0; i < 2; ++i) {
6617       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6618         default: break;
6619         case 0:
6620           V[i] = V[i*2];  // Must be a zero vector.
6621           break;
6622         case 1:
6623           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6624           break;
6625         case 2:
6626           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6627           break;
6628         case 3:
6629           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6630           break;
6631       }
6632     }
6633
6634     bool Reverse1 = (NonZeros & 0x3) == 2;
6635     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6636     int MaskVec[] = {
6637       Reverse1 ? 1 : 0,
6638       Reverse1 ? 0 : 1,
6639       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6640       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6641     };
6642     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6643   }
6644
6645   if (Values.size() > 1 && VT.is128BitVector()) {
6646     // Check for a build vector of consecutive loads.
6647     for (unsigned i = 0; i < NumElems; ++i)
6648       V[i] = Op.getOperand(i);
6649
6650     // Check for elements which are consecutive loads.
6651     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6652     if (LD.getNode())
6653       return LD;
6654
6655     // Check for a build vector from mostly shuffle plus few inserting.
6656     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6657     if (Sh.getNode())
6658       return Sh;
6659
6660     // For SSE 4.1, use insertps to put the high elements into the low element.
6661     if (getSubtarget()->hasSSE41()) {
6662       SDValue Result;
6663       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6664         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6665       else
6666         Result = DAG.getUNDEF(VT);
6667
6668       for (unsigned i = 1; i < NumElems; ++i) {
6669         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6670         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6671                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6672       }
6673       return Result;
6674     }
6675
6676     // Otherwise, expand into a number of unpckl*, start by extending each of
6677     // our (non-undef) elements to the full vector width with the element in the
6678     // bottom slot of the vector (which generates no code for SSE).
6679     for (unsigned i = 0; i < NumElems; ++i) {
6680       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6681         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6682       else
6683         V[i] = DAG.getUNDEF(VT);
6684     }
6685
6686     // Next, we iteratively mix elements, e.g. for v4f32:
6687     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6688     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6689     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6690     unsigned EltStride = NumElems >> 1;
6691     while (EltStride != 0) {
6692       for (unsigned i = 0; i < EltStride; ++i) {
6693         // If V[i+EltStride] is undef and this is the first round of mixing,
6694         // then it is safe to just drop this shuffle: V[i] is already in the
6695         // right place, the one element (since it's the first round) being
6696         // inserted as undef can be dropped.  This isn't safe for successive
6697         // rounds because they will permute elements within both vectors.
6698         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6699             EltStride == NumElems/2)
6700           continue;
6701
6702         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6703       }
6704       EltStride >>= 1;
6705     }
6706     return V[0];
6707   }
6708   return SDValue();
6709 }
6710
6711 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6712 // to create 256-bit vectors from two other 128-bit ones.
6713 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6714   SDLoc dl(Op);
6715   MVT ResVT = Op.getSimpleValueType();
6716
6717   assert((ResVT.is256BitVector() ||
6718           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6719
6720   SDValue V1 = Op.getOperand(0);
6721   SDValue V2 = Op.getOperand(1);
6722   unsigned NumElems = ResVT.getVectorNumElements();
6723   if(ResVT.is256BitVector())
6724     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6725
6726   if (Op.getNumOperands() == 4) {
6727     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6728                                 ResVT.getVectorNumElements()/2);
6729     SDValue V3 = Op.getOperand(2);
6730     SDValue V4 = Op.getOperand(3);
6731     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6732       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6733   }
6734   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6735 }
6736
6737 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6738   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6739   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6740          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6741           Op.getNumOperands() == 4)));
6742
6743   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6744   // from two other 128-bit ones.
6745
6746   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6747   return LowerAVXCONCAT_VECTORS(Op, DAG);
6748 }
6749
6750 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6751                         bool hasInt256, unsigned *MaskOut = nullptr) {
6752   MVT EltVT = VT.getVectorElementType();
6753
6754   // There is no blend with immediate in AVX-512.
6755   if (VT.is512BitVector())
6756     return false;
6757
6758   if (!hasSSE41 || EltVT == MVT::i8)
6759     return false;
6760   if (!hasInt256 && VT == MVT::v16i16)
6761     return false;
6762
6763   unsigned MaskValue = 0;
6764   unsigned NumElems = VT.getVectorNumElements();
6765   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6766   unsigned NumLanes = (NumElems - 1) / 8 + 1;
6767   unsigned NumElemsInLane = NumElems / NumLanes;
6768
6769   // Blend for v16i16 should be symetric for the both lanes.
6770   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6771
6772     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6773     int EltIdx = MaskVals[i];
6774
6775     if ((EltIdx < 0 || EltIdx == (int)i) &&
6776         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6777       continue;
6778
6779     if (((unsigned)EltIdx == (i + NumElems)) &&
6780         (SndLaneEltIdx < 0 ||
6781          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6782       MaskValue |= (1 << i);
6783     else
6784       return false;
6785   }
6786
6787   if (MaskOut)
6788     *MaskOut = MaskValue;
6789   return true;
6790 }
6791
6792 // Try to lower a shuffle node into a simple blend instruction.
6793 // This function assumes isBlendMask returns true for this
6794 // SuffleVectorSDNode
6795 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6796                                           unsigned MaskValue,
6797                                           const X86Subtarget *Subtarget,
6798                                           SelectionDAG &DAG) {
6799   MVT VT = SVOp->getSimpleValueType(0);
6800   MVT EltVT = VT.getVectorElementType();
6801   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6802                      Subtarget->hasInt256() && "Trying to lower a "
6803                                                "VECTOR_SHUFFLE to a Blend but "
6804                                                "with the wrong mask"));
6805   SDValue V1 = SVOp->getOperand(0);
6806   SDValue V2 = SVOp->getOperand(1);
6807   SDLoc dl(SVOp);
6808   unsigned NumElems = VT.getVectorNumElements();
6809
6810   // Convert i32 vectors to floating point if it is not AVX2.
6811   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6812   MVT BlendVT = VT;
6813   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6814     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6815                                NumElems);
6816     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6817     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6818   }
6819
6820   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6821                             DAG.getConstant(MaskValue, MVT::i32));
6822   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6823 }
6824
6825 /// In vector type \p VT, return true if the element at index \p InputIdx
6826 /// falls on a different 128-bit lane than \p OutputIdx.
6827 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6828                                      unsigned OutputIdx) {
6829   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6830   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6831 }
6832
6833 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6834 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6835 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6836 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6837 /// zero.
6838 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6839                          SelectionDAG &DAG) {
6840   MVT VT = V1.getSimpleValueType();
6841   assert(VT.is128BitVector() || VT.is256BitVector());
6842
6843   MVT EltVT = VT.getVectorElementType();
6844   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6845   unsigned NumElts = VT.getVectorNumElements();
6846
6847   SmallVector<SDValue, 32> PshufbMask;
6848   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6849     int InputIdx = MaskVals[OutputIdx];
6850     unsigned InputByteIdx;
6851
6852     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6853       InputByteIdx = 0x80;
6854     else {
6855       // Cross lane is not allowed.
6856       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6857         return SDValue();
6858       InputByteIdx = InputIdx * EltSizeInBytes;
6859       // Index is an byte offset within the 128-bit lane.
6860       InputByteIdx &= 0xf;
6861     }
6862
6863     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6864       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6865       if (InputByteIdx != 0x80)
6866         ++InputByteIdx;
6867     }
6868   }
6869
6870   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6871   if (ShufVT != VT)
6872     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6873   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6874                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6875 }
6876
6877 // v8i16 shuffles - Prefer shuffles in the following order:
6878 // 1. [all]   pshuflw, pshufhw, optional move
6879 // 2. [ssse3] 1 x pshufb
6880 // 3. [ssse3] 2 x pshufb + 1 x por
6881 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6882 static SDValue
6883 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6884                          SelectionDAG &DAG) {
6885   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6886   SDValue V1 = SVOp->getOperand(0);
6887   SDValue V2 = SVOp->getOperand(1);
6888   SDLoc dl(SVOp);
6889   SmallVector<int, 8> MaskVals;
6890
6891   // Determine if more than 1 of the words in each of the low and high quadwords
6892   // of the result come from the same quadword of one of the two inputs.  Undef
6893   // mask values count as coming from any quadword, for better codegen.
6894   //
6895   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6896   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6897   unsigned LoQuad[] = { 0, 0, 0, 0 };
6898   unsigned HiQuad[] = { 0, 0, 0, 0 };
6899   // Indices of quads used.
6900   std::bitset<4> InputQuads;
6901   for (unsigned i = 0; i < 8; ++i) {
6902     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6903     int EltIdx = SVOp->getMaskElt(i);
6904     MaskVals.push_back(EltIdx);
6905     if (EltIdx < 0) {
6906       ++Quad[0];
6907       ++Quad[1];
6908       ++Quad[2];
6909       ++Quad[3];
6910       continue;
6911     }
6912     ++Quad[EltIdx / 4];
6913     InputQuads.set(EltIdx / 4);
6914   }
6915
6916   int BestLoQuad = -1;
6917   unsigned MaxQuad = 1;
6918   for (unsigned i = 0; i < 4; ++i) {
6919     if (LoQuad[i] > MaxQuad) {
6920       BestLoQuad = i;
6921       MaxQuad = LoQuad[i];
6922     }
6923   }
6924
6925   int BestHiQuad = -1;
6926   MaxQuad = 1;
6927   for (unsigned i = 0; i < 4; ++i) {
6928     if (HiQuad[i] > MaxQuad) {
6929       BestHiQuad = i;
6930       MaxQuad = HiQuad[i];
6931     }
6932   }
6933
6934   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6935   // of the two input vectors, shuffle them into one input vector so only a
6936   // single pshufb instruction is necessary. If there are more than 2 input
6937   // quads, disable the next transformation since it does not help SSSE3.
6938   bool V1Used = InputQuads[0] || InputQuads[1];
6939   bool V2Used = InputQuads[2] || InputQuads[3];
6940   if (Subtarget->hasSSSE3()) {
6941     if (InputQuads.count() == 2 && V1Used && V2Used) {
6942       BestLoQuad = InputQuads[0] ? 0 : 1;
6943       BestHiQuad = InputQuads[2] ? 2 : 3;
6944     }
6945     if (InputQuads.count() > 2) {
6946       BestLoQuad = -1;
6947       BestHiQuad = -1;
6948     }
6949   }
6950
6951   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6952   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6953   // words from all 4 input quadwords.
6954   SDValue NewV;
6955   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6956     int MaskV[] = {
6957       BestLoQuad < 0 ? 0 : BestLoQuad,
6958       BestHiQuad < 0 ? 1 : BestHiQuad
6959     };
6960     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6961                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6962                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6963     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6964
6965     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6966     // source words for the shuffle, to aid later transformations.
6967     bool AllWordsInNewV = true;
6968     bool InOrder[2] = { true, true };
6969     for (unsigned i = 0; i != 8; ++i) {
6970       int idx = MaskVals[i];
6971       if (idx != (int)i)
6972         InOrder[i/4] = false;
6973       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6974         continue;
6975       AllWordsInNewV = false;
6976       break;
6977     }
6978
6979     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6980     if (AllWordsInNewV) {
6981       for (int i = 0; i != 8; ++i) {
6982         int idx = MaskVals[i];
6983         if (idx < 0)
6984           continue;
6985         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6986         if ((idx != i) && idx < 4)
6987           pshufhw = false;
6988         if ((idx != i) && idx > 3)
6989           pshuflw = false;
6990       }
6991       V1 = NewV;
6992       V2Used = false;
6993       BestLoQuad = 0;
6994       BestHiQuad = 1;
6995     }
6996
6997     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6998     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6999     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
7000       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
7001       unsigned TargetMask = 0;
7002       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
7003                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
7004       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7005       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
7006                              getShufflePSHUFLWImmediate(SVOp);
7007       V1 = NewV.getOperand(0);
7008       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
7009     }
7010   }
7011
7012   // Promote splats to a larger type which usually leads to more efficient code.
7013   // FIXME: Is this true if pshufb is available?
7014   if (SVOp->isSplat())
7015     return PromoteSplat(SVOp, DAG);
7016
7017   // If we have SSSE3, and all words of the result are from 1 input vector,
7018   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
7019   // is present, fall back to case 4.
7020   if (Subtarget->hasSSSE3()) {
7021     SmallVector<SDValue,16> pshufbMask;
7022
7023     // If we have elements from both input vectors, set the high bit of the
7024     // shuffle mask element to zero out elements that come from V2 in the V1
7025     // mask, and elements that come from V1 in the V2 mask, so that the two
7026     // results can be OR'd together.
7027     bool TwoInputs = V1Used && V2Used;
7028     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
7029     if (!TwoInputs)
7030       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7031
7032     // Calculate the shuffle mask for the second input, shuffle it, and
7033     // OR it with the first shuffled input.
7034     CommuteVectorShuffleMask(MaskVals, 8);
7035     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
7036     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7037     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7038   }
7039
7040   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
7041   // and update MaskVals with new element order.
7042   std::bitset<8> InOrder;
7043   if (BestLoQuad >= 0) {
7044     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
7045     for (int i = 0; i != 4; ++i) {
7046       int idx = MaskVals[i];
7047       if (idx < 0) {
7048         InOrder.set(i);
7049       } else if ((idx / 4) == BestLoQuad) {
7050         MaskV[i] = idx & 3;
7051         InOrder.set(i);
7052       }
7053     }
7054     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7055                                 &MaskV[0]);
7056
7057     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7058       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7059       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
7060                                   NewV.getOperand(0),
7061                                   getShufflePSHUFLWImmediate(SVOp), DAG);
7062     }
7063   }
7064
7065   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
7066   // and update MaskVals with the new element order.
7067   if (BestHiQuad >= 0) {
7068     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
7069     for (unsigned i = 4; i != 8; ++i) {
7070       int idx = MaskVals[i];
7071       if (idx < 0) {
7072         InOrder.set(i);
7073       } else if ((idx / 4) == BestHiQuad) {
7074         MaskV[i] = (idx & 3) + 4;
7075         InOrder.set(i);
7076       }
7077     }
7078     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
7079                                 &MaskV[0]);
7080
7081     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
7082       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
7083       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
7084                                   NewV.getOperand(0),
7085                                   getShufflePSHUFHWImmediate(SVOp), DAG);
7086     }
7087   }
7088
7089   // In case BestHi & BestLo were both -1, which means each quadword has a word
7090   // from each of the four input quadwords, calculate the InOrder bitvector now
7091   // before falling through to the insert/extract cleanup.
7092   if (BestLoQuad == -1 && BestHiQuad == -1) {
7093     NewV = V1;
7094     for (int i = 0; i != 8; ++i)
7095       if (MaskVals[i] < 0 || MaskVals[i] == i)
7096         InOrder.set(i);
7097   }
7098
7099   // The other elements are put in the right place using pextrw and pinsrw.
7100   for (unsigned i = 0; i != 8; ++i) {
7101     if (InOrder[i])
7102       continue;
7103     int EltIdx = MaskVals[i];
7104     if (EltIdx < 0)
7105       continue;
7106     SDValue ExtOp = (EltIdx < 8) ?
7107       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
7108                   DAG.getIntPtrConstant(EltIdx)) :
7109       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
7110                   DAG.getIntPtrConstant(EltIdx - 8));
7111     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
7112                        DAG.getIntPtrConstant(i));
7113   }
7114   return NewV;
7115 }
7116
7117 /// \brief v16i16 shuffles
7118 ///
7119 /// FIXME: We only support generation of a single pshufb currently.  We can
7120 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
7121 /// well (e.g 2 x pshufb + 1 x por).
7122 static SDValue
7123 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
7124   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7125   SDValue V1 = SVOp->getOperand(0);
7126   SDValue V2 = SVOp->getOperand(1);
7127   SDLoc dl(SVOp);
7128
7129   if (V2.getOpcode() != ISD::UNDEF)
7130     return SDValue();
7131
7132   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7133   return getPSHUFB(MaskVals, V1, dl, DAG);
7134 }
7135
7136 // v16i8 shuffles - Prefer shuffles in the following order:
7137 // 1. [ssse3] 1 x pshufb
7138 // 2. [ssse3] 2 x pshufb + 1 x por
7139 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
7140 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
7141                                         const X86Subtarget* Subtarget,
7142                                         SelectionDAG &DAG) {
7143   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7144   SDValue V1 = SVOp->getOperand(0);
7145   SDValue V2 = SVOp->getOperand(1);
7146   SDLoc dl(SVOp);
7147   ArrayRef<int> MaskVals = SVOp->getMask();
7148
7149   // Promote splats to a larger type which usually leads to more efficient code.
7150   // FIXME: Is this true if pshufb is available?
7151   if (SVOp->isSplat())
7152     return PromoteSplat(SVOp, DAG);
7153
7154   // If we have SSSE3, case 1 is generated when all result bytes come from
7155   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
7156   // present, fall back to case 3.
7157
7158   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
7159   if (Subtarget->hasSSSE3()) {
7160     SmallVector<SDValue,16> pshufbMask;
7161
7162     // If all result elements are from one input vector, then only translate
7163     // undef mask values to 0x80 (zero out result) in the pshufb mask.
7164     //
7165     // Otherwise, we have elements from both input vectors, and must zero out
7166     // elements that come from V2 in the first mask, and V1 in the second mask
7167     // so that we can OR them together.
7168     for (unsigned i = 0; i != 16; ++i) {
7169       int EltIdx = MaskVals[i];
7170       if (EltIdx < 0 || EltIdx >= 16)
7171         EltIdx = 0x80;
7172       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7173     }
7174     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
7175                      DAG.getNode(ISD::BUILD_VECTOR, dl,
7176                                  MVT::v16i8, pshufbMask));
7177
7178     // As PSHUFB will zero elements with negative indices, it's safe to ignore
7179     // the 2nd operand if it's undefined or zero.
7180     if (V2.getOpcode() == ISD::UNDEF ||
7181         ISD::isBuildVectorAllZeros(V2.getNode()))
7182       return V1;
7183
7184     // Calculate the shuffle mask for the second input, shuffle it, and
7185     // OR it with the first shuffled input.
7186     pshufbMask.clear();
7187     for (unsigned i = 0; i != 16; ++i) {
7188       int EltIdx = MaskVals[i];
7189       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
7190       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
7191     }
7192     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
7193                      DAG.getNode(ISD::BUILD_VECTOR, dl,
7194                                  MVT::v16i8, pshufbMask));
7195     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
7196   }
7197
7198   // No SSSE3 - Calculate in place words and then fix all out of place words
7199   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
7200   // the 16 different words that comprise the two doublequadword input vectors.
7201   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
7202   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
7203   SDValue NewV = V1;
7204   for (int i = 0; i != 8; ++i) {
7205     int Elt0 = MaskVals[i*2];
7206     int Elt1 = MaskVals[i*2+1];
7207
7208     // This word of the result is all undef, skip it.
7209     if (Elt0 < 0 && Elt1 < 0)
7210       continue;
7211
7212     // This word of the result is already in the correct place, skip it.
7213     if ((Elt0 == i*2) && (Elt1 == i*2+1))
7214       continue;
7215
7216     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
7217     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
7218     SDValue InsElt;
7219
7220     // If Elt0 and Elt1 are defined, are consecutive, and can be load
7221     // using a single extract together, load it and store it.
7222     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
7223       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7224                            DAG.getIntPtrConstant(Elt1 / 2));
7225       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7226                         DAG.getIntPtrConstant(i));
7227       continue;
7228     }
7229
7230     // If Elt1 is defined, extract it from the appropriate source.  If the
7231     // source byte is not also odd, shift the extracted word left 8 bits
7232     // otherwise clear the bottom 8 bits if we need to do an or.
7233     if (Elt1 >= 0) {
7234       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
7235                            DAG.getIntPtrConstant(Elt1 / 2));
7236       if ((Elt1 & 1) == 0)
7237         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
7238                              DAG.getConstant(8,
7239                                   TLI.getShiftAmountTy(InsElt.getValueType())));
7240       else if (Elt0 >= 0)
7241         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
7242                              DAG.getConstant(0xFF00, MVT::i16));
7243     }
7244     // If Elt0 is defined, extract it from the appropriate source.  If the
7245     // source byte is not also even, shift the extracted word right 8 bits. If
7246     // Elt1 was also defined, OR the extracted values together before
7247     // inserting them in the result.
7248     if (Elt0 >= 0) {
7249       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
7250                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
7251       if ((Elt0 & 1) != 0)
7252         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
7253                               DAG.getConstant(8,
7254                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
7255       else if (Elt1 >= 0)
7256         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
7257                              DAG.getConstant(0x00FF, MVT::i16));
7258       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
7259                          : InsElt0;
7260     }
7261     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
7262                        DAG.getIntPtrConstant(i));
7263   }
7264   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
7265 }
7266
7267 // v32i8 shuffles - Translate to VPSHUFB if possible.
7268 static
7269 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
7270                                  const X86Subtarget *Subtarget,
7271                                  SelectionDAG &DAG) {
7272   MVT VT = SVOp->getSimpleValueType(0);
7273   SDValue V1 = SVOp->getOperand(0);
7274   SDValue V2 = SVOp->getOperand(1);
7275   SDLoc dl(SVOp);
7276   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
7277
7278   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7279   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
7280   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
7281
7282   // VPSHUFB may be generated if
7283   // (1) one of input vector is undefined or zeroinitializer.
7284   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
7285   // And (2) the mask indexes don't cross the 128-bit lane.
7286   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
7287       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
7288     return SDValue();
7289
7290   if (V1IsAllZero && !V2IsAllZero) {
7291     CommuteVectorShuffleMask(MaskVals, 32);
7292     V1 = V2;
7293   }
7294   return getPSHUFB(MaskVals, V1, dl, DAG);
7295 }
7296
7297 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
7298 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
7299 /// done when every pair / quad of shuffle mask elements point to elements in
7300 /// the right sequence. e.g.
7301 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
7302 static
7303 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
7304                                  SelectionDAG &DAG) {
7305   MVT VT = SVOp->getSimpleValueType(0);
7306   SDLoc dl(SVOp);
7307   unsigned NumElems = VT.getVectorNumElements();
7308   MVT NewVT;
7309   unsigned Scale;
7310   switch (VT.SimpleTy) {
7311   default: llvm_unreachable("Unexpected!");
7312   case MVT::v2i64:
7313   case MVT::v2f64:
7314            return SDValue(SVOp, 0);
7315   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
7316   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
7317   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
7318   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
7319   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
7320   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
7321   }
7322
7323   SmallVector<int, 8> MaskVec;
7324   for (unsigned i = 0; i != NumElems; i += Scale) {
7325     int StartIdx = -1;
7326     for (unsigned j = 0; j != Scale; ++j) {
7327       int EltIdx = SVOp->getMaskElt(i+j);
7328       if (EltIdx < 0)
7329         continue;
7330       if (StartIdx < 0)
7331         StartIdx = (EltIdx / Scale);
7332       if (EltIdx != (int)(StartIdx*Scale + j))
7333         return SDValue();
7334     }
7335     MaskVec.push_back(StartIdx);
7336   }
7337
7338   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7339   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7340   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7341 }
7342
7343 /// getVZextMovL - Return a zero-extending vector move low node.
7344 ///
7345 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7346                             SDValue SrcOp, SelectionDAG &DAG,
7347                             const X86Subtarget *Subtarget, SDLoc dl) {
7348   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7349     LoadSDNode *LD = nullptr;
7350     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7351       LD = dyn_cast<LoadSDNode>(SrcOp);
7352     if (!LD) {
7353       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7354       // instead.
7355       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7356       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7357           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7358           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7359           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7360         // PR2108
7361         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7362         return DAG.getNode(ISD::BITCAST, dl, VT,
7363                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7364                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7365                                                    OpVT,
7366                                                    SrcOp.getOperand(0)
7367                                                           .getOperand(0))));
7368       }
7369     }
7370   }
7371
7372   return DAG.getNode(ISD::BITCAST, dl, VT,
7373                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7374                                  DAG.getNode(ISD::BITCAST, dl,
7375                                              OpVT, SrcOp)));
7376 }
7377
7378 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7379 /// which could not be matched by any known target speficic shuffle
7380 static SDValue
7381 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7382
7383   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7384   if (NewOp.getNode())
7385     return NewOp;
7386
7387   MVT VT = SVOp->getSimpleValueType(0);
7388
7389   unsigned NumElems = VT.getVectorNumElements();
7390   unsigned NumLaneElems = NumElems / 2;
7391
7392   SDLoc dl(SVOp);
7393   MVT EltVT = VT.getVectorElementType();
7394   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7395   SDValue Output[2];
7396
7397   SmallVector<int, 16> Mask;
7398   for (unsigned l = 0; l < 2; ++l) {
7399     // Build a shuffle mask for the output, discovering on the fly which
7400     // input vectors to use as shuffle operands (recorded in InputUsed).
7401     // If building a suitable shuffle vector proves too hard, then bail
7402     // out with UseBuildVector set.
7403     bool UseBuildVector = false;
7404     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7405     unsigned LaneStart = l * NumLaneElems;
7406     for (unsigned i = 0; i != NumLaneElems; ++i) {
7407       // The mask element.  This indexes into the input.
7408       int Idx = SVOp->getMaskElt(i+LaneStart);
7409       if (Idx < 0) {
7410         // the mask element does not index into any input vector.
7411         Mask.push_back(-1);
7412         continue;
7413       }
7414
7415       // The input vector this mask element indexes into.
7416       int Input = Idx / NumLaneElems;
7417
7418       // Turn the index into an offset from the start of the input vector.
7419       Idx -= Input * NumLaneElems;
7420
7421       // Find or create a shuffle vector operand to hold this input.
7422       unsigned OpNo;
7423       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7424         if (InputUsed[OpNo] == Input)
7425           // This input vector is already an operand.
7426           break;
7427         if (InputUsed[OpNo] < 0) {
7428           // Create a new operand for this input vector.
7429           InputUsed[OpNo] = Input;
7430           break;
7431         }
7432       }
7433
7434       if (OpNo >= array_lengthof(InputUsed)) {
7435         // More than two input vectors used!  Give up on trying to create a
7436         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7437         UseBuildVector = true;
7438         break;
7439       }
7440
7441       // Add the mask index for the new shuffle vector.
7442       Mask.push_back(Idx + OpNo * NumLaneElems);
7443     }
7444
7445     if (UseBuildVector) {
7446       SmallVector<SDValue, 16> SVOps;
7447       for (unsigned i = 0; i != NumLaneElems; ++i) {
7448         // The mask element.  This indexes into the input.
7449         int Idx = SVOp->getMaskElt(i+LaneStart);
7450         if (Idx < 0) {
7451           SVOps.push_back(DAG.getUNDEF(EltVT));
7452           continue;
7453         }
7454
7455         // The input vector this mask element indexes into.
7456         int Input = Idx / NumElems;
7457
7458         // Turn the index into an offset from the start of the input vector.
7459         Idx -= Input * NumElems;
7460
7461         // Extract the vector element by hand.
7462         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7463                                     SVOp->getOperand(Input),
7464                                     DAG.getIntPtrConstant(Idx)));
7465       }
7466
7467       // Construct the output using a BUILD_VECTOR.
7468       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7469     } else if (InputUsed[0] < 0) {
7470       // No input vectors were used! The result is undefined.
7471       Output[l] = DAG.getUNDEF(NVT);
7472     } else {
7473       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7474                                         (InputUsed[0] % 2) * NumLaneElems,
7475                                         DAG, dl);
7476       // If only one input was used, use an undefined vector for the other.
7477       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7478         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7479                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7480       // At least one input vector was used. Create a new shuffle vector.
7481       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7482     }
7483
7484     Mask.clear();
7485   }
7486
7487   // Concatenate the result back
7488   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7489 }
7490
7491 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7492 /// 4 elements, and match them with several different shuffle types.
7493 static SDValue
7494 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7495   SDValue V1 = SVOp->getOperand(0);
7496   SDValue V2 = SVOp->getOperand(1);
7497   SDLoc dl(SVOp);
7498   MVT VT = SVOp->getSimpleValueType(0);
7499
7500   assert(VT.is128BitVector() && "Unsupported vector size");
7501
7502   std::pair<int, int> Locs[4];
7503   int Mask1[] = { -1, -1, -1, -1 };
7504   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7505
7506   unsigned NumHi = 0;
7507   unsigned NumLo = 0;
7508   for (unsigned i = 0; i != 4; ++i) {
7509     int Idx = PermMask[i];
7510     if (Idx < 0) {
7511       Locs[i] = std::make_pair(-1, -1);
7512     } else {
7513       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7514       if (Idx < 4) {
7515         Locs[i] = std::make_pair(0, NumLo);
7516         Mask1[NumLo] = Idx;
7517         NumLo++;
7518       } else {
7519         Locs[i] = std::make_pair(1, NumHi);
7520         if (2+NumHi < 4)
7521           Mask1[2+NumHi] = Idx;
7522         NumHi++;
7523       }
7524     }
7525   }
7526
7527   if (NumLo <= 2 && NumHi <= 2) {
7528     // If no more than two elements come from either vector. This can be
7529     // implemented with two shuffles. First shuffle gather the elements.
7530     // The second shuffle, which takes the first shuffle as both of its
7531     // vector operands, put the elements into the right order.
7532     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7533
7534     int Mask2[] = { -1, -1, -1, -1 };
7535
7536     for (unsigned i = 0; i != 4; ++i)
7537       if (Locs[i].first != -1) {
7538         unsigned Idx = (i < 2) ? 0 : 4;
7539         Idx += Locs[i].first * 2 + Locs[i].second;
7540         Mask2[i] = Idx;
7541       }
7542
7543     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7544   }
7545
7546   if (NumLo == 3 || NumHi == 3) {
7547     // Otherwise, we must have three elements from one vector, call it X, and
7548     // one element from the other, call it Y.  First, use a shufps to build an
7549     // intermediate vector with the one element from Y and the element from X
7550     // that will be in the same half in the final destination (the indexes don't
7551     // matter). Then, use a shufps to build the final vector, taking the half
7552     // containing the element from Y from the intermediate, and the other half
7553     // from X.
7554     if (NumHi == 3) {
7555       // Normalize it so the 3 elements come from V1.
7556       CommuteVectorShuffleMask(PermMask, 4);
7557       std::swap(V1, V2);
7558     }
7559
7560     // Find the element from V2.
7561     unsigned HiIndex;
7562     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7563       int Val = PermMask[HiIndex];
7564       if (Val < 0)
7565         continue;
7566       if (Val >= 4)
7567         break;
7568     }
7569
7570     Mask1[0] = PermMask[HiIndex];
7571     Mask1[1] = -1;
7572     Mask1[2] = PermMask[HiIndex^1];
7573     Mask1[3] = -1;
7574     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7575
7576     if (HiIndex >= 2) {
7577       Mask1[0] = PermMask[0];
7578       Mask1[1] = PermMask[1];
7579       Mask1[2] = HiIndex & 1 ? 6 : 4;
7580       Mask1[3] = HiIndex & 1 ? 4 : 6;
7581       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7582     }
7583
7584     Mask1[0] = HiIndex & 1 ? 2 : 0;
7585     Mask1[1] = HiIndex & 1 ? 0 : 2;
7586     Mask1[2] = PermMask[2];
7587     Mask1[3] = PermMask[3];
7588     if (Mask1[2] >= 0)
7589       Mask1[2] += 4;
7590     if (Mask1[3] >= 0)
7591       Mask1[3] += 4;
7592     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7593   }
7594
7595   // Break it into (shuffle shuffle_hi, shuffle_lo).
7596   int LoMask[] = { -1, -1, -1, -1 };
7597   int HiMask[] = { -1, -1, -1, -1 };
7598
7599   int *MaskPtr = LoMask;
7600   unsigned MaskIdx = 0;
7601   unsigned LoIdx = 0;
7602   unsigned HiIdx = 2;
7603   for (unsigned i = 0; i != 4; ++i) {
7604     if (i == 2) {
7605       MaskPtr = HiMask;
7606       MaskIdx = 1;
7607       LoIdx = 0;
7608       HiIdx = 2;
7609     }
7610     int Idx = PermMask[i];
7611     if (Idx < 0) {
7612       Locs[i] = std::make_pair(-1, -1);
7613     } else if (Idx < 4) {
7614       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7615       MaskPtr[LoIdx] = Idx;
7616       LoIdx++;
7617     } else {
7618       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7619       MaskPtr[HiIdx] = Idx;
7620       HiIdx++;
7621     }
7622   }
7623
7624   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7625   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7626   int MaskOps[] = { -1, -1, -1, -1 };
7627   for (unsigned i = 0; i != 4; ++i)
7628     if (Locs[i].first != -1)
7629       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7630   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7631 }
7632
7633 static bool MayFoldVectorLoad(SDValue V) {
7634   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7635     V = V.getOperand(0);
7636
7637   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7638     V = V.getOperand(0);
7639   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7640       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7641     // BUILD_VECTOR (load), undef
7642     V = V.getOperand(0);
7643
7644   return MayFoldLoad(V);
7645 }
7646
7647 static
7648 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7649   MVT VT = Op.getSimpleValueType();
7650
7651   // Canonizalize to v2f64.
7652   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7653   return DAG.getNode(ISD::BITCAST, dl, VT,
7654                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7655                                           V1, DAG));
7656 }
7657
7658 static
7659 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7660                         bool HasSSE2) {
7661   SDValue V1 = Op.getOperand(0);
7662   SDValue V2 = Op.getOperand(1);
7663   MVT VT = Op.getSimpleValueType();
7664
7665   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7666
7667   if (HasSSE2 && VT == MVT::v2f64)
7668     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7669
7670   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7671   return DAG.getNode(ISD::BITCAST, dl, VT,
7672                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7673                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7674                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7675 }
7676
7677 static
7678 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7679   SDValue V1 = Op.getOperand(0);
7680   SDValue V2 = Op.getOperand(1);
7681   MVT VT = Op.getSimpleValueType();
7682
7683   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7684          "unsupported shuffle type");
7685
7686   if (V2.getOpcode() == ISD::UNDEF)
7687     V2 = V1;
7688
7689   // v4i32 or v4f32
7690   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7691 }
7692
7693 static
7694 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7695   SDValue V1 = Op.getOperand(0);
7696   SDValue V2 = Op.getOperand(1);
7697   MVT VT = Op.getSimpleValueType();
7698   unsigned NumElems = VT.getVectorNumElements();
7699
7700   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7701   // operand of these instructions is only memory, so check if there's a
7702   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7703   // same masks.
7704   bool CanFoldLoad = false;
7705
7706   // Trivial case, when V2 comes from a load.
7707   if (MayFoldVectorLoad(V2))
7708     CanFoldLoad = true;
7709
7710   // When V1 is a load, it can be folded later into a store in isel, example:
7711   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7712   //    turns into:
7713   //  (MOVLPSmr addr:$src1, VR128:$src2)
7714   // So, recognize this potential and also use MOVLPS or MOVLPD
7715   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7716     CanFoldLoad = true;
7717
7718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7719   if (CanFoldLoad) {
7720     if (HasSSE2 && NumElems == 2)
7721       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7722
7723     if (NumElems == 4)
7724       // If we don't care about the second element, proceed to use movss.
7725       if (SVOp->getMaskElt(1) != -1)
7726         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7727   }
7728
7729   // movl and movlp will both match v2i64, but v2i64 is never matched by
7730   // movl earlier because we make it strict to avoid messing with the movlp load
7731   // folding logic (see the code above getMOVLP call). Match it here then,
7732   // this is horrible, but will stay like this until we move all shuffle
7733   // matching to x86 specific nodes. Note that for the 1st condition all
7734   // types are matched with movsd.
7735   if (HasSSE2) {
7736     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7737     // as to remove this logic from here, as much as possible
7738     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7739       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7740     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7741   }
7742
7743   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7744
7745   // Invert the operand order and use SHUFPS to match it.
7746   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7747                               getShuffleSHUFImmediate(SVOp), DAG);
7748 }
7749
7750 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7751                                          SelectionDAG &DAG) {
7752   SDLoc dl(Load);
7753   MVT VT = Load->getSimpleValueType(0);
7754   MVT EVT = VT.getVectorElementType();
7755   SDValue Addr = Load->getOperand(1);
7756   SDValue NewAddr = DAG.getNode(
7757       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7758       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7759
7760   SDValue NewLoad =
7761       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7762                   DAG.getMachineFunction().getMachineMemOperand(
7763                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7764   return NewLoad;
7765 }
7766
7767 // It is only safe to call this function if isINSERTPSMask is true for
7768 // this shufflevector mask.
7769 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7770                            SelectionDAG &DAG) {
7771   // Generate an insertps instruction when inserting an f32 from memory onto a
7772   // v4f32 or when copying a member from one v4f32 to another.
7773   // We also use it for transferring i32 from one register to another,
7774   // since it simply copies the same bits.
7775   // If we're transferring an i32 from memory to a specific element in a
7776   // register, we output a generic DAG that will match the PINSRD
7777   // instruction.
7778   MVT VT = SVOp->getSimpleValueType(0);
7779   MVT EVT = VT.getVectorElementType();
7780   SDValue V1 = SVOp->getOperand(0);
7781   SDValue V2 = SVOp->getOperand(1);
7782   auto Mask = SVOp->getMask();
7783   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7784          "unsupported vector type for insertps/pinsrd");
7785
7786   auto FromV1Predicate = [](const int &i) { return i < 4 && i > -1; };
7787   auto FromV2Predicate = [](const int &i) { return i >= 4; };
7788   int FromV1 = std::count_if(Mask.begin(), Mask.end(), FromV1Predicate);
7789
7790   SDValue From;
7791   SDValue To;
7792   unsigned DestIndex;
7793   if (FromV1 == 1) {
7794     From = V1;
7795     To = V2;
7796     DestIndex = std::find_if(Mask.begin(), Mask.end(), FromV1Predicate) -
7797                 Mask.begin();
7798   } else {
7799     assert(std::count_if(Mask.begin(), Mask.end(), FromV2Predicate) == 1 &&
7800            "More than one element from V1 and from V2, or no elements from one "
7801            "of the vectors. This case should not have returned true from "
7802            "isINSERTPSMask");
7803     From = V2;
7804     To = V1;
7805     DestIndex =
7806         std::find_if(Mask.begin(), Mask.end(), FromV2Predicate) - Mask.begin();
7807   }
7808
7809   if (MayFoldLoad(From)) {
7810     // Trivial case, when From comes from a load and is only used by the
7811     // shuffle. Make it use insertps from the vector that we need from that
7812     // load.
7813     SDValue NewLoad =
7814         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7815     if (!NewLoad.getNode())
7816       return SDValue();
7817
7818     if (EVT == MVT::f32) {
7819       // Create this as a scalar to vector to match the instruction pattern.
7820       SDValue LoadScalarToVector =
7821           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7822       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7823       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7824                          InsertpsMask);
7825     } else { // EVT == MVT::i32
7826       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7827       // instruction, to match the PINSRD instruction, which loads an i32 to a
7828       // certain vector element.
7829       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7830                          DAG.getConstant(DestIndex, MVT::i32));
7831     }
7832   }
7833
7834   // Vector-element-to-vector
7835   unsigned SrcIndex = Mask[DestIndex] % 4;
7836   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7837   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7838 }
7839
7840 // Reduce a vector shuffle to zext.
7841 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7842                                     SelectionDAG &DAG) {
7843   // PMOVZX is only available from SSE41.
7844   if (!Subtarget->hasSSE41())
7845     return SDValue();
7846
7847   MVT VT = Op.getSimpleValueType();
7848
7849   // Only AVX2 support 256-bit vector integer extending.
7850   if (!Subtarget->hasInt256() && VT.is256BitVector())
7851     return SDValue();
7852
7853   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7854   SDLoc DL(Op);
7855   SDValue V1 = Op.getOperand(0);
7856   SDValue V2 = Op.getOperand(1);
7857   unsigned NumElems = VT.getVectorNumElements();
7858
7859   // Extending is an unary operation and the element type of the source vector
7860   // won't be equal to or larger than i64.
7861   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7862       VT.getVectorElementType() == MVT::i64)
7863     return SDValue();
7864
7865   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7866   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7867   while ((1U << Shift) < NumElems) {
7868     if (SVOp->getMaskElt(1U << Shift) == 1)
7869       break;
7870     Shift += 1;
7871     // The maximal ratio is 8, i.e. from i8 to i64.
7872     if (Shift > 3)
7873       return SDValue();
7874   }
7875
7876   // Check the shuffle mask.
7877   unsigned Mask = (1U << Shift) - 1;
7878   for (unsigned i = 0; i != NumElems; ++i) {
7879     int EltIdx = SVOp->getMaskElt(i);
7880     if ((i & Mask) != 0 && EltIdx != -1)
7881       return SDValue();
7882     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7883       return SDValue();
7884   }
7885
7886   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7887   MVT NeVT = MVT::getIntegerVT(NBits);
7888   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7889
7890   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7891     return SDValue();
7892
7893   // Simplify the operand as it's prepared to be fed into shuffle.
7894   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7895   if (V1.getOpcode() == ISD::BITCAST &&
7896       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7897       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7898       V1.getOperand(0).getOperand(0)
7899         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7900     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7901     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7902     ConstantSDNode *CIdx =
7903       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7904     // If it's foldable, i.e. normal load with single use, we will let code
7905     // selection to fold it. Otherwise, we will short the conversion sequence.
7906     if (CIdx && CIdx->getZExtValue() == 0 &&
7907         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7908       MVT FullVT = V.getSimpleValueType();
7909       MVT V1VT = V1.getSimpleValueType();
7910       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7911         // The "ext_vec_elt" node is wider than the result node.
7912         // In this case we should extract subvector from V.
7913         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7914         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7915         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7916                                         FullVT.getVectorNumElements()/Ratio);
7917         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7918                         DAG.getIntPtrConstant(0));
7919       }
7920       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7921     }
7922   }
7923
7924   return DAG.getNode(ISD::BITCAST, DL, VT,
7925                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7926 }
7927
7928 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7929                                       SelectionDAG &DAG) {
7930   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7931   MVT VT = Op.getSimpleValueType();
7932   SDLoc dl(Op);
7933   SDValue V1 = Op.getOperand(0);
7934   SDValue V2 = Op.getOperand(1);
7935
7936   if (isZeroShuffle(SVOp))
7937     return getZeroVector(VT, Subtarget, DAG, dl);
7938
7939   // Handle splat operations
7940   if (SVOp->isSplat()) {
7941     // Use vbroadcast whenever the splat comes from a foldable load
7942     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7943     if (Broadcast.getNode())
7944       return Broadcast;
7945   }
7946
7947   // Check integer expanding shuffles.
7948   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7949   if (NewOp.getNode())
7950     return NewOp;
7951
7952   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7953   // do it!
7954   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7955       VT == MVT::v32i8) {
7956     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7957     if (NewOp.getNode())
7958       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7959   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7960     // FIXME: Figure out a cleaner way to do this.
7961     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7962       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7963       if (NewOp.getNode()) {
7964         MVT NewVT = NewOp.getSimpleValueType();
7965         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7966                                NewVT, true, false))
7967           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7968                               dl);
7969       }
7970     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7971       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7972       if (NewOp.getNode()) {
7973         MVT NewVT = NewOp.getSimpleValueType();
7974         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7975           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7976                               dl);
7977       }
7978     }
7979   }
7980   return SDValue();
7981 }
7982
7983 SDValue
7984 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7985   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7986   SDValue V1 = Op.getOperand(0);
7987   SDValue V2 = Op.getOperand(1);
7988   MVT VT = Op.getSimpleValueType();
7989   SDLoc dl(Op);
7990   unsigned NumElems = VT.getVectorNumElements();
7991   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7992   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7993   bool V1IsSplat = false;
7994   bool V2IsSplat = false;
7995   bool HasSSE2 = Subtarget->hasSSE2();
7996   bool HasFp256    = Subtarget->hasFp256();
7997   bool HasInt256   = Subtarget->hasInt256();
7998   MachineFunction &MF = DAG.getMachineFunction();
7999   bool OptForSize = MF.getFunction()->getAttributes().
8000     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
8001
8002   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
8003
8004   if (V1IsUndef && V2IsUndef)
8005     return DAG.getUNDEF(VT);
8006
8007   // When we create a shuffle node we put the UNDEF node to second operand,
8008   // but in some cases the first operand may be transformed to UNDEF.
8009   // In this case we should just commute the node.
8010   if (V1IsUndef)
8011     return CommuteVectorShuffle(SVOp, DAG);
8012
8013   // Vector shuffle lowering takes 3 steps:
8014   //
8015   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
8016   //    narrowing and commutation of operands should be handled.
8017   // 2) Matching of shuffles with known shuffle masks to x86 target specific
8018   //    shuffle nodes.
8019   // 3) Rewriting of unmatched masks into new generic shuffle operations,
8020   //    so the shuffle can be broken into other shuffles and the legalizer can
8021   //    try the lowering again.
8022   //
8023   // The general idea is that no vector_shuffle operation should be left to
8024   // be matched during isel, all of them must be converted to a target specific
8025   // node here.
8026
8027   // Normalize the input vectors. Here splats, zeroed vectors, profitable
8028   // narrowing and commutation of operands should be handled. The actual code
8029   // doesn't include all of those, work in progress...
8030   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
8031   if (NewOp.getNode())
8032     return NewOp;
8033
8034   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
8035
8036   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
8037   // unpckh_undef). Only use pshufd if speed is more important than size.
8038   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8039     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8040   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8041     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8042
8043   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
8044       V2IsUndef && MayFoldVectorLoad(V1))
8045     return getMOVDDup(Op, dl, V1, DAG);
8046
8047   if (isMOVHLPS_v_undef_Mask(M, VT))
8048     return getMOVHighToLow(Op, dl, DAG);
8049
8050   // Use to match splats
8051   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
8052       (VT == MVT::v2f64 || VT == MVT::v2i64))
8053     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8054
8055   if (isPSHUFDMask(M, VT)) {
8056     // The actual implementation will match the mask in the if above and then
8057     // during isel it can match several different instructions, not only pshufd
8058     // as its name says, sad but true, emulate the behavior for now...
8059     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
8060       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
8061
8062     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
8063
8064     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
8065       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
8066
8067     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
8068       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
8069                                   DAG);
8070
8071     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
8072                                 TargetMask, DAG);
8073   }
8074
8075   if (isPALIGNRMask(M, VT, Subtarget))
8076     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
8077                                 getShufflePALIGNRImmediate(SVOp),
8078                                 DAG);
8079
8080   // Check if this can be converted into a logical shift.
8081   bool isLeft = false;
8082   unsigned ShAmt = 0;
8083   SDValue ShVal;
8084   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
8085   if (isShift && ShVal.hasOneUse()) {
8086     // If the shifted value has multiple uses, it may be cheaper to use
8087     // v_set0 + movlhps or movhlps, etc.
8088     MVT EltVT = VT.getVectorElementType();
8089     ShAmt *= EltVT.getSizeInBits();
8090     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8091   }
8092
8093   if (isMOVLMask(M, VT)) {
8094     if (ISD::isBuildVectorAllZeros(V1.getNode()))
8095       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
8096     if (!isMOVLPMask(M, VT)) {
8097       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
8098         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
8099
8100       if (VT == MVT::v4i32 || VT == MVT::v4f32)
8101         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
8102     }
8103   }
8104
8105   // FIXME: fold these into legal mask.
8106   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
8107     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
8108
8109   if (isMOVHLPSMask(M, VT))
8110     return getMOVHighToLow(Op, dl, DAG);
8111
8112   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
8113     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
8114
8115   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
8116     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
8117
8118   if (isMOVLPMask(M, VT))
8119     return getMOVLP(Op, dl, DAG, HasSSE2);
8120
8121   if (ShouldXformToMOVHLPS(M, VT) ||
8122       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
8123     return CommuteVectorShuffle(SVOp, DAG);
8124
8125   if (isShift) {
8126     // No better options. Use a vshldq / vsrldq.
8127     MVT EltVT = VT.getVectorElementType();
8128     ShAmt *= EltVT.getSizeInBits();
8129     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
8130   }
8131
8132   bool Commuted = false;
8133   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
8134   // 1,1,1,1 -> v8i16 though.
8135   V1IsSplat = isSplatVector(V1.getNode());
8136   V2IsSplat = isSplatVector(V2.getNode());
8137
8138   // Canonicalize the splat or undef, if present, to be on the RHS.
8139   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
8140     CommuteVectorShuffleMask(M, NumElems);
8141     std::swap(V1, V2);
8142     std::swap(V1IsSplat, V2IsSplat);
8143     Commuted = true;
8144   }
8145
8146   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
8147     // Shuffling low element of v1 into undef, just return v1.
8148     if (V2IsUndef)
8149       return V1;
8150     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
8151     // the instruction selector will not match, so get a canonical MOVL with
8152     // swapped operands to undo the commute.
8153     return getMOVL(DAG, dl, VT, V2, V1);
8154   }
8155
8156   if (isUNPCKLMask(M, VT, HasInt256))
8157     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8158
8159   if (isUNPCKHMask(M, VT, HasInt256))
8160     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8161
8162   if (V2IsSplat) {
8163     // Normalize mask so all entries that point to V2 points to its first
8164     // element then try to match unpck{h|l} again. If match, return a
8165     // new vector_shuffle with the corrected mask.p
8166     SmallVector<int, 8> NewMask(M.begin(), M.end());
8167     NormalizeMask(NewMask, NumElems);
8168     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
8169       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8170     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
8171       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8172   }
8173
8174   if (Commuted) {
8175     // Commute is back and try unpck* again.
8176     // FIXME: this seems wrong.
8177     CommuteVectorShuffleMask(M, NumElems);
8178     std::swap(V1, V2);
8179     std::swap(V1IsSplat, V2IsSplat);
8180
8181     if (isUNPCKLMask(M, VT, HasInt256))
8182       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
8183
8184     if (isUNPCKHMask(M, VT, HasInt256))
8185       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
8186   }
8187
8188   // Normalize the node to match x86 shuffle ops if needed
8189   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
8190     return CommuteVectorShuffle(SVOp, DAG);
8191
8192   // The checks below are all present in isShuffleMaskLegal, but they are
8193   // inlined here right now to enable us to directly emit target specific
8194   // nodes, and remove one by one until they don't return Op anymore.
8195
8196   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
8197       SVOp->getSplatIndex() == 0 && V2IsUndef) {
8198     if (VT == MVT::v2f64 || VT == MVT::v2i64)
8199       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8200   }
8201
8202   if (isPSHUFHWMask(M, VT, HasInt256))
8203     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
8204                                 getShufflePSHUFHWImmediate(SVOp),
8205                                 DAG);
8206
8207   if (isPSHUFLWMask(M, VT, HasInt256))
8208     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
8209                                 getShufflePSHUFLWImmediate(SVOp),
8210                                 DAG);
8211
8212   if (isSHUFPMask(M, VT))
8213     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
8214                                 getShuffleSHUFImmediate(SVOp), DAG);
8215
8216   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
8217     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
8218   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
8219     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
8220
8221   //===--------------------------------------------------------------------===//
8222   // Generate target specific nodes for 128 or 256-bit shuffles only
8223   // supported in the AVX instruction set.
8224   //
8225
8226   // Handle VMOVDDUPY permutations
8227   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
8228     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
8229
8230   // Handle VPERMILPS/D* permutations
8231   if (isVPERMILPMask(M, VT)) {
8232     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
8233       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
8234                                   getShuffleSHUFImmediate(SVOp), DAG);
8235     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
8236                                 getShuffleSHUFImmediate(SVOp), DAG);
8237   }
8238
8239   unsigned Idx;
8240   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
8241     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
8242                               Idx*(NumElems/2), DAG, dl);
8243
8244   // Handle VPERM2F128/VPERM2I128 permutations
8245   if (isVPERM2X128Mask(M, VT, HasFp256))
8246     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
8247                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
8248
8249   unsigned MaskValue;
8250   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
8251                   &MaskValue))
8252     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
8253
8254   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
8255     return getINSERTPS(SVOp, dl, DAG);
8256
8257   unsigned Imm8;
8258   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
8259     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
8260
8261   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
8262       VT.is512BitVector()) {
8263     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
8264     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
8265     SmallVector<SDValue, 16> permclMask;
8266     for (unsigned i = 0; i != NumElems; ++i) {
8267       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
8268     }
8269
8270     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
8271     if (V2IsUndef)
8272       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
8273       return DAG.getNode(X86ISD::VPERMV, dl, VT,
8274                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
8275     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
8276                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
8277   }
8278
8279   //===--------------------------------------------------------------------===//
8280   // Since no target specific shuffle was selected for this generic one,
8281   // lower it into other known shuffles. FIXME: this isn't true yet, but
8282   // this is the plan.
8283   //
8284
8285   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
8286   if (VT == MVT::v8i16) {
8287     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
8288     if (NewOp.getNode())
8289       return NewOp;
8290   }
8291
8292   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
8293     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
8294     if (NewOp.getNode())
8295       return NewOp;
8296   }
8297
8298   if (VT == MVT::v16i8) {
8299     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
8300     if (NewOp.getNode())
8301       return NewOp;
8302   }
8303
8304   if (VT == MVT::v32i8) {
8305     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
8306     if (NewOp.getNode())
8307       return NewOp;
8308   }
8309
8310   // Handle all 128-bit wide vectors with 4 elements, and match them with
8311   // several different shuffle types.
8312   if (NumElems == 4 && VT.is128BitVector())
8313     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
8314
8315   // Handle general 256-bit shuffles
8316   if (VT.is256BitVector())
8317     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
8318
8319   return SDValue();
8320 }
8321
8322 // This function assumes its argument is a BUILD_VECTOR of constants or
8323 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8324 // true.
8325 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8326                                     unsigned &MaskValue) {
8327   MaskValue = 0;
8328   unsigned NumElems = BuildVector->getNumOperands();
8329   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8330   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8331   unsigned NumElemsInLane = NumElems / NumLanes;
8332
8333   // Blend for v16i16 should be symetric for the both lanes.
8334   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8335     SDValue EltCond = BuildVector->getOperand(i);
8336     SDValue SndLaneEltCond =
8337         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8338
8339     int Lane1Cond = -1, Lane2Cond = -1;
8340     if (isa<ConstantSDNode>(EltCond))
8341       Lane1Cond = !isZero(EltCond);
8342     if (isa<ConstantSDNode>(SndLaneEltCond))
8343       Lane2Cond = !isZero(SndLaneEltCond);
8344
8345     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8346       // Lane1Cond != 0, means we want the first argument.
8347       // Lane1Cond == 0, means we want the second argument.
8348       // The encoding of this argument is 0 for the first argument, 1
8349       // for the second. Therefore, invert the condition.
8350       MaskValue |= !Lane1Cond << i;
8351     else if (Lane1Cond < 0)
8352       MaskValue |= !Lane2Cond << i;
8353     else
8354       return false;
8355   }
8356   return true;
8357 }
8358
8359 // Try to lower a vselect node into a simple blend instruction.
8360 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8361                                    SelectionDAG &DAG) {
8362   SDValue Cond = Op.getOperand(0);
8363   SDValue LHS = Op.getOperand(1);
8364   SDValue RHS = Op.getOperand(2);
8365   SDLoc dl(Op);
8366   MVT VT = Op.getSimpleValueType();
8367   MVT EltVT = VT.getVectorElementType();
8368   unsigned NumElems = VT.getVectorNumElements();
8369
8370   // There is no blend with immediate in AVX-512.
8371   if (VT.is512BitVector())
8372     return SDValue();
8373
8374   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8375     return SDValue();
8376   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8377     return SDValue();
8378
8379   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8380     return SDValue();
8381
8382   // Check the mask for BLEND and build the value.
8383   unsigned MaskValue = 0;
8384   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8385     return SDValue();
8386
8387   // Convert i32 vectors to floating point if it is not AVX2.
8388   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8389   MVT BlendVT = VT;
8390   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8391     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8392                                NumElems);
8393     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8394     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8395   }
8396
8397   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8398                             DAG.getConstant(MaskValue, MVT::i32));
8399   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8400 }
8401
8402 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8403   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8404   if (BlendOp.getNode())
8405     return BlendOp;
8406
8407   // Some types for vselect were previously set to Expand, not Legal or
8408   // Custom. Return an empty SDValue so we fall-through to Expand, after
8409   // the Custom lowering phase.
8410   MVT VT = Op.getSimpleValueType();
8411   switch (VT.SimpleTy) {
8412   default:
8413     break;
8414   case MVT::v8i16:
8415   case MVT::v16i16:
8416     return SDValue();
8417   }
8418
8419   // We couldn't create a "Blend with immediate" node.
8420   // This node should still be legal, but we'll have to emit a blendv*
8421   // instruction.
8422   return Op;
8423 }
8424
8425 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8426   MVT VT = Op.getSimpleValueType();
8427   SDLoc dl(Op);
8428
8429   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8430     return SDValue();
8431
8432   if (VT.getSizeInBits() == 8) {
8433     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8434                                   Op.getOperand(0), Op.getOperand(1));
8435     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8436                                   DAG.getValueType(VT));
8437     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8438   }
8439
8440   if (VT.getSizeInBits() == 16) {
8441     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8442     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8443     if (Idx == 0)
8444       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8445                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8446                                      DAG.getNode(ISD::BITCAST, dl,
8447                                                  MVT::v4i32,
8448                                                  Op.getOperand(0)),
8449                                      Op.getOperand(1)));
8450     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8451                                   Op.getOperand(0), Op.getOperand(1));
8452     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8453                                   DAG.getValueType(VT));
8454     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8455   }
8456
8457   if (VT == MVT::f32) {
8458     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8459     // the result back to FR32 register. It's only worth matching if the
8460     // result has a single use which is a store or a bitcast to i32.  And in
8461     // the case of a store, it's not worth it if the index is a constant 0,
8462     // because a MOVSSmr can be used instead, which is smaller and faster.
8463     if (!Op.hasOneUse())
8464       return SDValue();
8465     SDNode *User = *Op.getNode()->use_begin();
8466     if ((User->getOpcode() != ISD::STORE ||
8467          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8468           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8469         (User->getOpcode() != ISD::BITCAST ||
8470          User->getValueType(0) != MVT::i32))
8471       return SDValue();
8472     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8473                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8474                                               Op.getOperand(0)),
8475                                               Op.getOperand(1));
8476     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8477   }
8478
8479   if (VT == MVT::i32 || VT == MVT::i64) {
8480     // ExtractPS/pextrq works with constant index.
8481     if (isa<ConstantSDNode>(Op.getOperand(1)))
8482       return Op;
8483   }
8484   return SDValue();
8485 }
8486
8487 /// Extract one bit from mask vector, like v16i1 or v8i1.
8488 /// AVX-512 feature.
8489 SDValue
8490 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8491   SDValue Vec = Op.getOperand(0);
8492   SDLoc dl(Vec);
8493   MVT VecVT = Vec.getSimpleValueType();
8494   SDValue Idx = Op.getOperand(1);
8495   MVT EltVT = Op.getSimpleValueType();
8496
8497   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8498
8499   // variable index can't be handled in mask registers,
8500   // extend vector to VR512
8501   if (!isa<ConstantSDNode>(Idx)) {
8502     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8503     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8504     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8505                               ExtVT.getVectorElementType(), Ext, Idx);
8506     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8507   }
8508
8509   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8510   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8511   unsigned MaxSift = rc->getSize()*8 - 1;
8512   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8513                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8514   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8515                     DAG.getConstant(MaxSift, MVT::i8));
8516   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8517                        DAG.getIntPtrConstant(0));
8518 }
8519
8520 SDValue
8521 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8522                                            SelectionDAG &DAG) const {
8523   SDLoc dl(Op);
8524   SDValue Vec = Op.getOperand(0);
8525   MVT VecVT = Vec.getSimpleValueType();
8526   SDValue Idx = Op.getOperand(1);
8527
8528   if (Op.getSimpleValueType() == MVT::i1)
8529     return ExtractBitFromMaskVector(Op, DAG);
8530
8531   if (!isa<ConstantSDNode>(Idx)) {
8532     if (VecVT.is512BitVector() ||
8533         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8534          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8535
8536       MVT MaskEltVT =
8537         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8538       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8539                                     MaskEltVT.getSizeInBits());
8540
8541       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8542       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8543                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8544                                 Idx, DAG.getConstant(0, getPointerTy()));
8545       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8546       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8547                         Perm, DAG.getConstant(0, getPointerTy()));
8548     }
8549     return SDValue();
8550   }
8551
8552   // If this is a 256-bit vector result, first extract the 128-bit vector and
8553   // then extract the element from the 128-bit vector.
8554   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8555
8556     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8557     // Get the 128-bit vector.
8558     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8559     MVT EltVT = VecVT.getVectorElementType();
8560
8561     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8562
8563     //if (IdxVal >= NumElems/2)
8564     //  IdxVal -= NumElems/2;
8565     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8566     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8567                        DAG.getConstant(IdxVal, MVT::i32));
8568   }
8569
8570   assert(VecVT.is128BitVector() && "Unexpected vector length");
8571
8572   if (Subtarget->hasSSE41()) {
8573     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8574     if (Res.getNode())
8575       return Res;
8576   }
8577
8578   MVT VT = Op.getSimpleValueType();
8579   // TODO: handle v16i8.
8580   if (VT.getSizeInBits() == 16) {
8581     SDValue Vec = Op.getOperand(0);
8582     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8583     if (Idx == 0)
8584       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8585                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8586                                      DAG.getNode(ISD::BITCAST, dl,
8587                                                  MVT::v4i32, Vec),
8588                                      Op.getOperand(1)));
8589     // Transform it so it match pextrw which produces a 32-bit result.
8590     MVT EltVT = MVT::i32;
8591     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8592                                   Op.getOperand(0), Op.getOperand(1));
8593     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8594                                   DAG.getValueType(VT));
8595     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8596   }
8597
8598   if (VT.getSizeInBits() == 32) {
8599     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8600     if (Idx == 0)
8601       return Op;
8602
8603     // SHUFPS the element to the lowest double word, then movss.
8604     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8605     MVT VVT = Op.getOperand(0).getSimpleValueType();
8606     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8607                                        DAG.getUNDEF(VVT), Mask);
8608     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8609                        DAG.getIntPtrConstant(0));
8610   }
8611
8612   if (VT.getSizeInBits() == 64) {
8613     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8614     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8615     //        to match extract_elt for f64.
8616     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8617     if (Idx == 0)
8618       return Op;
8619
8620     // UNPCKHPD the element to the lowest double word, then movsd.
8621     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8622     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8623     int Mask[2] = { 1, -1 };
8624     MVT VVT = Op.getOperand(0).getSimpleValueType();
8625     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8626                                        DAG.getUNDEF(VVT), Mask);
8627     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8628                        DAG.getIntPtrConstant(0));
8629   }
8630
8631   return SDValue();
8632 }
8633
8634 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8635   MVT VT = Op.getSimpleValueType();
8636   MVT EltVT = VT.getVectorElementType();
8637   SDLoc dl(Op);
8638
8639   SDValue N0 = Op.getOperand(0);
8640   SDValue N1 = Op.getOperand(1);
8641   SDValue N2 = Op.getOperand(2);
8642
8643   if (!VT.is128BitVector())
8644     return SDValue();
8645
8646   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8647       isa<ConstantSDNode>(N2)) {
8648     unsigned Opc;
8649     if (VT == MVT::v8i16)
8650       Opc = X86ISD::PINSRW;
8651     else if (VT == MVT::v16i8)
8652       Opc = X86ISD::PINSRB;
8653     else
8654       Opc = X86ISD::PINSRB;
8655
8656     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8657     // argument.
8658     if (N1.getValueType() != MVT::i32)
8659       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8660     if (N2.getValueType() != MVT::i32)
8661       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8662     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8663   }
8664
8665   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8666     // Bits [7:6] of the constant are the source select.  This will always be
8667     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8668     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8669     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8670     // Bits [5:4] of the constant are the destination select.  This is the
8671     //  value of the incoming immediate.
8672     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8673     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8674     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8675     // Create this as a scalar to vector..
8676     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8677     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8678   }
8679
8680   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8681     // PINSR* works with constant index.
8682     return Op;
8683   }
8684   return SDValue();
8685 }
8686
8687 /// Insert one bit to mask vector, like v16i1 or v8i1.
8688 /// AVX-512 feature.
8689 SDValue 
8690 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8691   SDLoc dl(Op);
8692   SDValue Vec = Op.getOperand(0);
8693   SDValue Elt = Op.getOperand(1);
8694   SDValue Idx = Op.getOperand(2);
8695   MVT VecVT = Vec.getSimpleValueType();
8696
8697   if (!isa<ConstantSDNode>(Idx)) {
8698     // Non constant index. Extend source and destination,
8699     // insert element and then truncate the result.
8700     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8701     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8702     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8703       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8704       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8705     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8706   }
8707
8708   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8709   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8710   if (Vec.getOpcode() == ISD::UNDEF)
8711     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8712                        DAG.getConstant(IdxVal, MVT::i8));
8713   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8714   unsigned MaxSift = rc->getSize()*8 - 1;
8715   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8716                     DAG.getConstant(MaxSift, MVT::i8));
8717   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8718                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8719   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8720 }
8721 SDValue
8722 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8723   MVT VT = Op.getSimpleValueType();
8724   MVT EltVT = VT.getVectorElementType();
8725   
8726   if (EltVT == MVT::i1)
8727     return InsertBitToMaskVector(Op, DAG);
8728
8729   SDLoc dl(Op);
8730   SDValue N0 = Op.getOperand(0);
8731   SDValue N1 = Op.getOperand(1);
8732   SDValue N2 = Op.getOperand(2);
8733
8734   // If this is a 256-bit vector result, first extract the 128-bit vector,
8735   // insert the element into the extracted half and then place it back.
8736   if (VT.is256BitVector() || VT.is512BitVector()) {
8737     if (!isa<ConstantSDNode>(N2))
8738       return SDValue();
8739
8740     // Get the desired 128-bit vector half.
8741     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8742     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8743
8744     // Insert the element into the desired half.
8745     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8746     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8747
8748     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8749                     DAG.getConstant(IdxIn128, MVT::i32));
8750
8751     // Insert the changed part back to the 256-bit vector
8752     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8753   }
8754
8755   if (Subtarget->hasSSE41())
8756     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8757
8758   if (EltVT == MVT::i8)
8759     return SDValue();
8760
8761   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8762     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8763     // as its second argument.
8764     if (N1.getValueType() != MVT::i32)
8765       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8766     if (N2.getValueType() != MVT::i32)
8767       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8768     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8769   }
8770   return SDValue();
8771 }
8772
8773 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8774   SDLoc dl(Op);
8775   MVT OpVT = Op.getSimpleValueType();
8776
8777   // If this is a 256-bit vector result, first insert into a 128-bit
8778   // vector and then insert into the 256-bit vector.
8779   if (!OpVT.is128BitVector()) {
8780     // Insert into a 128-bit vector.
8781     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8782     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8783                                  OpVT.getVectorNumElements() / SizeFactor);
8784
8785     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8786
8787     // Insert the 128-bit vector.
8788     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8789   }
8790
8791   if (OpVT == MVT::v1i64 &&
8792       Op.getOperand(0).getValueType() == MVT::i64)
8793     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8794
8795   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8796   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8797   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8798                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8799 }
8800
8801 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8802 // a simple subregister reference or explicit instructions to grab
8803 // upper bits of a vector.
8804 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8805                                       SelectionDAG &DAG) {
8806   SDLoc dl(Op);
8807   SDValue In =  Op.getOperand(0);
8808   SDValue Idx = Op.getOperand(1);
8809   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8810   MVT ResVT   = Op.getSimpleValueType();
8811   MVT InVT    = In.getSimpleValueType();
8812
8813   if (Subtarget->hasFp256()) {
8814     if (ResVT.is128BitVector() &&
8815         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8816         isa<ConstantSDNode>(Idx)) {
8817       return Extract128BitVector(In, IdxVal, DAG, dl);
8818     }
8819     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8820         isa<ConstantSDNode>(Idx)) {
8821       return Extract256BitVector(In, IdxVal, DAG, dl);
8822     }
8823   }
8824   return SDValue();
8825 }
8826
8827 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8828 // simple superregister reference or explicit instructions to insert
8829 // the upper bits of a vector.
8830 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8831                                      SelectionDAG &DAG) {
8832   if (Subtarget->hasFp256()) {
8833     SDLoc dl(Op.getNode());
8834     SDValue Vec = Op.getNode()->getOperand(0);
8835     SDValue SubVec = Op.getNode()->getOperand(1);
8836     SDValue Idx = Op.getNode()->getOperand(2);
8837
8838     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8839          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8840         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8841         isa<ConstantSDNode>(Idx)) {
8842       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8843       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8844     }
8845
8846     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8847         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8848         isa<ConstantSDNode>(Idx)) {
8849       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8850       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8851     }
8852   }
8853   return SDValue();
8854 }
8855
8856 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8857 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8858 // one of the above mentioned nodes. It has to be wrapped because otherwise
8859 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8860 // be used to form addressing mode. These wrapped nodes will be selected
8861 // into MOV32ri.
8862 SDValue
8863 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8864   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8865
8866   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8867   // global base reg.
8868   unsigned char OpFlag = 0;
8869   unsigned WrapperKind = X86ISD::Wrapper;
8870   CodeModel::Model M = DAG.getTarget().getCodeModel();
8871
8872   if (Subtarget->isPICStyleRIPRel() &&
8873       (M == CodeModel::Small || M == CodeModel::Kernel))
8874     WrapperKind = X86ISD::WrapperRIP;
8875   else if (Subtarget->isPICStyleGOT())
8876     OpFlag = X86II::MO_GOTOFF;
8877   else if (Subtarget->isPICStyleStubPIC())
8878     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8879
8880   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8881                                              CP->getAlignment(),
8882                                              CP->getOffset(), OpFlag);
8883   SDLoc DL(CP);
8884   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8885   // With PIC, the address is actually $g + Offset.
8886   if (OpFlag) {
8887     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8888                          DAG.getNode(X86ISD::GlobalBaseReg,
8889                                      SDLoc(), getPointerTy()),
8890                          Result);
8891   }
8892
8893   return Result;
8894 }
8895
8896 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8897   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8898
8899   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8900   // global base reg.
8901   unsigned char OpFlag = 0;
8902   unsigned WrapperKind = X86ISD::Wrapper;
8903   CodeModel::Model M = DAG.getTarget().getCodeModel();
8904
8905   if (Subtarget->isPICStyleRIPRel() &&
8906       (M == CodeModel::Small || M == CodeModel::Kernel))
8907     WrapperKind = X86ISD::WrapperRIP;
8908   else if (Subtarget->isPICStyleGOT())
8909     OpFlag = X86II::MO_GOTOFF;
8910   else if (Subtarget->isPICStyleStubPIC())
8911     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8912
8913   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8914                                           OpFlag);
8915   SDLoc DL(JT);
8916   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8917
8918   // With PIC, the address is actually $g + Offset.
8919   if (OpFlag)
8920     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8921                          DAG.getNode(X86ISD::GlobalBaseReg,
8922                                      SDLoc(), getPointerTy()),
8923                          Result);
8924
8925   return Result;
8926 }
8927
8928 SDValue
8929 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8930   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8931
8932   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8933   // global base reg.
8934   unsigned char OpFlag = 0;
8935   unsigned WrapperKind = X86ISD::Wrapper;
8936   CodeModel::Model M = DAG.getTarget().getCodeModel();
8937
8938   if (Subtarget->isPICStyleRIPRel() &&
8939       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8940     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8941       OpFlag = X86II::MO_GOTPCREL;
8942     WrapperKind = X86ISD::WrapperRIP;
8943   } else if (Subtarget->isPICStyleGOT()) {
8944     OpFlag = X86II::MO_GOT;
8945   } else if (Subtarget->isPICStyleStubPIC()) {
8946     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8947   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8948     OpFlag = X86II::MO_DARWIN_NONLAZY;
8949   }
8950
8951   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8952
8953   SDLoc DL(Op);
8954   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8955
8956   // With PIC, the address is actually $g + Offset.
8957   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
8958       !Subtarget->is64Bit()) {
8959     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8960                          DAG.getNode(X86ISD::GlobalBaseReg,
8961                                      SDLoc(), getPointerTy()),
8962                          Result);
8963   }
8964
8965   // For symbols that require a load from a stub to get the address, emit the
8966   // load.
8967   if (isGlobalStubReference(OpFlag))
8968     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8969                          MachinePointerInfo::getGOT(), false, false, false, 0);
8970
8971   return Result;
8972 }
8973
8974 SDValue
8975 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8976   // Create the TargetBlockAddressAddress node.
8977   unsigned char OpFlags =
8978     Subtarget->ClassifyBlockAddressReference();
8979   CodeModel::Model M = DAG.getTarget().getCodeModel();
8980   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8981   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8982   SDLoc dl(Op);
8983   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8984                                              OpFlags);
8985
8986   if (Subtarget->isPICStyleRIPRel() &&
8987       (M == CodeModel::Small || M == CodeModel::Kernel))
8988     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8989   else
8990     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8991
8992   // With PIC, the address is actually $g + Offset.
8993   if (isGlobalRelativeToPICBase(OpFlags)) {
8994     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8995                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8996                          Result);
8997   }
8998
8999   return Result;
9000 }
9001
9002 SDValue
9003 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
9004                                       int64_t Offset, SelectionDAG &DAG) const {
9005   // Create the TargetGlobalAddress node, folding in the constant
9006   // offset if it is legal.
9007   unsigned char OpFlags =
9008       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
9009   CodeModel::Model M = DAG.getTarget().getCodeModel();
9010   SDValue Result;
9011   if (OpFlags == X86II::MO_NO_FLAG &&
9012       X86::isOffsetSuitableForCodeModel(Offset, M)) {
9013     // A direct static reference to a global.
9014     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
9015     Offset = 0;
9016   } else {
9017     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
9018   }
9019
9020   if (Subtarget->isPICStyleRIPRel() &&
9021       (M == CodeModel::Small || M == CodeModel::Kernel))
9022     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
9023   else
9024     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
9025
9026   // With PIC, the address is actually $g + Offset.
9027   if (isGlobalRelativeToPICBase(OpFlags)) {
9028     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
9029                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
9030                          Result);
9031   }
9032
9033   // For globals that require a load from a stub to get the address, emit the
9034   // load.
9035   if (isGlobalStubReference(OpFlags))
9036     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
9037                          MachinePointerInfo::getGOT(), false, false, false, 0);
9038
9039   // If there was a non-zero offset that we didn't fold, create an explicit
9040   // addition for it.
9041   if (Offset != 0)
9042     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
9043                          DAG.getConstant(Offset, getPointerTy()));
9044
9045   return Result;
9046 }
9047
9048 SDValue
9049 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
9050   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
9051   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
9052   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
9053 }
9054
9055 static SDValue
9056 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
9057            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
9058            unsigned char OperandFlags, bool LocalDynamic = false) {
9059   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9060   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9061   SDLoc dl(GA);
9062   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9063                                            GA->getValueType(0),
9064                                            GA->getOffset(),
9065                                            OperandFlags);
9066
9067   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
9068                                            : X86ISD::TLSADDR;
9069
9070   if (InFlag) {
9071     SDValue Ops[] = { Chain,  TGA, *InFlag };
9072     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9073   } else {
9074     SDValue Ops[]  = { Chain, TGA };
9075     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
9076   }
9077
9078   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
9079   MFI->setAdjustsStack(true);
9080
9081   SDValue Flag = Chain.getValue(1);
9082   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
9083 }
9084
9085 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
9086 static SDValue
9087 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9088                                 const EVT PtrVT) {
9089   SDValue InFlag;
9090   SDLoc dl(GA);  // ? function entry point might be better
9091   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9092                                    DAG.getNode(X86ISD::GlobalBaseReg,
9093                                                SDLoc(), PtrVT), InFlag);
9094   InFlag = Chain.getValue(1);
9095
9096   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
9097 }
9098
9099 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
9100 static SDValue
9101 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9102                                 const EVT PtrVT) {
9103   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
9104                     X86::RAX, X86II::MO_TLSGD);
9105 }
9106
9107 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
9108                                            SelectionDAG &DAG,
9109                                            const EVT PtrVT,
9110                                            bool is64Bit) {
9111   SDLoc dl(GA);
9112
9113   // Get the start address of the TLS block for this module.
9114   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
9115       .getInfo<X86MachineFunctionInfo>();
9116   MFI->incNumLocalDynamicTLSAccesses();
9117
9118   SDValue Base;
9119   if (is64Bit) {
9120     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
9121                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
9122   } else {
9123     SDValue InFlag;
9124     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
9125         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
9126     InFlag = Chain.getValue(1);
9127     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
9128                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
9129   }
9130
9131   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
9132   // of Base.
9133
9134   // Build x@dtpoff.
9135   unsigned char OperandFlags = X86II::MO_DTPOFF;
9136   unsigned WrapperKind = X86ISD::Wrapper;
9137   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9138                                            GA->getValueType(0),
9139                                            GA->getOffset(), OperandFlags);
9140   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9141
9142   // Add x@dtpoff with the base.
9143   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
9144 }
9145
9146 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
9147 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
9148                                    const EVT PtrVT, TLSModel::Model model,
9149                                    bool is64Bit, bool isPIC) {
9150   SDLoc dl(GA);
9151
9152   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
9153   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
9154                                                          is64Bit ? 257 : 256));
9155
9156   SDValue ThreadPointer =
9157       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
9158                   MachinePointerInfo(Ptr), false, false, false, 0);
9159
9160   unsigned char OperandFlags = 0;
9161   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
9162   // initialexec.
9163   unsigned WrapperKind = X86ISD::Wrapper;
9164   if (model == TLSModel::LocalExec) {
9165     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
9166   } else if (model == TLSModel::InitialExec) {
9167     if (is64Bit) {
9168       OperandFlags = X86II::MO_GOTTPOFF;
9169       WrapperKind = X86ISD::WrapperRIP;
9170     } else {
9171       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
9172     }
9173   } else {
9174     llvm_unreachable("Unexpected model");
9175   }
9176
9177   // emit "addl x@ntpoff,%eax" (local exec)
9178   // or "addl x@indntpoff,%eax" (initial exec)
9179   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
9180   SDValue TGA =
9181       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
9182                                  GA->getOffset(), OperandFlags);
9183   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
9184
9185   if (model == TLSModel::InitialExec) {
9186     if (isPIC && !is64Bit) {
9187       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
9188                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
9189                            Offset);
9190     }
9191
9192     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
9193                          MachinePointerInfo::getGOT(), false, false, false, 0);
9194   }
9195
9196   // The address of the thread local variable is the add of the thread
9197   // pointer with the offset of the variable.
9198   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
9199 }
9200
9201 SDValue
9202 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
9203
9204   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
9205   const GlobalValue *GV = GA->getGlobal();
9206
9207   if (Subtarget->isTargetELF()) {
9208     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
9209
9210     switch (model) {
9211       case TLSModel::GeneralDynamic:
9212         if (Subtarget->is64Bit())
9213           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
9214         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
9215       case TLSModel::LocalDynamic:
9216         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
9217                                            Subtarget->is64Bit());
9218       case TLSModel::InitialExec:
9219       case TLSModel::LocalExec:
9220         return LowerToTLSExecModel(
9221             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
9222             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
9223     }
9224     llvm_unreachable("Unknown TLS model.");
9225   }
9226
9227   if (Subtarget->isTargetDarwin()) {
9228     // Darwin only has one model of TLS.  Lower to that.
9229     unsigned char OpFlag = 0;
9230     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
9231                            X86ISD::WrapperRIP : X86ISD::Wrapper;
9232
9233     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
9234     // global base reg.
9235     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
9236                  !Subtarget->is64Bit();
9237     if (PIC32)
9238       OpFlag = X86II::MO_TLVP_PIC_BASE;
9239     else
9240       OpFlag = X86II::MO_TLVP;
9241     SDLoc DL(Op);
9242     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
9243                                                 GA->getValueType(0),
9244                                                 GA->getOffset(), OpFlag);
9245     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
9246
9247     // With PIC32, the address is actually $g + Offset.
9248     if (PIC32)
9249       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
9250                            DAG.getNode(X86ISD::GlobalBaseReg,
9251                                        SDLoc(), getPointerTy()),
9252                            Offset);
9253
9254     // Lowering the machine isd will make sure everything is in the right
9255     // location.
9256     SDValue Chain = DAG.getEntryNode();
9257     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
9258     SDValue Args[] = { Chain, Offset };
9259     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
9260
9261     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
9262     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
9263     MFI->setAdjustsStack(true);
9264
9265     // And our return value (tls address) is in the standard call return value
9266     // location.
9267     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
9268     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
9269                               Chain.getValue(1));
9270   }
9271
9272   if (Subtarget->isTargetKnownWindowsMSVC() ||
9273       Subtarget->isTargetWindowsGNU()) {
9274     // Just use the implicit TLS architecture
9275     // Need to generate someting similar to:
9276     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
9277     //                                  ; from TEB
9278     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
9279     //   mov     rcx, qword [rdx+rcx*8]
9280     //   mov     eax, .tls$:tlsvar
9281     //   [rax+rcx] contains the address
9282     // Windows 64bit: gs:0x58
9283     // Windows 32bit: fs:__tls_array
9284
9285     SDLoc dl(GA);
9286     SDValue Chain = DAG.getEntryNode();
9287
9288     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
9289     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
9290     // use its literal value of 0x2C.
9291     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
9292                                         ? Type::getInt8PtrTy(*DAG.getContext(),
9293                                                              256)
9294                                         : Type::getInt32PtrTy(*DAG.getContext(),
9295                                                               257));
9296
9297     SDValue TlsArray =
9298         Subtarget->is64Bit()
9299             ? DAG.getIntPtrConstant(0x58)
9300             : (Subtarget->isTargetWindowsGNU()
9301                    ? DAG.getIntPtrConstant(0x2C)
9302                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
9303
9304     SDValue ThreadPointer =
9305         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
9306                     MachinePointerInfo(Ptr), false, false, false, 0);
9307
9308     // Load the _tls_index variable
9309     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
9310     if (Subtarget->is64Bit())
9311       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
9312                            IDX, MachinePointerInfo(), MVT::i32,
9313                            false, false, 0);
9314     else
9315       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
9316                         false, false, false, 0);
9317
9318     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
9319                                     getPointerTy());
9320     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
9321
9322     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
9323     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9324                       false, false, false, 0);
9325
9326     // Get the offset of start of .tls section
9327     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9328                                              GA->getValueType(0),
9329                                              GA->getOffset(), X86II::MO_SECREL);
9330     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9331
9332     // The address of the thread local variable is the add of the thread
9333     // pointer with the offset of the variable.
9334     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9335   }
9336
9337   llvm_unreachable("TLS not implemented for this target.");
9338 }
9339
9340 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9341 /// and take a 2 x i32 value to shift plus a shift amount.
9342 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9343   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9344   MVT VT = Op.getSimpleValueType();
9345   unsigned VTBits = VT.getSizeInBits();
9346   SDLoc dl(Op);
9347   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9348   SDValue ShOpLo = Op.getOperand(0);
9349   SDValue ShOpHi = Op.getOperand(1);
9350   SDValue ShAmt  = Op.getOperand(2);
9351   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9352   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9353   // during isel.
9354   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9355                                   DAG.getConstant(VTBits - 1, MVT::i8));
9356   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9357                                      DAG.getConstant(VTBits - 1, MVT::i8))
9358                        : DAG.getConstant(0, VT);
9359
9360   SDValue Tmp2, Tmp3;
9361   if (Op.getOpcode() == ISD::SHL_PARTS) {
9362     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9363     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9364   } else {
9365     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9366     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9367   }
9368
9369   // If the shift amount is larger or equal than the width of a part we can't
9370   // rely on the results of shld/shrd. Insert a test and select the appropriate
9371   // values for large shift amounts.
9372   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9373                                 DAG.getConstant(VTBits, MVT::i8));
9374   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9375                              AndNode, DAG.getConstant(0, MVT::i8));
9376
9377   SDValue Hi, Lo;
9378   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9379   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9380   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9381
9382   if (Op.getOpcode() == ISD::SHL_PARTS) {
9383     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9384     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9385   } else {
9386     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9387     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9388   }
9389
9390   SDValue Ops[2] = { Lo, Hi };
9391   return DAG.getMergeValues(Ops, dl);
9392 }
9393
9394 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9395                                            SelectionDAG &DAG) const {
9396   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9397
9398   if (SrcVT.isVector())
9399     return SDValue();
9400
9401   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9402          "Unknown SINT_TO_FP to lower!");
9403
9404   // These are really Legal; return the operand so the caller accepts it as
9405   // Legal.
9406   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9407     return Op;
9408   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9409       Subtarget->is64Bit()) {
9410     return Op;
9411   }
9412
9413   SDLoc dl(Op);
9414   unsigned Size = SrcVT.getSizeInBits()/8;
9415   MachineFunction &MF = DAG.getMachineFunction();
9416   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9417   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9418   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9419                                StackSlot,
9420                                MachinePointerInfo::getFixedStack(SSFI),
9421                                false, false, 0);
9422   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9423 }
9424
9425 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9426                                      SDValue StackSlot,
9427                                      SelectionDAG &DAG) const {
9428   // Build the FILD
9429   SDLoc DL(Op);
9430   SDVTList Tys;
9431   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9432   if (useSSE)
9433     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9434   else
9435     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9436
9437   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9438
9439   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9440   MachineMemOperand *MMO;
9441   if (FI) {
9442     int SSFI = FI->getIndex();
9443     MMO =
9444       DAG.getMachineFunction()
9445       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9446                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9447   } else {
9448     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9449     StackSlot = StackSlot.getOperand(1);
9450   }
9451   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9452   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9453                                            X86ISD::FILD, DL,
9454                                            Tys, Ops, SrcVT, MMO);
9455
9456   if (useSSE) {
9457     Chain = Result.getValue(1);
9458     SDValue InFlag = Result.getValue(2);
9459
9460     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9461     // shouldn't be necessary except that RFP cannot be live across
9462     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9463     MachineFunction &MF = DAG.getMachineFunction();
9464     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9465     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9466     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9467     Tys = DAG.getVTList(MVT::Other);
9468     SDValue Ops[] = {
9469       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9470     };
9471     MachineMemOperand *MMO =
9472       DAG.getMachineFunction()
9473       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9474                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9475
9476     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9477                                     Ops, Op.getValueType(), MMO);
9478     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9479                          MachinePointerInfo::getFixedStack(SSFI),
9480                          false, false, false, 0);
9481   }
9482
9483   return Result;
9484 }
9485
9486 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9487 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9488                                                SelectionDAG &DAG) const {
9489   // This algorithm is not obvious. Here it is what we're trying to output:
9490   /*
9491      movq       %rax,  %xmm0
9492      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9493      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9494      #ifdef __SSE3__
9495        haddpd   %xmm0, %xmm0
9496      #else
9497        pshufd   $0x4e, %xmm0, %xmm1
9498        addpd    %xmm1, %xmm0
9499      #endif
9500   */
9501
9502   SDLoc dl(Op);
9503   LLVMContext *Context = DAG.getContext();
9504
9505   // Build some magic constants.
9506   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9507   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9508   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9509
9510   SmallVector<Constant*,2> CV1;
9511   CV1.push_back(
9512     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9513                                       APInt(64, 0x4330000000000000ULL))));
9514   CV1.push_back(
9515     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9516                                       APInt(64, 0x4530000000000000ULL))));
9517   Constant *C1 = ConstantVector::get(CV1);
9518   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9519
9520   // Load the 64-bit value into an XMM register.
9521   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9522                             Op.getOperand(0));
9523   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9524                               MachinePointerInfo::getConstantPool(),
9525                               false, false, false, 16);
9526   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9527                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9528                               CLod0);
9529
9530   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9531                               MachinePointerInfo::getConstantPool(),
9532                               false, false, false, 16);
9533   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9534   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9535   SDValue Result;
9536
9537   if (Subtarget->hasSSE3()) {
9538     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9539     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9540   } else {
9541     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9542     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9543                                            S2F, 0x4E, DAG);
9544     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9545                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9546                          Sub);
9547   }
9548
9549   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9550                      DAG.getIntPtrConstant(0));
9551 }
9552
9553 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9554 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9555                                                SelectionDAG &DAG) const {
9556   SDLoc dl(Op);
9557   // FP constant to bias correct the final result.
9558   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9559                                    MVT::f64);
9560
9561   // Load the 32-bit value into an XMM register.
9562   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9563                              Op.getOperand(0));
9564
9565   // Zero out the upper parts of the register.
9566   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9567
9568   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9569                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9570                      DAG.getIntPtrConstant(0));
9571
9572   // Or the load with the bias.
9573   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9574                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9575                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9576                                                    MVT::v2f64, Load)),
9577                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9578                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9579                                                    MVT::v2f64, Bias)));
9580   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9581                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9582                    DAG.getIntPtrConstant(0));
9583
9584   // Subtract the bias.
9585   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9586
9587   // Handle final rounding.
9588   EVT DestVT = Op.getValueType();
9589
9590   if (DestVT.bitsLT(MVT::f64))
9591     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9592                        DAG.getIntPtrConstant(0));
9593   if (DestVT.bitsGT(MVT::f64))
9594     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9595
9596   // Handle final rounding.
9597   return Sub;
9598 }
9599
9600 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9601                                                SelectionDAG &DAG) const {
9602   SDValue N0 = Op.getOperand(0);
9603   MVT SVT = N0.getSimpleValueType();
9604   SDLoc dl(Op);
9605
9606   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9607           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9608          "Custom UINT_TO_FP is not supported!");
9609
9610   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9611   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9612                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9613 }
9614
9615 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9616                                            SelectionDAG &DAG) const {
9617   SDValue N0 = Op.getOperand(0);
9618   SDLoc dl(Op);
9619
9620   if (Op.getValueType().isVector())
9621     return lowerUINT_TO_FP_vec(Op, DAG);
9622
9623   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9624   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9625   // the optimization here.
9626   if (DAG.SignBitIsZero(N0))
9627     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9628
9629   MVT SrcVT = N0.getSimpleValueType();
9630   MVT DstVT = Op.getSimpleValueType();
9631   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9632     return LowerUINT_TO_FP_i64(Op, DAG);
9633   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9634     return LowerUINT_TO_FP_i32(Op, DAG);
9635   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9636     return SDValue();
9637
9638   // Make a 64-bit buffer, and use it to build an FILD.
9639   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9640   if (SrcVT == MVT::i32) {
9641     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9642     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9643                                      getPointerTy(), StackSlot, WordOff);
9644     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9645                                   StackSlot, MachinePointerInfo(),
9646                                   false, false, 0);
9647     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9648                                   OffsetSlot, MachinePointerInfo(),
9649                                   false, false, 0);
9650     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9651     return Fild;
9652   }
9653
9654   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9655   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9656                                StackSlot, MachinePointerInfo(),
9657                                false, false, 0);
9658   // For i64 source, we need to add the appropriate power of 2 if the input
9659   // was negative.  This is the same as the optimization in
9660   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9661   // we must be careful to do the computation in x87 extended precision, not
9662   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9663   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9664   MachineMemOperand *MMO =
9665     DAG.getMachineFunction()
9666     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9667                           MachineMemOperand::MOLoad, 8, 8);
9668
9669   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9670   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9671   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9672                                          MVT::i64, MMO);
9673
9674   APInt FF(32, 0x5F800000ULL);
9675
9676   // Check whether the sign bit is set.
9677   SDValue SignSet = DAG.getSetCC(dl,
9678                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9679                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9680                                  ISD::SETLT);
9681
9682   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9683   SDValue FudgePtr = DAG.getConstantPool(
9684                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9685                                          getPointerTy());
9686
9687   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9688   SDValue Zero = DAG.getIntPtrConstant(0);
9689   SDValue Four = DAG.getIntPtrConstant(4);
9690   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9691                                Zero, Four);
9692   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9693
9694   // Load the value out, extending it from f32 to f80.
9695   // FIXME: Avoid the extend by constructing the right constant pool?
9696   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9697                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9698                                  MVT::f32, false, false, 4);
9699   // Extend everything to 80 bits to force it to be done on x87.
9700   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9701   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9702 }
9703
9704 std::pair<SDValue,SDValue>
9705 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9706                                     bool IsSigned, bool IsReplace) const {
9707   SDLoc DL(Op);
9708
9709   EVT DstTy = Op.getValueType();
9710
9711   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9712     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9713     DstTy = MVT::i64;
9714   }
9715
9716   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9717          DstTy.getSimpleVT() >= MVT::i16 &&
9718          "Unknown FP_TO_INT to lower!");
9719
9720   // These are really Legal.
9721   if (DstTy == MVT::i32 &&
9722       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9723     return std::make_pair(SDValue(), SDValue());
9724   if (Subtarget->is64Bit() &&
9725       DstTy == MVT::i64 &&
9726       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9727     return std::make_pair(SDValue(), SDValue());
9728
9729   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9730   // stack slot, or into the FTOL runtime function.
9731   MachineFunction &MF = DAG.getMachineFunction();
9732   unsigned MemSize = DstTy.getSizeInBits()/8;
9733   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9734   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9735
9736   unsigned Opc;
9737   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9738     Opc = X86ISD::WIN_FTOL;
9739   else
9740     switch (DstTy.getSimpleVT().SimpleTy) {
9741     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9742     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9743     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9744     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9745     }
9746
9747   SDValue Chain = DAG.getEntryNode();
9748   SDValue Value = Op.getOperand(0);
9749   EVT TheVT = Op.getOperand(0).getValueType();
9750   // FIXME This causes a redundant load/store if the SSE-class value is already
9751   // in memory, such as if it is on the callstack.
9752   if (isScalarFPTypeInSSEReg(TheVT)) {
9753     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9754     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9755                          MachinePointerInfo::getFixedStack(SSFI),
9756                          false, false, 0);
9757     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9758     SDValue Ops[] = {
9759       Chain, StackSlot, DAG.getValueType(TheVT)
9760     };
9761
9762     MachineMemOperand *MMO =
9763       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9764                               MachineMemOperand::MOLoad, MemSize, MemSize);
9765     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9766     Chain = Value.getValue(1);
9767     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9768     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9769   }
9770
9771   MachineMemOperand *MMO =
9772     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9773                             MachineMemOperand::MOStore, MemSize, MemSize);
9774
9775   if (Opc != X86ISD::WIN_FTOL) {
9776     // Build the FP_TO_INT*_IN_MEM
9777     SDValue Ops[] = { Chain, Value, StackSlot };
9778     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9779                                            Ops, DstTy, MMO);
9780     return std::make_pair(FIST, StackSlot);
9781   } else {
9782     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9783       DAG.getVTList(MVT::Other, MVT::Glue),
9784       Chain, Value);
9785     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9786       MVT::i32, ftol.getValue(1));
9787     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9788       MVT::i32, eax.getValue(2));
9789     SDValue Ops[] = { eax, edx };
9790     SDValue pair = IsReplace
9791       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9792       : DAG.getMergeValues(Ops, DL);
9793     return std::make_pair(pair, SDValue());
9794   }
9795 }
9796
9797 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9798                               const X86Subtarget *Subtarget) {
9799   MVT VT = Op->getSimpleValueType(0);
9800   SDValue In = Op->getOperand(0);
9801   MVT InVT = In.getSimpleValueType();
9802   SDLoc dl(Op);
9803
9804   // Optimize vectors in AVX mode:
9805   //
9806   //   v8i16 -> v8i32
9807   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9808   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9809   //   Concat upper and lower parts.
9810   //
9811   //   v4i32 -> v4i64
9812   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9813   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9814   //   Concat upper and lower parts.
9815   //
9816
9817   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9818       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9819       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9820     return SDValue();
9821
9822   if (Subtarget->hasInt256())
9823     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9824
9825   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9826   SDValue Undef = DAG.getUNDEF(InVT);
9827   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9828   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9829   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9830
9831   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9832                              VT.getVectorNumElements()/2);
9833
9834   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9835   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9836
9837   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9838 }
9839
9840 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9841                                         SelectionDAG &DAG) {
9842   MVT VT = Op->getSimpleValueType(0);
9843   SDValue In = Op->getOperand(0);
9844   MVT InVT = In.getSimpleValueType();
9845   SDLoc DL(Op);
9846   unsigned int NumElts = VT.getVectorNumElements();
9847   if (NumElts != 8 && NumElts != 16)
9848     return SDValue();
9849
9850   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9851     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9852
9853   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9854   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9855   // Now we have only mask extension
9856   assert(InVT.getVectorElementType() == MVT::i1);
9857   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9858   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9859   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9860   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9861   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9862                            MachinePointerInfo::getConstantPool(),
9863                            false, false, false, Alignment);
9864
9865   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9866   if (VT.is512BitVector())
9867     return Brcst;
9868   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9869 }
9870
9871 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9872                                SelectionDAG &DAG) {
9873   if (Subtarget->hasFp256()) {
9874     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9875     if (Res.getNode())
9876       return Res;
9877   }
9878
9879   return SDValue();
9880 }
9881
9882 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9883                                 SelectionDAG &DAG) {
9884   SDLoc DL(Op);
9885   MVT VT = Op.getSimpleValueType();
9886   SDValue In = Op.getOperand(0);
9887   MVT SVT = In.getSimpleValueType();
9888
9889   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9890     return LowerZERO_EXTEND_AVX512(Op, DAG);
9891
9892   if (Subtarget->hasFp256()) {
9893     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9894     if (Res.getNode())
9895       return Res;
9896   }
9897
9898   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9899          VT.getVectorNumElements() != SVT.getVectorNumElements());
9900   return SDValue();
9901 }
9902
9903 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9904   SDLoc DL(Op);
9905   MVT VT = Op.getSimpleValueType();
9906   SDValue In = Op.getOperand(0);
9907   MVT InVT = In.getSimpleValueType();
9908
9909   if (VT == MVT::i1) {
9910     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9911            "Invalid scalar TRUNCATE operation");
9912     if (InVT == MVT::i32)
9913       return SDValue();
9914     if (InVT.getSizeInBits() == 64)
9915       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9916     else if (InVT.getSizeInBits() < 32)
9917       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9918     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9919   }
9920   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9921          "Invalid TRUNCATE operation");
9922
9923   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9924     if (VT.getVectorElementType().getSizeInBits() >=8)
9925       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9926
9927     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9928     unsigned NumElts = InVT.getVectorNumElements();
9929     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9930     if (InVT.getSizeInBits() < 512) {
9931       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9932       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9933       InVT = ExtVT;
9934     }
9935     
9936     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9937     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9938     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9939     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9940     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9941                            MachinePointerInfo::getConstantPool(),
9942                            false, false, false, Alignment);
9943     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9944     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9945     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9946   }
9947
9948   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9949     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9950     if (Subtarget->hasInt256()) {
9951       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9952       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9953       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9954                                 ShufMask);
9955       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9956                          DAG.getIntPtrConstant(0));
9957     }
9958
9959     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9960                                DAG.getIntPtrConstant(0));
9961     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9962                                DAG.getIntPtrConstant(2));
9963     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9964     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9965     static const int ShufMask[] = {0, 2, 4, 6};
9966     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9967   }
9968
9969   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9970     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9971     if (Subtarget->hasInt256()) {
9972       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9973
9974       SmallVector<SDValue,32> pshufbMask;
9975       for (unsigned i = 0; i < 2; ++i) {
9976         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9977         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9978         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9979         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9980         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9981         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9982         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9983         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9984         for (unsigned j = 0; j < 8; ++j)
9985           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9986       }
9987       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9988       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9989       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9990
9991       static const int ShufMask[] = {0,  2,  -1,  -1};
9992       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9993                                 &ShufMask[0]);
9994       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9995                        DAG.getIntPtrConstant(0));
9996       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9997     }
9998
9999     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10000                                DAG.getIntPtrConstant(0));
10001
10002     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
10003                                DAG.getIntPtrConstant(4));
10004
10005     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
10006     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
10007
10008     // The PSHUFB mask:
10009     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
10010                                    -1, -1, -1, -1, -1, -1, -1, -1};
10011
10012     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
10013     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
10014     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
10015
10016     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
10017     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
10018
10019     // The MOVLHPS Mask:
10020     static const int ShufMask2[] = {0, 1, 4, 5};
10021     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
10022     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
10023   }
10024
10025   // Handle truncation of V256 to V128 using shuffles.
10026   if (!VT.is128BitVector() || !InVT.is256BitVector())
10027     return SDValue();
10028
10029   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
10030
10031   unsigned NumElems = VT.getVectorNumElements();
10032   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
10033
10034   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
10035   // Prepare truncation shuffle mask
10036   for (unsigned i = 0; i != NumElems; ++i)
10037     MaskVec[i] = i * 2;
10038   SDValue V = DAG.getVectorShuffle(NVT, DL,
10039                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
10040                                    DAG.getUNDEF(NVT), &MaskVec[0]);
10041   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
10042                      DAG.getIntPtrConstant(0));
10043 }
10044
10045 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
10046                                            SelectionDAG &DAG) const {
10047   assert(!Op.getSimpleValueType().isVector());
10048
10049   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10050     /*IsSigned=*/ true, /*IsReplace=*/ false);
10051   SDValue FIST = Vals.first, StackSlot = Vals.second;
10052   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
10053   if (!FIST.getNode()) return Op;
10054
10055   if (StackSlot.getNode())
10056     // Load the result.
10057     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10058                        FIST, StackSlot, MachinePointerInfo(),
10059                        false, false, false, 0);
10060
10061   // The node is the result.
10062   return FIST;
10063 }
10064
10065 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
10066                                            SelectionDAG &DAG) const {
10067   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
10068     /*IsSigned=*/ false, /*IsReplace=*/ false);
10069   SDValue FIST = Vals.first, StackSlot = Vals.second;
10070   assert(FIST.getNode() && "Unexpected failure");
10071
10072   if (StackSlot.getNode())
10073     // Load the result.
10074     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
10075                        FIST, StackSlot, MachinePointerInfo(),
10076                        false, false, false, 0);
10077
10078   // The node is the result.
10079   return FIST;
10080 }
10081
10082 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
10083   SDLoc DL(Op);
10084   MVT VT = Op.getSimpleValueType();
10085   SDValue In = Op.getOperand(0);
10086   MVT SVT = In.getSimpleValueType();
10087
10088   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
10089
10090   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
10091                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
10092                                  In, DAG.getUNDEF(SVT)));
10093 }
10094
10095 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
10096   LLVMContext *Context = DAG.getContext();
10097   SDLoc dl(Op);
10098   MVT VT = Op.getSimpleValueType();
10099   MVT EltVT = VT;
10100   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10101   if (VT.isVector()) {
10102     EltVT = VT.getVectorElementType();
10103     NumElts = VT.getVectorNumElements();
10104   }
10105   Constant *C;
10106   if (EltVT == MVT::f64)
10107     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10108                                           APInt(64, ~(1ULL << 63))));
10109   else
10110     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10111                                           APInt(32, ~(1U << 31))));
10112   C = ConstantVector::getSplat(NumElts, C);
10113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10114   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10115   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10116   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10117                              MachinePointerInfo::getConstantPool(),
10118                              false, false, false, Alignment);
10119   if (VT.isVector()) {
10120     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10121     return DAG.getNode(ISD::BITCAST, dl, VT,
10122                        DAG.getNode(ISD::AND, dl, ANDVT,
10123                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
10124                                                Op.getOperand(0)),
10125                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
10126   }
10127   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
10128 }
10129
10130 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
10131   LLVMContext *Context = DAG.getContext();
10132   SDLoc dl(Op);
10133   MVT VT = Op.getSimpleValueType();
10134   MVT EltVT = VT;
10135   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
10136   if (VT.isVector()) {
10137     EltVT = VT.getVectorElementType();
10138     NumElts = VT.getVectorNumElements();
10139   }
10140   Constant *C;
10141   if (EltVT == MVT::f64)
10142     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
10143                                           APInt(64, 1ULL << 63)));
10144   else
10145     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
10146                                           APInt(32, 1U << 31)));
10147   C = ConstantVector::getSplat(NumElts, C);
10148   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10149   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
10150   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10151   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10152                              MachinePointerInfo::getConstantPool(),
10153                              false, false, false, Alignment);
10154   if (VT.isVector()) {
10155     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
10156     return DAG.getNode(ISD::BITCAST, dl, VT,
10157                        DAG.getNode(ISD::XOR, dl, XORVT,
10158                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
10159                                                Op.getOperand(0)),
10160                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
10161   }
10162
10163   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
10164 }
10165
10166 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
10167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10168   LLVMContext *Context = DAG.getContext();
10169   SDValue Op0 = Op.getOperand(0);
10170   SDValue Op1 = Op.getOperand(1);
10171   SDLoc dl(Op);
10172   MVT VT = Op.getSimpleValueType();
10173   MVT SrcVT = Op1.getSimpleValueType();
10174
10175   // If second operand is smaller, extend it first.
10176   if (SrcVT.bitsLT(VT)) {
10177     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
10178     SrcVT = VT;
10179   }
10180   // And if it is bigger, shrink it first.
10181   if (SrcVT.bitsGT(VT)) {
10182     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
10183     SrcVT = VT;
10184   }
10185
10186   // At this point the operands and the result should have the same
10187   // type, and that won't be f80 since that is not custom lowered.
10188
10189   // First get the sign bit of second operand.
10190   SmallVector<Constant*,4> CV;
10191   if (SrcVT == MVT::f64) {
10192     const fltSemantics &Sem = APFloat::IEEEdouble;
10193     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
10194     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10195   } else {
10196     const fltSemantics &Sem = APFloat::IEEEsingle;
10197     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
10198     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10199     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10200     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10201   }
10202   Constant *C = ConstantVector::get(CV);
10203   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10204   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
10205                               MachinePointerInfo::getConstantPool(),
10206                               false, false, false, 16);
10207   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
10208
10209   // Shift sign bit right or left if the two operands have different types.
10210   if (SrcVT.bitsGT(VT)) {
10211     // Op0 is MVT::f32, Op1 is MVT::f64.
10212     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
10213     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
10214                           DAG.getConstant(32, MVT::i32));
10215     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
10216     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
10217                           DAG.getIntPtrConstant(0));
10218   }
10219
10220   // Clear first operand sign bit.
10221   CV.clear();
10222   if (VT == MVT::f64) {
10223     const fltSemantics &Sem = APFloat::IEEEdouble;
10224     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10225                                                    APInt(64, ~(1ULL << 63)))));
10226     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
10227   } else {
10228     const fltSemantics &Sem = APFloat::IEEEsingle;
10229     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
10230                                                    APInt(32, ~(1U << 31)))));
10231     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10232     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10233     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
10234   }
10235   C = ConstantVector::get(CV);
10236   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
10237   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
10238                               MachinePointerInfo::getConstantPool(),
10239                               false, false, false, 16);
10240   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
10241
10242   // Or the value with the sign bit.
10243   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
10244 }
10245
10246 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
10247   SDValue N0 = Op.getOperand(0);
10248   SDLoc dl(Op);
10249   MVT VT = Op.getSimpleValueType();
10250
10251   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
10252   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
10253                                   DAG.getConstant(1, VT));
10254   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
10255 }
10256
10257 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
10258 //
10259 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
10260                                       SelectionDAG &DAG) {
10261   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
10262
10263   if (!Subtarget->hasSSE41())
10264     return SDValue();
10265
10266   if (!Op->hasOneUse())
10267     return SDValue();
10268
10269   SDNode *N = Op.getNode();
10270   SDLoc DL(N);
10271
10272   SmallVector<SDValue, 8> Opnds;
10273   DenseMap<SDValue, unsigned> VecInMap;
10274   SmallVector<SDValue, 8> VecIns;
10275   EVT VT = MVT::Other;
10276
10277   // Recognize a special case where a vector is casted into wide integer to
10278   // test all 0s.
10279   Opnds.push_back(N->getOperand(0));
10280   Opnds.push_back(N->getOperand(1));
10281
10282   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
10283     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
10284     // BFS traverse all OR'd operands.
10285     if (I->getOpcode() == ISD::OR) {
10286       Opnds.push_back(I->getOperand(0));
10287       Opnds.push_back(I->getOperand(1));
10288       // Re-evaluate the number of nodes to be traversed.
10289       e += 2; // 2 more nodes (LHS and RHS) are pushed.
10290       continue;
10291     }
10292
10293     // Quit if a non-EXTRACT_VECTOR_ELT
10294     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10295       return SDValue();
10296
10297     // Quit if without a constant index.
10298     SDValue Idx = I->getOperand(1);
10299     if (!isa<ConstantSDNode>(Idx))
10300       return SDValue();
10301
10302     SDValue ExtractedFromVec = I->getOperand(0);
10303     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
10304     if (M == VecInMap.end()) {
10305       VT = ExtractedFromVec.getValueType();
10306       // Quit if not 128/256-bit vector.
10307       if (!VT.is128BitVector() && !VT.is256BitVector())
10308         return SDValue();
10309       // Quit if not the same type.
10310       if (VecInMap.begin() != VecInMap.end() &&
10311           VT != VecInMap.begin()->first.getValueType())
10312         return SDValue();
10313       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
10314       VecIns.push_back(ExtractedFromVec);
10315     }
10316     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
10317   }
10318
10319   assert((VT.is128BitVector() || VT.is256BitVector()) &&
10320          "Not extracted from 128-/256-bit vector.");
10321
10322   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
10323
10324   for (DenseMap<SDValue, unsigned>::const_iterator
10325         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10326     // Quit if not all elements are used.
10327     if (I->second != FullMask)
10328       return SDValue();
10329   }
10330
10331   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10332
10333   // Cast all vectors into TestVT for PTEST.
10334   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10335     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10336
10337   // If more than one full vectors are evaluated, OR them first before PTEST.
10338   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10339     // Each iteration will OR 2 nodes and append the result until there is only
10340     // 1 node left, i.e. the final OR'd value of all vectors.
10341     SDValue LHS = VecIns[Slot];
10342     SDValue RHS = VecIns[Slot + 1];
10343     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10344   }
10345
10346   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10347                      VecIns.back(), VecIns.back());
10348 }
10349
10350 /// \brief return true if \c Op has a use that doesn't just read flags.
10351 static bool hasNonFlagsUse(SDValue Op) {
10352   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10353        ++UI) {
10354     SDNode *User = *UI;
10355     unsigned UOpNo = UI.getOperandNo();
10356     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10357       // Look pass truncate.
10358       UOpNo = User->use_begin().getOperandNo();
10359       User = *User->use_begin();
10360     }
10361
10362     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10363         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10364       return true;
10365   }
10366   return false;
10367 }
10368
10369 /// Emit nodes that will be selected as "test Op0,Op0", or something
10370 /// equivalent.
10371 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10372                                     SelectionDAG &DAG) const {
10373   if (Op.getValueType() == MVT::i1)
10374     // KORTEST instruction should be selected
10375     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10376                        DAG.getConstant(0, Op.getValueType()));
10377
10378   // CF and OF aren't always set the way we want. Determine which
10379   // of these we need.
10380   bool NeedCF = false;
10381   bool NeedOF = false;
10382   switch (X86CC) {
10383   default: break;
10384   case X86::COND_A: case X86::COND_AE:
10385   case X86::COND_B: case X86::COND_BE:
10386     NeedCF = true;
10387     break;
10388   case X86::COND_G: case X86::COND_GE:
10389   case X86::COND_L: case X86::COND_LE:
10390   case X86::COND_O: case X86::COND_NO: {
10391     // Check if we really need to set the
10392     // Overflow flag. If NoSignedWrap is present
10393     // that is not actually needed.
10394     switch (Op->getOpcode()) {
10395     case ISD::ADD:
10396     case ISD::SUB:
10397     case ISD::MUL:
10398     case ISD::SHL: {
10399       const BinaryWithFlagsSDNode *BinNode =
10400           cast<BinaryWithFlagsSDNode>(Op.getNode());
10401       if (BinNode->hasNoSignedWrap())
10402         break;
10403     }
10404     default:
10405       NeedOF = true;
10406       break;
10407     }
10408     break;
10409   }
10410   }
10411   // See if we can use the EFLAGS value from the operand instead of
10412   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10413   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10414   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10415     // Emit a CMP with 0, which is the TEST pattern.
10416     //if (Op.getValueType() == MVT::i1)
10417     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10418     //                     DAG.getConstant(0, MVT::i1));
10419     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10420                        DAG.getConstant(0, Op.getValueType()));
10421   }
10422   unsigned Opcode = 0;
10423   unsigned NumOperands = 0;
10424
10425   // Truncate operations may prevent the merge of the SETCC instruction
10426   // and the arithmetic instruction before it. Attempt to truncate the operands
10427   // of the arithmetic instruction and use a reduced bit-width instruction.
10428   bool NeedTruncation = false;
10429   SDValue ArithOp = Op;
10430   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10431     SDValue Arith = Op->getOperand(0);
10432     // Both the trunc and the arithmetic op need to have one user each.
10433     if (Arith->hasOneUse())
10434       switch (Arith.getOpcode()) {
10435         default: break;
10436         case ISD::ADD:
10437         case ISD::SUB:
10438         case ISD::AND:
10439         case ISD::OR:
10440         case ISD::XOR: {
10441           NeedTruncation = true;
10442           ArithOp = Arith;
10443         }
10444       }
10445   }
10446
10447   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10448   // which may be the result of a CAST.  We use the variable 'Op', which is the
10449   // non-casted variable when we check for possible users.
10450   switch (ArithOp.getOpcode()) {
10451   case ISD::ADD:
10452     // Due to an isel shortcoming, be conservative if this add is likely to be
10453     // selected as part of a load-modify-store instruction. When the root node
10454     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10455     // uses of other nodes in the match, such as the ADD in this case. This
10456     // leads to the ADD being left around and reselected, with the result being
10457     // two adds in the output.  Alas, even if none our users are stores, that
10458     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10459     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10460     // climbing the DAG back to the root, and it doesn't seem to be worth the
10461     // effort.
10462     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10463          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10464       if (UI->getOpcode() != ISD::CopyToReg &&
10465           UI->getOpcode() != ISD::SETCC &&
10466           UI->getOpcode() != ISD::STORE)
10467         goto default_case;
10468
10469     if (ConstantSDNode *C =
10470         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10471       // An add of one will be selected as an INC.
10472       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
10473         Opcode = X86ISD::INC;
10474         NumOperands = 1;
10475         break;
10476       }
10477
10478       // An add of negative one (subtract of one) will be selected as a DEC.
10479       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
10480         Opcode = X86ISD::DEC;
10481         NumOperands = 1;
10482         break;
10483       }
10484     }
10485
10486     // Otherwise use a regular EFLAGS-setting add.
10487     Opcode = X86ISD::ADD;
10488     NumOperands = 2;
10489     break;
10490   case ISD::SHL:
10491   case ISD::SRL:
10492     // If we have a constant logical shift that's only used in a comparison
10493     // against zero turn it into an equivalent AND. This allows turning it into
10494     // a TEST instruction later.
10495     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
10496         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10497       EVT VT = Op.getValueType();
10498       unsigned BitWidth = VT.getSizeInBits();
10499       unsigned ShAmt = Op->getConstantOperandVal(1);
10500       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10501         break;
10502       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10503                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10504                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10505       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10506         break;
10507       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10508                                 DAG.getConstant(Mask, VT));
10509       DAG.ReplaceAllUsesWith(Op, New);
10510       Op = New;
10511     }
10512     break;
10513
10514   case ISD::AND:
10515     // If the primary and result isn't used, don't bother using X86ISD::AND,
10516     // because a TEST instruction will be better.
10517     if (!hasNonFlagsUse(Op))
10518       break;
10519     // FALL THROUGH
10520   case ISD::SUB:
10521   case ISD::OR:
10522   case ISD::XOR:
10523     // Due to the ISEL shortcoming noted above, be conservative if this op is
10524     // likely to be selected as part of a load-modify-store instruction.
10525     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10526            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10527       if (UI->getOpcode() == ISD::STORE)
10528         goto default_case;
10529
10530     // Otherwise use a regular EFLAGS-setting instruction.
10531     switch (ArithOp.getOpcode()) {
10532     default: llvm_unreachable("unexpected operator!");
10533     case ISD::SUB: Opcode = X86ISD::SUB; break;
10534     case ISD::XOR: Opcode = X86ISD::XOR; break;
10535     case ISD::AND: Opcode = X86ISD::AND; break;
10536     case ISD::OR: {
10537       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10538         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10539         if (EFLAGS.getNode())
10540           return EFLAGS;
10541       }
10542       Opcode = X86ISD::OR;
10543       break;
10544     }
10545     }
10546
10547     NumOperands = 2;
10548     break;
10549   case X86ISD::ADD:
10550   case X86ISD::SUB:
10551   case X86ISD::INC:
10552   case X86ISD::DEC:
10553   case X86ISD::OR:
10554   case X86ISD::XOR:
10555   case X86ISD::AND:
10556     return SDValue(Op.getNode(), 1);
10557   default:
10558   default_case:
10559     break;
10560   }
10561
10562   // If we found that truncation is beneficial, perform the truncation and
10563   // update 'Op'.
10564   if (NeedTruncation) {
10565     EVT VT = Op.getValueType();
10566     SDValue WideVal = Op->getOperand(0);
10567     EVT WideVT = WideVal.getValueType();
10568     unsigned ConvertedOp = 0;
10569     // Use a target machine opcode to prevent further DAGCombine
10570     // optimizations that may separate the arithmetic operations
10571     // from the setcc node.
10572     switch (WideVal.getOpcode()) {
10573       default: break;
10574       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10575       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10576       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10577       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10578       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10579     }
10580
10581     if (ConvertedOp) {
10582       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10583       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10584         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10585         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10586         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10587       }
10588     }
10589   }
10590
10591   if (Opcode == 0)
10592     // Emit a CMP with 0, which is the TEST pattern.
10593     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10594                        DAG.getConstant(0, Op.getValueType()));
10595
10596   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10597   SmallVector<SDValue, 4> Ops;
10598   for (unsigned i = 0; i != NumOperands; ++i)
10599     Ops.push_back(Op.getOperand(i));
10600
10601   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10602   DAG.ReplaceAllUsesWith(Op, New);
10603   return SDValue(New.getNode(), 1);
10604 }
10605
10606 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10607 /// equivalent.
10608 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10609                                    SDLoc dl, SelectionDAG &DAG) const {
10610   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10611     if (C->getAPIntValue() == 0)
10612       return EmitTest(Op0, X86CC, dl, DAG);
10613
10614      if (Op0.getValueType() == MVT::i1)
10615        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10616   }
10617  
10618   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10619        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10620     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10621     // This avoids subregister aliasing issues. Keep the smaller reference 
10622     // if we're optimizing for size, however, as that'll allow better folding 
10623     // of memory operations.
10624     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10625         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10626              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10627         !Subtarget->isAtom()) {
10628       unsigned ExtendOp =
10629           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10630       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10631       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10632     }
10633     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10634     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10635     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10636                               Op0, Op1);
10637     return SDValue(Sub.getNode(), 1);
10638   }
10639   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10640 }
10641
10642 /// Convert a comparison if required by the subtarget.
10643 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10644                                                  SelectionDAG &DAG) const {
10645   // If the subtarget does not support the FUCOMI instruction, floating-point
10646   // comparisons have to be converted.
10647   if (Subtarget->hasCMov() ||
10648       Cmp.getOpcode() != X86ISD::CMP ||
10649       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10650       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10651     return Cmp;
10652
10653   // The instruction selector will select an FUCOM instruction instead of
10654   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10655   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10656   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10657   SDLoc dl(Cmp);
10658   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10659   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10660   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10661                             DAG.getConstant(8, MVT::i8));
10662   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10663   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10664 }
10665
10666 static bool isAllOnes(SDValue V) {
10667   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10668   return C && C->isAllOnesValue();
10669 }
10670
10671 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10672 /// if it's possible.
10673 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10674                                      SDLoc dl, SelectionDAG &DAG) const {
10675   SDValue Op0 = And.getOperand(0);
10676   SDValue Op1 = And.getOperand(1);
10677   if (Op0.getOpcode() == ISD::TRUNCATE)
10678     Op0 = Op0.getOperand(0);
10679   if (Op1.getOpcode() == ISD::TRUNCATE)
10680     Op1 = Op1.getOperand(0);
10681
10682   SDValue LHS, RHS;
10683   if (Op1.getOpcode() == ISD::SHL)
10684     std::swap(Op0, Op1);
10685   if (Op0.getOpcode() == ISD::SHL) {
10686     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10687       if (And00C->getZExtValue() == 1) {
10688         // If we looked past a truncate, check that it's only truncating away
10689         // known zeros.
10690         unsigned BitWidth = Op0.getValueSizeInBits();
10691         unsigned AndBitWidth = And.getValueSizeInBits();
10692         if (BitWidth > AndBitWidth) {
10693           APInt Zeros, Ones;
10694           DAG.computeKnownBits(Op0, Zeros, Ones);
10695           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10696             return SDValue();
10697         }
10698         LHS = Op1;
10699         RHS = Op0.getOperand(1);
10700       }
10701   } else if (Op1.getOpcode() == ISD::Constant) {
10702     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10703     uint64_t AndRHSVal = AndRHS->getZExtValue();
10704     SDValue AndLHS = Op0;
10705
10706     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10707       LHS = AndLHS.getOperand(0);
10708       RHS = AndLHS.getOperand(1);
10709     }
10710
10711     // Use BT if the immediate can't be encoded in a TEST instruction.
10712     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10713       LHS = AndLHS;
10714       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10715     }
10716   }
10717
10718   if (LHS.getNode()) {
10719     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10720     // instruction.  Since the shift amount is in-range-or-undefined, we know
10721     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10722     // the encoding for the i16 version is larger than the i32 version.
10723     // Also promote i16 to i32 for performance / code size reason.
10724     if (LHS.getValueType() == MVT::i8 ||
10725         LHS.getValueType() == MVT::i16)
10726       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10727
10728     // If the operand types disagree, extend the shift amount to match.  Since
10729     // BT ignores high bits (like shifts) we can use anyextend.
10730     if (LHS.getValueType() != RHS.getValueType())
10731       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10732
10733     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10734     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10735     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10736                        DAG.getConstant(Cond, MVT::i8), BT);
10737   }
10738
10739   return SDValue();
10740 }
10741
10742 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10743 /// mask CMPs.
10744 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10745                               SDValue &Op1) {
10746   unsigned SSECC;
10747   bool Swap = false;
10748
10749   // SSE Condition code mapping:
10750   //  0 - EQ
10751   //  1 - LT
10752   //  2 - LE
10753   //  3 - UNORD
10754   //  4 - NEQ
10755   //  5 - NLT
10756   //  6 - NLE
10757   //  7 - ORD
10758   switch (SetCCOpcode) {
10759   default: llvm_unreachable("Unexpected SETCC condition");
10760   case ISD::SETOEQ:
10761   case ISD::SETEQ:  SSECC = 0; break;
10762   case ISD::SETOGT:
10763   case ISD::SETGT:  Swap = true; // Fallthrough
10764   case ISD::SETLT:
10765   case ISD::SETOLT: SSECC = 1; break;
10766   case ISD::SETOGE:
10767   case ISD::SETGE:  Swap = true; // Fallthrough
10768   case ISD::SETLE:
10769   case ISD::SETOLE: SSECC = 2; break;
10770   case ISD::SETUO:  SSECC = 3; break;
10771   case ISD::SETUNE:
10772   case ISD::SETNE:  SSECC = 4; break;
10773   case ISD::SETULE: Swap = true; // Fallthrough
10774   case ISD::SETUGE: SSECC = 5; break;
10775   case ISD::SETULT: Swap = true; // Fallthrough
10776   case ISD::SETUGT: SSECC = 6; break;
10777   case ISD::SETO:   SSECC = 7; break;
10778   case ISD::SETUEQ:
10779   case ISD::SETONE: SSECC = 8; break;
10780   }
10781   if (Swap)
10782     std::swap(Op0, Op1);
10783
10784   return SSECC;
10785 }
10786
10787 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10788 // ones, and then concatenate the result back.
10789 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10790   MVT VT = Op.getSimpleValueType();
10791
10792   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10793          "Unsupported value type for operation");
10794
10795   unsigned NumElems = VT.getVectorNumElements();
10796   SDLoc dl(Op);
10797   SDValue CC = Op.getOperand(2);
10798
10799   // Extract the LHS vectors
10800   SDValue LHS = Op.getOperand(0);
10801   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10802   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10803
10804   // Extract the RHS vectors
10805   SDValue RHS = Op.getOperand(1);
10806   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10807   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10808
10809   // Issue the operation on the smaller types and concatenate the result back
10810   MVT EltVT = VT.getVectorElementType();
10811   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10812   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10813                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10814                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10815 }
10816
10817 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10818                                      const X86Subtarget *Subtarget) {
10819   SDValue Op0 = Op.getOperand(0);
10820   SDValue Op1 = Op.getOperand(1);
10821   SDValue CC = Op.getOperand(2);
10822   MVT VT = Op.getSimpleValueType();
10823   SDLoc dl(Op);
10824
10825   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10826          Op.getValueType().getScalarType() == MVT::i1 &&
10827          "Cannot set masked compare for this operation");
10828
10829   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10830   unsigned  Opc = 0;
10831   bool Unsigned = false;
10832   bool Swap = false;
10833   unsigned SSECC;
10834   switch (SetCCOpcode) {
10835   default: llvm_unreachable("Unexpected SETCC condition");
10836   case ISD::SETNE:  SSECC = 4; break;
10837   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10838   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10839   case ISD::SETLT:  Swap = true; //fall-through
10840   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10841   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10842   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10843   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10844   case ISD::SETULE: Unsigned = true; //fall-through
10845   case ISD::SETLE:  SSECC = 2; break;
10846   }
10847
10848   if (Swap)
10849     std::swap(Op0, Op1);
10850   if (Opc)
10851     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10852   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10853   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10854                      DAG.getConstant(SSECC, MVT::i8));
10855 }
10856
10857 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10858 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10859 /// return an empty value.
10860 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10861 {
10862   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10863   if (!BV)
10864     return SDValue();
10865
10866   MVT VT = Op1.getSimpleValueType();
10867   MVT EVT = VT.getVectorElementType();
10868   unsigned n = VT.getVectorNumElements();
10869   SmallVector<SDValue, 8> ULTOp1;
10870
10871   for (unsigned i = 0; i < n; ++i) {
10872     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10873     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10874       return SDValue();
10875
10876     // Avoid underflow.
10877     APInt Val = Elt->getAPIntValue();
10878     if (Val == 0)
10879       return SDValue();
10880
10881     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10882   }
10883
10884   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10885 }
10886
10887 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10888                            SelectionDAG &DAG) {
10889   SDValue Op0 = Op.getOperand(0);
10890   SDValue Op1 = Op.getOperand(1);
10891   SDValue CC = Op.getOperand(2);
10892   MVT VT = Op.getSimpleValueType();
10893   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10894   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10895   SDLoc dl(Op);
10896
10897   if (isFP) {
10898 #ifndef NDEBUG
10899     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10900     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10901 #endif
10902
10903     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10904     unsigned Opc = X86ISD::CMPP;
10905     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10906       assert(VT.getVectorNumElements() <= 16);
10907       Opc = X86ISD::CMPM;
10908     }
10909     // In the two special cases we can't handle, emit two comparisons.
10910     if (SSECC == 8) {
10911       unsigned CC0, CC1;
10912       unsigned CombineOpc;
10913       if (SetCCOpcode == ISD::SETUEQ) {
10914         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10915       } else {
10916         assert(SetCCOpcode == ISD::SETONE);
10917         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10918       }
10919
10920       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10921                                  DAG.getConstant(CC0, MVT::i8));
10922       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10923                                  DAG.getConstant(CC1, MVT::i8));
10924       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10925     }
10926     // Handle all other FP comparisons here.
10927     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10928                        DAG.getConstant(SSECC, MVT::i8));
10929   }
10930
10931   // Break 256-bit integer vector compare into smaller ones.
10932   if (VT.is256BitVector() && !Subtarget->hasInt256())
10933     return Lower256IntVSETCC(Op, DAG);
10934
10935   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10936   EVT OpVT = Op1.getValueType();
10937   if (Subtarget->hasAVX512()) {
10938     if (Op1.getValueType().is512BitVector() ||
10939         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10940       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10941
10942     // In AVX-512 architecture setcc returns mask with i1 elements,
10943     // But there is no compare instruction for i8 and i16 elements.
10944     // We are not talking about 512-bit operands in this case, these
10945     // types are illegal.
10946     if (MaskResult &&
10947         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10948          OpVT.getVectorElementType().getSizeInBits() >= 8))
10949       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10950                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10951   }
10952
10953   // We are handling one of the integer comparisons here.  Since SSE only has
10954   // GT and EQ comparisons for integer, swapping operands and multiple
10955   // operations may be required for some comparisons.
10956   unsigned Opc;
10957   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10958   bool Subus = false;
10959
10960   switch (SetCCOpcode) {
10961   default: llvm_unreachable("Unexpected SETCC condition");
10962   case ISD::SETNE:  Invert = true;
10963   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10964   case ISD::SETLT:  Swap = true;
10965   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10966   case ISD::SETGE:  Swap = true;
10967   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10968                     Invert = true; break;
10969   case ISD::SETULT: Swap = true;
10970   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10971                     FlipSigns = true; break;
10972   case ISD::SETUGE: Swap = true;
10973   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10974                     FlipSigns = true; Invert = true; break;
10975   }
10976
10977   // Special case: Use min/max operations for SETULE/SETUGE
10978   MVT VET = VT.getVectorElementType();
10979   bool hasMinMax =
10980        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10981     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10982
10983   if (hasMinMax) {
10984     switch (SetCCOpcode) {
10985     default: break;
10986     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10987     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10988     }
10989
10990     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10991   }
10992
10993   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10994   if (!MinMax && hasSubus) {
10995     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10996     // Op0 u<= Op1:
10997     //   t = psubus Op0, Op1
10998     //   pcmpeq t, <0..0>
10999     switch (SetCCOpcode) {
11000     default: break;
11001     case ISD::SETULT: {
11002       // If the comparison is against a constant we can turn this into a
11003       // setule.  With psubus, setule does not require a swap.  This is
11004       // beneficial because the constant in the register is no longer
11005       // destructed as the destination so it can be hoisted out of a loop.
11006       // Only do this pre-AVX since vpcmp* is no longer destructive.
11007       if (Subtarget->hasAVX())
11008         break;
11009       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
11010       if (ULEOp1.getNode()) {
11011         Op1 = ULEOp1;
11012         Subus = true; Invert = false; Swap = false;
11013       }
11014       break;
11015     }
11016     // Psubus is better than flip-sign because it requires no inversion.
11017     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
11018     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
11019     }
11020
11021     if (Subus) {
11022       Opc = X86ISD::SUBUS;
11023       FlipSigns = false;
11024     }
11025   }
11026
11027   if (Swap)
11028     std::swap(Op0, Op1);
11029
11030   // Check that the operation in question is available (most are plain SSE2,
11031   // but PCMPGTQ and PCMPEQQ have different requirements).
11032   if (VT == MVT::v2i64) {
11033     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
11034       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
11035
11036       // First cast everything to the right type.
11037       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11038       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11039
11040       // Since SSE has no unsigned integer comparisons, we need to flip the sign
11041       // bits of the inputs before performing those operations. The lower
11042       // compare is always unsigned.
11043       SDValue SB;
11044       if (FlipSigns) {
11045         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
11046       } else {
11047         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
11048         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
11049         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
11050                          Sign, Zero, Sign, Zero);
11051       }
11052       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
11053       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
11054
11055       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
11056       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
11057       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
11058
11059       // Create masks for only the low parts/high parts of the 64 bit integers.
11060       static const int MaskHi[] = { 1, 1, 3, 3 };
11061       static const int MaskLo[] = { 0, 0, 2, 2 };
11062       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
11063       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
11064       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
11065
11066       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
11067       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
11068
11069       if (Invert)
11070         Result = DAG.getNOT(dl, Result, MVT::v4i32);
11071
11072       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11073     }
11074
11075     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
11076       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
11077       // pcmpeqd + pshufd + pand.
11078       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
11079
11080       // First cast everything to the right type.
11081       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
11082       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
11083
11084       // Do the compare.
11085       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
11086
11087       // Make sure the lower and upper halves are both all-ones.
11088       static const int Mask[] = { 1, 0, 3, 2 };
11089       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
11090       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
11091
11092       if (Invert)
11093         Result = DAG.getNOT(dl, Result, MVT::v4i32);
11094
11095       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
11096     }
11097   }
11098
11099   // Since SSE has no unsigned integer comparisons, we need to flip the sign
11100   // bits of the inputs before performing those operations.
11101   if (FlipSigns) {
11102     EVT EltVT = VT.getVectorElementType();
11103     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
11104     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
11105     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
11106   }
11107
11108   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
11109
11110   // If the logical-not of the result is required, perform that now.
11111   if (Invert)
11112     Result = DAG.getNOT(dl, Result, VT);
11113
11114   if (MinMax)
11115     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
11116
11117   if (Subus)
11118     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
11119                          getZeroVector(VT, Subtarget, DAG, dl));
11120
11121   return Result;
11122 }
11123
11124 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
11125
11126   MVT VT = Op.getSimpleValueType();
11127
11128   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
11129
11130   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
11131          && "SetCC type must be 8-bit or 1-bit integer");
11132   SDValue Op0 = Op.getOperand(0);
11133   SDValue Op1 = Op.getOperand(1);
11134   SDLoc dl(Op);
11135   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
11136
11137   // Optimize to BT if possible.
11138   // Lower (X & (1 << N)) == 0 to BT(X, N).
11139   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
11140   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
11141   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
11142       Op1.getOpcode() == ISD::Constant &&
11143       cast<ConstantSDNode>(Op1)->isNullValue() &&
11144       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11145     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
11146     if (NewSetCC.getNode())
11147       return NewSetCC;
11148   }
11149
11150   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
11151   // these.
11152   if (Op1.getOpcode() == ISD::Constant &&
11153       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
11154        cast<ConstantSDNode>(Op1)->isNullValue()) &&
11155       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11156
11157     // If the input is a setcc, then reuse the input setcc or use a new one with
11158     // the inverted condition.
11159     if (Op0.getOpcode() == X86ISD::SETCC) {
11160       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
11161       bool Invert = (CC == ISD::SETNE) ^
11162         cast<ConstantSDNode>(Op1)->isNullValue();
11163       if (!Invert)
11164         return Op0;
11165
11166       CCode = X86::GetOppositeBranchCondition(CCode);
11167       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11168                                   DAG.getConstant(CCode, MVT::i8),
11169                                   Op0.getOperand(1));
11170       if (VT == MVT::i1)
11171         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11172       return SetCC;
11173     }
11174   }
11175   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
11176       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
11177       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
11178
11179     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
11180     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
11181   }
11182
11183   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
11184   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
11185   if (X86CC == X86::COND_INVALID)
11186     return SDValue();
11187
11188   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
11189   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
11190   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11191                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
11192   if (VT == MVT::i1)
11193     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
11194   return SetCC;
11195 }
11196
11197 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
11198 static bool isX86LogicalCmp(SDValue Op) {
11199   unsigned Opc = Op.getNode()->getOpcode();
11200   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
11201       Opc == X86ISD::SAHF)
11202     return true;
11203   if (Op.getResNo() == 1 &&
11204       (Opc == X86ISD::ADD ||
11205        Opc == X86ISD::SUB ||
11206        Opc == X86ISD::ADC ||
11207        Opc == X86ISD::SBB ||
11208        Opc == X86ISD::SMUL ||
11209        Opc == X86ISD::UMUL ||
11210        Opc == X86ISD::INC ||
11211        Opc == X86ISD::DEC ||
11212        Opc == X86ISD::OR ||
11213        Opc == X86ISD::XOR ||
11214        Opc == X86ISD::AND))
11215     return true;
11216
11217   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
11218     return true;
11219
11220   return false;
11221 }
11222
11223 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
11224   if (V.getOpcode() != ISD::TRUNCATE)
11225     return false;
11226
11227   SDValue VOp0 = V.getOperand(0);
11228   unsigned InBits = VOp0.getValueSizeInBits();
11229   unsigned Bits = V.getValueSizeInBits();
11230   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
11231 }
11232
11233 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
11234   bool addTest = true;
11235   SDValue Cond  = Op.getOperand(0);
11236   SDValue Op1 = Op.getOperand(1);
11237   SDValue Op2 = Op.getOperand(2);
11238   SDLoc DL(Op);
11239   EVT VT = Op1.getValueType();
11240   SDValue CC;
11241
11242   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
11243   // are available. Otherwise fp cmovs get lowered into a less efficient branch
11244   // sequence later on.
11245   if (Cond.getOpcode() == ISD::SETCC &&
11246       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
11247        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
11248       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
11249     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
11250     int SSECC = translateX86FSETCC(
11251         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
11252
11253     if (SSECC != 8) {
11254       if (Subtarget->hasAVX512()) {
11255         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
11256                                   DAG.getConstant(SSECC, MVT::i8));
11257         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
11258       }
11259       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
11260                                 DAG.getConstant(SSECC, MVT::i8));
11261       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
11262       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
11263       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
11264     }
11265   }
11266
11267   if (Cond.getOpcode() == ISD::SETCC) {
11268     SDValue NewCond = LowerSETCC(Cond, DAG);
11269     if (NewCond.getNode())
11270       Cond = NewCond;
11271   }
11272
11273   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
11274   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
11275   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
11276   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
11277   if (Cond.getOpcode() == X86ISD::SETCC &&
11278       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
11279       isZero(Cond.getOperand(1).getOperand(1))) {
11280     SDValue Cmp = Cond.getOperand(1);
11281
11282     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
11283
11284     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
11285         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
11286       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
11287
11288       SDValue CmpOp0 = Cmp.getOperand(0);
11289       // Apply further optimizations for special cases
11290       // (select (x != 0), -1, 0) -> neg & sbb
11291       // (select (x == 0), 0, -1) -> neg & sbb
11292       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
11293         if (YC->isNullValue() &&
11294             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
11295           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
11296           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
11297                                     DAG.getConstant(0, CmpOp0.getValueType()),
11298                                     CmpOp0);
11299           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11300                                     DAG.getConstant(X86::COND_B, MVT::i8),
11301                                     SDValue(Neg.getNode(), 1));
11302           return Res;
11303         }
11304
11305       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
11306                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
11307       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11308
11309       SDValue Res =   // Res = 0 or -1.
11310         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11311                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
11312
11313       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
11314         Res = DAG.getNOT(DL, Res, Res.getValueType());
11315
11316       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
11317       if (!N2C || !N2C->isNullValue())
11318         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
11319       return Res;
11320     }
11321   }
11322
11323   // Look past (and (setcc_carry (cmp ...)), 1).
11324   if (Cond.getOpcode() == ISD::AND &&
11325       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11326     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11327     if (C && C->getAPIntValue() == 1)
11328       Cond = Cond.getOperand(0);
11329   }
11330
11331   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11332   // setting operand in place of the X86ISD::SETCC.
11333   unsigned CondOpcode = Cond.getOpcode();
11334   if (CondOpcode == X86ISD::SETCC ||
11335       CondOpcode == X86ISD::SETCC_CARRY) {
11336     CC = Cond.getOperand(0);
11337
11338     SDValue Cmp = Cond.getOperand(1);
11339     unsigned Opc = Cmp.getOpcode();
11340     MVT VT = Op.getSimpleValueType();
11341
11342     bool IllegalFPCMov = false;
11343     if (VT.isFloatingPoint() && !VT.isVector() &&
11344         !isScalarFPTypeInSSEReg(VT))  // FPStack?
11345       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11346
11347     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11348         Opc == X86ISD::BT) { // FIXME
11349       Cond = Cmp;
11350       addTest = false;
11351     }
11352   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11353              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11354              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11355               Cond.getOperand(0).getValueType() != MVT::i8)) {
11356     SDValue LHS = Cond.getOperand(0);
11357     SDValue RHS = Cond.getOperand(1);
11358     unsigned X86Opcode;
11359     unsigned X86Cond;
11360     SDVTList VTs;
11361     switch (CondOpcode) {
11362     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11363     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11364     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11365     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11366     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11367     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11368     default: llvm_unreachable("unexpected overflowing operator");
11369     }
11370     if (CondOpcode == ISD::UMULO)
11371       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11372                           MVT::i32);
11373     else
11374       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11375
11376     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11377
11378     if (CondOpcode == ISD::UMULO)
11379       Cond = X86Op.getValue(2);
11380     else
11381       Cond = X86Op.getValue(1);
11382
11383     CC = DAG.getConstant(X86Cond, MVT::i8);
11384     addTest = false;
11385   }
11386
11387   if (addTest) {
11388     // Look pass the truncate if the high bits are known zero.
11389     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11390         Cond = Cond.getOperand(0);
11391
11392     // We know the result of AND is compared against zero. Try to match
11393     // it to BT.
11394     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11395       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11396       if (NewSetCC.getNode()) {
11397         CC = NewSetCC.getOperand(0);
11398         Cond = NewSetCC.getOperand(1);
11399         addTest = false;
11400       }
11401     }
11402   }
11403
11404   if (addTest) {
11405     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11406     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11407   }
11408
11409   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11410   // a <  b ?  0 : -1 -> RES = setcc_carry
11411   // a >= b ? -1 :  0 -> RES = setcc_carry
11412   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11413   if (Cond.getOpcode() == X86ISD::SUB) {
11414     Cond = ConvertCmpIfNecessary(Cond, DAG);
11415     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11416
11417     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11418         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11419       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11420                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11421       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11422         return DAG.getNOT(DL, Res, Res.getValueType());
11423       return Res;
11424     }
11425   }
11426
11427   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11428   // widen the cmov and push the truncate through. This avoids introducing a new
11429   // branch during isel and doesn't add any extensions.
11430   if (Op.getValueType() == MVT::i8 &&
11431       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11432     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11433     if (T1.getValueType() == T2.getValueType() &&
11434         // Blacklist CopyFromReg to avoid partial register stalls.
11435         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11436       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11437       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11438       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11439     }
11440   }
11441
11442   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11443   // condition is true.
11444   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11445   SDValue Ops[] = { Op2, Op1, CC, Cond };
11446   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11447 }
11448
11449 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11450   MVT VT = Op->getSimpleValueType(0);
11451   SDValue In = Op->getOperand(0);
11452   MVT InVT = In.getSimpleValueType();
11453   SDLoc dl(Op);
11454
11455   unsigned int NumElts = VT.getVectorNumElements();
11456   if (NumElts != 8 && NumElts != 16)
11457     return SDValue();
11458
11459   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11460     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11461
11462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11463   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11464
11465   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11466   Constant *C = ConstantInt::get(*DAG.getContext(),
11467     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11468
11469   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11470   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11471   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11472                           MachinePointerInfo::getConstantPool(),
11473                           false, false, false, Alignment);
11474   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11475   if (VT.is512BitVector())
11476     return Brcst;
11477   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11478 }
11479
11480 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11481                                 SelectionDAG &DAG) {
11482   MVT VT = Op->getSimpleValueType(0);
11483   SDValue In = Op->getOperand(0);
11484   MVT InVT = In.getSimpleValueType();
11485   SDLoc dl(Op);
11486
11487   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11488     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11489
11490   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11491       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11492       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11493     return SDValue();
11494
11495   if (Subtarget->hasInt256())
11496     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11497
11498   // Optimize vectors in AVX mode
11499   // Sign extend  v8i16 to v8i32 and
11500   //              v4i32 to v4i64
11501   //
11502   // Divide input vector into two parts
11503   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11504   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11505   // concat the vectors to original VT
11506
11507   unsigned NumElems = InVT.getVectorNumElements();
11508   SDValue Undef = DAG.getUNDEF(InVT);
11509
11510   SmallVector<int,8> ShufMask1(NumElems, -1);
11511   for (unsigned i = 0; i != NumElems/2; ++i)
11512     ShufMask1[i] = i;
11513
11514   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11515
11516   SmallVector<int,8> ShufMask2(NumElems, -1);
11517   for (unsigned i = 0; i != NumElems/2; ++i)
11518     ShufMask2[i] = i + NumElems/2;
11519
11520   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11521
11522   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11523                                 VT.getVectorNumElements()/2);
11524
11525   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11526   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11527
11528   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11529 }
11530
11531 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11532 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11533 // from the AND / OR.
11534 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11535   Opc = Op.getOpcode();
11536   if (Opc != ISD::OR && Opc != ISD::AND)
11537     return false;
11538   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11539           Op.getOperand(0).hasOneUse() &&
11540           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11541           Op.getOperand(1).hasOneUse());
11542 }
11543
11544 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11545 // 1 and that the SETCC node has a single use.
11546 static bool isXor1OfSetCC(SDValue Op) {
11547   if (Op.getOpcode() != ISD::XOR)
11548     return false;
11549   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11550   if (N1C && N1C->getAPIntValue() == 1) {
11551     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11552       Op.getOperand(0).hasOneUse();
11553   }
11554   return false;
11555 }
11556
11557 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11558   bool addTest = true;
11559   SDValue Chain = Op.getOperand(0);
11560   SDValue Cond  = Op.getOperand(1);
11561   SDValue Dest  = Op.getOperand(2);
11562   SDLoc dl(Op);
11563   SDValue CC;
11564   bool Inverted = false;
11565
11566   if (Cond.getOpcode() == ISD::SETCC) {
11567     // Check for setcc([su]{add,sub,mul}o == 0).
11568     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11569         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11570         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11571         Cond.getOperand(0).getResNo() == 1 &&
11572         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11573          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11574          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11575          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11576          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11577          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11578       Inverted = true;
11579       Cond = Cond.getOperand(0);
11580     } else {
11581       SDValue NewCond = LowerSETCC(Cond, DAG);
11582       if (NewCond.getNode())
11583         Cond = NewCond;
11584     }
11585   }
11586 #if 0
11587   // FIXME: LowerXALUO doesn't handle these!!
11588   else if (Cond.getOpcode() == X86ISD::ADD  ||
11589            Cond.getOpcode() == X86ISD::SUB  ||
11590            Cond.getOpcode() == X86ISD::SMUL ||
11591            Cond.getOpcode() == X86ISD::UMUL)
11592     Cond = LowerXALUO(Cond, DAG);
11593 #endif
11594
11595   // Look pass (and (setcc_carry (cmp ...)), 1).
11596   if (Cond.getOpcode() == ISD::AND &&
11597       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11598     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11599     if (C && C->getAPIntValue() == 1)
11600       Cond = Cond.getOperand(0);
11601   }
11602
11603   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11604   // setting operand in place of the X86ISD::SETCC.
11605   unsigned CondOpcode = Cond.getOpcode();
11606   if (CondOpcode == X86ISD::SETCC ||
11607       CondOpcode == X86ISD::SETCC_CARRY) {
11608     CC = Cond.getOperand(0);
11609
11610     SDValue Cmp = Cond.getOperand(1);
11611     unsigned Opc = Cmp.getOpcode();
11612     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11613     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11614       Cond = Cmp;
11615       addTest = false;
11616     } else {
11617       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11618       default: break;
11619       case X86::COND_O:
11620       case X86::COND_B:
11621         // These can only come from an arithmetic instruction with overflow,
11622         // e.g. SADDO, UADDO.
11623         Cond = Cond.getNode()->getOperand(1);
11624         addTest = false;
11625         break;
11626       }
11627     }
11628   }
11629   CondOpcode = Cond.getOpcode();
11630   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11631       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11632       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11633        Cond.getOperand(0).getValueType() != MVT::i8)) {
11634     SDValue LHS = Cond.getOperand(0);
11635     SDValue RHS = Cond.getOperand(1);
11636     unsigned X86Opcode;
11637     unsigned X86Cond;
11638     SDVTList VTs;
11639     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11640     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11641     // X86ISD::INC).
11642     switch (CondOpcode) {
11643     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11644     case ISD::SADDO:
11645       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11646         if (C->isOne()) {
11647           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11648           break;
11649         }
11650       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11651     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11652     case ISD::SSUBO:
11653       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11654         if (C->isOne()) {
11655           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11656           break;
11657         }
11658       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11659     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11660     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11661     default: llvm_unreachable("unexpected overflowing operator");
11662     }
11663     if (Inverted)
11664       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11665     if (CondOpcode == ISD::UMULO)
11666       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11667                           MVT::i32);
11668     else
11669       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11670
11671     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11672
11673     if (CondOpcode == ISD::UMULO)
11674       Cond = X86Op.getValue(2);
11675     else
11676       Cond = X86Op.getValue(1);
11677
11678     CC = DAG.getConstant(X86Cond, MVT::i8);
11679     addTest = false;
11680   } else {
11681     unsigned CondOpc;
11682     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11683       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11684       if (CondOpc == ISD::OR) {
11685         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11686         // two branches instead of an explicit OR instruction with a
11687         // separate test.
11688         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11689             isX86LogicalCmp(Cmp)) {
11690           CC = Cond.getOperand(0).getOperand(0);
11691           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11692                               Chain, Dest, CC, Cmp);
11693           CC = Cond.getOperand(1).getOperand(0);
11694           Cond = Cmp;
11695           addTest = false;
11696         }
11697       } else { // ISD::AND
11698         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11699         // two branches instead of an explicit AND instruction with a
11700         // separate test. However, we only do this if this block doesn't
11701         // have a fall-through edge, because this requires an explicit
11702         // jmp when the condition is false.
11703         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11704             isX86LogicalCmp(Cmp) &&
11705             Op.getNode()->hasOneUse()) {
11706           X86::CondCode CCode =
11707             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11708           CCode = X86::GetOppositeBranchCondition(CCode);
11709           CC = DAG.getConstant(CCode, MVT::i8);
11710           SDNode *User = *Op.getNode()->use_begin();
11711           // Look for an unconditional branch following this conditional branch.
11712           // We need this because we need to reverse the successors in order
11713           // to implement FCMP_OEQ.
11714           if (User->getOpcode() == ISD::BR) {
11715             SDValue FalseBB = User->getOperand(1);
11716             SDNode *NewBR =
11717               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11718             assert(NewBR == User);
11719             (void)NewBR;
11720             Dest = FalseBB;
11721
11722             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11723                                 Chain, Dest, CC, Cmp);
11724             X86::CondCode CCode =
11725               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11726             CCode = X86::GetOppositeBranchCondition(CCode);
11727             CC = DAG.getConstant(CCode, MVT::i8);
11728             Cond = Cmp;
11729             addTest = false;
11730           }
11731         }
11732       }
11733     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11734       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11735       // It should be transformed during dag combiner except when the condition
11736       // is set by a arithmetics with overflow node.
11737       X86::CondCode CCode =
11738         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11739       CCode = X86::GetOppositeBranchCondition(CCode);
11740       CC = DAG.getConstant(CCode, MVT::i8);
11741       Cond = Cond.getOperand(0).getOperand(1);
11742       addTest = false;
11743     } else if (Cond.getOpcode() == ISD::SETCC &&
11744                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11745       // For FCMP_OEQ, we can emit
11746       // two branches instead of an explicit AND instruction with a
11747       // separate test. However, we only do this if this block doesn't
11748       // have a fall-through edge, because this requires an explicit
11749       // jmp when the condition is false.
11750       if (Op.getNode()->hasOneUse()) {
11751         SDNode *User = *Op.getNode()->use_begin();
11752         // Look for an unconditional branch following this conditional branch.
11753         // We need this because we need to reverse the successors in order
11754         // to implement FCMP_OEQ.
11755         if (User->getOpcode() == ISD::BR) {
11756           SDValue FalseBB = User->getOperand(1);
11757           SDNode *NewBR =
11758             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11759           assert(NewBR == User);
11760           (void)NewBR;
11761           Dest = FalseBB;
11762
11763           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11764                                     Cond.getOperand(0), Cond.getOperand(1));
11765           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11766           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11767           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11768                               Chain, Dest, CC, Cmp);
11769           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11770           Cond = Cmp;
11771           addTest = false;
11772         }
11773       }
11774     } else if (Cond.getOpcode() == ISD::SETCC &&
11775                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11776       // For FCMP_UNE, we can emit
11777       // two branches instead of an explicit AND instruction with a
11778       // separate test. However, we only do this if this block doesn't
11779       // have a fall-through edge, because this requires an explicit
11780       // jmp when the condition is false.
11781       if (Op.getNode()->hasOneUse()) {
11782         SDNode *User = *Op.getNode()->use_begin();
11783         // Look for an unconditional branch following this conditional branch.
11784         // We need this because we need to reverse the successors in order
11785         // to implement FCMP_UNE.
11786         if (User->getOpcode() == ISD::BR) {
11787           SDValue FalseBB = User->getOperand(1);
11788           SDNode *NewBR =
11789             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11790           assert(NewBR == User);
11791           (void)NewBR;
11792
11793           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11794                                     Cond.getOperand(0), Cond.getOperand(1));
11795           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11796           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11797           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11798                               Chain, Dest, CC, Cmp);
11799           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11800           Cond = Cmp;
11801           addTest = false;
11802           Dest = FalseBB;
11803         }
11804       }
11805     }
11806   }
11807
11808   if (addTest) {
11809     // Look pass the truncate if the high bits are known zero.
11810     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11811         Cond = Cond.getOperand(0);
11812
11813     // We know the result of AND is compared against zero. Try to match
11814     // it to BT.
11815     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11816       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11817       if (NewSetCC.getNode()) {
11818         CC = NewSetCC.getOperand(0);
11819         Cond = NewSetCC.getOperand(1);
11820         addTest = false;
11821       }
11822     }
11823   }
11824
11825   if (addTest) {
11826     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
11827     CC = DAG.getConstant(X86Cond, MVT::i8);
11828     Cond = EmitTest(Cond, X86Cond, dl, DAG);
11829   }
11830   Cond = ConvertCmpIfNecessary(Cond, DAG);
11831   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11832                      Chain, Dest, CC, Cond);
11833 }
11834
11835 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11836 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11837 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11838 // that the guard pages used by the OS virtual memory manager are allocated in
11839 // correct sequence.
11840 SDValue
11841 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11842                                            SelectionDAG &DAG) const {
11843   MachineFunction &MF = DAG.getMachineFunction();
11844   bool SplitStack = MF.shouldSplitStack();
11845   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11846                SplitStack;
11847   SDLoc dl(Op);
11848
11849   if (!Lower) {
11850     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11851     SDNode* Node = Op.getNode();
11852
11853     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11854     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11855         " not tell us which reg is the stack pointer!");
11856     EVT VT = Node->getValueType(0);
11857     SDValue Tmp1 = SDValue(Node, 0);
11858     SDValue Tmp2 = SDValue(Node, 1);
11859     SDValue Tmp3 = Node->getOperand(2);
11860     SDValue Chain = Tmp1.getOperand(0);
11861
11862     // Chain the dynamic stack allocation so that it doesn't modify the stack
11863     // pointer when other instructions are using the stack.
11864     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11865         SDLoc(Node));
11866
11867     SDValue Size = Tmp2.getOperand(1);
11868     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11869     Chain = SP.getValue(1);
11870     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11871     const TargetFrameLowering &TFI = *DAG.getTarget().getFrameLowering();
11872     unsigned StackAlign = TFI.getStackAlignment();
11873     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11874     if (Align > StackAlign)
11875       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11876           DAG.getConstant(-(uint64_t)Align, VT));
11877     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11878
11879     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11880         DAG.getIntPtrConstant(0, true), SDValue(),
11881         SDLoc(Node));
11882
11883     SDValue Ops[2] = { Tmp1, Tmp2 };
11884     return DAG.getMergeValues(Ops, dl);
11885   }
11886
11887   // Get the inputs.
11888   SDValue Chain = Op.getOperand(0);
11889   SDValue Size  = Op.getOperand(1);
11890   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11891   EVT VT = Op.getNode()->getValueType(0);
11892
11893   bool Is64Bit = Subtarget->is64Bit();
11894   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11895
11896   if (SplitStack) {
11897     MachineRegisterInfo &MRI = MF.getRegInfo();
11898
11899     if (Is64Bit) {
11900       // The 64 bit implementation of segmented stacks needs to clobber both r10
11901       // r11. This makes it impossible to use it along with nested parameters.
11902       const Function *F = MF.getFunction();
11903
11904       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11905            I != E; ++I)
11906         if (I->hasNestAttr())
11907           report_fatal_error("Cannot use segmented stacks with functions that "
11908                              "have nested arguments.");
11909     }
11910
11911     const TargetRegisterClass *AddrRegClass =
11912       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11913     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11914     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11915     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11916                                 DAG.getRegister(Vreg, SPTy));
11917     SDValue Ops1[2] = { Value, Chain };
11918     return DAG.getMergeValues(Ops1, dl);
11919   } else {
11920     SDValue Flag;
11921     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11922
11923     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11924     Flag = Chain.getValue(1);
11925     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11926
11927     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11928
11929     const X86RegisterInfo *RegInfo =
11930       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
11931     unsigned SPReg = RegInfo->getStackRegister();
11932     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11933     Chain = SP.getValue(1);
11934
11935     if (Align) {
11936       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11937                        DAG.getConstant(-(uint64_t)Align, VT));
11938       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11939     }
11940
11941     SDValue Ops1[2] = { SP, Chain };
11942     return DAG.getMergeValues(Ops1, dl);
11943   }
11944 }
11945
11946 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11947   MachineFunction &MF = DAG.getMachineFunction();
11948   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11949
11950   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11951   SDLoc DL(Op);
11952
11953   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11954     // vastart just stores the address of the VarArgsFrameIndex slot into the
11955     // memory location argument.
11956     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11957                                    getPointerTy());
11958     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11959                         MachinePointerInfo(SV), false, false, 0);
11960   }
11961
11962   // __va_list_tag:
11963   //   gp_offset         (0 - 6 * 8)
11964   //   fp_offset         (48 - 48 + 8 * 16)
11965   //   overflow_arg_area (point to parameters coming in memory).
11966   //   reg_save_area
11967   SmallVector<SDValue, 8> MemOps;
11968   SDValue FIN = Op.getOperand(1);
11969   // Store gp_offset
11970   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11971                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11972                                                MVT::i32),
11973                                FIN, MachinePointerInfo(SV), false, false, 0);
11974   MemOps.push_back(Store);
11975
11976   // Store fp_offset
11977   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11978                     FIN, DAG.getIntPtrConstant(4));
11979   Store = DAG.getStore(Op.getOperand(0), DL,
11980                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11981                                        MVT::i32),
11982                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11983   MemOps.push_back(Store);
11984
11985   // Store ptr to overflow_arg_area
11986   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11987                     FIN, DAG.getIntPtrConstant(4));
11988   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11989                                     getPointerTy());
11990   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11991                        MachinePointerInfo(SV, 8),
11992                        false, false, 0);
11993   MemOps.push_back(Store);
11994
11995   // Store ptr to reg_save_area.
11996   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11997                     FIN, DAG.getIntPtrConstant(8));
11998   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11999                                     getPointerTy());
12000   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
12001                        MachinePointerInfo(SV, 16), false, false, 0);
12002   MemOps.push_back(Store);
12003   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
12004 }
12005
12006 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
12007   assert(Subtarget->is64Bit() &&
12008          "LowerVAARG only handles 64-bit va_arg!");
12009   assert((Subtarget->isTargetLinux() ||
12010           Subtarget->isTargetDarwin()) &&
12011           "Unhandled target in LowerVAARG");
12012   assert(Op.getNode()->getNumOperands() == 4);
12013   SDValue Chain = Op.getOperand(0);
12014   SDValue SrcPtr = Op.getOperand(1);
12015   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
12016   unsigned Align = Op.getConstantOperandVal(3);
12017   SDLoc dl(Op);
12018
12019   EVT ArgVT = Op.getNode()->getValueType(0);
12020   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
12021   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
12022   uint8_t ArgMode;
12023
12024   // Decide which area this value should be read from.
12025   // TODO: Implement the AMD64 ABI in its entirety. This simple
12026   // selection mechanism works only for the basic types.
12027   if (ArgVT == MVT::f80) {
12028     llvm_unreachable("va_arg for f80 not yet implemented");
12029   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
12030     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
12031   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
12032     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
12033   } else {
12034     llvm_unreachable("Unhandled argument type in LowerVAARG");
12035   }
12036
12037   if (ArgMode == 2) {
12038     // Sanity Check: Make sure using fp_offset makes sense.
12039     assert(!DAG.getTarget().Options.UseSoftFloat &&
12040            !(DAG.getMachineFunction()
12041                 .getFunction()->getAttributes()
12042                 .hasAttribute(AttributeSet::FunctionIndex,
12043                               Attribute::NoImplicitFloat)) &&
12044            Subtarget->hasSSE1());
12045   }
12046
12047   // Insert VAARG_64 node into the DAG
12048   // VAARG_64 returns two values: Variable Argument Address, Chain
12049   SmallVector<SDValue, 11> InstOps;
12050   InstOps.push_back(Chain);
12051   InstOps.push_back(SrcPtr);
12052   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
12053   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
12054   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
12055   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
12056   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
12057                                           VTs, InstOps, MVT::i64,
12058                                           MachinePointerInfo(SV),
12059                                           /*Align=*/0,
12060                                           /*Volatile=*/false,
12061                                           /*ReadMem=*/true,
12062                                           /*WriteMem=*/true);
12063   Chain = VAARG.getValue(1);
12064
12065   // Load the next argument and return it
12066   return DAG.getLoad(ArgVT, dl,
12067                      Chain,
12068                      VAARG,
12069                      MachinePointerInfo(),
12070                      false, false, false, 0);
12071 }
12072
12073 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
12074                            SelectionDAG &DAG) {
12075   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
12076   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
12077   SDValue Chain = Op.getOperand(0);
12078   SDValue DstPtr = Op.getOperand(1);
12079   SDValue SrcPtr = Op.getOperand(2);
12080   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
12081   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12082   SDLoc DL(Op);
12083
12084   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
12085                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
12086                        false,
12087                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
12088 }
12089
12090 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
12091 // amount is a constant. Takes immediate version of shift as input.
12092 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
12093                                           SDValue SrcOp, uint64_t ShiftAmt,
12094                                           SelectionDAG &DAG) {
12095   MVT ElementType = VT.getVectorElementType();
12096
12097   // Fold this packed shift into its first operand if ShiftAmt is 0.
12098   if (ShiftAmt == 0)
12099     return SrcOp;
12100
12101   // Check for ShiftAmt >= element width
12102   if (ShiftAmt >= ElementType.getSizeInBits()) {
12103     if (Opc == X86ISD::VSRAI)
12104       ShiftAmt = ElementType.getSizeInBits() - 1;
12105     else
12106       return DAG.getConstant(0, VT);
12107   }
12108
12109   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
12110          && "Unknown target vector shift-by-constant node");
12111
12112   // Fold this packed vector shift into a build vector if SrcOp is a
12113   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
12114   if (VT == SrcOp.getSimpleValueType() &&
12115       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
12116     SmallVector<SDValue, 8> Elts;
12117     unsigned NumElts = SrcOp->getNumOperands();
12118     ConstantSDNode *ND;
12119
12120     switch(Opc) {
12121     default: llvm_unreachable(nullptr);
12122     case X86ISD::VSHLI:
12123       for (unsigned i=0; i!=NumElts; ++i) {
12124         SDValue CurrentOp = SrcOp->getOperand(i);
12125         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12126           Elts.push_back(CurrentOp);
12127           continue;
12128         }
12129         ND = cast<ConstantSDNode>(CurrentOp);
12130         const APInt &C = ND->getAPIntValue();
12131         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
12132       }
12133       break;
12134     case X86ISD::VSRLI:
12135       for (unsigned i=0; i!=NumElts; ++i) {
12136         SDValue CurrentOp = SrcOp->getOperand(i);
12137         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12138           Elts.push_back(CurrentOp);
12139           continue;
12140         }
12141         ND = cast<ConstantSDNode>(CurrentOp);
12142         const APInt &C = ND->getAPIntValue();
12143         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
12144       }
12145       break;
12146     case X86ISD::VSRAI:
12147       for (unsigned i=0; i!=NumElts; ++i) {
12148         SDValue CurrentOp = SrcOp->getOperand(i);
12149         if (CurrentOp->getOpcode() == ISD::UNDEF) {
12150           Elts.push_back(CurrentOp);
12151           continue;
12152         }
12153         ND = cast<ConstantSDNode>(CurrentOp);
12154         const APInt &C = ND->getAPIntValue();
12155         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
12156       }
12157       break;
12158     }
12159
12160     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
12161   }
12162
12163   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
12164 }
12165
12166 // getTargetVShiftNode - Handle vector element shifts where the shift amount
12167 // may or may not be a constant. Takes immediate version of shift as input.
12168 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
12169                                    SDValue SrcOp, SDValue ShAmt,
12170                                    SelectionDAG &DAG) {
12171   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
12172
12173   // Catch shift-by-constant.
12174   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
12175     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
12176                                       CShAmt->getZExtValue(), DAG);
12177
12178   // Change opcode to non-immediate version
12179   switch (Opc) {
12180     default: llvm_unreachable("Unknown target vector shift node");
12181     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
12182     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
12183     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
12184   }
12185
12186   // Need to build a vector containing shift amount
12187   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
12188   SDValue ShOps[4];
12189   ShOps[0] = ShAmt;
12190   ShOps[1] = DAG.getConstant(0, MVT::i32);
12191   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
12192   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
12193
12194   // The return type has to be a 128-bit type with the same element
12195   // type as the input type.
12196   MVT EltVT = VT.getVectorElementType();
12197   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
12198
12199   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
12200   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
12201 }
12202
12203 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
12204   SDLoc dl(Op);
12205   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12206   switch (IntNo) {
12207   default: return SDValue();    // Don't custom lower most intrinsics.
12208   // Comparison intrinsics.
12209   case Intrinsic::x86_sse_comieq_ss:
12210   case Intrinsic::x86_sse_comilt_ss:
12211   case Intrinsic::x86_sse_comile_ss:
12212   case Intrinsic::x86_sse_comigt_ss:
12213   case Intrinsic::x86_sse_comige_ss:
12214   case Intrinsic::x86_sse_comineq_ss:
12215   case Intrinsic::x86_sse_ucomieq_ss:
12216   case Intrinsic::x86_sse_ucomilt_ss:
12217   case Intrinsic::x86_sse_ucomile_ss:
12218   case Intrinsic::x86_sse_ucomigt_ss:
12219   case Intrinsic::x86_sse_ucomige_ss:
12220   case Intrinsic::x86_sse_ucomineq_ss:
12221   case Intrinsic::x86_sse2_comieq_sd:
12222   case Intrinsic::x86_sse2_comilt_sd:
12223   case Intrinsic::x86_sse2_comile_sd:
12224   case Intrinsic::x86_sse2_comigt_sd:
12225   case Intrinsic::x86_sse2_comige_sd:
12226   case Intrinsic::x86_sse2_comineq_sd:
12227   case Intrinsic::x86_sse2_ucomieq_sd:
12228   case Intrinsic::x86_sse2_ucomilt_sd:
12229   case Intrinsic::x86_sse2_ucomile_sd:
12230   case Intrinsic::x86_sse2_ucomigt_sd:
12231   case Intrinsic::x86_sse2_ucomige_sd:
12232   case Intrinsic::x86_sse2_ucomineq_sd: {
12233     unsigned Opc;
12234     ISD::CondCode CC;
12235     switch (IntNo) {
12236     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12237     case Intrinsic::x86_sse_comieq_ss:
12238     case Intrinsic::x86_sse2_comieq_sd:
12239       Opc = X86ISD::COMI;
12240       CC = ISD::SETEQ;
12241       break;
12242     case Intrinsic::x86_sse_comilt_ss:
12243     case Intrinsic::x86_sse2_comilt_sd:
12244       Opc = X86ISD::COMI;
12245       CC = ISD::SETLT;
12246       break;
12247     case Intrinsic::x86_sse_comile_ss:
12248     case Intrinsic::x86_sse2_comile_sd:
12249       Opc = X86ISD::COMI;
12250       CC = ISD::SETLE;
12251       break;
12252     case Intrinsic::x86_sse_comigt_ss:
12253     case Intrinsic::x86_sse2_comigt_sd:
12254       Opc = X86ISD::COMI;
12255       CC = ISD::SETGT;
12256       break;
12257     case Intrinsic::x86_sse_comige_ss:
12258     case Intrinsic::x86_sse2_comige_sd:
12259       Opc = X86ISD::COMI;
12260       CC = ISD::SETGE;
12261       break;
12262     case Intrinsic::x86_sse_comineq_ss:
12263     case Intrinsic::x86_sse2_comineq_sd:
12264       Opc = X86ISD::COMI;
12265       CC = ISD::SETNE;
12266       break;
12267     case Intrinsic::x86_sse_ucomieq_ss:
12268     case Intrinsic::x86_sse2_ucomieq_sd:
12269       Opc = X86ISD::UCOMI;
12270       CC = ISD::SETEQ;
12271       break;
12272     case Intrinsic::x86_sse_ucomilt_ss:
12273     case Intrinsic::x86_sse2_ucomilt_sd:
12274       Opc = X86ISD::UCOMI;
12275       CC = ISD::SETLT;
12276       break;
12277     case Intrinsic::x86_sse_ucomile_ss:
12278     case Intrinsic::x86_sse2_ucomile_sd:
12279       Opc = X86ISD::UCOMI;
12280       CC = ISD::SETLE;
12281       break;
12282     case Intrinsic::x86_sse_ucomigt_ss:
12283     case Intrinsic::x86_sse2_ucomigt_sd:
12284       Opc = X86ISD::UCOMI;
12285       CC = ISD::SETGT;
12286       break;
12287     case Intrinsic::x86_sse_ucomige_ss:
12288     case Intrinsic::x86_sse2_ucomige_sd:
12289       Opc = X86ISD::UCOMI;
12290       CC = ISD::SETGE;
12291       break;
12292     case Intrinsic::x86_sse_ucomineq_ss:
12293     case Intrinsic::x86_sse2_ucomineq_sd:
12294       Opc = X86ISD::UCOMI;
12295       CC = ISD::SETNE;
12296       break;
12297     }
12298
12299     SDValue LHS = Op.getOperand(1);
12300     SDValue RHS = Op.getOperand(2);
12301     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
12302     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
12303     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
12304     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12305                                 DAG.getConstant(X86CC, MVT::i8), Cond);
12306     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12307   }
12308
12309   // Arithmetic intrinsics.
12310   case Intrinsic::x86_sse2_pmulu_dq:
12311   case Intrinsic::x86_avx2_pmulu_dq:
12312     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
12313                        Op.getOperand(1), Op.getOperand(2));
12314
12315   case Intrinsic::x86_sse41_pmuldq:
12316   case Intrinsic::x86_avx2_pmul_dq:
12317     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
12318                        Op.getOperand(1), Op.getOperand(2));
12319
12320   case Intrinsic::x86_sse2_pmulhu_w:
12321   case Intrinsic::x86_avx2_pmulhu_w:
12322     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
12323                        Op.getOperand(1), Op.getOperand(2));
12324
12325   case Intrinsic::x86_sse2_pmulh_w:
12326   case Intrinsic::x86_avx2_pmulh_w:
12327     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
12328                        Op.getOperand(1), Op.getOperand(2));
12329
12330   // SSE2/AVX2 sub with unsigned saturation intrinsics
12331   case Intrinsic::x86_sse2_psubus_b:
12332   case Intrinsic::x86_sse2_psubus_w:
12333   case Intrinsic::x86_avx2_psubus_b:
12334   case Intrinsic::x86_avx2_psubus_w:
12335     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
12336                        Op.getOperand(1), Op.getOperand(2));
12337
12338   // SSE3/AVX horizontal add/sub intrinsics
12339   case Intrinsic::x86_sse3_hadd_ps:
12340   case Intrinsic::x86_sse3_hadd_pd:
12341   case Intrinsic::x86_avx_hadd_ps_256:
12342   case Intrinsic::x86_avx_hadd_pd_256:
12343   case Intrinsic::x86_sse3_hsub_ps:
12344   case Intrinsic::x86_sse3_hsub_pd:
12345   case Intrinsic::x86_avx_hsub_ps_256:
12346   case Intrinsic::x86_avx_hsub_pd_256:
12347   case Intrinsic::x86_ssse3_phadd_w_128:
12348   case Intrinsic::x86_ssse3_phadd_d_128:
12349   case Intrinsic::x86_avx2_phadd_w:
12350   case Intrinsic::x86_avx2_phadd_d:
12351   case Intrinsic::x86_ssse3_phsub_w_128:
12352   case Intrinsic::x86_ssse3_phsub_d_128:
12353   case Intrinsic::x86_avx2_phsub_w:
12354   case Intrinsic::x86_avx2_phsub_d: {
12355     unsigned Opcode;
12356     switch (IntNo) {
12357     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12358     case Intrinsic::x86_sse3_hadd_ps:
12359     case Intrinsic::x86_sse3_hadd_pd:
12360     case Intrinsic::x86_avx_hadd_ps_256:
12361     case Intrinsic::x86_avx_hadd_pd_256:
12362       Opcode = X86ISD::FHADD;
12363       break;
12364     case Intrinsic::x86_sse3_hsub_ps:
12365     case Intrinsic::x86_sse3_hsub_pd:
12366     case Intrinsic::x86_avx_hsub_ps_256:
12367     case Intrinsic::x86_avx_hsub_pd_256:
12368       Opcode = X86ISD::FHSUB;
12369       break;
12370     case Intrinsic::x86_ssse3_phadd_w_128:
12371     case Intrinsic::x86_ssse3_phadd_d_128:
12372     case Intrinsic::x86_avx2_phadd_w:
12373     case Intrinsic::x86_avx2_phadd_d:
12374       Opcode = X86ISD::HADD;
12375       break;
12376     case Intrinsic::x86_ssse3_phsub_w_128:
12377     case Intrinsic::x86_ssse3_phsub_d_128:
12378     case Intrinsic::x86_avx2_phsub_w:
12379     case Intrinsic::x86_avx2_phsub_d:
12380       Opcode = X86ISD::HSUB;
12381       break;
12382     }
12383     return DAG.getNode(Opcode, dl, Op.getValueType(),
12384                        Op.getOperand(1), Op.getOperand(2));
12385   }
12386
12387   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12388   case Intrinsic::x86_sse2_pmaxu_b:
12389   case Intrinsic::x86_sse41_pmaxuw:
12390   case Intrinsic::x86_sse41_pmaxud:
12391   case Intrinsic::x86_avx2_pmaxu_b:
12392   case Intrinsic::x86_avx2_pmaxu_w:
12393   case Intrinsic::x86_avx2_pmaxu_d:
12394   case Intrinsic::x86_sse2_pminu_b:
12395   case Intrinsic::x86_sse41_pminuw:
12396   case Intrinsic::x86_sse41_pminud:
12397   case Intrinsic::x86_avx2_pminu_b:
12398   case Intrinsic::x86_avx2_pminu_w:
12399   case Intrinsic::x86_avx2_pminu_d:
12400   case Intrinsic::x86_sse41_pmaxsb:
12401   case Intrinsic::x86_sse2_pmaxs_w:
12402   case Intrinsic::x86_sse41_pmaxsd:
12403   case Intrinsic::x86_avx2_pmaxs_b:
12404   case Intrinsic::x86_avx2_pmaxs_w:
12405   case Intrinsic::x86_avx2_pmaxs_d:
12406   case Intrinsic::x86_sse41_pminsb:
12407   case Intrinsic::x86_sse2_pmins_w:
12408   case Intrinsic::x86_sse41_pminsd:
12409   case Intrinsic::x86_avx2_pmins_b:
12410   case Intrinsic::x86_avx2_pmins_w:
12411   case Intrinsic::x86_avx2_pmins_d: {
12412     unsigned Opcode;
12413     switch (IntNo) {
12414     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12415     case Intrinsic::x86_sse2_pmaxu_b:
12416     case Intrinsic::x86_sse41_pmaxuw:
12417     case Intrinsic::x86_sse41_pmaxud:
12418     case Intrinsic::x86_avx2_pmaxu_b:
12419     case Intrinsic::x86_avx2_pmaxu_w:
12420     case Intrinsic::x86_avx2_pmaxu_d:
12421       Opcode = X86ISD::UMAX;
12422       break;
12423     case Intrinsic::x86_sse2_pminu_b:
12424     case Intrinsic::x86_sse41_pminuw:
12425     case Intrinsic::x86_sse41_pminud:
12426     case Intrinsic::x86_avx2_pminu_b:
12427     case Intrinsic::x86_avx2_pminu_w:
12428     case Intrinsic::x86_avx2_pminu_d:
12429       Opcode = X86ISD::UMIN;
12430       break;
12431     case Intrinsic::x86_sse41_pmaxsb:
12432     case Intrinsic::x86_sse2_pmaxs_w:
12433     case Intrinsic::x86_sse41_pmaxsd:
12434     case Intrinsic::x86_avx2_pmaxs_b:
12435     case Intrinsic::x86_avx2_pmaxs_w:
12436     case Intrinsic::x86_avx2_pmaxs_d:
12437       Opcode = X86ISD::SMAX;
12438       break;
12439     case Intrinsic::x86_sse41_pminsb:
12440     case Intrinsic::x86_sse2_pmins_w:
12441     case Intrinsic::x86_sse41_pminsd:
12442     case Intrinsic::x86_avx2_pmins_b:
12443     case Intrinsic::x86_avx2_pmins_w:
12444     case Intrinsic::x86_avx2_pmins_d:
12445       Opcode = X86ISD::SMIN;
12446       break;
12447     }
12448     return DAG.getNode(Opcode, dl, Op.getValueType(),
12449                        Op.getOperand(1), Op.getOperand(2));
12450   }
12451
12452   // SSE/SSE2/AVX floating point max/min intrinsics.
12453   case Intrinsic::x86_sse_max_ps:
12454   case Intrinsic::x86_sse2_max_pd:
12455   case Intrinsic::x86_avx_max_ps_256:
12456   case Intrinsic::x86_avx_max_pd_256:
12457   case Intrinsic::x86_sse_min_ps:
12458   case Intrinsic::x86_sse2_min_pd:
12459   case Intrinsic::x86_avx_min_ps_256:
12460   case Intrinsic::x86_avx_min_pd_256: {
12461     unsigned Opcode;
12462     switch (IntNo) {
12463     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12464     case Intrinsic::x86_sse_max_ps:
12465     case Intrinsic::x86_sse2_max_pd:
12466     case Intrinsic::x86_avx_max_ps_256:
12467     case Intrinsic::x86_avx_max_pd_256:
12468       Opcode = X86ISD::FMAX;
12469       break;
12470     case Intrinsic::x86_sse_min_ps:
12471     case Intrinsic::x86_sse2_min_pd:
12472     case Intrinsic::x86_avx_min_ps_256:
12473     case Intrinsic::x86_avx_min_pd_256:
12474       Opcode = X86ISD::FMIN;
12475       break;
12476     }
12477     return DAG.getNode(Opcode, dl, Op.getValueType(),
12478                        Op.getOperand(1), Op.getOperand(2));
12479   }
12480
12481   // AVX2 variable shift intrinsics
12482   case Intrinsic::x86_avx2_psllv_d:
12483   case Intrinsic::x86_avx2_psllv_q:
12484   case Intrinsic::x86_avx2_psllv_d_256:
12485   case Intrinsic::x86_avx2_psllv_q_256:
12486   case Intrinsic::x86_avx2_psrlv_d:
12487   case Intrinsic::x86_avx2_psrlv_q:
12488   case Intrinsic::x86_avx2_psrlv_d_256:
12489   case Intrinsic::x86_avx2_psrlv_q_256:
12490   case Intrinsic::x86_avx2_psrav_d:
12491   case Intrinsic::x86_avx2_psrav_d_256: {
12492     unsigned Opcode;
12493     switch (IntNo) {
12494     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12495     case Intrinsic::x86_avx2_psllv_d:
12496     case Intrinsic::x86_avx2_psllv_q:
12497     case Intrinsic::x86_avx2_psllv_d_256:
12498     case Intrinsic::x86_avx2_psllv_q_256:
12499       Opcode = ISD::SHL;
12500       break;
12501     case Intrinsic::x86_avx2_psrlv_d:
12502     case Intrinsic::x86_avx2_psrlv_q:
12503     case Intrinsic::x86_avx2_psrlv_d_256:
12504     case Intrinsic::x86_avx2_psrlv_q_256:
12505       Opcode = ISD::SRL;
12506       break;
12507     case Intrinsic::x86_avx2_psrav_d:
12508     case Intrinsic::x86_avx2_psrav_d_256:
12509       Opcode = ISD::SRA;
12510       break;
12511     }
12512     return DAG.getNode(Opcode, dl, Op.getValueType(),
12513                        Op.getOperand(1), Op.getOperand(2));
12514   }
12515
12516   case Intrinsic::x86_ssse3_pshuf_b_128:
12517   case Intrinsic::x86_avx2_pshuf_b:
12518     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12519                        Op.getOperand(1), Op.getOperand(2));
12520
12521   case Intrinsic::x86_ssse3_psign_b_128:
12522   case Intrinsic::x86_ssse3_psign_w_128:
12523   case Intrinsic::x86_ssse3_psign_d_128:
12524   case Intrinsic::x86_avx2_psign_b:
12525   case Intrinsic::x86_avx2_psign_w:
12526   case Intrinsic::x86_avx2_psign_d:
12527     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12528                        Op.getOperand(1), Op.getOperand(2));
12529
12530   case Intrinsic::x86_sse41_insertps:
12531     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12532                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12533
12534   case Intrinsic::x86_avx_vperm2f128_ps_256:
12535   case Intrinsic::x86_avx_vperm2f128_pd_256:
12536   case Intrinsic::x86_avx_vperm2f128_si_256:
12537   case Intrinsic::x86_avx2_vperm2i128:
12538     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12539                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12540
12541   case Intrinsic::x86_avx2_permd:
12542   case Intrinsic::x86_avx2_permps:
12543     // Operands intentionally swapped. Mask is last operand to intrinsic,
12544     // but second operand for node/instruction.
12545     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12546                        Op.getOperand(2), Op.getOperand(1));
12547
12548   case Intrinsic::x86_sse_sqrt_ps:
12549   case Intrinsic::x86_sse2_sqrt_pd:
12550   case Intrinsic::x86_avx_sqrt_ps_256:
12551   case Intrinsic::x86_avx_sqrt_pd_256:
12552     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12553
12554   // ptest and testp intrinsics. The intrinsic these come from are designed to
12555   // return an integer value, not just an instruction so lower it to the ptest
12556   // or testp pattern and a setcc for the result.
12557   case Intrinsic::x86_sse41_ptestz:
12558   case Intrinsic::x86_sse41_ptestc:
12559   case Intrinsic::x86_sse41_ptestnzc:
12560   case Intrinsic::x86_avx_ptestz_256:
12561   case Intrinsic::x86_avx_ptestc_256:
12562   case Intrinsic::x86_avx_ptestnzc_256:
12563   case Intrinsic::x86_avx_vtestz_ps:
12564   case Intrinsic::x86_avx_vtestc_ps:
12565   case Intrinsic::x86_avx_vtestnzc_ps:
12566   case Intrinsic::x86_avx_vtestz_pd:
12567   case Intrinsic::x86_avx_vtestc_pd:
12568   case Intrinsic::x86_avx_vtestnzc_pd:
12569   case Intrinsic::x86_avx_vtestz_ps_256:
12570   case Intrinsic::x86_avx_vtestc_ps_256:
12571   case Intrinsic::x86_avx_vtestnzc_ps_256:
12572   case Intrinsic::x86_avx_vtestz_pd_256:
12573   case Intrinsic::x86_avx_vtestc_pd_256:
12574   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12575     bool IsTestPacked = false;
12576     unsigned X86CC;
12577     switch (IntNo) {
12578     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12579     case Intrinsic::x86_avx_vtestz_ps:
12580     case Intrinsic::x86_avx_vtestz_pd:
12581     case Intrinsic::x86_avx_vtestz_ps_256:
12582     case Intrinsic::x86_avx_vtestz_pd_256:
12583       IsTestPacked = true; // Fallthrough
12584     case Intrinsic::x86_sse41_ptestz:
12585     case Intrinsic::x86_avx_ptestz_256:
12586       // ZF = 1
12587       X86CC = X86::COND_E;
12588       break;
12589     case Intrinsic::x86_avx_vtestc_ps:
12590     case Intrinsic::x86_avx_vtestc_pd:
12591     case Intrinsic::x86_avx_vtestc_ps_256:
12592     case Intrinsic::x86_avx_vtestc_pd_256:
12593       IsTestPacked = true; // Fallthrough
12594     case Intrinsic::x86_sse41_ptestc:
12595     case Intrinsic::x86_avx_ptestc_256:
12596       // CF = 1
12597       X86CC = X86::COND_B;
12598       break;
12599     case Intrinsic::x86_avx_vtestnzc_ps:
12600     case Intrinsic::x86_avx_vtestnzc_pd:
12601     case Intrinsic::x86_avx_vtestnzc_ps_256:
12602     case Intrinsic::x86_avx_vtestnzc_pd_256:
12603       IsTestPacked = true; // Fallthrough
12604     case Intrinsic::x86_sse41_ptestnzc:
12605     case Intrinsic::x86_avx_ptestnzc_256:
12606       // ZF and CF = 0
12607       X86CC = X86::COND_A;
12608       break;
12609     }
12610
12611     SDValue LHS = Op.getOperand(1);
12612     SDValue RHS = Op.getOperand(2);
12613     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12614     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12615     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12616     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12617     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12618   }
12619   case Intrinsic::x86_avx512_kortestz_w:
12620   case Intrinsic::x86_avx512_kortestc_w: {
12621     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12622     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12623     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12624     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12625     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12626     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12627     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12628   }
12629
12630   // SSE/AVX shift intrinsics
12631   case Intrinsic::x86_sse2_psll_w:
12632   case Intrinsic::x86_sse2_psll_d:
12633   case Intrinsic::x86_sse2_psll_q:
12634   case Intrinsic::x86_avx2_psll_w:
12635   case Intrinsic::x86_avx2_psll_d:
12636   case Intrinsic::x86_avx2_psll_q:
12637   case Intrinsic::x86_sse2_psrl_w:
12638   case Intrinsic::x86_sse2_psrl_d:
12639   case Intrinsic::x86_sse2_psrl_q:
12640   case Intrinsic::x86_avx2_psrl_w:
12641   case Intrinsic::x86_avx2_psrl_d:
12642   case Intrinsic::x86_avx2_psrl_q:
12643   case Intrinsic::x86_sse2_psra_w:
12644   case Intrinsic::x86_sse2_psra_d:
12645   case Intrinsic::x86_avx2_psra_w:
12646   case Intrinsic::x86_avx2_psra_d: {
12647     unsigned Opcode;
12648     switch (IntNo) {
12649     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12650     case Intrinsic::x86_sse2_psll_w:
12651     case Intrinsic::x86_sse2_psll_d:
12652     case Intrinsic::x86_sse2_psll_q:
12653     case Intrinsic::x86_avx2_psll_w:
12654     case Intrinsic::x86_avx2_psll_d:
12655     case Intrinsic::x86_avx2_psll_q:
12656       Opcode = X86ISD::VSHL;
12657       break;
12658     case Intrinsic::x86_sse2_psrl_w:
12659     case Intrinsic::x86_sse2_psrl_d:
12660     case Intrinsic::x86_sse2_psrl_q:
12661     case Intrinsic::x86_avx2_psrl_w:
12662     case Intrinsic::x86_avx2_psrl_d:
12663     case Intrinsic::x86_avx2_psrl_q:
12664       Opcode = X86ISD::VSRL;
12665       break;
12666     case Intrinsic::x86_sse2_psra_w:
12667     case Intrinsic::x86_sse2_psra_d:
12668     case Intrinsic::x86_avx2_psra_w:
12669     case Intrinsic::x86_avx2_psra_d:
12670       Opcode = X86ISD::VSRA;
12671       break;
12672     }
12673     return DAG.getNode(Opcode, dl, Op.getValueType(),
12674                        Op.getOperand(1), Op.getOperand(2));
12675   }
12676
12677   // SSE/AVX immediate shift intrinsics
12678   case Intrinsic::x86_sse2_pslli_w:
12679   case Intrinsic::x86_sse2_pslli_d:
12680   case Intrinsic::x86_sse2_pslli_q:
12681   case Intrinsic::x86_avx2_pslli_w:
12682   case Intrinsic::x86_avx2_pslli_d:
12683   case Intrinsic::x86_avx2_pslli_q:
12684   case Intrinsic::x86_sse2_psrli_w:
12685   case Intrinsic::x86_sse2_psrli_d:
12686   case Intrinsic::x86_sse2_psrli_q:
12687   case Intrinsic::x86_avx2_psrli_w:
12688   case Intrinsic::x86_avx2_psrli_d:
12689   case Intrinsic::x86_avx2_psrli_q:
12690   case Intrinsic::x86_sse2_psrai_w:
12691   case Intrinsic::x86_sse2_psrai_d:
12692   case Intrinsic::x86_avx2_psrai_w:
12693   case Intrinsic::x86_avx2_psrai_d: {
12694     unsigned Opcode;
12695     switch (IntNo) {
12696     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12697     case Intrinsic::x86_sse2_pslli_w:
12698     case Intrinsic::x86_sse2_pslli_d:
12699     case Intrinsic::x86_sse2_pslli_q:
12700     case Intrinsic::x86_avx2_pslli_w:
12701     case Intrinsic::x86_avx2_pslli_d:
12702     case Intrinsic::x86_avx2_pslli_q:
12703       Opcode = X86ISD::VSHLI;
12704       break;
12705     case Intrinsic::x86_sse2_psrli_w:
12706     case Intrinsic::x86_sse2_psrli_d:
12707     case Intrinsic::x86_sse2_psrli_q:
12708     case Intrinsic::x86_avx2_psrli_w:
12709     case Intrinsic::x86_avx2_psrli_d:
12710     case Intrinsic::x86_avx2_psrli_q:
12711       Opcode = X86ISD::VSRLI;
12712       break;
12713     case Intrinsic::x86_sse2_psrai_w:
12714     case Intrinsic::x86_sse2_psrai_d:
12715     case Intrinsic::x86_avx2_psrai_w:
12716     case Intrinsic::x86_avx2_psrai_d:
12717       Opcode = X86ISD::VSRAI;
12718       break;
12719     }
12720     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12721                                Op.getOperand(1), Op.getOperand(2), DAG);
12722   }
12723
12724   case Intrinsic::x86_sse42_pcmpistria128:
12725   case Intrinsic::x86_sse42_pcmpestria128:
12726   case Intrinsic::x86_sse42_pcmpistric128:
12727   case Intrinsic::x86_sse42_pcmpestric128:
12728   case Intrinsic::x86_sse42_pcmpistrio128:
12729   case Intrinsic::x86_sse42_pcmpestrio128:
12730   case Intrinsic::x86_sse42_pcmpistris128:
12731   case Intrinsic::x86_sse42_pcmpestris128:
12732   case Intrinsic::x86_sse42_pcmpistriz128:
12733   case Intrinsic::x86_sse42_pcmpestriz128: {
12734     unsigned Opcode;
12735     unsigned X86CC;
12736     switch (IntNo) {
12737     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12738     case Intrinsic::x86_sse42_pcmpistria128:
12739       Opcode = X86ISD::PCMPISTRI;
12740       X86CC = X86::COND_A;
12741       break;
12742     case Intrinsic::x86_sse42_pcmpestria128:
12743       Opcode = X86ISD::PCMPESTRI;
12744       X86CC = X86::COND_A;
12745       break;
12746     case Intrinsic::x86_sse42_pcmpistric128:
12747       Opcode = X86ISD::PCMPISTRI;
12748       X86CC = X86::COND_B;
12749       break;
12750     case Intrinsic::x86_sse42_pcmpestric128:
12751       Opcode = X86ISD::PCMPESTRI;
12752       X86CC = X86::COND_B;
12753       break;
12754     case Intrinsic::x86_sse42_pcmpistrio128:
12755       Opcode = X86ISD::PCMPISTRI;
12756       X86CC = X86::COND_O;
12757       break;
12758     case Intrinsic::x86_sse42_pcmpestrio128:
12759       Opcode = X86ISD::PCMPESTRI;
12760       X86CC = X86::COND_O;
12761       break;
12762     case Intrinsic::x86_sse42_pcmpistris128:
12763       Opcode = X86ISD::PCMPISTRI;
12764       X86CC = X86::COND_S;
12765       break;
12766     case Intrinsic::x86_sse42_pcmpestris128:
12767       Opcode = X86ISD::PCMPESTRI;
12768       X86CC = X86::COND_S;
12769       break;
12770     case Intrinsic::x86_sse42_pcmpistriz128:
12771       Opcode = X86ISD::PCMPISTRI;
12772       X86CC = X86::COND_E;
12773       break;
12774     case Intrinsic::x86_sse42_pcmpestriz128:
12775       Opcode = X86ISD::PCMPESTRI;
12776       X86CC = X86::COND_E;
12777       break;
12778     }
12779     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12780     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12781     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12782     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12783                                 DAG.getConstant(X86CC, MVT::i8),
12784                                 SDValue(PCMP.getNode(), 1));
12785     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12786   }
12787
12788   case Intrinsic::x86_sse42_pcmpistri128:
12789   case Intrinsic::x86_sse42_pcmpestri128: {
12790     unsigned Opcode;
12791     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12792       Opcode = X86ISD::PCMPISTRI;
12793     else
12794       Opcode = X86ISD::PCMPESTRI;
12795
12796     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12797     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12798     return DAG.getNode(Opcode, dl, VTs, NewOps);
12799   }
12800   case Intrinsic::x86_fma_vfmadd_ps:
12801   case Intrinsic::x86_fma_vfmadd_pd:
12802   case Intrinsic::x86_fma_vfmsub_ps:
12803   case Intrinsic::x86_fma_vfmsub_pd:
12804   case Intrinsic::x86_fma_vfnmadd_ps:
12805   case Intrinsic::x86_fma_vfnmadd_pd:
12806   case Intrinsic::x86_fma_vfnmsub_ps:
12807   case Intrinsic::x86_fma_vfnmsub_pd:
12808   case Intrinsic::x86_fma_vfmaddsub_ps:
12809   case Intrinsic::x86_fma_vfmaddsub_pd:
12810   case Intrinsic::x86_fma_vfmsubadd_ps:
12811   case Intrinsic::x86_fma_vfmsubadd_pd:
12812   case Intrinsic::x86_fma_vfmadd_ps_256:
12813   case Intrinsic::x86_fma_vfmadd_pd_256:
12814   case Intrinsic::x86_fma_vfmsub_ps_256:
12815   case Intrinsic::x86_fma_vfmsub_pd_256:
12816   case Intrinsic::x86_fma_vfnmadd_ps_256:
12817   case Intrinsic::x86_fma_vfnmadd_pd_256:
12818   case Intrinsic::x86_fma_vfnmsub_ps_256:
12819   case Intrinsic::x86_fma_vfnmsub_pd_256:
12820   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12821   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12822   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12823   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12824   case Intrinsic::x86_fma_vfmadd_ps_512:
12825   case Intrinsic::x86_fma_vfmadd_pd_512:
12826   case Intrinsic::x86_fma_vfmsub_ps_512:
12827   case Intrinsic::x86_fma_vfmsub_pd_512:
12828   case Intrinsic::x86_fma_vfnmadd_ps_512:
12829   case Intrinsic::x86_fma_vfnmadd_pd_512:
12830   case Intrinsic::x86_fma_vfnmsub_ps_512:
12831   case Intrinsic::x86_fma_vfnmsub_pd_512:
12832   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12833   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12834   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12835   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12836     unsigned Opc;
12837     switch (IntNo) {
12838     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12839     case Intrinsic::x86_fma_vfmadd_ps:
12840     case Intrinsic::x86_fma_vfmadd_pd:
12841     case Intrinsic::x86_fma_vfmadd_ps_256:
12842     case Intrinsic::x86_fma_vfmadd_pd_256:
12843     case Intrinsic::x86_fma_vfmadd_ps_512:
12844     case Intrinsic::x86_fma_vfmadd_pd_512:
12845       Opc = X86ISD::FMADD;
12846       break;
12847     case Intrinsic::x86_fma_vfmsub_ps:
12848     case Intrinsic::x86_fma_vfmsub_pd:
12849     case Intrinsic::x86_fma_vfmsub_ps_256:
12850     case Intrinsic::x86_fma_vfmsub_pd_256:
12851     case Intrinsic::x86_fma_vfmsub_ps_512:
12852     case Intrinsic::x86_fma_vfmsub_pd_512:
12853       Opc = X86ISD::FMSUB;
12854       break;
12855     case Intrinsic::x86_fma_vfnmadd_ps:
12856     case Intrinsic::x86_fma_vfnmadd_pd:
12857     case Intrinsic::x86_fma_vfnmadd_ps_256:
12858     case Intrinsic::x86_fma_vfnmadd_pd_256:
12859     case Intrinsic::x86_fma_vfnmadd_ps_512:
12860     case Intrinsic::x86_fma_vfnmadd_pd_512:
12861       Opc = X86ISD::FNMADD;
12862       break;
12863     case Intrinsic::x86_fma_vfnmsub_ps:
12864     case Intrinsic::x86_fma_vfnmsub_pd:
12865     case Intrinsic::x86_fma_vfnmsub_ps_256:
12866     case Intrinsic::x86_fma_vfnmsub_pd_256:
12867     case Intrinsic::x86_fma_vfnmsub_ps_512:
12868     case Intrinsic::x86_fma_vfnmsub_pd_512:
12869       Opc = X86ISD::FNMSUB;
12870       break;
12871     case Intrinsic::x86_fma_vfmaddsub_ps:
12872     case Intrinsic::x86_fma_vfmaddsub_pd:
12873     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12874     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12875     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12876     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12877       Opc = X86ISD::FMADDSUB;
12878       break;
12879     case Intrinsic::x86_fma_vfmsubadd_ps:
12880     case Intrinsic::x86_fma_vfmsubadd_pd:
12881     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12882     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12883     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12884     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12885       Opc = X86ISD::FMSUBADD;
12886       break;
12887     }
12888
12889     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12890                        Op.getOperand(2), Op.getOperand(3));
12891   }
12892   }
12893 }
12894
12895 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12896                               SDValue Src, SDValue Mask, SDValue Base,
12897                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12898                               const X86Subtarget * Subtarget) {
12899   SDLoc dl(Op);
12900   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12901   assert(C && "Invalid scale type");
12902   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12903   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12904                              Index.getSimpleValueType().getVectorNumElements());
12905   SDValue MaskInReg;
12906   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12907   if (MaskC)
12908     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12909   else
12910     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12911   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12912   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12913   SDValue Segment = DAG.getRegister(0, MVT::i32);
12914   if (Src.getOpcode() == ISD::UNDEF)
12915     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12916   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12917   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12918   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12919   return DAG.getMergeValues(RetOps, dl);
12920 }
12921
12922 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12923                                SDValue Src, SDValue Mask, SDValue Base,
12924                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12925   SDLoc dl(Op);
12926   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12927   assert(C && "Invalid scale type");
12928   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12929   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12930   SDValue Segment = DAG.getRegister(0, MVT::i32);
12931   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12932                              Index.getSimpleValueType().getVectorNumElements());
12933   SDValue MaskInReg;
12934   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12935   if (MaskC)
12936     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12937   else
12938     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12939   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12940   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12941   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12942   return SDValue(Res, 1);
12943 }
12944
12945 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12946                                SDValue Mask, SDValue Base, SDValue Index,
12947                                SDValue ScaleOp, SDValue Chain) {
12948   SDLoc dl(Op);
12949   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12950   assert(C && "Invalid scale type");
12951   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12952   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12953   SDValue Segment = DAG.getRegister(0, MVT::i32);
12954   EVT MaskVT =
12955     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12956   SDValue MaskInReg;
12957   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12958   if (MaskC)
12959     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12960   else
12961     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12962   //SDVTList VTs = DAG.getVTList(MVT::Other);
12963   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12964   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12965   return SDValue(Res, 0);
12966 }
12967
12968 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12969 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12970 // also used to custom lower READCYCLECOUNTER nodes.
12971 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12972                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12973                               SmallVectorImpl<SDValue> &Results) {
12974   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12975   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12976   SDValue LO, HI;
12977
12978   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12979   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12980   // and the EAX register is loaded with the low-order 32 bits.
12981   if (Subtarget->is64Bit()) {
12982     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12983     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12984                             LO.getValue(2));
12985   } else {
12986     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12987     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12988                             LO.getValue(2));
12989   }
12990   SDValue Chain = HI.getValue(1);
12991
12992   if (Opcode == X86ISD::RDTSCP_DAG) {
12993     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12994
12995     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12996     // the ECX register. Add 'ecx' explicitly to the chain.
12997     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12998                                      HI.getValue(2));
12999     // Explicitly store the content of ECX at the location passed in input
13000     // to the 'rdtscp' intrinsic.
13001     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
13002                          MachinePointerInfo(), false, false, 0);
13003   }
13004
13005   if (Subtarget->is64Bit()) {
13006     // The EDX register is loaded with the high-order 32 bits of the MSR, and
13007     // the EAX register is loaded with the low-order 32 bits.
13008     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
13009                               DAG.getConstant(32, MVT::i8));
13010     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
13011     Results.push_back(Chain);
13012     return;
13013   }
13014
13015   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
13016   SDValue Ops[] = { LO, HI };
13017   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
13018   Results.push_back(Pair);
13019   Results.push_back(Chain);
13020 }
13021
13022 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
13023                                      SelectionDAG &DAG) {
13024   SmallVector<SDValue, 2> Results;
13025   SDLoc DL(Op);
13026   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
13027                           Results);
13028   return DAG.getMergeValues(Results, DL);
13029 }
13030
13031 enum IntrinsicType {
13032   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
13033 };
13034
13035 struct IntrinsicData {
13036   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
13037     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
13038   IntrinsicType Type;
13039   unsigned      Opc0;
13040   unsigned      Opc1;
13041 };
13042
13043 std::map < unsigned, IntrinsicData> IntrMap;
13044 static void InitIntinsicsMap() {
13045   static bool Initialized = false;
13046   if (Initialized) 
13047     return;
13048   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13049                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13050   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
13051                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
13052   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
13053                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
13054   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
13055                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
13056   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
13057                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
13058   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
13059                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
13060   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
13061                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
13062   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
13063                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
13064   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
13065                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
13066
13067   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
13068                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
13069   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
13070                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
13071   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
13072                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
13073   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
13074                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
13075   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
13076                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
13077   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
13078                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
13079   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
13080                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
13081   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
13082                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
13083    
13084   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
13085                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
13086                                                         X86::VGATHERPF1QPSm)));
13087   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
13088                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
13089                                                         X86::VGATHERPF1QPDm)));
13090   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
13091                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
13092                                                         X86::VGATHERPF1DPDm)));
13093   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
13094                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
13095                                                         X86::VGATHERPF1DPSm)));
13096   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
13097                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
13098                                                         X86::VSCATTERPF1QPSm)));
13099   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
13100                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
13101                                                         X86::VSCATTERPF1QPDm)));
13102   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
13103                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
13104                                                         X86::VSCATTERPF1DPDm)));
13105   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
13106                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
13107                                                         X86::VSCATTERPF1DPSm)));
13108   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
13109                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13110   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
13111                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13112   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
13113                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
13114   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
13115                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13116   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
13117                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13118   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
13119                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
13120   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
13121                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
13122   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
13123                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
13124   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
13125                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
13126   Initialized = true;
13127 }
13128
13129 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
13130                                       SelectionDAG &DAG) {
13131   InitIntinsicsMap();
13132   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
13133   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
13134   if (itr == IntrMap.end())
13135     return SDValue();
13136
13137   SDLoc dl(Op);
13138   IntrinsicData Intr = itr->second;
13139   switch(Intr.Type) {
13140   case RDSEED:
13141   case RDRAND: {
13142     // Emit the node with the right value type.
13143     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
13144     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
13145
13146     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
13147     // Otherwise return the value from Rand, which is always 0, casted to i32.
13148     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
13149                       DAG.getConstant(1, Op->getValueType(1)),
13150                       DAG.getConstant(X86::COND_B, MVT::i32),
13151                       SDValue(Result.getNode(), 1) };
13152     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
13153                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
13154                                   Ops);
13155
13156     // Return { result, isValid, chain }.
13157     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
13158                        SDValue(Result.getNode(), 2));
13159   }
13160   case GATHER: {
13161   //gather(v1, mask, index, base, scale);
13162     SDValue Chain = Op.getOperand(0);
13163     SDValue Src   = Op.getOperand(2);
13164     SDValue Base  = Op.getOperand(3);
13165     SDValue Index = Op.getOperand(4);
13166     SDValue Mask  = Op.getOperand(5);
13167     SDValue Scale = Op.getOperand(6);
13168     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
13169                           Subtarget);
13170   }
13171   case SCATTER: {
13172   //scatter(base, mask, index, v1, scale);
13173     SDValue Chain = Op.getOperand(0);
13174     SDValue Base  = Op.getOperand(2);
13175     SDValue Mask  = Op.getOperand(3);
13176     SDValue Index = Op.getOperand(4);
13177     SDValue Src   = Op.getOperand(5);
13178     SDValue Scale = Op.getOperand(6);
13179     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
13180   }
13181   case PREFETCH: {
13182     SDValue Hint = Op.getOperand(6);
13183     unsigned HintVal;
13184     if (dyn_cast<ConstantSDNode> (Hint) == nullptr ||
13185         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
13186       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
13187     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
13188     SDValue Chain = Op.getOperand(0);
13189     SDValue Mask  = Op.getOperand(2);
13190     SDValue Index = Op.getOperand(3);
13191     SDValue Base  = Op.getOperand(4);
13192     SDValue Scale = Op.getOperand(5);
13193     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
13194   }
13195   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
13196   case RDTSC: {
13197     SmallVector<SDValue, 2> Results;
13198     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
13199     return DAG.getMergeValues(Results, dl);
13200   }
13201   // XTEST intrinsics.
13202   case XTEST: {
13203     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
13204     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
13205     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13206                                 DAG.getConstant(X86::COND_NE, MVT::i8),
13207                                 InTrans);
13208     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
13209     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
13210                        Ret, SDValue(InTrans.getNode(), 1));
13211   }
13212   }
13213   llvm_unreachable("Unknown Intrinsic Type");
13214 }
13215
13216 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
13217                                            SelectionDAG &DAG) const {
13218   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13219   MFI->setReturnAddressIsTaken(true);
13220
13221   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
13222     return SDValue();
13223
13224   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13225   SDLoc dl(Op);
13226   EVT PtrVT = getPointerTy();
13227
13228   if (Depth > 0) {
13229     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
13230     const X86RegisterInfo *RegInfo =
13231       static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13232     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
13233     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13234                        DAG.getNode(ISD::ADD, dl, PtrVT,
13235                                    FrameAddr, Offset),
13236                        MachinePointerInfo(), false, false, false, 0);
13237   }
13238
13239   // Just load the return address.
13240   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
13241   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
13242                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
13243 }
13244
13245 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
13246   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13247   MFI->setFrameAddressIsTaken(true);
13248
13249   EVT VT = Op.getValueType();
13250   SDLoc dl(Op);  // FIXME probably not meaningful
13251   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
13252   const X86RegisterInfo *RegInfo =
13253     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13254   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13255   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
13256           (FrameReg == X86::EBP && VT == MVT::i32)) &&
13257          "Invalid Frame Register!");
13258   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
13259   while (Depth--)
13260     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
13261                             MachinePointerInfo(),
13262                             false, false, false, 0);
13263   return FrameAddr;
13264 }
13265
13266 // FIXME? Maybe this could be a TableGen attribute on some registers and
13267 // this table could be generated automatically from RegInfo.
13268 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
13269                                               EVT VT) const {
13270   unsigned Reg = StringSwitch<unsigned>(RegName)
13271                        .Case("esp", X86::ESP)
13272                        .Case("rsp", X86::RSP)
13273                        .Default(0);
13274   if (Reg)
13275     return Reg;
13276   report_fatal_error("Invalid register name global variable");
13277 }
13278
13279 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
13280                                                      SelectionDAG &DAG) const {
13281   const X86RegisterInfo *RegInfo =
13282     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13283   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
13284 }
13285
13286 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
13287   SDValue Chain     = Op.getOperand(0);
13288   SDValue Offset    = Op.getOperand(1);
13289   SDValue Handler   = Op.getOperand(2);
13290   SDLoc dl      (Op);
13291
13292   EVT PtrVT = getPointerTy();
13293   const X86RegisterInfo *RegInfo =
13294     static_cast<const X86RegisterInfo*>(DAG.getTarget().getRegisterInfo());
13295   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
13296   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
13297           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
13298          "Invalid Frame Register!");
13299   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
13300   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
13301
13302   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
13303                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
13304   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
13305   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
13306                        false, false, 0);
13307   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
13308
13309   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
13310                      DAG.getRegister(StoreAddrReg, PtrVT));
13311 }
13312
13313 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
13314                                                SelectionDAG &DAG) const {
13315   SDLoc DL(Op);
13316   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
13317                      DAG.getVTList(MVT::i32, MVT::Other),
13318                      Op.getOperand(0), Op.getOperand(1));
13319 }
13320
13321 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
13322                                                 SelectionDAG &DAG) const {
13323   SDLoc DL(Op);
13324   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
13325                      Op.getOperand(0), Op.getOperand(1));
13326 }
13327
13328 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
13329   return Op.getOperand(0);
13330 }
13331
13332 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
13333                                                 SelectionDAG &DAG) const {
13334   SDValue Root = Op.getOperand(0);
13335   SDValue Trmp = Op.getOperand(1); // trampoline
13336   SDValue FPtr = Op.getOperand(2); // nested function
13337   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
13338   SDLoc dl (Op);
13339
13340   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
13341   const TargetRegisterInfo* TRI = DAG.getTarget().getRegisterInfo();
13342
13343   if (Subtarget->is64Bit()) {
13344     SDValue OutChains[6];
13345
13346     // Large code-model.
13347     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
13348     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13349
13350     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13351     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13352
13353     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13354
13355     // Load the pointer to the nested function into R11.
13356     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13357     SDValue Addr = Trmp;
13358     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13359                                 Addr, MachinePointerInfo(TrmpAddr),
13360                                 false, false, 0);
13361
13362     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13363                        DAG.getConstant(2, MVT::i64));
13364     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13365                                 MachinePointerInfo(TrmpAddr, 2),
13366                                 false, false, 2);
13367
13368     // Load the 'nest' parameter value into R10.
13369     // R10 is specified in X86CallingConv.td
13370     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13371     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13372                        DAG.getConstant(10, MVT::i64));
13373     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13374                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13375                                 false, false, 0);
13376
13377     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13378                        DAG.getConstant(12, MVT::i64));
13379     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13380                                 MachinePointerInfo(TrmpAddr, 12),
13381                                 false, false, 2);
13382
13383     // Jump to the nested function.
13384     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13385     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13386                        DAG.getConstant(20, MVT::i64));
13387     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13388                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13389                                 false, false, 0);
13390
13391     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13392     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13393                        DAG.getConstant(22, MVT::i64));
13394     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13395                                 MachinePointerInfo(TrmpAddr, 22),
13396                                 false, false, 0);
13397
13398     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13399   } else {
13400     const Function *Func =
13401       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13402     CallingConv::ID CC = Func->getCallingConv();
13403     unsigned NestReg;
13404
13405     switch (CC) {
13406     default:
13407       llvm_unreachable("Unsupported calling convention");
13408     case CallingConv::C:
13409     case CallingConv::X86_StdCall: {
13410       // Pass 'nest' parameter in ECX.
13411       // Must be kept in sync with X86CallingConv.td
13412       NestReg = X86::ECX;
13413
13414       // Check that ECX wasn't needed by an 'inreg' parameter.
13415       FunctionType *FTy = Func->getFunctionType();
13416       const AttributeSet &Attrs = Func->getAttributes();
13417
13418       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13419         unsigned InRegCount = 0;
13420         unsigned Idx = 1;
13421
13422         for (FunctionType::param_iterator I = FTy->param_begin(),
13423              E = FTy->param_end(); I != E; ++I, ++Idx)
13424           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13425             // FIXME: should only count parameters that are lowered to integers.
13426             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13427
13428         if (InRegCount > 2) {
13429           report_fatal_error("Nest register in use - reduce number of inreg"
13430                              " parameters!");
13431         }
13432       }
13433       break;
13434     }
13435     case CallingConv::X86_FastCall:
13436     case CallingConv::X86_ThisCall:
13437     case CallingConv::Fast:
13438       // Pass 'nest' parameter in EAX.
13439       // Must be kept in sync with X86CallingConv.td
13440       NestReg = X86::EAX;
13441       break;
13442     }
13443
13444     SDValue OutChains[4];
13445     SDValue Addr, Disp;
13446
13447     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13448                        DAG.getConstant(10, MVT::i32));
13449     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13450
13451     // This is storing the opcode for MOV32ri.
13452     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13453     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13454     OutChains[0] = DAG.getStore(Root, dl,
13455                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13456                                 Trmp, MachinePointerInfo(TrmpAddr),
13457                                 false, false, 0);
13458
13459     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13460                        DAG.getConstant(1, MVT::i32));
13461     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13462                                 MachinePointerInfo(TrmpAddr, 1),
13463                                 false, false, 1);
13464
13465     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13466     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13467                        DAG.getConstant(5, MVT::i32));
13468     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13469                                 MachinePointerInfo(TrmpAddr, 5),
13470                                 false, false, 1);
13471
13472     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13473                        DAG.getConstant(6, MVT::i32));
13474     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13475                                 MachinePointerInfo(TrmpAddr, 6),
13476                                 false, false, 1);
13477
13478     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13479   }
13480 }
13481
13482 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13483                                             SelectionDAG &DAG) const {
13484   /*
13485    The rounding mode is in bits 11:10 of FPSR, and has the following
13486    settings:
13487      00 Round to nearest
13488      01 Round to -inf
13489      10 Round to +inf
13490      11 Round to 0
13491
13492   FLT_ROUNDS, on the other hand, expects the following:
13493     -1 Undefined
13494      0 Round to 0
13495      1 Round to nearest
13496      2 Round to +inf
13497      3 Round to -inf
13498
13499   To perform the conversion, we do:
13500     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13501   */
13502
13503   MachineFunction &MF = DAG.getMachineFunction();
13504   const TargetMachine &TM = MF.getTarget();
13505   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13506   unsigned StackAlignment = TFI.getStackAlignment();
13507   MVT VT = Op.getSimpleValueType();
13508   SDLoc DL(Op);
13509
13510   // Save FP Control Word to stack slot
13511   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13512   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13513
13514   MachineMemOperand *MMO =
13515    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13516                            MachineMemOperand::MOStore, 2, 2);
13517
13518   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13519   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13520                                           DAG.getVTList(MVT::Other),
13521                                           Ops, MVT::i16, MMO);
13522
13523   // Load FP Control Word from stack slot
13524   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13525                             MachinePointerInfo(), false, false, false, 0);
13526
13527   // Transform as necessary
13528   SDValue CWD1 =
13529     DAG.getNode(ISD::SRL, DL, MVT::i16,
13530                 DAG.getNode(ISD::AND, DL, MVT::i16,
13531                             CWD, DAG.getConstant(0x800, MVT::i16)),
13532                 DAG.getConstant(11, MVT::i8));
13533   SDValue CWD2 =
13534     DAG.getNode(ISD::SRL, DL, MVT::i16,
13535                 DAG.getNode(ISD::AND, DL, MVT::i16,
13536                             CWD, DAG.getConstant(0x400, MVT::i16)),
13537                 DAG.getConstant(9, MVT::i8));
13538
13539   SDValue RetVal =
13540     DAG.getNode(ISD::AND, DL, MVT::i16,
13541                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13542                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13543                             DAG.getConstant(1, MVT::i16)),
13544                 DAG.getConstant(3, MVT::i16));
13545
13546   return DAG.getNode((VT.getSizeInBits() < 16 ?
13547                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13548 }
13549
13550 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13551   MVT VT = Op.getSimpleValueType();
13552   EVT OpVT = VT;
13553   unsigned NumBits = VT.getSizeInBits();
13554   SDLoc dl(Op);
13555
13556   Op = Op.getOperand(0);
13557   if (VT == MVT::i8) {
13558     // Zero extend to i32 since there is not an i8 bsr.
13559     OpVT = MVT::i32;
13560     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13561   }
13562
13563   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13564   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13565   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13566
13567   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13568   SDValue Ops[] = {
13569     Op,
13570     DAG.getConstant(NumBits+NumBits-1, OpVT),
13571     DAG.getConstant(X86::COND_E, MVT::i8),
13572     Op.getValue(1)
13573   };
13574   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13575
13576   // Finally xor with NumBits-1.
13577   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13578
13579   if (VT == MVT::i8)
13580     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13581   return Op;
13582 }
13583
13584 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13585   MVT VT = Op.getSimpleValueType();
13586   EVT OpVT = VT;
13587   unsigned NumBits = VT.getSizeInBits();
13588   SDLoc dl(Op);
13589
13590   Op = Op.getOperand(0);
13591   if (VT == MVT::i8) {
13592     // Zero extend to i32 since there is not an i8 bsr.
13593     OpVT = MVT::i32;
13594     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13595   }
13596
13597   // Issue a bsr (scan bits in reverse).
13598   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13599   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13600
13601   // And xor with NumBits-1.
13602   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13603
13604   if (VT == MVT::i8)
13605     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13606   return Op;
13607 }
13608
13609 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13610   MVT VT = Op.getSimpleValueType();
13611   unsigned NumBits = VT.getSizeInBits();
13612   SDLoc dl(Op);
13613   Op = Op.getOperand(0);
13614
13615   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13616   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13617   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13618
13619   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13620   SDValue Ops[] = {
13621     Op,
13622     DAG.getConstant(NumBits, VT),
13623     DAG.getConstant(X86::COND_E, MVT::i8),
13624     Op.getValue(1)
13625   };
13626   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13627 }
13628
13629 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13630 // ones, and then concatenate the result back.
13631 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13632   MVT VT = Op.getSimpleValueType();
13633
13634   assert(VT.is256BitVector() && VT.isInteger() &&
13635          "Unsupported value type for operation");
13636
13637   unsigned NumElems = VT.getVectorNumElements();
13638   SDLoc dl(Op);
13639
13640   // Extract the LHS vectors
13641   SDValue LHS = Op.getOperand(0);
13642   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13643   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13644
13645   // Extract the RHS vectors
13646   SDValue RHS = Op.getOperand(1);
13647   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13648   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13649
13650   MVT EltVT = VT.getVectorElementType();
13651   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13652
13653   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13654                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13655                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13656 }
13657
13658 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13659   assert(Op.getSimpleValueType().is256BitVector() &&
13660          Op.getSimpleValueType().isInteger() &&
13661          "Only handle AVX 256-bit vector integer operation");
13662   return Lower256IntArith(Op, DAG);
13663 }
13664
13665 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13666   assert(Op.getSimpleValueType().is256BitVector() &&
13667          Op.getSimpleValueType().isInteger() &&
13668          "Only handle AVX 256-bit vector integer operation");
13669   return Lower256IntArith(Op, DAG);
13670 }
13671
13672 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13673                         SelectionDAG &DAG) {
13674   SDLoc dl(Op);
13675   MVT VT = Op.getSimpleValueType();
13676
13677   // Decompose 256-bit ops into smaller 128-bit ops.
13678   if (VT.is256BitVector() && !Subtarget->hasInt256())
13679     return Lower256IntArith(Op, DAG);
13680
13681   SDValue A = Op.getOperand(0);
13682   SDValue B = Op.getOperand(1);
13683
13684   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13685   if (VT == MVT::v4i32) {
13686     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13687            "Should not custom lower when pmuldq is available!");
13688
13689     // Extract the odd parts.
13690     static const int UnpackMask[] = { 1, -1, 3, -1 };
13691     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13692     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13693
13694     // Multiply the even parts.
13695     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13696     // Now multiply odd parts.
13697     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13698
13699     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13700     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13701
13702     // Merge the two vectors back together with a shuffle. This expands into 2
13703     // shuffles.
13704     static const int ShufMask[] = { 0, 4, 2, 6 };
13705     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13706   }
13707
13708   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13709          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13710
13711   //  Ahi = psrlqi(a, 32);
13712   //  Bhi = psrlqi(b, 32);
13713   //
13714   //  AloBlo = pmuludq(a, b);
13715   //  AloBhi = pmuludq(a, Bhi);
13716   //  AhiBlo = pmuludq(Ahi, b);
13717
13718   //  AloBhi = psllqi(AloBhi, 32);
13719   //  AhiBlo = psllqi(AhiBlo, 32);
13720   //  return AloBlo + AloBhi + AhiBlo;
13721
13722   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13723   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13724
13725   // Bit cast to 32-bit vectors for MULUDQ
13726   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13727                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13728   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13729   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13730   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13731   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13732
13733   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13734   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13735   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13736
13737   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13738   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13739
13740   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13741   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13742 }
13743
13744 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13745   assert(Subtarget->isTargetWin64() && "Unexpected target");
13746   EVT VT = Op.getValueType();
13747   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13748          "Unexpected return type for lowering");
13749
13750   RTLIB::Libcall LC;
13751   bool isSigned;
13752   switch (Op->getOpcode()) {
13753   default: llvm_unreachable("Unexpected request for libcall!");
13754   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13755   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13756   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13757   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13758   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13759   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13760   }
13761
13762   SDLoc dl(Op);
13763   SDValue InChain = DAG.getEntryNode();
13764
13765   TargetLowering::ArgListTy Args;
13766   TargetLowering::ArgListEntry Entry;
13767   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13768     EVT ArgVT = Op->getOperand(i).getValueType();
13769     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13770            "Unexpected argument type for lowering");
13771     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13772     Entry.Node = StackPtr;
13773     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13774                            false, false, 16);
13775     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13776     Entry.Ty = PointerType::get(ArgTy,0);
13777     Entry.isSExt = false;
13778     Entry.isZExt = false;
13779     Args.push_back(Entry);
13780   }
13781
13782   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13783                                          getPointerTy());
13784
13785   TargetLowering::CallLoweringInfo CLI(DAG);
13786   CLI.setDebugLoc(dl).setChain(InChain)
13787     .setCallee(getLibcallCallingConv(LC),
13788                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13789                Callee, &Args, 0)
13790     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13791
13792   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13793   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13794 }
13795
13796 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13797                              SelectionDAG &DAG) {
13798   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13799   EVT VT = Op0.getValueType();
13800   SDLoc dl(Op);
13801
13802   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13803          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13804
13805   // Get the high parts.
13806   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13807   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13808   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13809
13810   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13811   // ints.
13812   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13813   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13814   unsigned Opcode =
13815       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13816   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13817                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13818   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13819                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13820
13821   // Shuffle it back into the right order.
13822   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13823   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13824   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13825   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13826
13827   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13828   // unsigned multiply.
13829   if (IsSigned && !Subtarget->hasSSE41()) {
13830     SDValue ShAmt =
13831         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13832     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13833                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13834     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13835                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13836
13837     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13838     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13839   }
13840
13841   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13842 }
13843
13844 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13845                                          const X86Subtarget *Subtarget) {
13846   MVT VT = Op.getSimpleValueType();
13847   SDLoc dl(Op);
13848   SDValue R = Op.getOperand(0);
13849   SDValue Amt = Op.getOperand(1);
13850
13851   // Optimize shl/srl/sra with constant shift amount.
13852   if (isSplatVector(Amt.getNode())) {
13853     SDValue SclrAmt = Amt->getOperand(0);
13854     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13855       uint64_t ShiftAmt = C->getZExtValue();
13856
13857       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13858           (Subtarget->hasInt256() &&
13859            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13860           (Subtarget->hasAVX512() &&
13861            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13862         if (Op.getOpcode() == ISD::SHL)
13863           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13864                                             DAG);
13865         if (Op.getOpcode() == ISD::SRL)
13866           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13867                                             DAG);
13868         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13869           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13870                                             DAG);
13871       }
13872
13873       if (VT == MVT::v16i8) {
13874         if (Op.getOpcode() == ISD::SHL) {
13875           // Make a large shift.
13876           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13877                                                    MVT::v8i16, R, ShiftAmt,
13878                                                    DAG);
13879           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13880           // Zero out the rightmost bits.
13881           SmallVector<SDValue, 16> V(16,
13882                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13883                                                      MVT::i8));
13884           return DAG.getNode(ISD::AND, dl, VT, SHL,
13885                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13886         }
13887         if (Op.getOpcode() == ISD::SRL) {
13888           // Make a large shift.
13889           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13890                                                    MVT::v8i16, R, ShiftAmt,
13891                                                    DAG);
13892           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13893           // Zero out the leftmost bits.
13894           SmallVector<SDValue, 16> V(16,
13895                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13896                                                      MVT::i8));
13897           return DAG.getNode(ISD::AND, dl, VT, SRL,
13898                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13899         }
13900         if (Op.getOpcode() == ISD::SRA) {
13901           if (ShiftAmt == 7) {
13902             // R s>> 7  ===  R s< 0
13903             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13904             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13905           }
13906
13907           // R s>> a === ((R u>> a) ^ m) - m
13908           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13909           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13910                                                          MVT::i8));
13911           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13912           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13913           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13914           return Res;
13915         }
13916         llvm_unreachable("Unknown shift opcode.");
13917       }
13918
13919       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13920         if (Op.getOpcode() == ISD::SHL) {
13921           // Make a large shift.
13922           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13923                                                    MVT::v16i16, R, ShiftAmt,
13924                                                    DAG);
13925           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13926           // Zero out the rightmost bits.
13927           SmallVector<SDValue, 32> V(32,
13928                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13929                                                      MVT::i8));
13930           return DAG.getNode(ISD::AND, dl, VT, SHL,
13931                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13932         }
13933         if (Op.getOpcode() == ISD::SRL) {
13934           // Make a large shift.
13935           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13936                                                    MVT::v16i16, R, ShiftAmt,
13937                                                    DAG);
13938           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13939           // Zero out the leftmost bits.
13940           SmallVector<SDValue, 32> V(32,
13941                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13942                                                      MVT::i8));
13943           return DAG.getNode(ISD::AND, dl, VT, SRL,
13944                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13945         }
13946         if (Op.getOpcode() == ISD::SRA) {
13947           if (ShiftAmt == 7) {
13948             // R s>> 7  ===  R s< 0
13949             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13950             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13951           }
13952
13953           // R s>> a === ((R u>> a) ^ m) - m
13954           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13955           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13956                                                          MVT::i8));
13957           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13958           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13959           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13960           return Res;
13961         }
13962         llvm_unreachable("Unknown shift opcode.");
13963       }
13964     }
13965   }
13966
13967   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13968   if (!Subtarget->is64Bit() &&
13969       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13970       Amt.getOpcode() == ISD::BITCAST &&
13971       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13972     Amt = Amt.getOperand(0);
13973     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13974                      VT.getVectorNumElements();
13975     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13976     uint64_t ShiftAmt = 0;
13977     for (unsigned i = 0; i != Ratio; ++i) {
13978       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13979       if (!C)
13980         return SDValue();
13981       // 6 == Log2(64)
13982       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13983     }
13984     // Check remaining shift amounts.
13985     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13986       uint64_t ShAmt = 0;
13987       for (unsigned j = 0; j != Ratio; ++j) {
13988         ConstantSDNode *C =
13989           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13990         if (!C)
13991           return SDValue();
13992         // 6 == Log2(64)
13993         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13994       }
13995       if (ShAmt != ShiftAmt)
13996         return SDValue();
13997     }
13998     switch (Op.getOpcode()) {
13999     default:
14000       llvm_unreachable("Unknown shift opcode!");
14001     case ISD::SHL:
14002       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
14003                                         DAG);
14004     case ISD::SRL:
14005       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
14006                                         DAG);
14007     case ISD::SRA:
14008       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
14009                                         DAG);
14010     }
14011   }
14012
14013   return SDValue();
14014 }
14015
14016 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
14017                                         const X86Subtarget* Subtarget) {
14018   MVT VT = Op.getSimpleValueType();
14019   SDLoc dl(Op);
14020   SDValue R = Op.getOperand(0);
14021   SDValue Amt = Op.getOperand(1);
14022
14023   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
14024       VT == MVT::v4i32 || VT == MVT::v8i16 ||
14025       (Subtarget->hasInt256() &&
14026        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
14027         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
14028        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
14029     SDValue BaseShAmt;
14030     EVT EltVT = VT.getVectorElementType();
14031
14032     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14033       unsigned NumElts = VT.getVectorNumElements();
14034       unsigned i, j;
14035       for (i = 0; i != NumElts; ++i) {
14036         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
14037           continue;
14038         break;
14039       }
14040       for (j = i; j != NumElts; ++j) {
14041         SDValue Arg = Amt.getOperand(j);
14042         if (Arg.getOpcode() == ISD::UNDEF) continue;
14043         if (Arg != Amt.getOperand(i))
14044           break;
14045       }
14046       if (i != NumElts && j == NumElts)
14047         BaseShAmt = Amt.getOperand(i);
14048     } else {
14049       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
14050         Amt = Amt.getOperand(0);
14051       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
14052                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
14053         SDValue InVec = Amt.getOperand(0);
14054         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
14055           unsigned NumElts = InVec.getValueType().getVectorNumElements();
14056           unsigned i = 0;
14057           for (; i != NumElts; ++i) {
14058             SDValue Arg = InVec.getOperand(i);
14059             if (Arg.getOpcode() == ISD::UNDEF) continue;
14060             BaseShAmt = Arg;
14061             break;
14062           }
14063         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
14064            if (ConstantSDNode *C =
14065                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
14066              unsigned SplatIdx =
14067                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
14068              if (C->getZExtValue() == SplatIdx)
14069                BaseShAmt = InVec.getOperand(1);
14070            }
14071         }
14072         if (!BaseShAmt.getNode())
14073           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
14074                                   DAG.getIntPtrConstant(0));
14075       }
14076     }
14077
14078     if (BaseShAmt.getNode()) {
14079       if (EltVT.bitsGT(MVT::i32))
14080         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
14081       else if (EltVT.bitsLT(MVT::i32))
14082         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
14083
14084       switch (Op.getOpcode()) {
14085       default:
14086         llvm_unreachable("Unknown shift opcode!");
14087       case ISD::SHL:
14088         switch (VT.SimpleTy) {
14089         default: return SDValue();
14090         case MVT::v2i64:
14091         case MVT::v4i32:
14092         case MVT::v8i16:
14093         case MVT::v4i64:
14094         case MVT::v8i32:
14095         case MVT::v16i16:
14096         case MVT::v16i32:
14097         case MVT::v8i64:
14098           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
14099         }
14100       case ISD::SRA:
14101         switch (VT.SimpleTy) {
14102         default: return SDValue();
14103         case MVT::v4i32:
14104         case MVT::v8i16:
14105         case MVT::v8i32:
14106         case MVT::v16i16:
14107         case MVT::v16i32:
14108         case MVT::v8i64:
14109           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
14110         }
14111       case ISD::SRL:
14112         switch (VT.SimpleTy) {
14113         default: return SDValue();
14114         case MVT::v2i64:
14115         case MVT::v4i32:
14116         case MVT::v8i16:
14117         case MVT::v4i64:
14118         case MVT::v8i32:
14119         case MVT::v16i16:
14120         case MVT::v16i32:
14121         case MVT::v8i64:
14122           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
14123         }
14124       }
14125     }
14126   }
14127
14128   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
14129   if (!Subtarget->is64Bit() &&
14130       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
14131       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
14132       Amt.getOpcode() == ISD::BITCAST &&
14133       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
14134     Amt = Amt.getOperand(0);
14135     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
14136                      VT.getVectorNumElements();
14137     std::vector<SDValue> Vals(Ratio);
14138     for (unsigned i = 0; i != Ratio; ++i)
14139       Vals[i] = Amt.getOperand(i);
14140     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
14141       for (unsigned j = 0; j != Ratio; ++j)
14142         if (Vals[j] != Amt.getOperand(i + j))
14143           return SDValue();
14144     }
14145     switch (Op.getOpcode()) {
14146     default:
14147       llvm_unreachable("Unknown shift opcode!");
14148     case ISD::SHL:
14149       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
14150     case ISD::SRL:
14151       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
14152     case ISD::SRA:
14153       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
14154     }
14155   }
14156
14157   return SDValue();
14158 }
14159
14160 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
14161                           SelectionDAG &DAG) {
14162
14163   MVT VT = Op.getSimpleValueType();
14164   SDLoc dl(Op);
14165   SDValue R = Op.getOperand(0);
14166   SDValue Amt = Op.getOperand(1);
14167   SDValue V;
14168
14169   if (!Subtarget->hasSSE2())
14170     return SDValue();
14171
14172   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
14173   if (V.getNode())
14174     return V;
14175
14176   V = LowerScalarVariableShift(Op, DAG, Subtarget);
14177   if (V.getNode())
14178       return V;
14179
14180   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
14181     return Op;
14182   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
14183   if (Subtarget->hasInt256()) {
14184     if (Op.getOpcode() == ISD::SRL &&
14185         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14186          VT == MVT::v4i64 || VT == MVT::v8i32))
14187       return Op;
14188     if (Op.getOpcode() == ISD::SHL &&
14189         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
14190          VT == MVT::v4i64 || VT == MVT::v8i32))
14191       return Op;
14192     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
14193       return Op;
14194   }
14195
14196   // If possible, lower this packed shift into a vector multiply instead of
14197   // expanding it into a sequence of scalar shifts.
14198   // Do this only if the vector shift count is a constant build_vector.
14199   if (Op.getOpcode() == ISD::SHL && 
14200       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
14201        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
14202       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14203     SmallVector<SDValue, 8> Elts;
14204     EVT SVT = VT.getScalarType();
14205     unsigned SVTBits = SVT.getSizeInBits();
14206     const APInt &One = APInt(SVTBits, 1);
14207     unsigned NumElems = VT.getVectorNumElements();
14208
14209     for (unsigned i=0; i !=NumElems; ++i) {
14210       SDValue Op = Amt->getOperand(i);
14211       if (Op->getOpcode() == ISD::UNDEF) {
14212         Elts.push_back(Op);
14213         continue;
14214       }
14215
14216       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
14217       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
14218       uint64_t ShAmt = C.getZExtValue();
14219       if (ShAmt >= SVTBits) {
14220         Elts.push_back(DAG.getUNDEF(SVT));
14221         continue;
14222       }
14223       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
14224     }
14225     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14226     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
14227   }
14228
14229   // Lower SHL with variable shift amount.
14230   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
14231     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
14232
14233     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
14234     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
14235     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
14236     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
14237   }
14238
14239   // If possible, lower this shift as a sequence of two shifts by
14240   // constant plus a MOVSS/MOVSD instead of scalarizing it.
14241   // Example:
14242   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
14243   //
14244   // Could be rewritten as:
14245   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
14246   //
14247   // The advantage is that the two shifts from the example would be
14248   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
14249   // the vector shift into four scalar shifts plus four pairs of vector
14250   // insert/extract.
14251   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
14252       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
14253     unsigned TargetOpcode = X86ISD::MOVSS;
14254     bool CanBeSimplified;
14255     // The splat value for the first packed shift (the 'X' from the example).
14256     SDValue Amt1 = Amt->getOperand(0);
14257     // The splat value for the second packed shift (the 'Y' from the example).
14258     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
14259                                         Amt->getOperand(2);
14260
14261     // See if it is possible to replace this node with a sequence of
14262     // two shifts followed by a MOVSS/MOVSD
14263     if (VT == MVT::v4i32) {
14264       // Check if it is legal to use a MOVSS.
14265       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
14266                         Amt2 == Amt->getOperand(3);
14267       if (!CanBeSimplified) {
14268         // Otherwise, check if we can still simplify this node using a MOVSD.
14269         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
14270                           Amt->getOperand(2) == Amt->getOperand(3);
14271         TargetOpcode = X86ISD::MOVSD;
14272         Amt2 = Amt->getOperand(2);
14273       }
14274     } else {
14275       // Do similar checks for the case where the machine value type
14276       // is MVT::v8i16.
14277       CanBeSimplified = Amt1 == Amt->getOperand(1);
14278       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
14279         CanBeSimplified = Amt2 == Amt->getOperand(i);
14280
14281       if (!CanBeSimplified) {
14282         TargetOpcode = X86ISD::MOVSD;
14283         CanBeSimplified = true;
14284         Amt2 = Amt->getOperand(4);
14285         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
14286           CanBeSimplified = Amt1 == Amt->getOperand(i);
14287         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
14288           CanBeSimplified = Amt2 == Amt->getOperand(j);
14289       }
14290     }
14291     
14292     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
14293         isa<ConstantSDNode>(Amt2)) {
14294       // Replace this node with two shifts followed by a MOVSS/MOVSD.
14295       EVT CastVT = MVT::v4i32;
14296       SDValue Splat1 = 
14297         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
14298       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
14299       SDValue Splat2 = 
14300         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
14301       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
14302       if (TargetOpcode == X86ISD::MOVSD)
14303         CastVT = MVT::v2i64;
14304       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
14305       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
14306       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
14307                                             BitCast1, DAG);
14308       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
14309     }
14310   }
14311
14312   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
14313     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
14314
14315     // a = a << 5;
14316     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
14317     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
14318
14319     // Turn 'a' into a mask suitable for VSELECT
14320     SDValue VSelM = DAG.getConstant(0x80, VT);
14321     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14322     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14323
14324     SDValue CM1 = DAG.getConstant(0x0f, VT);
14325     SDValue CM2 = DAG.getConstant(0x3f, VT);
14326
14327     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
14328     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
14329     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
14330     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14331     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14332
14333     // a += a
14334     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14335     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14336     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14337
14338     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
14339     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
14340     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
14341     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14342     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14343
14344     // a += a
14345     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14346     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14347     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14348
14349     // return VSELECT(r, r+r, a);
14350     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14351                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14352     return R;
14353   }
14354
14355   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14356   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14357   // solution better.
14358   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14359     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14360     unsigned ExtOpc =
14361         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14362     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14363     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14364     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14365                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14366     }
14367
14368   // Decompose 256-bit shifts into smaller 128-bit shifts.
14369   if (VT.is256BitVector()) {
14370     unsigned NumElems = VT.getVectorNumElements();
14371     MVT EltVT = VT.getVectorElementType();
14372     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14373
14374     // Extract the two vectors
14375     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14376     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14377
14378     // Recreate the shift amount vectors
14379     SDValue Amt1, Amt2;
14380     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14381       // Constant shift amount
14382       SmallVector<SDValue, 4> Amt1Csts;
14383       SmallVector<SDValue, 4> Amt2Csts;
14384       for (unsigned i = 0; i != NumElems/2; ++i)
14385         Amt1Csts.push_back(Amt->getOperand(i));
14386       for (unsigned i = NumElems/2; i != NumElems; ++i)
14387         Amt2Csts.push_back(Amt->getOperand(i));
14388
14389       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14390       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14391     } else {
14392       // Variable shift amount
14393       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14394       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14395     }
14396
14397     // Issue new vector shifts for the smaller types
14398     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14399     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14400
14401     // Concatenate the result back
14402     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14403   }
14404
14405   return SDValue();
14406 }
14407
14408 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14409   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14410   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14411   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14412   // has only one use.
14413   SDNode *N = Op.getNode();
14414   SDValue LHS = N->getOperand(0);
14415   SDValue RHS = N->getOperand(1);
14416   unsigned BaseOp = 0;
14417   unsigned Cond = 0;
14418   SDLoc DL(Op);
14419   switch (Op.getOpcode()) {
14420   default: llvm_unreachable("Unknown ovf instruction!");
14421   case ISD::SADDO:
14422     // A subtract of one will be selected as a INC. Note that INC doesn't
14423     // set CF, so we can't do this for UADDO.
14424     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14425       if (C->isOne()) {
14426         BaseOp = X86ISD::INC;
14427         Cond = X86::COND_O;
14428         break;
14429       }
14430     BaseOp = X86ISD::ADD;
14431     Cond = X86::COND_O;
14432     break;
14433   case ISD::UADDO:
14434     BaseOp = X86ISD::ADD;
14435     Cond = X86::COND_B;
14436     break;
14437   case ISD::SSUBO:
14438     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14439     // set CF, so we can't do this for USUBO.
14440     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14441       if (C->isOne()) {
14442         BaseOp = X86ISD::DEC;
14443         Cond = X86::COND_O;
14444         break;
14445       }
14446     BaseOp = X86ISD::SUB;
14447     Cond = X86::COND_O;
14448     break;
14449   case ISD::USUBO:
14450     BaseOp = X86ISD::SUB;
14451     Cond = X86::COND_B;
14452     break;
14453   case ISD::SMULO:
14454     BaseOp = X86ISD::SMUL;
14455     Cond = X86::COND_O;
14456     break;
14457   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14458     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14459                                  MVT::i32);
14460     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14461
14462     SDValue SetCC =
14463       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14464                   DAG.getConstant(X86::COND_O, MVT::i32),
14465                   SDValue(Sum.getNode(), 2));
14466
14467     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14468   }
14469   }
14470
14471   // Also sets EFLAGS.
14472   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14473   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14474
14475   SDValue SetCC =
14476     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14477                 DAG.getConstant(Cond, MVT::i32),
14478                 SDValue(Sum.getNode(), 1));
14479
14480   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14481 }
14482
14483 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14484                                                   SelectionDAG &DAG) const {
14485   SDLoc dl(Op);
14486   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14487   MVT VT = Op.getSimpleValueType();
14488
14489   if (!Subtarget->hasSSE2() || !VT.isVector())
14490     return SDValue();
14491
14492   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14493                       ExtraVT.getScalarType().getSizeInBits();
14494
14495   switch (VT.SimpleTy) {
14496     default: return SDValue();
14497     case MVT::v8i32:
14498     case MVT::v16i16:
14499       if (!Subtarget->hasFp256())
14500         return SDValue();
14501       if (!Subtarget->hasInt256()) {
14502         // needs to be split
14503         unsigned NumElems = VT.getVectorNumElements();
14504
14505         // Extract the LHS vectors
14506         SDValue LHS = Op.getOperand(0);
14507         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14508         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14509
14510         MVT EltVT = VT.getVectorElementType();
14511         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14512
14513         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14514         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14515         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14516                                    ExtraNumElems/2);
14517         SDValue Extra = DAG.getValueType(ExtraVT);
14518
14519         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14520         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14521
14522         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14523       }
14524       // fall through
14525     case MVT::v4i32:
14526     case MVT::v8i16: {
14527       SDValue Op0 = Op.getOperand(0);
14528       SDValue Op00 = Op0.getOperand(0);
14529       SDValue Tmp1;
14530       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14531       if (Op0.getOpcode() == ISD::BITCAST &&
14532           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14533         // (sext (vzext x)) -> (vsext x)
14534         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14535         if (Tmp1.getNode()) {
14536           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14537           // This folding is only valid when the in-reg type is a vector of i8,
14538           // i16, or i32.
14539           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14540               ExtraEltVT == MVT::i32) {
14541             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14542             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14543                    "This optimization is invalid without a VZEXT.");
14544             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14545           }
14546           Op0 = Tmp1;
14547         }
14548       }
14549
14550       // If the above didn't work, then just use Shift-Left + Shift-Right.
14551       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14552                                         DAG);
14553       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14554                                         DAG);
14555     }
14556   }
14557 }
14558
14559 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14560                                  SelectionDAG &DAG) {
14561   SDLoc dl(Op);
14562   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14563     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14564   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14565     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14566
14567   // The only fence that needs an instruction is a sequentially-consistent
14568   // cross-thread fence.
14569   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14570     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14571     // no-sse2). There isn't any reason to disable it if the target processor
14572     // supports it.
14573     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14574       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14575
14576     SDValue Chain = Op.getOperand(0);
14577     SDValue Zero = DAG.getConstant(0, MVT::i32);
14578     SDValue Ops[] = {
14579       DAG.getRegister(X86::ESP, MVT::i32), // Base
14580       DAG.getTargetConstant(1, MVT::i8),   // Scale
14581       DAG.getRegister(0, MVT::i32),        // Index
14582       DAG.getTargetConstant(0, MVT::i32),  // Disp
14583       DAG.getRegister(0, MVT::i32),        // Segment.
14584       Zero,
14585       Chain
14586     };
14587     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14588     return SDValue(Res, 0);
14589   }
14590
14591   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14592   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14593 }
14594
14595 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14596                              SelectionDAG &DAG) {
14597   MVT T = Op.getSimpleValueType();
14598   SDLoc DL(Op);
14599   unsigned Reg = 0;
14600   unsigned size = 0;
14601   switch(T.SimpleTy) {
14602   default: llvm_unreachable("Invalid value type!");
14603   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14604   case MVT::i16: Reg = X86::AX;  size = 2; break;
14605   case MVT::i32: Reg = X86::EAX; size = 4; break;
14606   case MVT::i64:
14607     assert(Subtarget->is64Bit() && "Node not type legal!");
14608     Reg = X86::RAX; size = 8;
14609     break;
14610   }
14611   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14612                                   Op.getOperand(2), SDValue());
14613   SDValue Ops[] = { cpIn.getValue(0),
14614                     Op.getOperand(1),
14615                     Op.getOperand(3),
14616                     DAG.getTargetConstant(size, MVT::i8),
14617                     cpIn.getValue(1) };
14618   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14619   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14620   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14621                                            Ops, T, MMO);
14622
14623   SDValue cpOut =
14624     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14625   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
14626                                       MVT::i32, cpOut.getValue(2));
14627   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
14628                                 DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
14629
14630   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
14631   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
14632   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
14633   return SDValue();
14634 }
14635
14636 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14637                             SelectionDAG &DAG) {
14638   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14639   MVT DstVT = Op.getSimpleValueType();
14640
14641   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14642     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14643     if (DstVT != MVT::f64)
14644       // This conversion needs to be expanded.
14645       return SDValue();
14646
14647     SDValue InVec = Op->getOperand(0);
14648     SDLoc dl(Op);
14649     unsigned NumElts = SrcVT.getVectorNumElements();
14650     EVT SVT = SrcVT.getVectorElementType();
14651
14652     // Widen the vector in input in the case of MVT::v2i32.
14653     // Example: from MVT::v2i32 to MVT::v4i32.
14654     SmallVector<SDValue, 16> Elts;
14655     for (unsigned i = 0, e = NumElts; i != e; ++i)
14656       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14657                                  DAG.getIntPtrConstant(i)));
14658
14659     // Explicitly mark the extra elements as Undef.
14660     SDValue Undef = DAG.getUNDEF(SVT);
14661     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14662       Elts.push_back(Undef);
14663
14664     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14665     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14666     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14667     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14668                        DAG.getIntPtrConstant(0));
14669   }
14670
14671   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14672          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14673   assert((DstVT == MVT::i64 ||
14674           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14675          "Unexpected custom BITCAST");
14676   // i64 <=> MMX conversions are Legal.
14677   if (SrcVT==MVT::i64 && DstVT.isVector())
14678     return Op;
14679   if (DstVT==MVT::i64 && SrcVT.isVector())
14680     return Op;
14681   // MMX <=> MMX conversions are Legal.
14682   if (SrcVT.isVector() && DstVT.isVector())
14683     return Op;
14684   // All other conversions need to be expanded.
14685   return SDValue();
14686 }
14687
14688 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14689   SDNode *Node = Op.getNode();
14690   SDLoc dl(Node);
14691   EVT T = Node->getValueType(0);
14692   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14693                               DAG.getConstant(0, T), Node->getOperand(2));
14694   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14695                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14696                        Node->getOperand(0),
14697                        Node->getOperand(1), negOp,
14698                        cast<AtomicSDNode>(Node)->getMemOperand(),
14699                        cast<AtomicSDNode>(Node)->getOrdering(),
14700                        cast<AtomicSDNode>(Node)->getSynchScope());
14701 }
14702
14703 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14704   SDNode *Node = Op.getNode();
14705   SDLoc dl(Node);
14706   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14707
14708   // Convert seq_cst store -> xchg
14709   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14710   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14711   //        (The only way to get a 16-byte store is cmpxchg16b)
14712   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14713   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14714       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14715     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14716                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14717                                  Node->getOperand(0),
14718                                  Node->getOperand(1), Node->getOperand(2),
14719                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14720                                  cast<AtomicSDNode>(Node)->getOrdering(),
14721                                  cast<AtomicSDNode>(Node)->getSynchScope());
14722     return Swap.getValue(1);
14723   }
14724   // Other atomic stores have a simple pattern.
14725   return Op;
14726 }
14727
14728 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14729   EVT VT = Op.getNode()->getSimpleValueType(0);
14730
14731   // Let legalize expand this if it isn't a legal type yet.
14732   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14733     return SDValue();
14734
14735   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14736
14737   unsigned Opc;
14738   bool ExtraOp = false;
14739   switch (Op.getOpcode()) {
14740   default: llvm_unreachable("Invalid code");
14741   case ISD::ADDC: Opc = X86ISD::ADD; break;
14742   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14743   case ISD::SUBC: Opc = X86ISD::SUB; break;
14744   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14745   }
14746
14747   if (!ExtraOp)
14748     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14749                        Op.getOperand(1));
14750   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14751                      Op.getOperand(1), Op.getOperand(2));
14752 }
14753
14754 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14755                             SelectionDAG &DAG) {
14756   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14757
14758   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14759   // which returns the values as { float, float } (in XMM0) or
14760   // { double, double } (which is returned in XMM0, XMM1).
14761   SDLoc dl(Op);
14762   SDValue Arg = Op.getOperand(0);
14763   EVT ArgVT = Arg.getValueType();
14764   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14765
14766   TargetLowering::ArgListTy Args;
14767   TargetLowering::ArgListEntry Entry;
14768
14769   Entry.Node = Arg;
14770   Entry.Ty = ArgTy;
14771   Entry.isSExt = false;
14772   Entry.isZExt = false;
14773   Args.push_back(Entry);
14774
14775   bool isF64 = ArgVT == MVT::f64;
14776   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14777   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14778   // the results are returned via SRet in memory.
14779   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14780   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14781   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14782
14783   Type *RetTy = isF64
14784     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14785     : (Type*)VectorType::get(ArgTy, 4);
14786
14787   TargetLowering::CallLoweringInfo CLI(DAG);
14788   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14789     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14790
14791   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14792
14793   if (isF64)
14794     // Returned in xmm0 and xmm1.
14795     return CallResult.first;
14796
14797   // Returned in bits 0:31 and 32:64 xmm0.
14798   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14799                                CallResult.first, DAG.getIntPtrConstant(0));
14800   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14801                                CallResult.first, DAG.getIntPtrConstant(1));
14802   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14803   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14804 }
14805
14806 /// LowerOperation - Provide custom lowering hooks for some operations.
14807 ///
14808 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14809   switch (Op.getOpcode()) {
14810   default: llvm_unreachable("Should not custom lower this!");
14811   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14812   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14813   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
14814     return LowerCMP_SWAP(Op, Subtarget, DAG);
14815   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14816   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14817   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14818   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14819   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14820   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14821   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14822   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14823   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14824   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14825   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14826   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14827   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14828   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14829   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14830   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14831   case ISD::SHL_PARTS:
14832   case ISD::SRA_PARTS:
14833   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14834   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14835   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14836   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14837   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14838   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14839   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14840   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14841   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14842   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14843   case ISD::FABS:               return LowerFABS(Op, DAG);
14844   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14845   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14846   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14847   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14848   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14849   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14850   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14851   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14852   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14853   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14854   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14855   case ISD::INTRINSIC_VOID:
14856   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14857   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14858   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14859   case ISD::FRAME_TO_ARGS_OFFSET:
14860                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14861   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14862   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14863   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14864   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14865   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14866   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14867   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14868   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14869   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14870   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14871   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14872   case ISD::UMUL_LOHI:
14873   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14874   case ISD::SRA:
14875   case ISD::SRL:
14876   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14877   case ISD::SADDO:
14878   case ISD::UADDO:
14879   case ISD::SSUBO:
14880   case ISD::USUBO:
14881   case ISD::SMULO:
14882   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14883   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14884   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14885   case ISD::ADDC:
14886   case ISD::ADDE:
14887   case ISD::SUBC:
14888   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14889   case ISD::ADD:                return LowerADD(Op, DAG);
14890   case ISD::SUB:                return LowerSUB(Op, DAG);
14891   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14892   }
14893 }
14894
14895 static void ReplaceATOMIC_LOAD(SDNode *Node,
14896                                SmallVectorImpl<SDValue> &Results,
14897                                SelectionDAG &DAG) {
14898   SDLoc dl(Node);
14899   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14900
14901   // Convert wide load -> cmpxchg8b/cmpxchg16b
14902   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14903   //        (The only way to get a 16-byte load is cmpxchg16b)
14904   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14905   SDValue Zero = DAG.getConstant(0, VT);
14906   SDVTList VTs = DAG.getVTList(VT, MVT::i1, MVT::Other);
14907   SDValue Swap =
14908       DAG.getAtomicCmpSwap(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, dl, VT, VTs,
14909                            Node->getOperand(0), Node->getOperand(1), Zero, Zero,
14910                            cast<AtomicSDNode>(Node)->getMemOperand(),
14911                            cast<AtomicSDNode>(Node)->getOrdering(),
14912                            cast<AtomicSDNode>(Node)->getOrdering(),
14913                            cast<AtomicSDNode>(Node)->getSynchScope());
14914   Results.push_back(Swap.getValue(0));
14915   Results.push_back(Swap.getValue(2));
14916 }
14917
14918 static void
14919 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14920                         SelectionDAG &DAG, unsigned NewOp) {
14921   SDLoc dl(Node);
14922   assert (Node->getValueType(0) == MVT::i64 &&
14923           "Only know how to expand i64 atomics");
14924
14925   SDValue Chain = Node->getOperand(0);
14926   SDValue In1 = Node->getOperand(1);
14927   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14928                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14929   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14930                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14931   SDValue Ops[] = { Chain, In1, In2L, In2H };
14932   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14933   SDValue Result =
14934     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14935                             cast<MemSDNode>(Node)->getMemOperand());
14936   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14937   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14938   Results.push_back(Result.getValue(2));
14939 }
14940
14941 /// ReplaceNodeResults - Replace a node with an illegal result type
14942 /// with a new node built out of custom code.
14943 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14944                                            SmallVectorImpl<SDValue>&Results,
14945                                            SelectionDAG &DAG) const {
14946   SDLoc dl(N);
14947   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14948   switch (N->getOpcode()) {
14949   default:
14950     llvm_unreachable("Do not know how to custom type legalize this operation!");
14951   case ISD::SIGN_EXTEND_INREG:
14952   case ISD::ADDC:
14953   case ISD::ADDE:
14954   case ISD::SUBC:
14955   case ISD::SUBE:
14956     // We don't want to expand or promote these.
14957     return;
14958   case ISD::SDIV:
14959   case ISD::UDIV:
14960   case ISD::SREM:
14961   case ISD::UREM:
14962   case ISD::SDIVREM:
14963   case ISD::UDIVREM: {
14964     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14965     Results.push_back(V);
14966     return;
14967   }
14968   case ISD::FP_TO_SINT:
14969   case ISD::FP_TO_UINT: {
14970     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14971
14972     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14973       return;
14974
14975     std::pair<SDValue,SDValue> Vals =
14976         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14977     SDValue FIST = Vals.first, StackSlot = Vals.second;
14978     if (FIST.getNode()) {
14979       EVT VT = N->getValueType(0);
14980       // Return a load from the stack slot.
14981       if (StackSlot.getNode())
14982         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14983                                       MachinePointerInfo(),
14984                                       false, false, false, 0));
14985       else
14986         Results.push_back(FIST);
14987     }
14988     return;
14989   }
14990   case ISD::UINT_TO_FP: {
14991     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14992     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14993         N->getValueType(0) != MVT::v2f32)
14994       return;
14995     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14996                                  N->getOperand(0));
14997     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14998                                      MVT::f64);
14999     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
15000     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
15001                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
15002     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
15003     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
15004     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
15005     return;
15006   }
15007   case ISD::FP_ROUND: {
15008     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
15009         return;
15010     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
15011     Results.push_back(V);
15012     return;
15013   }
15014   case ISD::INTRINSIC_W_CHAIN: {
15015     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
15016     switch (IntNo) {
15017     default : llvm_unreachable("Do not know how to custom type "
15018                                "legalize this intrinsic operation!");
15019     case Intrinsic::x86_rdtsc:
15020       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15021                                      Results);
15022     case Intrinsic::x86_rdtscp:
15023       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
15024                                      Results);
15025     }
15026   }
15027   case ISD::READCYCLECOUNTER: {
15028     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
15029                                    Results);
15030   }
15031   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
15032     EVT T = N->getValueType(0);
15033     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
15034     bool Regs64bit = T == MVT::i128;
15035     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
15036     SDValue cpInL, cpInH;
15037     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15038                         DAG.getConstant(0, HalfT));
15039     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
15040                         DAG.getConstant(1, HalfT));
15041     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
15042                              Regs64bit ? X86::RAX : X86::EAX,
15043                              cpInL, SDValue());
15044     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
15045                              Regs64bit ? X86::RDX : X86::EDX,
15046                              cpInH, cpInL.getValue(1));
15047     SDValue swapInL, swapInH;
15048     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15049                           DAG.getConstant(0, HalfT));
15050     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
15051                           DAG.getConstant(1, HalfT));
15052     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
15053                                Regs64bit ? X86::RBX : X86::EBX,
15054                                swapInL, cpInH.getValue(1));
15055     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
15056                                Regs64bit ? X86::RCX : X86::ECX,
15057                                swapInH, swapInL.getValue(1));
15058     SDValue Ops[] = { swapInH.getValue(0),
15059                       N->getOperand(1),
15060                       swapInH.getValue(1) };
15061     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15062     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
15063     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
15064                                   X86ISD::LCMPXCHG8_DAG;
15065     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
15066     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
15067                                         Regs64bit ? X86::RAX : X86::EAX,
15068                                         HalfT, Result.getValue(1));
15069     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
15070                                         Regs64bit ? X86::RDX : X86::EDX,
15071                                         HalfT, cpOutL.getValue(2));
15072     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
15073
15074     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
15075                                         MVT::i32, cpOutH.getValue(2));
15076     SDValue Success =
15077         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15078                     DAG.getConstant(X86::COND_E, MVT::i8), EFLAGS);
15079     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
15080
15081     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
15082     Results.push_back(Success);
15083     Results.push_back(EFLAGS.getValue(1));
15084     return;
15085   }
15086   case ISD::ATOMIC_LOAD_ADD:
15087   case ISD::ATOMIC_LOAD_AND:
15088   case ISD::ATOMIC_LOAD_NAND:
15089   case ISD::ATOMIC_LOAD_OR:
15090   case ISD::ATOMIC_LOAD_SUB:
15091   case ISD::ATOMIC_LOAD_XOR:
15092   case ISD::ATOMIC_LOAD_MAX:
15093   case ISD::ATOMIC_LOAD_MIN:
15094   case ISD::ATOMIC_LOAD_UMAX:
15095   case ISD::ATOMIC_LOAD_UMIN:
15096   case ISD::ATOMIC_SWAP: {
15097     unsigned Opc;
15098     switch (N->getOpcode()) {
15099     default: llvm_unreachable("Unexpected opcode");
15100     case ISD::ATOMIC_LOAD_ADD:
15101       Opc = X86ISD::ATOMADD64_DAG;
15102       break;
15103     case ISD::ATOMIC_LOAD_AND:
15104       Opc = X86ISD::ATOMAND64_DAG;
15105       break;
15106     case ISD::ATOMIC_LOAD_NAND:
15107       Opc = X86ISD::ATOMNAND64_DAG;
15108       break;
15109     case ISD::ATOMIC_LOAD_OR:
15110       Opc = X86ISD::ATOMOR64_DAG;
15111       break;
15112     case ISD::ATOMIC_LOAD_SUB:
15113       Opc = X86ISD::ATOMSUB64_DAG;
15114       break;
15115     case ISD::ATOMIC_LOAD_XOR:
15116       Opc = X86ISD::ATOMXOR64_DAG;
15117       break;
15118     case ISD::ATOMIC_LOAD_MAX:
15119       Opc = X86ISD::ATOMMAX64_DAG;
15120       break;
15121     case ISD::ATOMIC_LOAD_MIN:
15122       Opc = X86ISD::ATOMMIN64_DAG;
15123       break;
15124     case ISD::ATOMIC_LOAD_UMAX:
15125       Opc = X86ISD::ATOMUMAX64_DAG;
15126       break;
15127     case ISD::ATOMIC_LOAD_UMIN:
15128       Opc = X86ISD::ATOMUMIN64_DAG;
15129       break;
15130     case ISD::ATOMIC_SWAP:
15131       Opc = X86ISD::ATOMSWAP64_DAG;
15132       break;
15133     }
15134     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
15135     return;
15136   }
15137   case ISD::ATOMIC_LOAD: {
15138     ReplaceATOMIC_LOAD(N, Results, DAG);
15139     return;
15140   }
15141   case ISD::BITCAST: {
15142     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
15143     EVT DstVT = N->getValueType(0);
15144     EVT SrcVT = N->getOperand(0)->getValueType(0);
15145
15146     if (SrcVT != MVT::f64 ||
15147         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
15148       return;
15149
15150     unsigned NumElts = DstVT.getVectorNumElements();
15151     EVT SVT = DstVT.getVectorElementType();
15152     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
15153     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
15154                                    MVT::v2f64, N->getOperand(0));
15155     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
15156
15157     SmallVector<SDValue, 8> Elts;
15158     for (unsigned i = 0, e = NumElts; i != e; ++i)
15159       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
15160                                    ToVecInt, DAG.getIntPtrConstant(i)));
15161
15162     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
15163   }
15164   }
15165 }
15166
15167 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
15168   switch (Opcode) {
15169   default: return nullptr;
15170   case X86ISD::BSF:                return "X86ISD::BSF";
15171   case X86ISD::BSR:                return "X86ISD::BSR";
15172   case X86ISD::SHLD:               return "X86ISD::SHLD";
15173   case X86ISD::SHRD:               return "X86ISD::SHRD";
15174   case X86ISD::FAND:               return "X86ISD::FAND";
15175   case X86ISD::FANDN:              return "X86ISD::FANDN";
15176   case X86ISD::FOR:                return "X86ISD::FOR";
15177   case X86ISD::FXOR:               return "X86ISD::FXOR";
15178   case X86ISD::FSRL:               return "X86ISD::FSRL";
15179   case X86ISD::FILD:               return "X86ISD::FILD";
15180   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
15181   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
15182   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
15183   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
15184   case X86ISD::FLD:                return "X86ISD::FLD";
15185   case X86ISD::FST:                return "X86ISD::FST";
15186   case X86ISD::CALL:               return "X86ISD::CALL";
15187   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
15188   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
15189   case X86ISD::BT:                 return "X86ISD::BT";
15190   case X86ISD::CMP:                return "X86ISD::CMP";
15191   case X86ISD::COMI:               return "X86ISD::COMI";
15192   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
15193   case X86ISD::CMPM:               return "X86ISD::CMPM";
15194   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
15195   case X86ISD::SETCC:              return "X86ISD::SETCC";
15196   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
15197   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
15198   case X86ISD::CMOV:               return "X86ISD::CMOV";
15199   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
15200   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
15201   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
15202   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
15203   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
15204   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
15205   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
15206   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
15207   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
15208   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
15209   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
15210   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
15211   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
15212   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
15213   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
15214   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
15215   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
15216   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
15217   case X86ISD::HADD:               return "X86ISD::HADD";
15218   case X86ISD::HSUB:               return "X86ISD::HSUB";
15219   case X86ISD::FHADD:              return "X86ISD::FHADD";
15220   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
15221   case X86ISD::UMAX:               return "X86ISD::UMAX";
15222   case X86ISD::UMIN:               return "X86ISD::UMIN";
15223   case X86ISD::SMAX:               return "X86ISD::SMAX";
15224   case X86ISD::SMIN:               return "X86ISD::SMIN";
15225   case X86ISD::FMAX:               return "X86ISD::FMAX";
15226   case X86ISD::FMIN:               return "X86ISD::FMIN";
15227   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
15228   case X86ISD::FMINC:              return "X86ISD::FMINC";
15229   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
15230   case X86ISD::FRCP:               return "X86ISD::FRCP";
15231   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
15232   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
15233   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
15234   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
15235   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
15236   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
15237   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
15238   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
15239   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
15240   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
15241   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
15242   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
15243   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
15244   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
15245   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
15246   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
15247   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
15248   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
15249   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
15250   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
15251   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
15252   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
15253   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
15254   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
15255   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
15256   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
15257   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
15258   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
15259   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
15260   case X86ISD::VSHL:               return "X86ISD::VSHL";
15261   case X86ISD::VSRL:               return "X86ISD::VSRL";
15262   case X86ISD::VSRA:               return "X86ISD::VSRA";
15263   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
15264   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
15265   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
15266   case X86ISD::CMPP:               return "X86ISD::CMPP";
15267   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
15268   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
15269   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
15270   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
15271   case X86ISD::ADD:                return "X86ISD::ADD";
15272   case X86ISD::SUB:                return "X86ISD::SUB";
15273   case X86ISD::ADC:                return "X86ISD::ADC";
15274   case X86ISD::SBB:                return "X86ISD::SBB";
15275   case X86ISD::SMUL:               return "X86ISD::SMUL";
15276   case X86ISD::UMUL:               return "X86ISD::UMUL";
15277   case X86ISD::INC:                return "X86ISD::INC";
15278   case X86ISD::DEC:                return "X86ISD::DEC";
15279   case X86ISD::OR:                 return "X86ISD::OR";
15280   case X86ISD::XOR:                return "X86ISD::XOR";
15281   case X86ISD::AND:                return "X86ISD::AND";
15282   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
15283   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
15284   case X86ISD::PTEST:              return "X86ISD::PTEST";
15285   case X86ISD::TESTP:              return "X86ISD::TESTP";
15286   case X86ISD::TESTM:              return "X86ISD::TESTM";
15287   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
15288   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
15289   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
15290   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
15291   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
15292   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
15293   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
15294   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
15295   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
15296   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
15297   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
15298   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
15299   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
15300   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
15301   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
15302   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
15303   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
15304   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
15305   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
15306   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
15307   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
15308   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
15309   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
15310   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
15311   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
15312   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
15313   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
15314   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
15315   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
15316   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
15317   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
15318   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
15319   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
15320   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
15321   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
15322   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
15323   case X86ISD::SAHF:               return "X86ISD::SAHF";
15324   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
15325   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
15326   case X86ISD::FMADD:              return "X86ISD::FMADD";
15327   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
15328   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
15329   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
15330   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
15331   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
15332   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
15333   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
15334   case X86ISD::XTEST:              return "X86ISD::XTEST";
15335   }
15336 }
15337
15338 // isLegalAddressingMode - Return true if the addressing mode represented
15339 // by AM is legal for this target, for a load/store of the specified type.
15340 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
15341                                               Type *Ty) const {
15342   // X86 supports extremely general addressing modes.
15343   CodeModel::Model M = getTargetMachine().getCodeModel();
15344   Reloc::Model R = getTargetMachine().getRelocationModel();
15345
15346   // X86 allows a sign-extended 32-bit immediate field as a displacement.
15347   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
15348     return false;
15349
15350   if (AM.BaseGV) {
15351     unsigned GVFlags =
15352       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
15353
15354     // If a reference to this global requires an extra load, we can't fold it.
15355     if (isGlobalStubReference(GVFlags))
15356       return false;
15357
15358     // If BaseGV requires a register for the PIC base, we cannot also have a
15359     // BaseReg specified.
15360     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
15361       return false;
15362
15363     // If lower 4G is not available, then we must use rip-relative addressing.
15364     if ((M != CodeModel::Small || R != Reloc::Static) &&
15365         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15366       return false;
15367   }
15368
15369   switch (AM.Scale) {
15370   case 0:
15371   case 1:
15372   case 2:
15373   case 4:
15374   case 8:
15375     // These scales always work.
15376     break;
15377   case 3:
15378   case 5:
15379   case 9:
15380     // These scales are formed with basereg+scalereg.  Only accept if there is
15381     // no basereg yet.
15382     if (AM.HasBaseReg)
15383       return false;
15384     break;
15385   default:  // Other stuff never works.
15386     return false;
15387   }
15388
15389   return true;
15390 }
15391
15392 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15393   unsigned Bits = Ty->getScalarSizeInBits();
15394
15395   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15396   // particularly cheaper than those without.
15397   if (Bits == 8)
15398     return false;
15399
15400   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15401   // variable shifts just as cheap as scalar ones.
15402   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15403     return false;
15404
15405   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15406   // fully general vector.
15407   return true;
15408 }
15409
15410 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15411   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15412     return false;
15413   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15414   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15415   return NumBits1 > NumBits2;
15416 }
15417
15418 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15419   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15420     return false;
15421
15422   if (!isTypeLegal(EVT::getEVT(Ty1)))
15423     return false;
15424
15425   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15426
15427   // Assuming the caller doesn't have a zeroext or signext return parameter,
15428   // truncation all the way down to i1 is valid.
15429   return true;
15430 }
15431
15432 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15433   return isInt<32>(Imm);
15434 }
15435
15436 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15437   // Can also use sub to handle negated immediates.
15438   return isInt<32>(Imm);
15439 }
15440
15441 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15442   if (!VT1.isInteger() || !VT2.isInteger())
15443     return false;
15444   unsigned NumBits1 = VT1.getSizeInBits();
15445   unsigned NumBits2 = VT2.getSizeInBits();
15446   return NumBits1 > NumBits2;
15447 }
15448
15449 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15450   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15451   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15452 }
15453
15454 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15455   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15456   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15457 }
15458
15459 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15460   EVT VT1 = Val.getValueType();
15461   if (isZExtFree(VT1, VT2))
15462     return true;
15463
15464   if (Val.getOpcode() != ISD::LOAD)
15465     return false;
15466
15467   if (!VT1.isSimple() || !VT1.isInteger() ||
15468       !VT2.isSimple() || !VT2.isInteger())
15469     return false;
15470
15471   switch (VT1.getSimpleVT().SimpleTy) {
15472   default: break;
15473   case MVT::i8:
15474   case MVT::i16:
15475   case MVT::i32:
15476     // X86 has 8, 16, and 32-bit zero-extending loads.
15477     return true;
15478   }
15479
15480   return false;
15481 }
15482
15483 bool
15484 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15485   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15486     return false;
15487
15488   VT = VT.getScalarType();
15489
15490   if (!VT.isSimple())
15491     return false;
15492
15493   switch (VT.getSimpleVT().SimpleTy) {
15494   case MVT::f32:
15495   case MVT::f64:
15496     return true;
15497   default:
15498     break;
15499   }
15500
15501   return false;
15502 }
15503
15504 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15505   // i16 instructions are longer (0x66 prefix) and potentially slower.
15506   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15507 }
15508
15509 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15510 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15511 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15512 /// are assumed to be legal.
15513 bool
15514 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15515                                       EVT VT) const {
15516   if (!VT.isSimple())
15517     return false;
15518
15519   MVT SVT = VT.getSimpleVT();
15520
15521   // Very little shuffling can be done for 64-bit vectors right now.
15522   if (VT.getSizeInBits() == 64)
15523     return false;
15524
15525   // If this is a single-input shuffle with no 128 bit lane crossings we can
15526   // lower it into pshufb.
15527   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15528       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15529     bool isLegal = true;
15530     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15531       if (M[I] >= (int)SVT.getVectorNumElements() ||
15532           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15533         isLegal = false;
15534         break;
15535       }
15536     }
15537     if (isLegal)
15538       return true;
15539   }
15540
15541   // FIXME: blends, shifts.
15542   return (SVT.getVectorNumElements() == 2 ||
15543           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15544           isMOVLMask(M, SVT) ||
15545           isSHUFPMask(M, SVT) ||
15546           isPSHUFDMask(M, SVT) ||
15547           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15548           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15549           isPALIGNRMask(M, SVT, Subtarget) ||
15550           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15551           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15552           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15553           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15554           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15555 }
15556
15557 bool
15558 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15559                                           EVT VT) const {
15560   if (!VT.isSimple())
15561     return false;
15562
15563   MVT SVT = VT.getSimpleVT();
15564   unsigned NumElts = SVT.getVectorNumElements();
15565   // FIXME: This collection of masks seems suspect.
15566   if (NumElts == 2)
15567     return true;
15568   if (NumElts == 4 && SVT.is128BitVector()) {
15569     return (isMOVLMask(Mask, SVT)  ||
15570             isCommutedMOVLMask(Mask, SVT, true) ||
15571             isSHUFPMask(Mask, SVT) ||
15572             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15573   }
15574   return false;
15575 }
15576
15577 //===----------------------------------------------------------------------===//
15578 //                           X86 Scheduler Hooks
15579 //===----------------------------------------------------------------------===//
15580
15581 /// Utility function to emit xbegin specifying the start of an RTM region.
15582 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15583                                      const TargetInstrInfo *TII) {
15584   DebugLoc DL = MI->getDebugLoc();
15585
15586   const BasicBlock *BB = MBB->getBasicBlock();
15587   MachineFunction::iterator I = MBB;
15588   ++I;
15589
15590   // For the v = xbegin(), we generate
15591   //
15592   // thisMBB:
15593   //  xbegin sinkMBB
15594   //
15595   // mainMBB:
15596   //  eax = -1
15597   //
15598   // sinkMBB:
15599   //  v = eax
15600
15601   MachineBasicBlock *thisMBB = MBB;
15602   MachineFunction *MF = MBB->getParent();
15603   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15604   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15605   MF->insert(I, mainMBB);
15606   MF->insert(I, sinkMBB);
15607
15608   // Transfer the remainder of BB and its successor edges to sinkMBB.
15609   sinkMBB->splice(sinkMBB->begin(), MBB,
15610                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15611   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15612
15613   // thisMBB:
15614   //  xbegin sinkMBB
15615   //  # fallthrough to mainMBB
15616   //  # abortion to sinkMBB
15617   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15618   thisMBB->addSuccessor(mainMBB);
15619   thisMBB->addSuccessor(sinkMBB);
15620
15621   // mainMBB:
15622   //  EAX = -1
15623   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15624   mainMBB->addSuccessor(sinkMBB);
15625
15626   // sinkMBB:
15627   // EAX is live into the sinkMBB
15628   sinkMBB->addLiveIn(X86::EAX);
15629   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15630           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15631     .addReg(X86::EAX);
15632
15633   MI->eraseFromParent();
15634   return sinkMBB;
15635 }
15636
15637 // Get CMPXCHG opcode for the specified data type.
15638 static unsigned getCmpXChgOpcode(EVT VT) {
15639   switch (VT.getSimpleVT().SimpleTy) {
15640   case MVT::i8:  return X86::LCMPXCHG8;
15641   case MVT::i16: return X86::LCMPXCHG16;
15642   case MVT::i32: return X86::LCMPXCHG32;
15643   case MVT::i64: return X86::LCMPXCHG64;
15644   default:
15645     break;
15646   }
15647   llvm_unreachable("Invalid operand size!");
15648 }
15649
15650 // Get LOAD opcode for the specified data type.
15651 static unsigned getLoadOpcode(EVT VT) {
15652   switch (VT.getSimpleVT().SimpleTy) {
15653   case MVT::i8:  return X86::MOV8rm;
15654   case MVT::i16: return X86::MOV16rm;
15655   case MVT::i32: return X86::MOV32rm;
15656   case MVT::i64: return X86::MOV64rm;
15657   default:
15658     break;
15659   }
15660   llvm_unreachable("Invalid operand size!");
15661 }
15662
15663 // Get opcode of the non-atomic one from the specified atomic instruction.
15664 static unsigned getNonAtomicOpcode(unsigned Opc) {
15665   switch (Opc) {
15666   case X86::ATOMAND8:  return X86::AND8rr;
15667   case X86::ATOMAND16: return X86::AND16rr;
15668   case X86::ATOMAND32: return X86::AND32rr;
15669   case X86::ATOMAND64: return X86::AND64rr;
15670   case X86::ATOMOR8:   return X86::OR8rr;
15671   case X86::ATOMOR16:  return X86::OR16rr;
15672   case X86::ATOMOR32:  return X86::OR32rr;
15673   case X86::ATOMOR64:  return X86::OR64rr;
15674   case X86::ATOMXOR8:  return X86::XOR8rr;
15675   case X86::ATOMXOR16: return X86::XOR16rr;
15676   case X86::ATOMXOR32: return X86::XOR32rr;
15677   case X86::ATOMXOR64: return X86::XOR64rr;
15678   }
15679   llvm_unreachable("Unhandled atomic-load-op opcode!");
15680 }
15681
15682 // Get opcode of the non-atomic one from the specified atomic instruction with
15683 // extra opcode.
15684 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15685                                                unsigned &ExtraOpc) {
15686   switch (Opc) {
15687   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15688   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15689   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15690   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15691   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15692   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15693   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15694   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15695   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15696   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15697   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15698   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15699   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15700   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15701   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15702   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15703   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15704   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15705   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15706   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15707   }
15708   llvm_unreachable("Unhandled atomic-load-op opcode!");
15709 }
15710
15711 // Get opcode of the non-atomic one from the specified atomic instruction for
15712 // 64-bit data type on 32-bit target.
15713 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15714   switch (Opc) {
15715   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15716   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15717   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15718   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15719   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15720   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15721   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15722   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15723   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15724   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15725   }
15726   llvm_unreachable("Unhandled atomic-load-op opcode!");
15727 }
15728
15729 // Get opcode of the non-atomic one from the specified atomic instruction for
15730 // 64-bit data type on 32-bit target with extra opcode.
15731 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15732                                                    unsigned &HiOpc,
15733                                                    unsigned &ExtraOpc) {
15734   switch (Opc) {
15735   case X86::ATOMNAND6432:
15736     ExtraOpc = X86::NOT32r;
15737     HiOpc = X86::AND32rr;
15738     return X86::AND32rr;
15739   }
15740   llvm_unreachable("Unhandled atomic-load-op opcode!");
15741 }
15742
15743 // Get pseudo CMOV opcode from the specified data type.
15744 static unsigned getPseudoCMOVOpc(EVT VT) {
15745   switch (VT.getSimpleVT().SimpleTy) {
15746   case MVT::i8:  return X86::CMOV_GR8;
15747   case MVT::i16: return X86::CMOV_GR16;
15748   case MVT::i32: return X86::CMOV_GR32;
15749   default:
15750     break;
15751   }
15752   llvm_unreachable("Unknown CMOV opcode!");
15753 }
15754
15755 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15756 // They will be translated into a spin-loop or compare-exchange loop from
15757 //
15758 //    ...
15759 //    dst = atomic-fetch-op MI.addr, MI.val
15760 //    ...
15761 //
15762 // to
15763 //
15764 //    ...
15765 //    t1 = LOAD MI.addr
15766 // loop:
15767 //    t4 = phi(t1, t3 / loop)
15768 //    t2 = OP MI.val, t4
15769 //    EAX = t4
15770 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15771 //    t3 = EAX
15772 //    JNE loop
15773 // sink:
15774 //    dst = t3
15775 //    ...
15776 MachineBasicBlock *
15777 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15778                                        MachineBasicBlock *MBB) const {
15779   MachineFunction *MF = MBB->getParent();
15780   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
15781   DebugLoc DL = MI->getDebugLoc();
15782
15783   MachineRegisterInfo &MRI = MF->getRegInfo();
15784
15785   const BasicBlock *BB = MBB->getBasicBlock();
15786   MachineFunction::iterator I = MBB;
15787   ++I;
15788
15789   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15790          "Unexpected number of operands");
15791
15792   assert(MI->hasOneMemOperand() &&
15793          "Expected atomic-load-op to have one memoperand");
15794
15795   // Memory Reference
15796   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15797   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15798
15799   unsigned DstReg, SrcReg;
15800   unsigned MemOpndSlot;
15801
15802   unsigned CurOp = 0;
15803
15804   DstReg = MI->getOperand(CurOp++).getReg();
15805   MemOpndSlot = CurOp;
15806   CurOp += X86::AddrNumOperands;
15807   SrcReg = MI->getOperand(CurOp++).getReg();
15808
15809   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15810   MVT::SimpleValueType VT = *RC->vt_begin();
15811   unsigned t1 = MRI.createVirtualRegister(RC);
15812   unsigned t2 = MRI.createVirtualRegister(RC);
15813   unsigned t3 = MRI.createVirtualRegister(RC);
15814   unsigned t4 = MRI.createVirtualRegister(RC);
15815   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15816
15817   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15818   unsigned LOADOpc = getLoadOpcode(VT);
15819
15820   // For the atomic load-arith operator, we generate
15821   //
15822   //  thisMBB:
15823   //    t1 = LOAD [MI.addr]
15824   //  mainMBB:
15825   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15826   //    t1 = OP MI.val, EAX
15827   //    EAX = t4
15828   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15829   //    t3 = EAX
15830   //    JNE mainMBB
15831   //  sinkMBB:
15832   //    dst = t3
15833
15834   MachineBasicBlock *thisMBB = MBB;
15835   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15836   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15837   MF->insert(I, mainMBB);
15838   MF->insert(I, sinkMBB);
15839
15840   MachineInstrBuilder MIB;
15841
15842   // Transfer the remainder of BB and its successor edges to sinkMBB.
15843   sinkMBB->splice(sinkMBB->begin(), MBB,
15844                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15845   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15846
15847   // thisMBB:
15848   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15849   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15850     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15851     if (NewMO.isReg())
15852       NewMO.setIsKill(false);
15853     MIB.addOperand(NewMO);
15854   }
15855   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15856     unsigned flags = (*MMOI)->getFlags();
15857     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15858     MachineMemOperand *MMO =
15859       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15860                                (*MMOI)->getSize(),
15861                                (*MMOI)->getBaseAlignment(),
15862                                (*MMOI)->getTBAAInfo(),
15863                                (*MMOI)->getRanges());
15864     MIB.addMemOperand(MMO);
15865   }
15866
15867   thisMBB->addSuccessor(mainMBB);
15868
15869   // mainMBB:
15870   MachineBasicBlock *origMainMBB = mainMBB;
15871
15872   // Add a PHI.
15873   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15874                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15875
15876   unsigned Opc = MI->getOpcode();
15877   switch (Opc) {
15878   default:
15879     llvm_unreachable("Unhandled atomic-load-op opcode!");
15880   case X86::ATOMAND8:
15881   case X86::ATOMAND16:
15882   case X86::ATOMAND32:
15883   case X86::ATOMAND64:
15884   case X86::ATOMOR8:
15885   case X86::ATOMOR16:
15886   case X86::ATOMOR32:
15887   case X86::ATOMOR64:
15888   case X86::ATOMXOR8:
15889   case X86::ATOMXOR16:
15890   case X86::ATOMXOR32:
15891   case X86::ATOMXOR64: {
15892     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15893     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15894       .addReg(t4);
15895     break;
15896   }
15897   case X86::ATOMNAND8:
15898   case X86::ATOMNAND16:
15899   case X86::ATOMNAND32:
15900   case X86::ATOMNAND64: {
15901     unsigned Tmp = MRI.createVirtualRegister(RC);
15902     unsigned NOTOpc;
15903     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15904     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15905       .addReg(t4);
15906     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15907     break;
15908   }
15909   case X86::ATOMMAX8:
15910   case X86::ATOMMAX16:
15911   case X86::ATOMMAX32:
15912   case X86::ATOMMAX64:
15913   case X86::ATOMMIN8:
15914   case X86::ATOMMIN16:
15915   case X86::ATOMMIN32:
15916   case X86::ATOMMIN64:
15917   case X86::ATOMUMAX8:
15918   case X86::ATOMUMAX16:
15919   case X86::ATOMUMAX32:
15920   case X86::ATOMUMAX64:
15921   case X86::ATOMUMIN8:
15922   case X86::ATOMUMIN16:
15923   case X86::ATOMUMIN32:
15924   case X86::ATOMUMIN64: {
15925     unsigned CMPOpc;
15926     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15927
15928     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15929       .addReg(SrcReg)
15930       .addReg(t4);
15931
15932     if (Subtarget->hasCMov()) {
15933       if (VT != MVT::i8) {
15934         // Native support
15935         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15936           .addReg(SrcReg)
15937           .addReg(t4);
15938       } else {
15939         // Promote i8 to i32 to use CMOV32
15940         const TargetRegisterInfo* TRI = MF->getTarget().getRegisterInfo();
15941         const TargetRegisterClass *RC32 =
15942           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15943         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15944         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15945         unsigned Tmp = MRI.createVirtualRegister(RC32);
15946
15947         unsigned Undef = MRI.createVirtualRegister(RC32);
15948         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15949
15950         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15951           .addReg(Undef)
15952           .addReg(SrcReg)
15953           .addImm(X86::sub_8bit);
15954         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15955           .addReg(Undef)
15956           .addReg(t4)
15957           .addImm(X86::sub_8bit);
15958
15959         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15960           .addReg(SrcReg32)
15961           .addReg(AccReg32);
15962
15963         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15964           .addReg(Tmp, 0, X86::sub_8bit);
15965       }
15966     } else {
15967       // Use pseudo select and lower them.
15968       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15969              "Invalid atomic-load-op transformation!");
15970       unsigned SelOpc = getPseudoCMOVOpc(VT);
15971       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15972       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15973       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15974               .addReg(SrcReg).addReg(t4)
15975               .addImm(CC);
15976       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15977       // Replace the original PHI node as mainMBB is changed after CMOV
15978       // lowering.
15979       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15980         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15981       Phi->eraseFromParent();
15982     }
15983     break;
15984   }
15985   }
15986
15987   // Copy PhyReg back from virtual register.
15988   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15989     .addReg(t4);
15990
15991   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15992   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15993     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15994     if (NewMO.isReg())
15995       NewMO.setIsKill(false);
15996     MIB.addOperand(NewMO);
15997   }
15998   MIB.addReg(t2);
15999   MIB.setMemRefs(MMOBegin, MMOEnd);
16000
16001   // Copy PhyReg back to virtual register.
16002   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
16003     .addReg(PhyReg);
16004
16005   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16006
16007   mainMBB->addSuccessor(origMainMBB);
16008   mainMBB->addSuccessor(sinkMBB);
16009
16010   // sinkMBB:
16011   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16012           TII->get(TargetOpcode::COPY), DstReg)
16013     .addReg(t3);
16014
16015   MI->eraseFromParent();
16016   return sinkMBB;
16017 }
16018
16019 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
16020 // instructions. They will be translated into a spin-loop or compare-exchange
16021 // loop from
16022 //
16023 //    ...
16024 //    dst = atomic-fetch-op MI.addr, MI.val
16025 //    ...
16026 //
16027 // to
16028 //
16029 //    ...
16030 //    t1L = LOAD [MI.addr + 0]
16031 //    t1H = LOAD [MI.addr + 4]
16032 // loop:
16033 //    t4L = phi(t1L, t3L / loop)
16034 //    t4H = phi(t1H, t3H / loop)
16035 //    t2L = OP MI.val.lo, t4L
16036 //    t2H = OP MI.val.hi, t4H
16037 //    EAX = t4L
16038 //    EDX = t4H
16039 //    EBX = t2L
16040 //    ECX = t2H
16041 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16042 //    t3L = EAX
16043 //    t3H = EDX
16044 //    JNE loop
16045 // sink:
16046 //    dstL = t3L
16047 //    dstH = t3H
16048 //    ...
16049 MachineBasicBlock *
16050 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
16051                                            MachineBasicBlock *MBB) const {
16052   MachineFunction *MF = MBB->getParent();
16053   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16054   DebugLoc DL = MI->getDebugLoc();
16055
16056   MachineRegisterInfo &MRI = MF->getRegInfo();
16057
16058   const BasicBlock *BB = MBB->getBasicBlock();
16059   MachineFunction::iterator I = MBB;
16060   ++I;
16061
16062   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
16063          "Unexpected number of operands");
16064
16065   assert(MI->hasOneMemOperand() &&
16066          "Expected atomic-load-op32 to have one memoperand");
16067
16068   // Memory Reference
16069   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16070   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16071
16072   unsigned DstLoReg, DstHiReg;
16073   unsigned SrcLoReg, SrcHiReg;
16074   unsigned MemOpndSlot;
16075
16076   unsigned CurOp = 0;
16077
16078   DstLoReg = MI->getOperand(CurOp++).getReg();
16079   DstHiReg = MI->getOperand(CurOp++).getReg();
16080   MemOpndSlot = CurOp;
16081   CurOp += X86::AddrNumOperands;
16082   SrcLoReg = MI->getOperand(CurOp++).getReg();
16083   SrcHiReg = MI->getOperand(CurOp++).getReg();
16084
16085   const TargetRegisterClass *RC = &X86::GR32RegClass;
16086   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
16087
16088   unsigned t1L = MRI.createVirtualRegister(RC);
16089   unsigned t1H = MRI.createVirtualRegister(RC);
16090   unsigned t2L = MRI.createVirtualRegister(RC);
16091   unsigned t2H = MRI.createVirtualRegister(RC);
16092   unsigned t3L = MRI.createVirtualRegister(RC);
16093   unsigned t3H = MRI.createVirtualRegister(RC);
16094   unsigned t4L = MRI.createVirtualRegister(RC);
16095   unsigned t4H = MRI.createVirtualRegister(RC);
16096
16097   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
16098   unsigned LOADOpc = X86::MOV32rm;
16099
16100   // For the atomic load-arith operator, we generate
16101   //
16102   //  thisMBB:
16103   //    t1L = LOAD [MI.addr + 0]
16104   //    t1H = LOAD [MI.addr + 4]
16105   //  mainMBB:
16106   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
16107   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
16108   //    t2L = OP MI.val.lo, t4L
16109   //    t2H = OP MI.val.hi, t4H
16110   //    EBX = t2L
16111   //    ECX = t2H
16112   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
16113   //    t3L = EAX
16114   //    t3H = EDX
16115   //    JNE loop
16116   //  sinkMBB:
16117   //    dstL = t3L
16118   //    dstH = t3H
16119
16120   MachineBasicBlock *thisMBB = MBB;
16121   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16122   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16123   MF->insert(I, mainMBB);
16124   MF->insert(I, sinkMBB);
16125
16126   MachineInstrBuilder MIB;
16127
16128   // Transfer the remainder of BB and its successor edges to sinkMBB.
16129   sinkMBB->splice(sinkMBB->begin(), MBB,
16130                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16131   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16132
16133   // thisMBB:
16134   // Lo
16135   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
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   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
16143     unsigned flags = (*MMOI)->getFlags();
16144     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
16145     MachineMemOperand *MMO =
16146       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
16147                                (*MMOI)->getSize(),
16148                                (*MMOI)->getBaseAlignment(),
16149                                (*MMOI)->getTBAAInfo(),
16150                                (*MMOI)->getRanges());
16151     MIB.addMemOperand(MMO);
16152   };
16153   MachineInstr *LowMI = MIB;
16154
16155   // Hi
16156   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
16157   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16158     if (i == X86::AddrDisp) {
16159       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
16160     } else {
16161       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16162       if (NewMO.isReg())
16163         NewMO.setIsKill(false);
16164       MIB.addOperand(NewMO);
16165     }
16166   }
16167   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
16168
16169   thisMBB->addSuccessor(mainMBB);
16170
16171   // mainMBB:
16172   MachineBasicBlock *origMainMBB = mainMBB;
16173
16174   // Add PHIs.
16175   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
16176                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16177   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
16178                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16179
16180   unsigned Opc = MI->getOpcode();
16181   switch (Opc) {
16182   default:
16183     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
16184   case X86::ATOMAND6432:
16185   case X86::ATOMOR6432:
16186   case X86::ATOMXOR6432:
16187   case X86::ATOMADD6432:
16188   case X86::ATOMSUB6432: {
16189     unsigned HiOpc;
16190     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16191     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
16192       .addReg(SrcLoReg);
16193     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
16194       .addReg(SrcHiReg);
16195     break;
16196   }
16197   case X86::ATOMNAND6432: {
16198     unsigned HiOpc, NOTOpc;
16199     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
16200     unsigned TmpL = MRI.createVirtualRegister(RC);
16201     unsigned TmpH = MRI.createVirtualRegister(RC);
16202     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
16203       .addReg(t4L);
16204     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
16205       .addReg(t4H);
16206     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
16207     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
16208     break;
16209   }
16210   case X86::ATOMMAX6432:
16211   case X86::ATOMMIN6432:
16212   case X86::ATOMUMAX6432:
16213   case X86::ATOMUMIN6432: {
16214     unsigned HiOpc;
16215     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16216     unsigned cL = MRI.createVirtualRegister(RC8);
16217     unsigned cH = MRI.createVirtualRegister(RC8);
16218     unsigned cL32 = MRI.createVirtualRegister(RC);
16219     unsigned cH32 = MRI.createVirtualRegister(RC);
16220     unsigned cc = MRI.createVirtualRegister(RC);
16221     // cl := cmp src_lo, lo
16222     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16223       .addReg(SrcLoReg).addReg(t4L);
16224     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
16225     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
16226     // ch := cmp src_hi, hi
16227     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
16228       .addReg(SrcHiReg).addReg(t4H);
16229     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
16230     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
16231     // cc := if (src_hi == hi) ? cl : ch;
16232     if (Subtarget->hasCMov()) {
16233       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
16234         .addReg(cH32).addReg(cL32);
16235     } else {
16236       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
16237               .addReg(cH32).addReg(cL32)
16238               .addImm(X86::COND_E);
16239       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16240     }
16241     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
16242     if (Subtarget->hasCMov()) {
16243       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
16244         .addReg(SrcLoReg).addReg(t4L);
16245       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
16246         .addReg(SrcHiReg).addReg(t4H);
16247     } else {
16248       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
16249               .addReg(SrcLoReg).addReg(t4L)
16250               .addImm(X86::COND_NE);
16251       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16252       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
16253       // 2nd CMOV lowering.
16254       mainMBB->addLiveIn(X86::EFLAGS);
16255       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
16256               .addReg(SrcHiReg).addReg(t4H)
16257               .addImm(X86::COND_NE);
16258       mainMBB = EmitLoweredSelect(MIB, mainMBB);
16259       // Replace the original PHI node as mainMBB is changed after CMOV
16260       // lowering.
16261       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
16262         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
16263       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
16264         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
16265       PhiL->eraseFromParent();
16266       PhiH->eraseFromParent();
16267     }
16268     break;
16269   }
16270   case X86::ATOMSWAP6432: {
16271     unsigned HiOpc;
16272     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
16273     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
16274     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
16275     break;
16276   }
16277   }
16278
16279   // Copy EDX:EAX back from HiReg:LoReg
16280   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
16281   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
16282   // Copy ECX:EBX from t1H:t1L
16283   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
16284   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
16285
16286   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
16287   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16288     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
16289     if (NewMO.isReg())
16290       NewMO.setIsKill(false);
16291     MIB.addOperand(NewMO);
16292   }
16293   MIB.setMemRefs(MMOBegin, MMOEnd);
16294
16295   // Copy EDX:EAX back to t3H:t3L
16296   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
16297   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
16298
16299   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
16300
16301   mainMBB->addSuccessor(origMainMBB);
16302   mainMBB->addSuccessor(sinkMBB);
16303
16304   // sinkMBB:
16305   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16306           TII->get(TargetOpcode::COPY), DstLoReg)
16307     .addReg(t3L);
16308   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16309           TII->get(TargetOpcode::COPY), DstHiReg)
16310     .addReg(t3H);
16311
16312   MI->eraseFromParent();
16313   return sinkMBB;
16314 }
16315
16316 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
16317 // or XMM0_V32I8 in AVX all of this code can be replaced with that
16318 // in the .td file.
16319 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
16320                                        const TargetInstrInfo *TII) {
16321   unsigned Opc;
16322   switch (MI->getOpcode()) {
16323   default: llvm_unreachable("illegal opcode!");
16324   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
16325   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
16326   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
16327   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
16328   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
16329   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
16330   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
16331   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
16332   }
16333
16334   DebugLoc dl = MI->getDebugLoc();
16335   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16336
16337   unsigned NumArgs = MI->getNumOperands();
16338   for (unsigned i = 1; i < NumArgs; ++i) {
16339     MachineOperand &Op = MI->getOperand(i);
16340     if (!(Op.isReg() && Op.isImplicit()))
16341       MIB.addOperand(Op);
16342   }
16343   if (MI->hasOneMemOperand())
16344     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16345
16346   BuildMI(*BB, MI, dl,
16347     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16348     .addReg(X86::XMM0);
16349
16350   MI->eraseFromParent();
16351   return BB;
16352 }
16353
16354 // FIXME: Custom handling because TableGen doesn't support multiple implicit
16355 // defs in an instruction pattern
16356 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
16357                                        const TargetInstrInfo *TII) {
16358   unsigned Opc;
16359   switch (MI->getOpcode()) {
16360   default: llvm_unreachable("illegal opcode!");
16361   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
16362   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
16363   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16364   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16365   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16366   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16367   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16368   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16369   }
16370
16371   DebugLoc dl = MI->getDebugLoc();
16372   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16373
16374   unsigned NumArgs = MI->getNumOperands(); // remove the results
16375   for (unsigned i = 1; i < NumArgs; ++i) {
16376     MachineOperand &Op = MI->getOperand(i);
16377     if (!(Op.isReg() && Op.isImplicit()))
16378       MIB.addOperand(Op);
16379   }
16380   if (MI->hasOneMemOperand())
16381     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16382
16383   BuildMI(*BB, MI, dl,
16384     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16385     .addReg(X86::ECX);
16386
16387   MI->eraseFromParent();
16388   return BB;
16389 }
16390
16391 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16392                                        const TargetInstrInfo *TII,
16393                                        const X86Subtarget* Subtarget) {
16394   DebugLoc dl = MI->getDebugLoc();
16395
16396   // Address into RAX/EAX, other two args into ECX, EDX.
16397   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16398   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16399   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16400   for (int i = 0; i < X86::AddrNumOperands; ++i)
16401     MIB.addOperand(MI->getOperand(i));
16402
16403   unsigned ValOps = X86::AddrNumOperands;
16404   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16405     .addReg(MI->getOperand(ValOps).getReg());
16406   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16407     .addReg(MI->getOperand(ValOps+1).getReg());
16408
16409   // The instruction doesn't actually take any operands though.
16410   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16411
16412   MI->eraseFromParent(); // The pseudo is gone now.
16413   return BB;
16414 }
16415
16416 MachineBasicBlock *
16417 X86TargetLowering::EmitVAARG64WithCustomInserter(
16418                    MachineInstr *MI,
16419                    MachineBasicBlock *MBB) const {
16420   // Emit va_arg instruction on X86-64.
16421
16422   // Operands to this pseudo-instruction:
16423   // 0  ) Output        : destination address (reg)
16424   // 1-5) Input         : va_list address (addr, i64mem)
16425   // 6  ) ArgSize       : Size (in bytes) of vararg type
16426   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16427   // 8  ) Align         : Alignment of type
16428   // 9  ) EFLAGS (implicit-def)
16429
16430   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16431   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16432
16433   unsigned DestReg = MI->getOperand(0).getReg();
16434   MachineOperand &Base = MI->getOperand(1);
16435   MachineOperand &Scale = MI->getOperand(2);
16436   MachineOperand &Index = MI->getOperand(3);
16437   MachineOperand &Disp = MI->getOperand(4);
16438   MachineOperand &Segment = MI->getOperand(5);
16439   unsigned ArgSize = MI->getOperand(6).getImm();
16440   unsigned ArgMode = MI->getOperand(7).getImm();
16441   unsigned Align = MI->getOperand(8).getImm();
16442
16443   // Memory Reference
16444   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16445   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16446   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16447
16448   // Machine Information
16449   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16450   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16451   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16452   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16453   DebugLoc DL = MI->getDebugLoc();
16454
16455   // struct va_list {
16456   //   i32   gp_offset
16457   //   i32   fp_offset
16458   //   i64   overflow_area (address)
16459   //   i64   reg_save_area (address)
16460   // }
16461   // sizeof(va_list) = 24
16462   // alignment(va_list) = 8
16463
16464   unsigned TotalNumIntRegs = 6;
16465   unsigned TotalNumXMMRegs = 8;
16466   bool UseGPOffset = (ArgMode == 1);
16467   bool UseFPOffset = (ArgMode == 2);
16468   unsigned MaxOffset = TotalNumIntRegs * 8 +
16469                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16470
16471   /* Align ArgSize to a multiple of 8 */
16472   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16473   bool NeedsAlign = (Align > 8);
16474
16475   MachineBasicBlock *thisMBB = MBB;
16476   MachineBasicBlock *overflowMBB;
16477   MachineBasicBlock *offsetMBB;
16478   MachineBasicBlock *endMBB;
16479
16480   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16481   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16482   unsigned OffsetReg = 0;
16483
16484   if (!UseGPOffset && !UseFPOffset) {
16485     // If we only pull from the overflow region, we don't create a branch.
16486     // We don't need to alter control flow.
16487     OffsetDestReg = 0; // unused
16488     OverflowDestReg = DestReg;
16489
16490     offsetMBB = nullptr;
16491     overflowMBB = thisMBB;
16492     endMBB = thisMBB;
16493   } else {
16494     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16495     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16496     // If not, pull from overflow_area. (branch to overflowMBB)
16497     //
16498     //       thisMBB
16499     //         |     .
16500     //         |        .
16501     //     offsetMBB   overflowMBB
16502     //         |        .
16503     //         |     .
16504     //        endMBB
16505
16506     // Registers for the PHI in endMBB
16507     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16508     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16509
16510     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16511     MachineFunction *MF = MBB->getParent();
16512     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16513     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16514     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16515
16516     MachineFunction::iterator MBBIter = MBB;
16517     ++MBBIter;
16518
16519     // Insert the new basic blocks
16520     MF->insert(MBBIter, offsetMBB);
16521     MF->insert(MBBIter, overflowMBB);
16522     MF->insert(MBBIter, endMBB);
16523
16524     // Transfer the remainder of MBB and its successor edges to endMBB.
16525     endMBB->splice(endMBB->begin(), thisMBB,
16526                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16527     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16528
16529     // Make offsetMBB and overflowMBB successors of thisMBB
16530     thisMBB->addSuccessor(offsetMBB);
16531     thisMBB->addSuccessor(overflowMBB);
16532
16533     // endMBB is a successor of both offsetMBB and overflowMBB
16534     offsetMBB->addSuccessor(endMBB);
16535     overflowMBB->addSuccessor(endMBB);
16536
16537     // Load the offset value into a register
16538     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16539     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16540       .addOperand(Base)
16541       .addOperand(Scale)
16542       .addOperand(Index)
16543       .addDisp(Disp, UseFPOffset ? 4 : 0)
16544       .addOperand(Segment)
16545       .setMemRefs(MMOBegin, MMOEnd);
16546
16547     // Check if there is enough room left to pull this argument.
16548     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16549       .addReg(OffsetReg)
16550       .addImm(MaxOffset + 8 - ArgSizeA8);
16551
16552     // Branch to "overflowMBB" if offset >= max
16553     // Fall through to "offsetMBB" otherwise
16554     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16555       .addMBB(overflowMBB);
16556   }
16557
16558   // In offsetMBB, emit code to use the reg_save_area.
16559   if (offsetMBB) {
16560     assert(OffsetReg != 0);
16561
16562     // Read the reg_save_area address.
16563     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16564     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16565       .addOperand(Base)
16566       .addOperand(Scale)
16567       .addOperand(Index)
16568       .addDisp(Disp, 16)
16569       .addOperand(Segment)
16570       .setMemRefs(MMOBegin, MMOEnd);
16571
16572     // Zero-extend the offset
16573     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16574       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16575         .addImm(0)
16576         .addReg(OffsetReg)
16577         .addImm(X86::sub_32bit);
16578
16579     // Add the offset to the reg_save_area to get the final address.
16580     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16581       .addReg(OffsetReg64)
16582       .addReg(RegSaveReg);
16583
16584     // Compute the offset for the next argument
16585     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16586     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16587       .addReg(OffsetReg)
16588       .addImm(UseFPOffset ? 16 : 8);
16589
16590     // Store it back into the va_list.
16591     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16592       .addOperand(Base)
16593       .addOperand(Scale)
16594       .addOperand(Index)
16595       .addDisp(Disp, UseFPOffset ? 4 : 0)
16596       .addOperand(Segment)
16597       .addReg(NextOffsetReg)
16598       .setMemRefs(MMOBegin, MMOEnd);
16599
16600     // Jump to endMBB
16601     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16602       .addMBB(endMBB);
16603   }
16604
16605   //
16606   // Emit code to use overflow area
16607   //
16608
16609   // Load the overflow_area address into a register.
16610   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16611   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16612     .addOperand(Base)
16613     .addOperand(Scale)
16614     .addOperand(Index)
16615     .addDisp(Disp, 8)
16616     .addOperand(Segment)
16617     .setMemRefs(MMOBegin, MMOEnd);
16618
16619   // If we need to align it, do so. Otherwise, just copy the address
16620   // to OverflowDestReg.
16621   if (NeedsAlign) {
16622     // Align the overflow address
16623     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16624     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16625
16626     // aligned_addr = (addr + (align-1)) & ~(align-1)
16627     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16628       .addReg(OverflowAddrReg)
16629       .addImm(Align-1);
16630
16631     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16632       .addReg(TmpReg)
16633       .addImm(~(uint64_t)(Align-1));
16634   } else {
16635     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16636       .addReg(OverflowAddrReg);
16637   }
16638
16639   // Compute the next overflow address after this argument.
16640   // (the overflow address should be kept 8-byte aligned)
16641   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16642   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16643     .addReg(OverflowDestReg)
16644     .addImm(ArgSizeA8);
16645
16646   // Store the new overflow address.
16647   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16648     .addOperand(Base)
16649     .addOperand(Scale)
16650     .addOperand(Index)
16651     .addDisp(Disp, 8)
16652     .addOperand(Segment)
16653     .addReg(NextAddrReg)
16654     .setMemRefs(MMOBegin, MMOEnd);
16655
16656   // If we branched, emit the PHI to the front of endMBB.
16657   if (offsetMBB) {
16658     BuildMI(*endMBB, endMBB->begin(), DL,
16659             TII->get(X86::PHI), DestReg)
16660       .addReg(OffsetDestReg).addMBB(offsetMBB)
16661       .addReg(OverflowDestReg).addMBB(overflowMBB);
16662   }
16663
16664   // Erase the pseudo instruction
16665   MI->eraseFromParent();
16666
16667   return endMBB;
16668 }
16669
16670 MachineBasicBlock *
16671 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16672                                                  MachineInstr *MI,
16673                                                  MachineBasicBlock *MBB) const {
16674   // Emit code to save XMM registers to the stack. The ABI says that the
16675   // number of registers to save is given in %al, so it's theoretically
16676   // possible to do an indirect jump trick to avoid saving all of them,
16677   // however this code takes a simpler approach and just executes all
16678   // of the stores if %al is non-zero. It's less code, and it's probably
16679   // easier on the hardware branch predictor, and stores aren't all that
16680   // expensive anyway.
16681
16682   // Create the new basic blocks. One block contains all the XMM stores,
16683   // and one block is the final destination regardless of whether any
16684   // stores were performed.
16685   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16686   MachineFunction *F = MBB->getParent();
16687   MachineFunction::iterator MBBIter = MBB;
16688   ++MBBIter;
16689   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16690   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16691   F->insert(MBBIter, XMMSaveMBB);
16692   F->insert(MBBIter, EndMBB);
16693
16694   // Transfer the remainder of MBB and its successor edges to EndMBB.
16695   EndMBB->splice(EndMBB->begin(), MBB,
16696                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16697   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16698
16699   // The original block will now fall through to the XMM save block.
16700   MBB->addSuccessor(XMMSaveMBB);
16701   // The XMMSaveMBB will fall through to the end block.
16702   XMMSaveMBB->addSuccessor(EndMBB);
16703
16704   // Now add the instructions.
16705   const TargetInstrInfo *TII = MBB->getParent()->getTarget().getInstrInfo();
16706   DebugLoc DL = MI->getDebugLoc();
16707
16708   unsigned CountReg = MI->getOperand(0).getReg();
16709   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16710   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16711
16712   if (!Subtarget->isTargetWin64()) {
16713     // If %al is 0, branch around the XMM save block.
16714     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16715     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16716     MBB->addSuccessor(EndMBB);
16717   }
16718
16719   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16720   // that was just emitted, but clearly shouldn't be "saved".
16721   assert((MI->getNumOperands() <= 3 ||
16722           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16723           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16724          && "Expected last argument to be EFLAGS");
16725   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16726   // In the XMM save block, save all the XMM argument registers.
16727   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16728     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16729     MachineMemOperand *MMO =
16730       F->getMachineMemOperand(
16731           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16732         MachineMemOperand::MOStore,
16733         /*Size=*/16, /*Align=*/16);
16734     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16735       .addFrameIndex(RegSaveFrameIndex)
16736       .addImm(/*Scale=*/1)
16737       .addReg(/*IndexReg=*/0)
16738       .addImm(/*Disp=*/Offset)
16739       .addReg(/*Segment=*/0)
16740       .addReg(MI->getOperand(i).getReg())
16741       .addMemOperand(MMO);
16742   }
16743
16744   MI->eraseFromParent();   // The pseudo instruction is gone now.
16745
16746   return EndMBB;
16747 }
16748
16749 // The EFLAGS operand of SelectItr might be missing a kill marker
16750 // because there were multiple uses of EFLAGS, and ISel didn't know
16751 // which to mark. Figure out whether SelectItr should have had a
16752 // kill marker, and set it if it should. Returns the correct kill
16753 // marker value.
16754 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16755                                      MachineBasicBlock* BB,
16756                                      const TargetRegisterInfo* TRI) {
16757   // Scan forward through BB for a use/def of EFLAGS.
16758   MachineBasicBlock::iterator miI(std::next(SelectItr));
16759   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16760     const MachineInstr& mi = *miI;
16761     if (mi.readsRegister(X86::EFLAGS))
16762       return false;
16763     if (mi.definesRegister(X86::EFLAGS))
16764       break; // Should have kill-flag - update below.
16765   }
16766
16767   // If we hit the end of the block, check whether EFLAGS is live into a
16768   // successor.
16769   if (miI == BB->end()) {
16770     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16771                                           sEnd = BB->succ_end();
16772          sItr != sEnd; ++sItr) {
16773       MachineBasicBlock* succ = *sItr;
16774       if (succ->isLiveIn(X86::EFLAGS))
16775         return false;
16776     }
16777   }
16778
16779   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16780   // out. SelectMI should have a kill flag on EFLAGS.
16781   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16782   return true;
16783 }
16784
16785 MachineBasicBlock *
16786 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16787                                      MachineBasicBlock *BB) const {
16788   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16789   DebugLoc DL = MI->getDebugLoc();
16790
16791   // To "insert" a SELECT_CC instruction, we actually have to insert the
16792   // diamond control-flow pattern.  The incoming instruction knows the
16793   // destination vreg to set, the condition code register to branch on, the
16794   // true/false values to select between, and a branch opcode to use.
16795   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16796   MachineFunction::iterator It = BB;
16797   ++It;
16798
16799   //  thisMBB:
16800   //  ...
16801   //   TrueVal = ...
16802   //   cmpTY ccX, r1, r2
16803   //   bCC copy1MBB
16804   //   fallthrough --> copy0MBB
16805   MachineBasicBlock *thisMBB = BB;
16806   MachineFunction *F = BB->getParent();
16807   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16808   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16809   F->insert(It, copy0MBB);
16810   F->insert(It, sinkMBB);
16811
16812   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16813   // live into the sink and copy blocks.
16814   const TargetRegisterInfo* TRI = BB->getParent()->getTarget().getRegisterInfo();
16815   if (!MI->killsRegister(X86::EFLAGS) &&
16816       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16817     copy0MBB->addLiveIn(X86::EFLAGS);
16818     sinkMBB->addLiveIn(X86::EFLAGS);
16819   }
16820
16821   // Transfer the remainder of BB and its successor edges to sinkMBB.
16822   sinkMBB->splice(sinkMBB->begin(), BB,
16823                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16824   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16825
16826   // Add the true and fallthrough blocks as its successors.
16827   BB->addSuccessor(copy0MBB);
16828   BB->addSuccessor(sinkMBB);
16829
16830   // Create the conditional branch instruction.
16831   unsigned Opc =
16832     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16833   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16834
16835   //  copy0MBB:
16836   //   %FalseValue = ...
16837   //   # fallthrough to sinkMBB
16838   copy0MBB->addSuccessor(sinkMBB);
16839
16840   //  sinkMBB:
16841   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16842   //  ...
16843   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16844           TII->get(X86::PHI), MI->getOperand(0).getReg())
16845     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16846     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16847
16848   MI->eraseFromParent();   // The pseudo instruction is gone now.
16849   return sinkMBB;
16850 }
16851
16852 MachineBasicBlock *
16853 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16854                                         bool Is64Bit) const {
16855   MachineFunction *MF = BB->getParent();
16856   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
16857   DebugLoc DL = MI->getDebugLoc();
16858   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16859
16860   assert(MF->shouldSplitStack());
16861
16862   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16863   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16864
16865   // BB:
16866   //  ... [Till the alloca]
16867   // If stacklet is not large enough, jump to mallocMBB
16868   //
16869   // bumpMBB:
16870   //  Allocate by subtracting from RSP
16871   //  Jump to continueMBB
16872   //
16873   // mallocMBB:
16874   //  Allocate by call to runtime
16875   //
16876   // continueMBB:
16877   //  ...
16878   //  [rest of original BB]
16879   //
16880
16881   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16882   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16883   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16884
16885   MachineRegisterInfo &MRI = MF->getRegInfo();
16886   const TargetRegisterClass *AddrRegClass =
16887     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16888
16889   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16890     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16891     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16892     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16893     sizeVReg = MI->getOperand(1).getReg(),
16894     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16895
16896   MachineFunction::iterator MBBIter = BB;
16897   ++MBBIter;
16898
16899   MF->insert(MBBIter, bumpMBB);
16900   MF->insert(MBBIter, mallocMBB);
16901   MF->insert(MBBIter, continueMBB);
16902
16903   continueMBB->splice(continueMBB->begin(), BB,
16904                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16905   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16906
16907   // Add code to the main basic block to check if the stack limit has been hit,
16908   // and if so, jump to mallocMBB otherwise to bumpMBB.
16909   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16910   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16911     .addReg(tmpSPVReg).addReg(sizeVReg);
16912   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16913     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16914     .addReg(SPLimitVReg);
16915   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16916
16917   // bumpMBB simply decreases the stack pointer, since we know the current
16918   // stacklet has enough space.
16919   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16920     .addReg(SPLimitVReg);
16921   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16922     .addReg(SPLimitVReg);
16923   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16924
16925   // Calls into a routine in libgcc to allocate more space from the heap.
16926   const uint32_t *RegMask =
16927     MF->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16928   if (Is64Bit) {
16929     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16930       .addReg(sizeVReg);
16931     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16932       .addExternalSymbol("__morestack_allocate_stack_space")
16933       .addRegMask(RegMask)
16934       .addReg(X86::RDI, RegState::Implicit)
16935       .addReg(X86::RAX, RegState::ImplicitDefine);
16936   } else {
16937     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16938       .addImm(12);
16939     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16940     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16941       .addExternalSymbol("__morestack_allocate_stack_space")
16942       .addRegMask(RegMask)
16943       .addReg(X86::EAX, RegState::ImplicitDefine);
16944   }
16945
16946   if (!Is64Bit)
16947     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16948       .addImm(16);
16949
16950   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16951     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16952   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16953
16954   // Set up the CFG correctly.
16955   BB->addSuccessor(bumpMBB);
16956   BB->addSuccessor(mallocMBB);
16957   mallocMBB->addSuccessor(continueMBB);
16958   bumpMBB->addSuccessor(continueMBB);
16959
16960   // Take care of the PHI nodes.
16961   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16962           MI->getOperand(0).getReg())
16963     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16964     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16965
16966   // Delete the original pseudo instruction.
16967   MI->eraseFromParent();
16968
16969   // And we're done.
16970   return continueMBB;
16971 }
16972
16973 MachineBasicBlock *
16974 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16975                                         MachineBasicBlock *BB) const {
16976   const TargetInstrInfo *TII = BB->getParent()->getTarget().getInstrInfo();
16977   DebugLoc DL = MI->getDebugLoc();
16978
16979   assert(!Subtarget->isTargetMacho());
16980
16981   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16982   // non-trivial part is impdef of ESP.
16983
16984   if (Subtarget->isTargetWin64()) {
16985     if (Subtarget->isTargetCygMing()) {
16986       // ___chkstk(Mingw64):
16987       // Clobbers R10, R11, RAX and EFLAGS.
16988       // Updates RSP.
16989       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16990         .addExternalSymbol("___chkstk")
16991         .addReg(X86::RAX, RegState::Implicit)
16992         .addReg(X86::RSP, RegState::Implicit)
16993         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16994         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16995         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16996     } else {
16997       // __chkstk(MSVCRT): does not update stack pointer.
16998       // Clobbers R10, R11 and EFLAGS.
16999       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
17000         .addExternalSymbol("__chkstk")
17001         .addReg(X86::RAX, RegState::Implicit)
17002         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17003       // RAX has the offset to be subtracted from RSP.
17004       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
17005         .addReg(X86::RSP)
17006         .addReg(X86::RAX);
17007     }
17008   } else {
17009     const char *StackProbeSymbol =
17010       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
17011
17012     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
17013       .addExternalSymbol(StackProbeSymbol)
17014       .addReg(X86::EAX, RegState::Implicit)
17015       .addReg(X86::ESP, RegState::Implicit)
17016       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
17017       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
17018       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
17019   }
17020
17021   MI->eraseFromParent();   // The pseudo instruction is gone now.
17022   return BB;
17023 }
17024
17025 MachineBasicBlock *
17026 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
17027                                       MachineBasicBlock *BB) const {
17028   // This is pretty easy.  We're taking the value that we received from
17029   // our load from the relocation, sticking it in either RDI (x86-64)
17030   // or EAX and doing an indirect call.  The return value will then
17031   // be in the normal return register.
17032   MachineFunction *F = BB->getParent();
17033   const X86InstrInfo *TII
17034     = static_cast<const X86InstrInfo*>(F->getTarget().getInstrInfo());
17035   DebugLoc DL = MI->getDebugLoc();
17036
17037   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
17038   assert(MI->getOperand(3).isGlobal() && "This should be a global");
17039
17040   // Get a register mask for the lowered call.
17041   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
17042   // proper register mask.
17043   const uint32_t *RegMask =
17044     F->getTarget().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
17045   if (Subtarget->is64Bit()) {
17046     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17047                                       TII->get(X86::MOV64rm), X86::RDI)
17048     .addReg(X86::RIP)
17049     .addImm(0).addReg(0)
17050     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17051                       MI->getOperand(3).getTargetFlags())
17052     .addReg(0);
17053     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
17054     addDirectMem(MIB, X86::RDI);
17055     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
17056   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
17057     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17058                                       TII->get(X86::MOV32rm), X86::EAX)
17059     .addReg(0)
17060     .addImm(0).addReg(0)
17061     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17062                       MI->getOperand(3).getTargetFlags())
17063     .addReg(0);
17064     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17065     addDirectMem(MIB, X86::EAX);
17066     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17067   } else {
17068     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
17069                                       TII->get(X86::MOV32rm), X86::EAX)
17070     .addReg(TII->getGlobalBaseReg(F))
17071     .addImm(0).addReg(0)
17072     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
17073                       MI->getOperand(3).getTargetFlags())
17074     .addReg(0);
17075     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
17076     addDirectMem(MIB, X86::EAX);
17077     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
17078   }
17079
17080   MI->eraseFromParent(); // The pseudo instruction is gone now.
17081   return BB;
17082 }
17083
17084 MachineBasicBlock *
17085 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
17086                                     MachineBasicBlock *MBB) const {
17087   DebugLoc DL = MI->getDebugLoc();
17088   MachineFunction *MF = MBB->getParent();
17089   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17090   MachineRegisterInfo &MRI = MF->getRegInfo();
17091
17092   const BasicBlock *BB = MBB->getBasicBlock();
17093   MachineFunction::iterator I = MBB;
17094   ++I;
17095
17096   // Memory Reference
17097   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17098   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17099
17100   unsigned DstReg;
17101   unsigned MemOpndSlot = 0;
17102
17103   unsigned CurOp = 0;
17104
17105   DstReg = MI->getOperand(CurOp++).getReg();
17106   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
17107   assert(RC->hasType(MVT::i32) && "Invalid destination!");
17108   unsigned mainDstReg = MRI.createVirtualRegister(RC);
17109   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
17110
17111   MemOpndSlot = CurOp;
17112
17113   MVT PVT = getPointerTy();
17114   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17115          "Invalid Pointer Size!");
17116
17117   // For v = setjmp(buf), we generate
17118   //
17119   // thisMBB:
17120   //  buf[LabelOffset] = restoreMBB
17121   //  SjLjSetup restoreMBB
17122   //
17123   // mainMBB:
17124   //  v_main = 0
17125   //
17126   // sinkMBB:
17127   //  v = phi(main, restore)
17128   //
17129   // restoreMBB:
17130   //  v_restore = 1
17131
17132   MachineBasicBlock *thisMBB = MBB;
17133   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
17134   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
17135   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
17136   MF->insert(I, mainMBB);
17137   MF->insert(I, sinkMBB);
17138   MF->push_back(restoreMBB);
17139
17140   MachineInstrBuilder MIB;
17141
17142   // Transfer the remainder of BB and its successor edges to sinkMBB.
17143   sinkMBB->splice(sinkMBB->begin(), MBB,
17144                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
17145   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
17146
17147   // thisMBB:
17148   unsigned PtrStoreOpc = 0;
17149   unsigned LabelReg = 0;
17150   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17151   Reloc::Model RM = MF->getTarget().getRelocationModel();
17152   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
17153                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
17154
17155   // Prepare IP either in reg or imm.
17156   if (!UseImmLabel) {
17157     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
17158     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
17159     LabelReg = MRI.createVirtualRegister(PtrRC);
17160     if (Subtarget->is64Bit()) {
17161       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
17162               .addReg(X86::RIP)
17163               .addImm(0)
17164               .addReg(0)
17165               .addMBB(restoreMBB)
17166               .addReg(0);
17167     } else {
17168       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
17169       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
17170               .addReg(XII->getGlobalBaseReg(MF))
17171               .addImm(0)
17172               .addReg(0)
17173               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
17174               .addReg(0);
17175     }
17176   } else
17177     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
17178   // Store IP
17179   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
17180   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17181     if (i == X86::AddrDisp)
17182       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
17183     else
17184       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
17185   }
17186   if (!UseImmLabel)
17187     MIB.addReg(LabelReg);
17188   else
17189     MIB.addMBB(restoreMBB);
17190   MIB.setMemRefs(MMOBegin, MMOEnd);
17191   // Setup
17192   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
17193           .addMBB(restoreMBB);
17194
17195   const X86RegisterInfo *RegInfo =
17196     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17197   MIB.addRegMask(RegInfo->getNoPreservedMask());
17198   thisMBB->addSuccessor(mainMBB);
17199   thisMBB->addSuccessor(restoreMBB);
17200
17201   // mainMBB:
17202   //  EAX = 0
17203   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
17204   mainMBB->addSuccessor(sinkMBB);
17205
17206   // sinkMBB:
17207   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
17208           TII->get(X86::PHI), DstReg)
17209     .addReg(mainDstReg).addMBB(mainMBB)
17210     .addReg(restoreDstReg).addMBB(restoreMBB);
17211
17212   // restoreMBB:
17213   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
17214   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
17215   restoreMBB->addSuccessor(sinkMBB);
17216
17217   MI->eraseFromParent();
17218   return sinkMBB;
17219 }
17220
17221 MachineBasicBlock *
17222 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
17223                                      MachineBasicBlock *MBB) const {
17224   DebugLoc DL = MI->getDebugLoc();
17225   MachineFunction *MF = MBB->getParent();
17226   const TargetInstrInfo *TII = MF->getTarget().getInstrInfo();
17227   MachineRegisterInfo &MRI = MF->getRegInfo();
17228
17229   // Memory Reference
17230   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
17231   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
17232
17233   MVT PVT = getPointerTy();
17234   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
17235          "Invalid Pointer Size!");
17236
17237   const TargetRegisterClass *RC =
17238     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
17239   unsigned Tmp = MRI.createVirtualRegister(RC);
17240   // Since FP is only updated here but NOT referenced, it's treated as GPR.
17241   const X86RegisterInfo *RegInfo =
17242     static_cast<const X86RegisterInfo*>(MF->getTarget().getRegisterInfo());
17243   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
17244   unsigned SP = RegInfo->getStackRegister();
17245
17246   MachineInstrBuilder MIB;
17247
17248   const int64_t LabelOffset = 1 * PVT.getStoreSize();
17249   const int64_t SPOffset = 2 * PVT.getStoreSize();
17250
17251   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
17252   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
17253
17254   // Reload FP
17255   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
17256   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
17257     MIB.addOperand(MI->getOperand(i));
17258   MIB.setMemRefs(MMOBegin, MMOEnd);
17259   // Reload IP
17260   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
17261   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17262     if (i == X86::AddrDisp)
17263       MIB.addDisp(MI->getOperand(i), LabelOffset);
17264     else
17265       MIB.addOperand(MI->getOperand(i));
17266   }
17267   MIB.setMemRefs(MMOBegin, MMOEnd);
17268   // Reload SP
17269   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
17270   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
17271     if (i == X86::AddrDisp)
17272       MIB.addDisp(MI->getOperand(i), SPOffset);
17273     else
17274       MIB.addOperand(MI->getOperand(i));
17275   }
17276   MIB.setMemRefs(MMOBegin, MMOEnd);
17277   // Jump
17278   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
17279
17280   MI->eraseFromParent();
17281   return MBB;
17282 }
17283
17284 // Replace 213-type (isel default) FMA3 instructions with 231-type for
17285 // accumulator loops. Writing back to the accumulator allows the coalescer
17286 // to remove extra copies in the loop.   
17287 MachineBasicBlock *
17288 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
17289                                  MachineBasicBlock *MBB) const {
17290   MachineOperand &AddendOp = MI->getOperand(3);
17291
17292   // Bail out early if the addend isn't a register - we can't switch these.
17293   if (!AddendOp.isReg())
17294     return MBB;
17295
17296   MachineFunction &MF = *MBB->getParent();
17297   MachineRegisterInfo &MRI = MF.getRegInfo();
17298
17299   // Check whether the addend is defined by a PHI:
17300   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
17301   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
17302   if (!AddendDef.isPHI())
17303     return MBB;
17304
17305   // Look for the following pattern:
17306   // loop:
17307   //   %addend = phi [%entry, 0], [%loop, %result]
17308   //   ...
17309   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
17310
17311   // Replace with:
17312   //   loop:
17313   //   %addend = phi [%entry, 0], [%loop, %result]
17314   //   ...
17315   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
17316
17317   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
17318     assert(AddendDef.getOperand(i).isReg());
17319     MachineOperand PHISrcOp = AddendDef.getOperand(i);
17320     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
17321     if (&PHISrcInst == MI) {
17322       // Found a matching instruction.
17323       unsigned NewFMAOpc = 0;
17324       switch (MI->getOpcode()) {
17325         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
17326         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
17327         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
17328         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
17329         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
17330         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
17331         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
17332         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
17333         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
17334         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
17335         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
17336         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
17337         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
17338         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
17339         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
17340         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
17341         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
17342         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
17343         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
17344         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
17345         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
17346         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
17347         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
17348         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
17349         default: llvm_unreachable("Unrecognized FMA variant.");
17350       }
17351
17352       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
17353       MachineInstrBuilder MIB =
17354         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
17355         .addOperand(MI->getOperand(0))
17356         .addOperand(MI->getOperand(3))
17357         .addOperand(MI->getOperand(2))
17358         .addOperand(MI->getOperand(1));
17359       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
17360       MI->eraseFromParent();
17361     }
17362   }
17363
17364   return MBB;
17365 }
17366
17367 MachineBasicBlock *
17368 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17369                                                MachineBasicBlock *BB) const {
17370   switch (MI->getOpcode()) {
17371   default: llvm_unreachable("Unexpected instr type to insert");
17372   case X86::TAILJMPd64:
17373   case X86::TAILJMPr64:
17374   case X86::TAILJMPm64:
17375     llvm_unreachable("TAILJMP64 would not be touched here.");
17376   case X86::TCRETURNdi64:
17377   case X86::TCRETURNri64:
17378   case X86::TCRETURNmi64:
17379     return BB;
17380   case X86::WIN_ALLOCA:
17381     return EmitLoweredWinAlloca(MI, BB);
17382   case X86::SEG_ALLOCA_32:
17383     return EmitLoweredSegAlloca(MI, BB, false);
17384   case X86::SEG_ALLOCA_64:
17385     return EmitLoweredSegAlloca(MI, BB, true);
17386   case X86::TLSCall_32:
17387   case X86::TLSCall_64:
17388     return EmitLoweredTLSCall(MI, BB);
17389   case X86::CMOV_GR8:
17390   case X86::CMOV_FR32:
17391   case X86::CMOV_FR64:
17392   case X86::CMOV_V4F32:
17393   case X86::CMOV_V2F64:
17394   case X86::CMOV_V2I64:
17395   case X86::CMOV_V8F32:
17396   case X86::CMOV_V4F64:
17397   case X86::CMOV_V4I64:
17398   case X86::CMOV_V16F32:
17399   case X86::CMOV_V8F64:
17400   case X86::CMOV_V8I64:
17401   case X86::CMOV_GR16:
17402   case X86::CMOV_GR32:
17403   case X86::CMOV_RFP32:
17404   case X86::CMOV_RFP64:
17405   case X86::CMOV_RFP80:
17406     return EmitLoweredSelect(MI, BB);
17407
17408   case X86::FP32_TO_INT16_IN_MEM:
17409   case X86::FP32_TO_INT32_IN_MEM:
17410   case X86::FP32_TO_INT64_IN_MEM:
17411   case X86::FP64_TO_INT16_IN_MEM:
17412   case X86::FP64_TO_INT32_IN_MEM:
17413   case X86::FP64_TO_INT64_IN_MEM:
17414   case X86::FP80_TO_INT16_IN_MEM:
17415   case X86::FP80_TO_INT32_IN_MEM:
17416   case X86::FP80_TO_INT64_IN_MEM: {
17417     MachineFunction *F = BB->getParent();
17418     const TargetInstrInfo *TII = F->getTarget().getInstrInfo();
17419     DebugLoc DL = MI->getDebugLoc();
17420
17421     // Change the floating point control register to use "round towards zero"
17422     // mode when truncating to an integer value.
17423     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17424     addFrameReference(BuildMI(*BB, MI, DL,
17425                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17426
17427     // Load the old value of the high byte of the control word...
17428     unsigned OldCW =
17429       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17430     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17431                       CWFrameIdx);
17432
17433     // Set the high part to be round to zero...
17434     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17435       .addImm(0xC7F);
17436
17437     // Reload the modified control word now...
17438     addFrameReference(BuildMI(*BB, MI, DL,
17439                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17440
17441     // Restore the memory image of control word to original value
17442     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17443       .addReg(OldCW);
17444
17445     // Get the X86 opcode to use.
17446     unsigned Opc;
17447     switch (MI->getOpcode()) {
17448     default: llvm_unreachable("illegal opcode!");
17449     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17450     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17451     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17452     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17453     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17454     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17455     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17456     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17457     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17458     }
17459
17460     X86AddressMode AM;
17461     MachineOperand &Op = MI->getOperand(0);
17462     if (Op.isReg()) {
17463       AM.BaseType = X86AddressMode::RegBase;
17464       AM.Base.Reg = Op.getReg();
17465     } else {
17466       AM.BaseType = X86AddressMode::FrameIndexBase;
17467       AM.Base.FrameIndex = Op.getIndex();
17468     }
17469     Op = MI->getOperand(1);
17470     if (Op.isImm())
17471       AM.Scale = Op.getImm();
17472     Op = MI->getOperand(2);
17473     if (Op.isImm())
17474       AM.IndexReg = Op.getImm();
17475     Op = MI->getOperand(3);
17476     if (Op.isGlobal()) {
17477       AM.GV = Op.getGlobal();
17478     } else {
17479       AM.Disp = Op.getImm();
17480     }
17481     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17482                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17483
17484     // Reload the original control word now.
17485     addFrameReference(BuildMI(*BB, MI, DL,
17486                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17487
17488     MI->eraseFromParent();   // The pseudo instruction is gone now.
17489     return BB;
17490   }
17491     // String/text processing lowering.
17492   case X86::PCMPISTRM128REG:
17493   case X86::VPCMPISTRM128REG:
17494   case X86::PCMPISTRM128MEM:
17495   case X86::VPCMPISTRM128MEM:
17496   case X86::PCMPESTRM128REG:
17497   case X86::VPCMPESTRM128REG:
17498   case X86::PCMPESTRM128MEM:
17499   case X86::VPCMPESTRM128MEM:
17500     assert(Subtarget->hasSSE42() &&
17501            "Target must have SSE4.2 or AVX features enabled");
17502     return EmitPCMPSTRM(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17503
17504   // String/text processing lowering.
17505   case X86::PCMPISTRIREG:
17506   case X86::VPCMPISTRIREG:
17507   case X86::PCMPISTRIMEM:
17508   case X86::VPCMPISTRIMEM:
17509   case X86::PCMPESTRIREG:
17510   case X86::VPCMPESTRIREG:
17511   case X86::PCMPESTRIMEM:
17512   case X86::VPCMPESTRIMEM:
17513     assert(Subtarget->hasSSE42() &&
17514            "Target must have SSE4.2 or AVX features enabled");
17515     return EmitPCMPSTRI(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17516
17517   // Thread synchronization.
17518   case X86::MONITOR:
17519     return EmitMonitor(MI, BB, BB->getParent()->getTarget().getInstrInfo(), Subtarget);
17520
17521   // xbegin
17522   case X86::XBEGIN:
17523     return EmitXBegin(MI, BB, BB->getParent()->getTarget().getInstrInfo());
17524
17525   // Atomic Lowering.
17526   case X86::ATOMAND8:
17527   case X86::ATOMAND16:
17528   case X86::ATOMAND32:
17529   case X86::ATOMAND64:
17530     // Fall through
17531   case X86::ATOMOR8:
17532   case X86::ATOMOR16:
17533   case X86::ATOMOR32:
17534   case X86::ATOMOR64:
17535     // Fall through
17536   case X86::ATOMXOR16:
17537   case X86::ATOMXOR8:
17538   case X86::ATOMXOR32:
17539   case X86::ATOMXOR64:
17540     // Fall through
17541   case X86::ATOMNAND8:
17542   case X86::ATOMNAND16:
17543   case X86::ATOMNAND32:
17544   case X86::ATOMNAND64:
17545     // Fall through
17546   case X86::ATOMMAX8:
17547   case X86::ATOMMAX16:
17548   case X86::ATOMMAX32:
17549   case X86::ATOMMAX64:
17550     // Fall through
17551   case X86::ATOMMIN8:
17552   case X86::ATOMMIN16:
17553   case X86::ATOMMIN32:
17554   case X86::ATOMMIN64:
17555     // Fall through
17556   case X86::ATOMUMAX8:
17557   case X86::ATOMUMAX16:
17558   case X86::ATOMUMAX32:
17559   case X86::ATOMUMAX64:
17560     // Fall through
17561   case X86::ATOMUMIN8:
17562   case X86::ATOMUMIN16:
17563   case X86::ATOMUMIN32:
17564   case X86::ATOMUMIN64:
17565     return EmitAtomicLoadArith(MI, BB);
17566
17567   // This group does 64-bit operations on a 32-bit host.
17568   case X86::ATOMAND6432:
17569   case X86::ATOMOR6432:
17570   case X86::ATOMXOR6432:
17571   case X86::ATOMNAND6432:
17572   case X86::ATOMADD6432:
17573   case X86::ATOMSUB6432:
17574   case X86::ATOMMAX6432:
17575   case X86::ATOMMIN6432:
17576   case X86::ATOMUMAX6432:
17577   case X86::ATOMUMIN6432:
17578   case X86::ATOMSWAP6432:
17579     return EmitAtomicLoadArith6432(MI, BB);
17580
17581   case X86::VASTART_SAVE_XMM_REGS:
17582     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17583
17584   case X86::VAARG_64:
17585     return EmitVAARG64WithCustomInserter(MI, BB);
17586
17587   case X86::EH_SjLj_SetJmp32:
17588   case X86::EH_SjLj_SetJmp64:
17589     return emitEHSjLjSetJmp(MI, BB);
17590
17591   case X86::EH_SjLj_LongJmp32:
17592   case X86::EH_SjLj_LongJmp64:
17593     return emitEHSjLjLongJmp(MI, BB);
17594
17595   case TargetOpcode::STACKMAP:
17596   case TargetOpcode::PATCHPOINT:
17597     return emitPatchPoint(MI, BB);
17598
17599   case X86::VFMADDPDr213r:
17600   case X86::VFMADDPSr213r:
17601   case X86::VFMADDSDr213r:
17602   case X86::VFMADDSSr213r:
17603   case X86::VFMSUBPDr213r:
17604   case X86::VFMSUBPSr213r:
17605   case X86::VFMSUBSDr213r:
17606   case X86::VFMSUBSSr213r:
17607   case X86::VFNMADDPDr213r:
17608   case X86::VFNMADDPSr213r:
17609   case X86::VFNMADDSDr213r:
17610   case X86::VFNMADDSSr213r:
17611   case X86::VFNMSUBPDr213r:
17612   case X86::VFNMSUBPSr213r:
17613   case X86::VFNMSUBSDr213r:
17614   case X86::VFNMSUBSSr213r:
17615   case X86::VFMADDPDr213rY:
17616   case X86::VFMADDPSr213rY:
17617   case X86::VFMSUBPDr213rY:
17618   case X86::VFMSUBPSr213rY:
17619   case X86::VFNMADDPDr213rY:
17620   case X86::VFNMADDPSr213rY:
17621   case X86::VFNMSUBPDr213rY:
17622   case X86::VFNMSUBPSr213rY:
17623     return emitFMA3Instr(MI, BB);
17624   }
17625 }
17626
17627 //===----------------------------------------------------------------------===//
17628 //                           X86 Optimization Hooks
17629 //===----------------------------------------------------------------------===//
17630
17631 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17632                                                       APInt &KnownZero,
17633                                                       APInt &KnownOne,
17634                                                       const SelectionDAG &DAG,
17635                                                       unsigned Depth) const {
17636   unsigned BitWidth = KnownZero.getBitWidth();
17637   unsigned Opc = Op.getOpcode();
17638   assert((Opc >= ISD::BUILTIN_OP_END ||
17639           Opc == ISD::INTRINSIC_WO_CHAIN ||
17640           Opc == ISD::INTRINSIC_W_CHAIN ||
17641           Opc == ISD::INTRINSIC_VOID) &&
17642          "Should use MaskedValueIsZero if you don't know whether Op"
17643          " is a target node!");
17644
17645   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17646   switch (Opc) {
17647   default: break;
17648   case X86ISD::ADD:
17649   case X86ISD::SUB:
17650   case X86ISD::ADC:
17651   case X86ISD::SBB:
17652   case X86ISD::SMUL:
17653   case X86ISD::UMUL:
17654   case X86ISD::INC:
17655   case X86ISD::DEC:
17656   case X86ISD::OR:
17657   case X86ISD::XOR:
17658   case X86ISD::AND:
17659     // These nodes' second result is a boolean.
17660     if (Op.getResNo() == 0)
17661       break;
17662     // Fallthrough
17663   case X86ISD::SETCC:
17664     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17665     break;
17666   case ISD::INTRINSIC_WO_CHAIN: {
17667     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17668     unsigned NumLoBits = 0;
17669     switch (IntId) {
17670     default: break;
17671     case Intrinsic::x86_sse_movmsk_ps:
17672     case Intrinsic::x86_avx_movmsk_ps_256:
17673     case Intrinsic::x86_sse2_movmsk_pd:
17674     case Intrinsic::x86_avx_movmsk_pd_256:
17675     case Intrinsic::x86_mmx_pmovmskb:
17676     case Intrinsic::x86_sse2_pmovmskb_128:
17677     case Intrinsic::x86_avx2_pmovmskb: {
17678       // High bits of movmskp{s|d}, pmovmskb are known zero.
17679       switch (IntId) {
17680         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17681         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17682         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17683         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17684         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17685         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17686         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17687         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17688       }
17689       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17690       break;
17691     }
17692     }
17693     break;
17694   }
17695   }
17696 }
17697
17698 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17699   SDValue Op,
17700   const SelectionDAG &,
17701   unsigned Depth) const {
17702   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17703   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17704     return Op.getValueType().getScalarType().getSizeInBits();
17705
17706   // Fallback case.
17707   return 1;
17708 }
17709
17710 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17711 /// node is a GlobalAddress + offset.
17712 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17713                                        const GlobalValue* &GA,
17714                                        int64_t &Offset) const {
17715   if (N->getOpcode() == X86ISD::Wrapper) {
17716     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17717       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17718       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17719       return true;
17720     }
17721   }
17722   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17723 }
17724
17725 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17726 /// same as extracting the high 128-bit part of 256-bit vector and then
17727 /// inserting the result into the low part of a new 256-bit vector
17728 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17729   EVT VT = SVOp->getValueType(0);
17730   unsigned NumElems = VT.getVectorNumElements();
17731
17732   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17733   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17734     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17735         SVOp->getMaskElt(j) >= 0)
17736       return false;
17737
17738   return true;
17739 }
17740
17741 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17742 /// same as extracting the low 128-bit part of 256-bit vector and then
17743 /// inserting the result into the high part of a new 256-bit vector
17744 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17745   EVT VT = SVOp->getValueType(0);
17746   unsigned NumElems = VT.getVectorNumElements();
17747
17748   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17749   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17750     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17751         SVOp->getMaskElt(j) >= 0)
17752       return false;
17753
17754   return true;
17755 }
17756
17757 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17758 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17759                                         TargetLowering::DAGCombinerInfo &DCI,
17760                                         const X86Subtarget* Subtarget) {
17761   SDLoc dl(N);
17762   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17763   SDValue V1 = SVOp->getOperand(0);
17764   SDValue V2 = SVOp->getOperand(1);
17765   EVT VT = SVOp->getValueType(0);
17766   unsigned NumElems = VT.getVectorNumElements();
17767
17768   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17769       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17770     //
17771     //                   0,0,0,...
17772     //                      |
17773     //    V      UNDEF    BUILD_VECTOR    UNDEF
17774     //     \      /           \           /
17775     //  CONCAT_VECTOR         CONCAT_VECTOR
17776     //         \                  /
17777     //          \                /
17778     //          RESULT: V + zero extended
17779     //
17780     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17781         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17782         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17783       return SDValue();
17784
17785     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17786       return SDValue();
17787
17788     // To match the shuffle mask, the first half of the mask should
17789     // be exactly the first vector, and all the rest a splat with the
17790     // first element of the second one.
17791     for (unsigned i = 0; i != NumElems/2; ++i)
17792       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17793           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17794         return SDValue();
17795
17796     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17797     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17798       if (Ld->hasNUsesOfValue(1, 0)) {
17799         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17800         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17801         SDValue ResNode =
17802           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17803                                   Ld->getMemoryVT(),
17804                                   Ld->getPointerInfo(),
17805                                   Ld->getAlignment(),
17806                                   false/*isVolatile*/, true/*ReadMem*/,
17807                                   false/*WriteMem*/);
17808
17809         // Make sure the newly-created LOAD is in the same position as Ld in
17810         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17811         // and update uses of Ld's output chain to use the TokenFactor.
17812         if (Ld->hasAnyUseOfValue(1)) {
17813           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17814                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17815           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17816           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17817                                  SDValue(ResNode.getNode(), 1));
17818         }
17819
17820         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17821       }
17822     }
17823
17824     // Emit a zeroed vector and insert the desired subvector on its
17825     // first half.
17826     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17827     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17828     return DCI.CombineTo(N, InsV);
17829   }
17830
17831   //===--------------------------------------------------------------------===//
17832   // Combine some shuffles into subvector extracts and inserts:
17833   //
17834
17835   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17836   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17837     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17838     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17839     return DCI.CombineTo(N, InsV);
17840   }
17841
17842   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17843   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17844     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17845     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17846     return DCI.CombineTo(N, InsV);
17847   }
17848
17849   return SDValue();
17850 }
17851
17852 /// PerformShuffleCombine - Performs several different shuffle combines.
17853 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17854                                      TargetLowering::DAGCombinerInfo &DCI,
17855                                      const X86Subtarget *Subtarget) {
17856   SDLoc dl(N);
17857   SDValue N0 = N->getOperand(0);
17858   SDValue N1 = N->getOperand(1);
17859   EVT VT = N->getValueType(0);
17860
17861   // Don't create instructions with illegal types after legalize types has run.
17862   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17863   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17864     return SDValue();
17865
17866   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17867   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17868       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17869     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17870
17871   // During Type Legalization, when promoting illegal vector types,
17872   // the backend might introduce new shuffle dag nodes and bitcasts.
17873   //
17874   // This code performs the following transformation:
17875   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17876   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17877   //
17878   // We do this only if both the bitcast and the BINOP dag nodes have
17879   // one use. Also, perform this transformation only if the new binary
17880   // operation is legal. This is to avoid introducing dag nodes that
17881   // potentially need to be further expanded (or custom lowered) into a
17882   // less optimal sequence of dag nodes.
17883   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17884       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17885       N0.getOpcode() == ISD::BITCAST) {
17886     SDValue BC0 = N0.getOperand(0);
17887     EVT SVT = BC0.getValueType();
17888     unsigned Opcode = BC0.getOpcode();
17889     unsigned NumElts = VT.getVectorNumElements();
17890     
17891     if (BC0.hasOneUse() && SVT.isVector() &&
17892         SVT.getVectorNumElements() * 2 == NumElts &&
17893         TLI.isOperationLegal(Opcode, VT)) {
17894       bool CanFold = false;
17895       switch (Opcode) {
17896       default : break;
17897       case ISD::ADD :
17898       case ISD::FADD :
17899       case ISD::SUB :
17900       case ISD::FSUB :
17901       case ISD::MUL :
17902       case ISD::FMUL :
17903         CanFold = true;
17904       }
17905
17906       unsigned SVTNumElts = SVT.getVectorNumElements();
17907       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17908       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17909         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17910       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17911         CanFold = SVOp->getMaskElt(i) < 0;
17912
17913       if (CanFold) {
17914         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17915         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17916         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17917         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17918       }
17919     }
17920   }
17921
17922   // Only handle 128 wide vector from here on.
17923   if (!VT.is128BitVector())
17924     return SDValue();
17925
17926   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17927   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17928   // consecutive, non-overlapping, and in the right order.
17929   SmallVector<SDValue, 16> Elts;
17930   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17931     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17932
17933   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17934 }
17935
17936 /// PerformTruncateCombine - Converts truncate operation to
17937 /// a sequence of vector shuffle operations.
17938 /// It is possible when we truncate 256-bit vector to 128-bit vector
17939 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17940                                       TargetLowering::DAGCombinerInfo &DCI,
17941                                       const X86Subtarget *Subtarget)  {
17942   return SDValue();
17943 }
17944
17945 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17946 /// specific shuffle of a load can be folded into a single element load.
17947 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17948 /// shuffles have been customed lowered so we need to handle those here.
17949 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17950                                          TargetLowering::DAGCombinerInfo &DCI) {
17951   if (DCI.isBeforeLegalizeOps())
17952     return SDValue();
17953
17954   SDValue InVec = N->getOperand(0);
17955   SDValue EltNo = N->getOperand(1);
17956
17957   if (!isa<ConstantSDNode>(EltNo))
17958     return SDValue();
17959
17960   EVT VT = InVec.getValueType();
17961
17962   bool HasShuffleIntoBitcast = false;
17963   if (InVec.getOpcode() == ISD::BITCAST) {
17964     // Don't duplicate a load with other uses.
17965     if (!InVec.hasOneUse())
17966       return SDValue();
17967     EVT BCVT = InVec.getOperand(0).getValueType();
17968     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17969       return SDValue();
17970     InVec = InVec.getOperand(0);
17971     HasShuffleIntoBitcast = true;
17972   }
17973
17974   if (!isTargetShuffle(InVec.getOpcode()))
17975     return SDValue();
17976
17977   // Don't duplicate a load with other uses.
17978   if (!InVec.hasOneUse())
17979     return SDValue();
17980
17981   SmallVector<int, 16> ShuffleMask;
17982   bool UnaryShuffle;
17983   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17984                             UnaryShuffle))
17985     return SDValue();
17986
17987   // Select the input vector, guarding against out of range extract vector.
17988   unsigned NumElems = VT.getVectorNumElements();
17989   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17990   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17991   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17992                                          : InVec.getOperand(1);
17993
17994   // If inputs to shuffle are the same for both ops, then allow 2 uses
17995   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17996
17997   if (LdNode.getOpcode() == ISD::BITCAST) {
17998     // Don't duplicate a load with other uses.
17999     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
18000       return SDValue();
18001
18002     AllowedUses = 1; // only allow 1 load use if we have a bitcast
18003     LdNode = LdNode.getOperand(0);
18004   }
18005
18006   if (!ISD::isNormalLoad(LdNode.getNode()))
18007     return SDValue();
18008
18009   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
18010
18011   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
18012     return SDValue();
18013
18014   if (HasShuffleIntoBitcast) {
18015     // If there's a bitcast before the shuffle, check if the load type and
18016     // alignment is valid.
18017     unsigned Align = LN0->getAlignment();
18018     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18019     unsigned NewAlign = TLI.getDataLayout()->
18020       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
18021
18022     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
18023       return SDValue();
18024   }
18025
18026   // All checks match so transform back to vector_shuffle so that DAG combiner
18027   // can finish the job
18028   SDLoc dl(N);
18029
18030   // Create shuffle node taking into account the case that its a unary shuffle
18031   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
18032   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
18033                                  InVec.getOperand(0), Shuffle,
18034                                  &ShuffleMask[0]);
18035   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
18036   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
18037                      EltNo);
18038 }
18039
18040 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
18041 /// generation and convert it from being a bunch of shuffles and extracts
18042 /// to a simple store and scalar loads to extract the elements.
18043 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
18044                                          TargetLowering::DAGCombinerInfo &DCI) {
18045   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
18046   if (NewOp.getNode())
18047     return NewOp;
18048
18049   SDValue InputVector = N->getOperand(0);
18050
18051   // Detect whether we are trying to convert from mmx to i32 and the bitcast
18052   // from mmx to v2i32 has a single usage.
18053   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
18054       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
18055       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
18056     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
18057                        N->getValueType(0),
18058                        InputVector.getNode()->getOperand(0));
18059
18060   // Only operate on vectors of 4 elements, where the alternative shuffling
18061   // gets to be more expensive.
18062   if (InputVector.getValueType() != MVT::v4i32)
18063     return SDValue();
18064
18065   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
18066   // single use which is a sign-extend or zero-extend, and all elements are
18067   // used.
18068   SmallVector<SDNode *, 4> Uses;
18069   unsigned ExtractedElements = 0;
18070   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
18071        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
18072     if (UI.getUse().getResNo() != InputVector.getResNo())
18073       return SDValue();
18074
18075     SDNode *Extract = *UI;
18076     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
18077       return SDValue();
18078
18079     if (Extract->getValueType(0) != MVT::i32)
18080       return SDValue();
18081     if (!Extract->hasOneUse())
18082       return SDValue();
18083     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
18084         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
18085       return SDValue();
18086     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
18087       return SDValue();
18088
18089     // Record which element was extracted.
18090     ExtractedElements |=
18091       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
18092
18093     Uses.push_back(Extract);
18094   }
18095
18096   // If not all the elements were used, this may not be worthwhile.
18097   if (ExtractedElements != 15)
18098     return SDValue();
18099
18100   // Ok, we've now decided to do the transformation.
18101   SDLoc dl(InputVector);
18102
18103   // Store the value to a temporary stack slot.
18104   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
18105   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
18106                             MachinePointerInfo(), false, false, 0);
18107
18108   // Replace each use (extract) with a load of the appropriate element.
18109   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
18110        UE = Uses.end(); UI != UE; ++UI) {
18111     SDNode *Extract = *UI;
18112
18113     // cOMpute the element's address.
18114     SDValue Idx = Extract->getOperand(1);
18115     unsigned EltSize =
18116         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
18117     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
18118     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18119     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
18120
18121     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
18122                                      StackPtr, OffsetVal);
18123
18124     // Load the scalar.
18125     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
18126                                      ScalarAddr, MachinePointerInfo(),
18127                                      false, false, false, 0);
18128
18129     // Replace the exact with the load.
18130     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
18131   }
18132
18133   // The replacement was made in place; don't return anything.
18134   return SDValue();
18135 }
18136
18137 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
18138 static std::pair<unsigned, bool>
18139 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
18140                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
18141   if (!VT.isVector())
18142     return std::make_pair(0, false);
18143
18144   bool NeedSplit = false;
18145   switch (VT.getSimpleVT().SimpleTy) {
18146   default: return std::make_pair(0, false);
18147   case MVT::v32i8:
18148   case MVT::v16i16:
18149   case MVT::v8i32:
18150     if (!Subtarget->hasAVX2())
18151       NeedSplit = true;
18152     if (!Subtarget->hasAVX())
18153       return std::make_pair(0, false);
18154     break;
18155   case MVT::v16i8:
18156   case MVT::v8i16:
18157   case MVT::v4i32:
18158     if (!Subtarget->hasSSE2())
18159       return std::make_pair(0, false);
18160   }
18161
18162   // SSE2 has only a small subset of the operations.
18163   bool hasUnsigned = Subtarget->hasSSE41() ||
18164                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
18165   bool hasSigned = Subtarget->hasSSE41() ||
18166                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
18167
18168   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18169
18170   unsigned Opc = 0;
18171   // Check for x CC y ? x : y.
18172   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18173       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18174     switch (CC) {
18175     default: break;
18176     case ISD::SETULT:
18177     case ISD::SETULE:
18178       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18179     case ISD::SETUGT:
18180     case ISD::SETUGE:
18181       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18182     case ISD::SETLT:
18183     case ISD::SETLE:
18184       Opc = hasSigned ? X86ISD::SMIN : 0; break;
18185     case ISD::SETGT:
18186     case ISD::SETGE:
18187       Opc = hasSigned ? X86ISD::SMAX : 0; break;
18188     }
18189   // Check for x CC y ? y : x -- a min/max with reversed arms.
18190   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18191              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18192     switch (CC) {
18193     default: break;
18194     case ISD::SETULT:
18195     case ISD::SETULE:
18196       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
18197     case ISD::SETUGT:
18198     case ISD::SETUGE:
18199       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
18200     case ISD::SETLT:
18201     case ISD::SETLE:
18202       Opc = hasSigned ? X86ISD::SMAX : 0; break;
18203     case ISD::SETGT:
18204     case ISD::SETGE:
18205       Opc = hasSigned ? X86ISD::SMIN : 0; break;
18206     }
18207   }
18208
18209   return std::make_pair(Opc, NeedSplit);
18210 }
18211
18212 static SDValue
18213 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
18214                                       const X86Subtarget *Subtarget) {
18215   SDLoc dl(N);
18216   SDValue Cond = N->getOperand(0);
18217   SDValue LHS = N->getOperand(1);
18218   SDValue RHS = N->getOperand(2);
18219
18220   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
18221     SDValue CondSrc = Cond->getOperand(0);
18222     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
18223       Cond = CondSrc->getOperand(0);
18224   }
18225
18226   MVT VT = N->getSimpleValueType(0);
18227   MVT EltVT = VT.getVectorElementType();
18228   unsigned NumElems = VT.getVectorNumElements();
18229   // There is no blend with immediate in AVX-512.
18230   if (VT.is512BitVector())
18231     return SDValue();
18232
18233   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
18234     return SDValue();
18235   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
18236     return SDValue();
18237
18238   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
18239     return SDValue();
18240
18241   unsigned MaskValue = 0;
18242   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
18243     return SDValue();
18244
18245   SmallVector<int, 8> ShuffleMask(NumElems, -1);
18246   for (unsigned i = 0; i < NumElems; ++i) {
18247     // Be sure we emit undef where we can.
18248     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
18249       ShuffleMask[i] = -1;
18250     else
18251       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
18252   }
18253
18254   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
18255 }
18256
18257 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
18258 /// nodes.
18259 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
18260                                     TargetLowering::DAGCombinerInfo &DCI,
18261                                     const X86Subtarget *Subtarget) {
18262   SDLoc DL(N);
18263   SDValue Cond = N->getOperand(0);
18264   // Get the LHS/RHS of the select.
18265   SDValue LHS = N->getOperand(1);
18266   SDValue RHS = N->getOperand(2);
18267   EVT VT = LHS.getValueType();
18268   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18269
18270   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
18271   // instructions match the semantics of the common C idiom x<y?x:y but not
18272   // x<=y?x:y, because of how they handle negative zero (which can be
18273   // ignored in unsafe-math mode).
18274   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
18275       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
18276       (Subtarget->hasSSE2() ||
18277        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
18278     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18279
18280     unsigned Opcode = 0;
18281     // Check for x CC y ? x : y.
18282     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18283         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18284       switch (CC) {
18285       default: break;
18286       case ISD::SETULT:
18287         // Converting this to a min would handle NaNs incorrectly, and swapping
18288         // the operands would cause it to handle comparisons between positive
18289         // and negative zero incorrectly.
18290         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18291           if (!DAG.getTarget().Options.UnsafeFPMath &&
18292               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18293             break;
18294           std::swap(LHS, RHS);
18295         }
18296         Opcode = X86ISD::FMIN;
18297         break;
18298       case ISD::SETOLE:
18299         // Converting this to a min would handle comparisons between positive
18300         // and negative zero incorrectly.
18301         if (!DAG.getTarget().Options.UnsafeFPMath &&
18302             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18303           break;
18304         Opcode = X86ISD::FMIN;
18305         break;
18306       case ISD::SETULE:
18307         // Converting this to a min would handle both negative zeros and NaNs
18308         // incorrectly, but we can swap the operands to fix both.
18309         std::swap(LHS, RHS);
18310       case ISD::SETOLT:
18311       case ISD::SETLT:
18312       case ISD::SETLE:
18313         Opcode = X86ISD::FMIN;
18314         break;
18315
18316       case ISD::SETOGE:
18317         // Converting this to a max would handle comparisons between positive
18318         // and negative zero incorrectly.
18319         if (!DAG.getTarget().Options.UnsafeFPMath &&
18320             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
18321           break;
18322         Opcode = X86ISD::FMAX;
18323         break;
18324       case ISD::SETUGT:
18325         // Converting this to a max would handle NaNs incorrectly, and swapping
18326         // the operands would cause it to handle comparisons between positive
18327         // and negative zero incorrectly.
18328         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
18329           if (!DAG.getTarget().Options.UnsafeFPMath &&
18330               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
18331             break;
18332           std::swap(LHS, RHS);
18333         }
18334         Opcode = X86ISD::FMAX;
18335         break;
18336       case ISD::SETUGE:
18337         // Converting this to a max would handle both negative zeros and NaNs
18338         // incorrectly, but we can swap the operands to fix both.
18339         std::swap(LHS, RHS);
18340       case ISD::SETOGT:
18341       case ISD::SETGT:
18342       case ISD::SETGE:
18343         Opcode = X86ISD::FMAX;
18344         break;
18345       }
18346     // Check for x CC y ? y : x -- a min/max with reversed arms.
18347     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
18348                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
18349       switch (CC) {
18350       default: break;
18351       case ISD::SETOGE:
18352         // Converting this to a min would handle comparisons between positive
18353         // and negative zero incorrectly, and swapping the operands would
18354         // cause it to handle NaNs incorrectly.
18355         if (!DAG.getTarget().Options.UnsafeFPMath &&
18356             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
18357           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18358             break;
18359           std::swap(LHS, RHS);
18360         }
18361         Opcode = X86ISD::FMIN;
18362         break;
18363       case ISD::SETUGT:
18364         // Converting this to a min would handle NaNs incorrectly.
18365         if (!DAG.getTarget().Options.UnsafeFPMath &&
18366             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18367           break;
18368         Opcode = X86ISD::FMIN;
18369         break;
18370       case ISD::SETUGE:
18371         // Converting this to a min would handle both negative zeros and NaNs
18372         // incorrectly, but we can swap the operands to fix both.
18373         std::swap(LHS, RHS);
18374       case ISD::SETOGT:
18375       case ISD::SETGT:
18376       case ISD::SETGE:
18377         Opcode = X86ISD::FMIN;
18378         break;
18379
18380       case ISD::SETULT:
18381         // Converting this to a max would handle NaNs incorrectly.
18382         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18383           break;
18384         Opcode = X86ISD::FMAX;
18385         break;
18386       case ISD::SETOLE:
18387         // Converting this to a max would handle comparisons between positive
18388         // and negative zero incorrectly, and swapping the operands would
18389         // cause it to handle NaNs incorrectly.
18390         if (!DAG.getTarget().Options.UnsafeFPMath &&
18391             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18392           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18393             break;
18394           std::swap(LHS, RHS);
18395         }
18396         Opcode = X86ISD::FMAX;
18397         break;
18398       case ISD::SETULE:
18399         // Converting this to a max would handle both negative zeros and NaNs
18400         // incorrectly, but we can swap the operands to fix both.
18401         std::swap(LHS, RHS);
18402       case ISD::SETOLT:
18403       case ISD::SETLT:
18404       case ISD::SETLE:
18405         Opcode = X86ISD::FMAX;
18406         break;
18407       }
18408     }
18409
18410     if (Opcode)
18411       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18412   }
18413
18414   EVT CondVT = Cond.getValueType();
18415   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18416       CondVT.getVectorElementType() == MVT::i1) {
18417     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18418     // lowering on AVX-512. In this case we convert it to
18419     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18420     // The same situation for all 128 and 256-bit vectors of i8 and i16
18421     EVT OpVT = LHS.getValueType();
18422     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18423         (OpVT.getVectorElementType() == MVT::i8 ||
18424          OpVT.getVectorElementType() == MVT::i16)) {
18425       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18426       DCI.AddToWorklist(Cond.getNode());
18427       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18428     }
18429   }
18430   // If this is a select between two integer constants, try to do some
18431   // optimizations.
18432   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18433     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18434       // Don't do this for crazy integer types.
18435       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18436         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18437         // so that TrueC (the true value) is larger than FalseC.
18438         bool NeedsCondInvert = false;
18439
18440         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18441             // Efficiently invertible.
18442             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18443              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18444               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18445           NeedsCondInvert = true;
18446           std::swap(TrueC, FalseC);
18447         }
18448
18449         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18450         if (FalseC->getAPIntValue() == 0 &&
18451             TrueC->getAPIntValue().isPowerOf2()) {
18452           if (NeedsCondInvert) // Invert the condition if needed.
18453             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18454                                DAG.getConstant(1, Cond.getValueType()));
18455
18456           // Zero extend the condition if needed.
18457           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18458
18459           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18460           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18461                              DAG.getConstant(ShAmt, MVT::i8));
18462         }
18463
18464         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18465         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18466           if (NeedsCondInvert) // Invert the condition if needed.
18467             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18468                                DAG.getConstant(1, Cond.getValueType()));
18469
18470           // Zero extend the condition if needed.
18471           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18472                              FalseC->getValueType(0), Cond);
18473           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18474                              SDValue(FalseC, 0));
18475         }
18476
18477         // Optimize cases that will turn into an LEA instruction.  This requires
18478         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18479         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18480           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18481           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18482
18483           bool isFastMultiplier = false;
18484           if (Diff < 10) {
18485             switch ((unsigned char)Diff) {
18486               default: break;
18487               case 1:  // result = add base, cond
18488               case 2:  // result = lea base(    , cond*2)
18489               case 3:  // result = lea base(cond, cond*2)
18490               case 4:  // result = lea base(    , cond*4)
18491               case 5:  // result = lea base(cond, cond*4)
18492               case 8:  // result = lea base(    , cond*8)
18493               case 9:  // result = lea base(cond, cond*8)
18494                 isFastMultiplier = true;
18495                 break;
18496             }
18497           }
18498
18499           if (isFastMultiplier) {
18500             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18501             if (NeedsCondInvert) // Invert the condition if needed.
18502               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18503                                  DAG.getConstant(1, Cond.getValueType()));
18504
18505             // Zero extend the condition if needed.
18506             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18507                                Cond);
18508             // Scale the condition by the difference.
18509             if (Diff != 1)
18510               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18511                                  DAG.getConstant(Diff, Cond.getValueType()));
18512
18513             // Add the base if non-zero.
18514             if (FalseC->getAPIntValue() != 0)
18515               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18516                                  SDValue(FalseC, 0));
18517             return Cond;
18518           }
18519         }
18520       }
18521   }
18522
18523   // Canonicalize max and min:
18524   // (x > y) ? x : y -> (x >= y) ? x : y
18525   // (x < y) ? x : y -> (x <= y) ? x : y
18526   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18527   // the need for an extra compare
18528   // against zero. e.g.
18529   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18530   // subl   %esi, %edi
18531   // testl  %edi, %edi
18532   // movl   $0, %eax
18533   // cmovgl %edi, %eax
18534   // =>
18535   // xorl   %eax, %eax
18536   // subl   %esi, $edi
18537   // cmovsl %eax, %edi
18538   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18539       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18540       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18541     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18542     switch (CC) {
18543     default: break;
18544     case ISD::SETLT:
18545     case ISD::SETGT: {
18546       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18547       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18548                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18549       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18550     }
18551     }
18552   }
18553
18554   // Early exit check
18555   if (!TLI.isTypeLegal(VT))
18556     return SDValue();
18557
18558   // Match VSELECTs into subs with unsigned saturation.
18559   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18560       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18561       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18562        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18563     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18564
18565     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18566     // left side invert the predicate to simplify logic below.
18567     SDValue Other;
18568     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18569       Other = RHS;
18570       CC = ISD::getSetCCInverse(CC, true);
18571     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18572       Other = LHS;
18573     }
18574
18575     if (Other.getNode() && Other->getNumOperands() == 2 &&
18576         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18577       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18578       SDValue CondRHS = Cond->getOperand(1);
18579
18580       // Look for a general sub with unsigned saturation first.
18581       // x >= y ? x-y : 0 --> subus x, y
18582       // x >  y ? x-y : 0 --> subus x, y
18583       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18584           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18585         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18586
18587       // If the RHS is a constant we have to reverse the const canonicalization.
18588       // x > C-1 ? x+-C : 0 --> subus x, C
18589       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18590           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18591         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18592         if (CondRHS.getConstantOperandVal(0) == -A-1)
18593           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18594                              DAG.getConstant(-A, VT));
18595       }
18596
18597       // Another special case: If C was a sign bit, the sub has been
18598       // canonicalized into a xor.
18599       // FIXME: Would it be better to use computeKnownBits to determine whether
18600       //        it's safe to decanonicalize the xor?
18601       // x s< 0 ? x^C : 0 --> subus x, C
18602       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18603           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18604           isSplatVector(OpRHS.getNode())) {
18605         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18606         if (A.isSignBit())
18607           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18608       }
18609     }
18610   }
18611
18612   // Try to match a min/max vector operation.
18613   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18614     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18615     unsigned Opc = ret.first;
18616     bool NeedSplit = ret.second;
18617
18618     if (Opc && NeedSplit) {
18619       unsigned NumElems = VT.getVectorNumElements();
18620       // Extract the LHS vectors
18621       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18622       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18623
18624       // Extract the RHS vectors
18625       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18626       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18627
18628       // Create min/max for each subvector
18629       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18630       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18631
18632       // Merge the result
18633       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18634     } else if (Opc)
18635       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18636   }
18637
18638   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18639   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18640       // Check if SETCC has already been promoted
18641       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18642       // Check that condition value type matches vselect operand type
18643       CondVT == VT) { 
18644
18645     assert(Cond.getValueType().isVector() &&
18646            "vector select expects a vector selector!");
18647
18648     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18649     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18650
18651     if (!TValIsAllOnes && !FValIsAllZeros) {
18652       // Try invert the condition if true value is not all 1s and false value
18653       // is not all 0s.
18654       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18655       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18656
18657       if (TValIsAllZeros || FValIsAllOnes) {
18658         SDValue CC = Cond.getOperand(2);
18659         ISD::CondCode NewCC =
18660           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18661                                Cond.getOperand(0).getValueType().isInteger());
18662         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18663         std::swap(LHS, RHS);
18664         TValIsAllOnes = FValIsAllOnes;
18665         FValIsAllZeros = TValIsAllZeros;
18666       }
18667     }
18668
18669     if (TValIsAllOnes || FValIsAllZeros) {
18670       SDValue Ret;
18671
18672       if (TValIsAllOnes && FValIsAllZeros)
18673         Ret = Cond;
18674       else if (TValIsAllOnes)
18675         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18676                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18677       else if (FValIsAllZeros)
18678         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18679                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18680
18681       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18682     }
18683   }
18684
18685   // Try to fold this VSELECT into a MOVSS/MOVSD
18686   if (N->getOpcode() == ISD::VSELECT &&
18687       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18688     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18689         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18690       bool CanFold = false;
18691       unsigned NumElems = Cond.getNumOperands();
18692       SDValue A = LHS;
18693       SDValue B = RHS;
18694       
18695       if (isZero(Cond.getOperand(0))) {
18696         CanFold = true;
18697
18698         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18699         // fold (vselect <0,-1> -> (movsd A, B)
18700         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18701           CanFold = isAllOnes(Cond.getOperand(i));
18702       } else if (isAllOnes(Cond.getOperand(0))) {
18703         CanFold = true;
18704         std::swap(A, B);
18705
18706         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18707         // fold (vselect <-1,0> -> (movsd B, A)
18708         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18709           CanFold = isZero(Cond.getOperand(i));
18710       }
18711
18712       if (CanFold) {
18713         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18714           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18715         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18716       }
18717
18718       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18719         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18720         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18721         //                             (v2i64 (bitcast B)))))
18722         //
18723         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18724         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18725         //                             (v2f64 (bitcast B)))))
18726         //
18727         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18728         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18729         //                             (v2i64 (bitcast A)))))
18730         //
18731         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18732         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18733         //                             (v2f64 (bitcast A)))))
18734
18735         CanFold = (isZero(Cond.getOperand(0)) &&
18736                    isZero(Cond.getOperand(1)) &&
18737                    isAllOnes(Cond.getOperand(2)) &&
18738                    isAllOnes(Cond.getOperand(3)));
18739
18740         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18741             isAllOnes(Cond.getOperand(1)) &&
18742             isZero(Cond.getOperand(2)) &&
18743             isZero(Cond.getOperand(3))) {
18744           CanFold = true;
18745           std::swap(LHS, RHS);
18746         }
18747
18748         if (CanFold) {
18749           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18750           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18751           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18752           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18753                                                 NewB, DAG);
18754           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18755         }
18756       }
18757     }
18758   }
18759
18760   // If we know that this node is legal then we know that it is going to be
18761   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18762   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18763   // to simplify previous instructions.
18764   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18765       !DCI.isBeforeLegalize() &&
18766       // We explicitly check against v8i16 and v16i16 because, although
18767       // they're marked as Custom, they might only be legal when Cond is a
18768       // build_vector of constants. This will be taken care in a later
18769       // condition.
18770       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18771        VT != MVT::v8i16)) {
18772     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18773
18774     // Don't optimize vector selects that map to mask-registers.
18775     if (BitWidth == 1)
18776       return SDValue();
18777
18778     // Check all uses of that condition operand to check whether it will be
18779     // consumed by non-BLEND instructions, which may depend on all bits are set
18780     // properly.
18781     for (SDNode::use_iterator I = Cond->use_begin(),
18782                               E = Cond->use_end(); I != E; ++I)
18783       if (I->getOpcode() != ISD::VSELECT)
18784         // TODO: Add other opcodes eventually lowered into BLEND.
18785         return SDValue();
18786
18787     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18788     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18789
18790     APInt KnownZero, KnownOne;
18791     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18792                                           DCI.isBeforeLegalizeOps());
18793     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18794         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18795       DCI.CommitTargetLoweringOpt(TLO);
18796   }
18797
18798   // We should generate an X86ISD::BLENDI from a vselect if its argument
18799   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18800   // constants. This specific pattern gets generated when we split a
18801   // selector for a 512 bit vector in a machine without AVX512 (but with
18802   // 256-bit vectors), during legalization:
18803   //
18804   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18805   //
18806   // Iff we find this pattern and the build_vectors are built from
18807   // constants, we translate the vselect into a shuffle_vector that we
18808   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18809   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18810     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18811     if (Shuffle.getNode())
18812       return Shuffle;
18813   }
18814
18815   return SDValue();
18816 }
18817
18818 // Check whether a boolean test is testing a boolean value generated by
18819 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18820 // code.
18821 //
18822 // Simplify the following patterns:
18823 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18824 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18825 // to (Op EFLAGS Cond)
18826 //
18827 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18828 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18829 // to (Op EFLAGS !Cond)
18830 //
18831 // where Op could be BRCOND or CMOV.
18832 //
18833 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18834   // Quit if not CMP and SUB with its value result used.
18835   if (Cmp.getOpcode() != X86ISD::CMP &&
18836       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18837       return SDValue();
18838
18839   // Quit if not used as a boolean value.
18840   if (CC != X86::COND_E && CC != X86::COND_NE)
18841     return SDValue();
18842
18843   // Check CMP operands. One of them should be 0 or 1 and the other should be
18844   // an SetCC or extended from it.
18845   SDValue Op1 = Cmp.getOperand(0);
18846   SDValue Op2 = Cmp.getOperand(1);
18847
18848   SDValue SetCC;
18849   const ConstantSDNode* C = nullptr;
18850   bool needOppositeCond = (CC == X86::COND_E);
18851   bool checkAgainstTrue = false; // Is it a comparison against 1?
18852
18853   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18854     SetCC = Op2;
18855   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18856     SetCC = Op1;
18857   else // Quit if all operands are not constants.
18858     return SDValue();
18859
18860   if (C->getZExtValue() == 1) {
18861     needOppositeCond = !needOppositeCond;
18862     checkAgainstTrue = true;
18863   } else if (C->getZExtValue() != 0)
18864     // Quit if the constant is neither 0 or 1.
18865     return SDValue();
18866
18867   bool truncatedToBoolWithAnd = false;
18868   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18869   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18870          SetCC.getOpcode() == ISD::TRUNCATE ||
18871          SetCC.getOpcode() == ISD::AND) {
18872     if (SetCC.getOpcode() == ISD::AND) {
18873       int OpIdx = -1;
18874       ConstantSDNode *CS;
18875       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18876           CS->getZExtValue() == 1)
18877         OpIdx = 1;
18878       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18879           CS->getZExtValue() == 1)
18880         OpIdx = 0;
18881       if (OpIdx == -1)
18882         break;
18883       SetCC = SetCC.getOperand(OpIdx);
18884       truncatedToBoolWithAnd = true;
18885     } else
18886       SetCC = SetCC.getOperand(0);
18887   }
18888
18889   switch (SetCC.getOpcode()) {
18890   case X86ISD::SETCC_CARRY:
18891     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18892     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18893     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18894     // truncated to i1 using 'and'.
18895     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18896       break;
18897     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18898            "Invalid use of SETCC_CARRY!");
18899     // FALL THROUGH
18900   case X86ISD::SETCC:
18901     // Set the condition code or opposite one if necessary.
18902     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18903     if (needOppositeCond)
18904       CC = X86::GetOppositeBranchCondition(CC);
18905     return SetCC.getOperand(1);
18906   case X86ISD::CMOV: {
18907     // Check whether false/true value has canonical one, i.e. 0 or 1.
18908     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18909     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18910     // Quit if true value is not a constant.
18911     if (!TVal)
18912       return SDValue();
18913     // Quit if false value is not a constant.
18914     if (!FVal) {
18915       SDValue Op = SetCC.getOperand(0);
18916       // Skip 'zext' or 'trunc' node.
18917       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18918           Op.getOpcode() == ISD::TRUNCATE)
18919         Op = Op.getOperand(0);
18920       // A special case for rdrand/rdseed, where 0 is set if false cond is
18921       // found.
18922       if ((Op.getOpcode() != X86ISD::RDRAND &&
18923            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18924         return SDValue();
18925     }
18926     // Quit if false value is not the constant 0 or 1.
18927     bool FValIsFalse = true;
18928     if (FVal && FVal->getZExtValue() != 0) {
18929       if (FVal->getZExtValue() != 1)
18930         return SDValue();
18931       // If FVal is 1, opposite cond is needed.
18932       needOppositeCond = !needOppositeCond;
18933       FValIsFalse = false;
18934     }
18935     // Quit if TVal is not the constant opposite of FVal.
18936     if (FValIsFalse && TVal->getZExtValue() != 1)
18937       return SDValue();
18938     if (!FValIsFalse && TVal->getZExtValue() != 0)
18939       return SDValue();
18940     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18941     if (needOppositeCond)
18942       CC = X86::GetOppositeBranchCondition(CC);
18943     return SetCC.getOperand(3);
18944   }
18945   }
18946
18947   return SDValue();
18948 }
18949
18950 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18951 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18952                                   TargetLowering::DAGCombinerInfo &DCI,
18953                                   const X86Subtarget *Subtarget) {
18954   SDLoc DL(N);
18955
18956   // If the flag operand isn't dead, don't touch this CMOV.
18957   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18958     return SDValue();
18959
18960   SDValue FalseOp = N->getOperand(0);
18961   SDValue TrueOp = N->getOperand(1);
18962   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18963   SDValue Cond = N->getOperand(3);
18964
18965   if (CC == X86::COND_E || CC == X86::COND_NE) {
18966     switch (Cond.getOpcode()) {
18967     default: break;
18968     case X86ISD::BSR:
18969     case X86ISD::BSF:
18970       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18971       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18972         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18973     }
18974   }
18975
18976   SDValue Flags;
18977
18978   Flags = checkBoolTestSetCCCombine(Cond, CC);
18979   if (Flags.getNode() &&
18980       // Extra check as FCMOV only supports a subset of X86 cond.
18981       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18982     SDValue Ops[] = { FalseOp, TrueOp,
18983                       DAG.getConstant(CC, MVT::i8), Flags };
18984     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18985   }
18986
18987   // If this is a select between two integer constants, try to do some
18988   // optimizations.  Note that the operands are ordered the opposite of SELECT
18989   // operands.
18990   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18991     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18992       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18993       // larger than FalseC (the false value).
18994       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18995         CC = X86::GetOppositeBranchCondition(CC);
18996         std::swap(TrueC, FalseC);
18997         std::swap(TrueOp, FalseOp);
18998       }
18999
19000       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
19001       // This is efficient for any integer data type (including i8/i16) and
19002       // shift amount.
19003       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
19004         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19005                            DAG.getConstant(CC, MVT::i8), Cond);
19006
19007         // Zero extend the condition if needed.
19008         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
19009
19010         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
19011         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
19012                            DAG.getConstant(ShAmt, MVT::i8));
19013         if (N->getNumValues() == 2)  // Dead flag value?
19014           return DCI.CombineTo(N, Cond, SDValue());
19015         return Cond;
19016       }
19017
19018       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
19019       // for any integer data type, including i8/i16.
19020       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
19021         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19022                            DAG.getConstant(CC, MVT::i8), Cond);
19023
19024         // Zero extend the condition if needed.
19025         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
19026                            FalseC->getValueType(0), Cond);
19027         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19028                            SDValue(FalseC, 0));
19029
19030         if (N->getNumValues() == 2)  // Dead flag value?
19031           return DCI.CombineTo(N, Cond, SDValue());
19032         return Cond;
19033       }
19034
19035       // Optimize cases that will turn into an LEA instruction.  This requires
19036       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
19037       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
19038         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
19039         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
19040
19041         bool isFastMultiplier = false;
19042         if (Diff < 10) {
19043           switch ((unsigned char)Diff) {
19044           default: break;
19045           case 1:  // result = add base, cond
19046           case 2:  // result = lea base(    , cond*2)
19047           case 3:  // result = lea base(cond, cond*2)
19048           case 4:  // result = lea base(    , cond*4)
19049           case 5:  // result = lea base(cond, cond*4)
19050           case 8:  // result = lea base(    , cond*8)
19051           case 9:  // result = lea base(cond, cond*8)
19052             isFastMultiplier = true;
19053             break;
19054           }
19055         }
19056
19057         if (isFastMultiplier) {
19058           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
19059           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
19060                              DAG.getConstant(CC, MVT::i8), Cond);
19061           // Zero extend the condition if needed.
19062           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
19063                              Cond);
19064           // Scale the condition by the difference.
19065           if (Diff != 1)
19066             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
19067                                DAG.getConstant(Diff, Cond.getValueType()));
19068
19069           // Add the base if non-zero.
19070           if (FalseC->getAPIntValue() != 0)
19071             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
19072                                SDValue(FalseC, 0));
19073           if (N->getNumValues() == 2)  // Dead flag value?
19074             return DCI.CombineTo(N, Cond, SDValue());
19075           return Cond;
19076         }
19077       }
19078     }
19079   }
19080
19081   // Handle these cases:
19082   //   (select (x != c), e, c) -> select (x != c), e, x),
19083   //   (select (x == c), c, e) -> select (x == c), x, e)
19084   // where the c is an integer constant, and the "select" is the combination
19085   // of CMOV and CMP.
19086   //
19087   // The rationale for this change is that the conditional-move from a constant
19088   // needs two instructions, however, conditional-move from a register needs
19089   // only one instruction.
19090   //
19091   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
19092   //  some instruction-combining opportunities. This opt needs to be
19093   //  postponed as late as possible.
19094   //
19095   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
19096     // the DCI.xxxx conditions are provided to postpone the optimization as
19097     // late as possible.
19098
19099     ConstantSDNode *CmpAgainst = nullptr;
19100     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
19101         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
19102         !isa<ConstantSDNode>(Cond.getOperand(0))) {
19103
19104       if (CC == X86::COND_NE &&
19105           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
19106         CC = X86::GetOppositeBranchCondition(CC);
19107         std::swap(TrueOp, FalseOp);
19108       }
19109
19110       if (CC == X86::COND_E &&
19111           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
19112         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
19113                           DAG.getConstant(CC, MVT::i8), Cond };
19114         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
19115       }
19116     }
19117   }
19118
19119   return SDValue();
19120 }
19121
19122 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
19123                                                 const X86Subtarget *Subtarget) {
19124   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
19125   switch (IntNo) {
19126   default: return SDValue();
19127   // SSE/AVX/AVX2 blend intrinsics.
19128   case Intrinsic::x86_avx2_pblendvb:
19129   case Intrinsic::x86_avx2_pblendw:
19130   case Intrinsic::x86_avx2_pblendd_128:
19131   case Intrinsic::x86_avx2_pblendd_256:
19132     // Don't try to simplify this intrinsic if we don't have AVX2.
19133     if (!Subtarget->hasAVX2())
19134       return SDValue();
19135     // FALL-THROUGH
19136   case Intrinsic::x86_avx_blend_pd_256:
19137   case Intrinsic::x86_avx_blend_ps_256:
19138   case Intrinsic::x86_avx_blendv_pd_256:
19139   case Intrinsic::x86_avx_blendv_ps_256:
19140     // Don't try to simplify this intrinsic if we don't have AVX.
19141     if (!Subtarget->hasAVX())
19142       return SDValue();
19143     // FALL-THROUGH
19144   case Intrinsic::x86_sse41_pblendw:
19145   case Intrinsic::x86_sse41_blendpd:
19146   case Intrinsic::x86_sse41_blendps:
19147   case Intrinsic::x86_sse41_blendvps:
19148   case Intrinsic::x86_sse41_blendvpd:
19149   case Intrinsic::x86_sse41_pblendvb: {
19150     SDValue Op0 = N->getOperand(1);
19151     SDValue Op1 = N->getOperand(2);
19152     SDValue Mask = N->getOperand(3);
19153
19154     // Don't try to simplify this intrinsic if we don't have SSE4.1.
19155     if (!Subtarget->hasSSE41())
19156       return SDValue();
19157
19158     // fold (blend A, A, Mask) -> A
19159     if (Op0 == Op1)
19160       return Op0;
19161     // fold (blend A, B, allZeros) -> A
19162     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
19163       return Op0;
19164     // fold (blend A, B, allOnes) -> B
19165     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
19166       return Op1;
19167     
19168     // Simplify the case where the mask is a constant i32 value.
19169     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
19170       if (C->isNullValue())
19171         return Op0;
19172       if (C->isAllOnesValue())
19173         return Op1;
19174     }
19175   }
19176
19177   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
19178   case Intrinsic::x86_sse2_psrai_w:
19179   case Intrinsic::x86_sse2_psrai_d:
19180   case Intrinsic::x86_avx2_psrai_w:
19181   case Intrinsic::x86_avx2_psrai_d:
19182   case Intrinsic::x86_sse2_psra_w:
19183   case Intrinsic::x86_sse2_psra_d:
19184   case Intrinsic::x86_avx2_psra_w:
19185   case Intrinsic::x86_avx2_psra_d: {
19186     SDValue Op0 = N->getOperand(1);
19187     SDValue Op1 = N->getOperand(2);
19188     EVT VT = Op0.getValueType();
19189     assert(VT.isVector() && "Expected a vector type!");
19190
19191     if (isa<BuildVectorSDNode>(Op1))
19192       Op1 = Op1.getOperand(0);
19193
19194     if (!isa<ConstantSDNode>(Op1))
19195       return SDValue();
19196
19197     EVT SVT = VT.getVectorElementType();
19198     unsigned SVTBits = SVT.getSizeInBits();
19199
19200     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
19201     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
19202     uint64_t ShAmt = C.getZExtValue();
19203
19204     // Don't try to convert this shift into a ISD::SRA if the shift
19205     // count is bigger than or equal to the element size.
19206     if (ShAmt >= SVTBits)
19207       return SDValue();
19208
19209     // Trivial case: if the shift count is zero, then fold this
19210     // into the first operand.
19211     if (ShAmt == 0)
19212       return Op0;
19213
19214     // Replace this packed shift intrinsic with a target independent
19215     // shift dag node.
19216     SDValue Splat = DAG.getConstant(C, VT);
19217     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
19218   }
19219   }
19220 }
19221
19222 /// PerformMulCombine - Optimize a single multiply with constant into two
19223 /// in order to implement it with two cheaper instructions, e.g.
19224 /// LEA + SHL, LEA + LEA.
19225 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
19226                                  TargetLowering::DAGCombinerInfo &DCI) {
19227   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
19228     return SDValue();
19229
19230   EVT VT = N->getValueType(0);
19231   if (VT != MVT::i64)
19232     return SDValue();
19233
19234   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
19235   if (!C)
19236     return SDValue();
19237   uint64_t MulAmt = C->getZExtValue();
19238   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
19239     return SDValue();
19240
19241   uint64_t MulAmt1 = 0;
19242   uint64_t MulAmt2 = 0;
19243   if ((MulAmt % 9) == 0) {
19244     MulAmt1 = 9;
19245     MulAmt2 = MulAmt / 9;
19246   } else if ((MulAmt % 5) == 0) {
19247     MulAmt1 = 5;
19248     MulAmt2 = MulAmt / 5;
19249   } else if ((MulAmt % 3) == 0) {
19250     MulAmt1 = 3;
19251     MulAmt2 = MulAmt / 3;
19252   }
19253   if (MulAmt2 &&
19254       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
19255     SDLoc DL(N);
19256
19257     if (isPowerOf2_64(MulAmt2) &&
19258         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
19259       // If second multiplifer is pow2, issue it first. We want the multiply by
19260       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
19261       // is an add.
19262       std::swap(MulAmt1, MulAmt2);
19263
19264     SDValue NewMul;
19265     if (isPowerOf2_64(MulAmt1))
19266       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
19267                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
19268     else
19269       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
19270                            DAG.getConstant(MulAmt1, VT));
19271
19272     if (isPowerOf2_64(MulAmt2))
19273       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
19274                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
19275     else
19276       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
19277                            DAG.getConstant(MulAmt2, VT));
19278
19279     // Do not add new nodes to DAG combiner worklist.
19280     DCI.CombineTo(N, NewMul, false);
19281   }
19282   return SDValue();
19283 }
19284
19285 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
19286   SDValue N0 = N->getOperand(0);
19287   SDValue N1 = N->getOperand(1);
19288   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
19289   EVT VT = N0.getValueType();
19290
19291   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
19292   // since the result of setcc_c is all zero's or all ones.
19293   if (VT.isInteger() && !VT.isVector() &&
19294       N1C && N0.getOpcode() == ISD::AND &&
19295       N0.getOperand(1).getOpcode() == ISD::Constant) {
19296     SDValue N00 = N0.getOperand(0);
19297     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
19298         ((N00.getOpcode() == ISD::ANY_EXTEND ||
19299           N00.getOpcode() == ISD::ZERO_EXTEND) &&
19300          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
19301       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
19302       APInt ShAmt = N1C->getAPIntValue();
19303       Mask = Mask.shl(ShAmt);
19304       if (Mask != 0)
19305         return DAG.getNode(ISD::AND, SDLoc(N), VT,
19306                            N00, DAG.getConstant(Mask, VT));
19307     }
19308   }
19309
19310   // Hardware support for vector shifts is sparse which makes us scalarize the
19311   // vector operations in many cases. Also, on sandybridge ADD is faster than
19312   // shl.
19313   // (shl V, 1) -> add V,V
19314   if (isSplatVector(N1.getNode())) {
19315     assert(N0.getValueType().isVector() && "Invalid vector shift type");
19316     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
19317     // We shift all of the values by one. In many cases we do not have
19318     // hardware support for this operation. This is better expressed as an ADD
19319     // of two values.
19320     if (N1C && (1 == N1C->getZExtValue())) {
19321       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
19322     }
19323   }
19324
19325   return SDValue();
19326 }
19327
19328 /// \brief Returns a vector of 0s if the node in input is a vector logical
19329 /// shift by a constant amount which is known to be bigger than or equal
19330 /// to the vector element size in bits.
19331 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
19332                                       const X86Subtarget *Subtarget) {
19333   EVT VT = N->getValueType(0);
19334
19335   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
19336       (!Subtarget->hasInt256() ||
19337        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
19338     return SDValue();
19339
19340   SDValue Amt = N->getOperand(1);
19341   SDLoc DL(N);
19342   if (isSplatVector(Amt.getNode())) {
19343     SDValue SclrAmt = Amt->getOperand(0);
19344     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
19345       APInt ShiftAmt = C->getAPIntValue();
19346       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
19347
19348       // SSE2/AVX2 logical shifts always return a vector of 0s
19349       // if the shift amount is bigger than or equal to
19350       // the element size. The constant shift amount will be
19351       // encoded as a 8-bit immediate.
19352       if (ShiftAmt.trunc(8).uge(MaxAmount))
19353         return getZeroVector(VT, Subtarget, DAG, DL);
19354     }
19355   }
19356
19357   return SDValue();
19358 }
19359
19360 /// PerformShiftCombine - Combine shifts.
19361 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19362                                    TargetLowering::DAGCombinerInfo &DCI,
19363                                    const X86Subtarget *Subtarget) {
19364   if (N->getOpcode() == ISD::SHL) {
19365     SDValue V = PerformSHLCombine(N, DAG);
19366     if (V.getNode()) return V;
19367   }
19368
19369   if (N->getOpcode() != ISD::SRA) {
19370     // Try to fold this logical shift into a zero vector.
19371     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19372     if (V.getNode()) return V;
19373   }
19374
19375   return SDValue();
19376 }
19377
19378 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
19379 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19380 // and friends.  Likewise for OR -> CMPNEQSS.
19381 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19382                             TargetLowering::DAGCombinerInfo &DCI,
19383                             const X86Subtarget *Subtarget) {
19384   unsigned opcode;
19385
19386   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19387   // we're requiring SSE2 for both.
19388   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19389     SDValue N0 = N->getOperand(0);
19390     SDValue N1 = N->getOperand(1);
19391     SDValue CMP0 = N0->getOperand(1);
19392     SDValue CMP1 = N1->getOperand(1);
19393     SDLoc DL(N);
19394
19395     // The SETCCs should both refer to the same CMP.
19396     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19397       return SDValue();
19398
19399     SDValue CMP00 = CMP0->getOperand(0);
19400     SDValue CMP01 = CMP0->getOperand(1);
19401     EVT     VT    = CMP00.getValueType();
19402
19403     if (VT == MVT::f32 || VT == MVT::f64) {
19404       bool ExpectingFlags = false;
19405       // Check for any users that want flags:
19406       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19407            !ExpectingFlags && UI != UE; ++UI)
19408         switch (UI->getOpcode()) {
19409         default:
19410         case ISD::BR_CC:
19411         case ISD::BRCOND:
19412         case ISD::SELECT:
19413           ExpectingFlags = true;
19414           break;
19415         case ISD::CopyToReg:
19416         case ISD::SIGN_EXTEND:
19417         case ISD::ZERO_EXTEND:
19418         case ISD::ANY_EXTEND:
19419           break;
19420         }
19421
19422       if (!ExpectingFlags) {
19423         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19424         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19425
19426         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19427           X86::CondCode tmp = cc0;
19428           cc0 = cc1;
19429           cc1 = tmp;
19430         }
19431
19432         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19433             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19434           // FIXME: need symbolic constants for these magic numbers.
19435           // See X86ATTInstPrinter.cpp:printSSECC().
19436           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19437           if (Subtarget->hasAVX512()) {
19438             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19439                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19440             if (N->getValueType(0) != MVT::i1)
19441               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19442                                  FSetCC);
19443             return FSetCC;
19444           }
19445           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19446                                               CMP00.getValueType(), CMP00, CMP01,
19447                                               DAG.getConstant(x86cc, MVT::i8));
19448
19449           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19450           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19451
19452           if (is64BitFP && !Subtarget->is64Bit()) {
19453             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19454             // 64-bit integer, since that's not a legal type. Since
19455             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19456             // bits, but can do this little dance to extract the lowest 32 bits
19457             // and work with those going forward.
19458             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19459                                            OnesOrZeroesF);
19460             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19461                                            Vector64);
19462             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19463                                         Vector32, DAG.getIntPtrConstant(0));
19464             IntVT = MVT::i32;
19465           }
19466
19467           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19468           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19469                                       DAG.getConstant(1, IntVT));
19470           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19471           return OneBitOfTruth;
19472         }
19473       }
19474     }
19475   }
19476   return SDValue();
19477 }
19478
19479 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19480 /// so it can be folded inside ANDNP.
19481 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19482   EVT VT = N->getValueType(0);
19483
19484   // Match direct AllOnes for 128 and 256-bit vectors
19485   if (ISD::isBuildVectorAllOnes(N))
19486     return true;
19487
19488   // Look through a bit convert.
19489   if (N->getOpcode() == ISD::BITCAST)
19490     N = N->getOperand(0).getNode();
19491
19492   // Sometimes the operand may come from a insert_subvector building a 256-bit
19493   // allones vector
19494   if (VT.is256BitVector() &&
19495       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19496     SDValue V1 = N->getOperand(0);
19497     SDValue V2 = N->getOperand(1);
19498
19499     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19500         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19501         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19502         ISD::isBuildVectorAllOnes(V2.getNode()))
19503       return true;
19504   }
19505
19506   return false;
19507 }
19508
19509 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19510 // register. In most cases we actually compare or select YMM-sized registers
19511 // and mixing the two types creates horrible code. This method optimizes
19512 // some of the transition sequences.
19513 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19514                                  TargetLowering::DAGCombinerInfo &DCI,
19515                                  const X86Subtarget *Subtarget) {
19516   EVT VT = N->getValueType(0);
19517   if (!VT.is256BitVector())
19518     return SDValue();
19519
19520   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19521           N->getOpcode() == ISD::ZERO_EXTEND ||
19522           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19523
19524   SDValue Narrow = N->getOperand(0);
19525   EVT NarrowVT = Narrow->getValueType(0);
19526   if (!NarrowVT.is128BitVector())
19527     return SDValue();
19528
19529   if (Narrow->getOpcode() != ISD::XOR &&
19530       Narrow->getOpcode() != ISD::AND &&
19531       Narrow->getOpcode() != ISD::OR)
19532     return SDValue();
19533
19534   SDValue N0  = Narrow->getOperand(0);
19535   SDValue N1  = Narrow->getOperand(1);
19536   SDLoc DL(Narrow);
19537
19538   // The Left side has to be a trunc.
19539   if (N0.getOpcode() != ISD::TRUNCATE)
19540     return SDValue();
19541
19542   // The type of the truncated inputs.
19543   EVT WideVT = N0->getOperand(0)->getValueType(0);
19544   if (WideVT != VT)
19545     return SDValue();
19546
19547   // The right side has to be a 'trunc' or a constant vector.
19548   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19549   bool RHSConst = (isSplatVector(N1.getNode()) &&
19550                    isa<ConstantSDNode>(N1->getOperand(0)));
19551   if (!RHSTrunc && !RHSConst)
19552     return SDValue();
19553
19554   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19555
19556   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19557     return SDValue();
19558
19559   // Set N0 and N1 to hold the inputs to the new wide operation.
19560   N0 = N0->getOperand(0);
19561   if (RHSConst) {
19562     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19563                      N1->getOperand(0));
19564     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19565     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19566   } else if (RHSTrunc) {
19567     N1 = N1->getOperand(0);
19568   }
19569
19570   // Generate the wide operation.
19571   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19572   unsigned Opcode = N->getOpcode();
19573   switch (Opcode) {
19574   case ISD::ANY_EXTEND:
19575     return Op;
19576   case ISD::ZERO_EXTEND: {
19577     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19578     APInt Mask = APInt::getAllOnesValue(InBits);
19579     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19580     return DAG.getNode(ISD::AND, DL, VT,
19581                        Op, DAG.getConstant(Mask, VT));
19582   }
19583   case ISD::SIGN_EXTEND:
19584     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19585                        Op, DAG.getValueType(NarrowVT));
19586   default:
19587     llvm_unreachable("Unexpected opcode");
19588   }
19589 }
19590
19591 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19592                                  TargetLowering::DAGCombinerInfo &DCI,
19593                                  const X86Subtarget *Subtarget) {
19594   EVT VT = N->getValueType(0);
19595   if (DCI.isBeforeLegalizeOps())
19596     return SDValue();
19597
19598   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19599   if (R.getNode())
19600     return R;
19601
19602   // Create BEXTR instructions
19603   // BEXTR is ((X >> imm) & (2**size-1))
19604   if (VT == MVT::i32 || VT == MVT::i64) {
19605     SDValue N0 = N->getOperand(0);
19606     SDValue N1 = N->getOperand(1);
19607     SDLoc DL(N);
19608
19609     // Check for BEXTR.
19610     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19611         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19612       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19613       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19614       if (MaskNode && ShiftNode) {
19615         uint64_t Mask = MaskNode->getZExtValue();
19616         uint64_t Shift = ShiftNode->getZExtValue();
19617         if (isMask_64(Mask)) {
19618           uint64_t MaskSize = CountPopulation_64(Mask);
19619           if (Shift + MaskSize <= VT.getSizeInBits())
19620             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19621                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19622         }
19623       }
19624     } // BEXTR
19625
19626     return SDValue();
19627   }
19628
19629   // Want to form ANDNP nodes:
19630   // 1) In the hopes of then easily combining them with OR and AND nodes
19631   //    to form PBLEND/PSIGN.
19632   // 2) To match ANDN packed intrinsics
19633   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19634     return SDValue();
19635
19636   SDValue N0 = N->getOperand(0);
19637   SDValue N1 = N->getOperand(1);
19638   SDLoc DL(N);
19639
19640   // Check LHS for vnot
19641   if (N0.getOpcode() == ISD::XOR &&
19642       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19643       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19644     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19645
19646   // Check RHS for vnot
19647   if (N1.getOpcode() == ISD::XOR &&
19648       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19649       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19650     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19651
19652   return SDValue();
19653 }
19654
19655 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19656                                 TargetLowering::DAGCombinerInfo &DCI,
19657                                 const X86Subtarget *Subtarget) {
19658   if (DCI.isBeforeLegalizeOps())
19659     return SDValue();
19660
19661   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19662   if (R.getNode())
19663     return R;
19664
19665   SDValue N0 = N->getOperand(0);
19666   SDValue N1 = N->getOperand(1);
19667   EVT VT = N->getValueType(0);
19668
19669   // look for psign/blend
19670   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19671     if (!Subtarget->hasSSSE3() ||
19672         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19673       return SDValue();
19674
19675     // Canonicalize pandn to RHS
19676     if (N0.getOpcode() == X86ISD::ANDNP)
19677       std::swap(N0, N1);
19678     // or (and (m, y), (pandn m, x))
19679     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19680       SDValue Mask = N1.getOperand(0);
19681       SDValue X    = N1.getOperand(1);
19682       SDValue Y;
19683       if (N0.getOperand(0) == Mask)
19684         Y = N0.getOperand(1);
19685       if (N0.getOperand(1) == Mask)
19686         Y = N0.getOperand(0);
19687
19688       // Check to see if the mask appeared in both the AND and ANDNP and
19689       if (!Y.getNode())
19690         return SDValue();
19691
19692       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19693       // Look through mask bitcast.
19694       if (Mask.getOpcode() == ISD::BITCAST)
19695         Mask = Mask.getOperand(0);
19696       if (X.getOpcode() == ISD::BITCAST)
19697         X = X.getOperand(0);
19698       if (Y.getOpcode() == ISD::BITCAST)
19699         Y = Y.getOperand(0);
19700
19701       EVT MaskVT = Mask.getValueType();
19702
19703       // Validate that the Mask operand is a vector sra node.
19704       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19705       // there is no psrai.b
19706       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19707       unsigned SraAmt = ~0;
19708       if (Mask.getOpcode() == ISD::SRA) {
19709         SDValue Amt = Mask.getOperand(1);
19710         if (isSplatVector(Amt.getNode())) {
19711           SDValue SclrAmt = Amt->getOperand(0);
19712           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19713             SraAmt = C->getZExtValue();
19714         }
19715       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19716         SDValue SraC = Mask.getOperand(1);
19717         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19718       }
19719       if ((SraAmt + 1) != EltBits)
19720         return SDValue();
19721
19722       SDLoc DL(N);
19723
19724       // Now we know we at least have a plendvb with the mask val.  See if
19725       // we can form a psignb/w/d.
19726       // psign = x.type == y.type == mask.type && y = sub(0, x);
19727       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19728           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19729           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19730         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19731                "Unsupported VT for PSIGN");
19732         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19733         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19734       }
19735       // PBLENDVB only available on SSE 4.1
19736       if (!Subtarget->hasSSE41())
19737         return SDValue();
19738
19739       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19740
19741       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19742       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19743       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19744       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19745       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19746     }
19747   }
19748
19749   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19750     return SDValue();
19751
19752   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19753   MachineFunction &MF = DAG.getMachineFunction();
19754   bool OptForSize = MF.getFunction()->getAttributes().
19755     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19756
19757   // SHLD/SHRD instructions have lower register pressure, but on some
19758   // platforms they have higher latency than the equivalent
19759   // series of shifts/or that would otherwise be generated.
19760   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19761   // have higher latencies and we are not optimizing for size.
19762   if (!OptForSize && Subtarget->isSHLDSlow())
19763     return SDValue();
19764
19765   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19766     std::swap(N0, N1);
19767   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19768     return SDValue();
19769   if (!N0.hasOneUse() || !N1.hasOneUse())
19770     return SDValue();
19771
19772   SDValue ShAmt0 = N0.getOperand(1);
19773   if (ShAmt0.getValueType() != MVT::i8)
19774     return SDValue();
19775   SDValue ShAmt1 = N1.getOperand(1);
19776   if (ShAmt1.getValueType() != MVT::i8)
19777     return SDValue();
19778   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19779     ShAmt0 = ShAmt0.getOperand(0);
19780   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19781     ShAmt1 = ShAmt1.getOperand(0);
19782
19783   SDLoc DL(N);
19784   unsigned Opc = X86ISD::SHLD;
19785   SDValue Op0 = N0.getOperand(0);
19786   SDValue Op1 = N1.getOperand(0);
19787   if (ShAmt0.getOpcode() == ISD::SUB) {
19788     Opc = X86ISD::SHRD;
19789     std::swap(Op0, Op1);
19790     std::swap(ShAmt0, ShAmt1);
19791   }
19792
19793   unsigned Bits = VT.getSizeInBits();
19794   if (ShAmt1.getOpcode() == ISD::SUB) {
19795     SDValue Sum = ShAmt1.getOperand(0);
19796     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19797       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19798       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19799         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19800       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19801         return DAG.getNode(Opc, DL, VT,
19802                            Op0, Op1,
19803                            DAG.getNode(ISD::TRUNCATE, DL,
19804                                        MVT::i8, ShAmt0));
19805     }
19806   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19807     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19808     if (ShAmt0C &&
19809         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19810       return DAG.getNode(Opc, DL, VT,
19811                          N0.getOperand(0), N1.getOperand(0),
19812                          DAG.getNode(ISD::TRUNCATE, DL,
19813                                        MVT::i8, ShAmt0));
19814   }
19815
19816   return SDValue();
19817 }
19818
19819 // Generate NEG and CMOV for integer abs.
19820 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19821   EVT VT = N->getValueType(0);
19822
19823   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19824   // 8-bit integer abs to NEG and CMOV.
19825   if (VT.isInteger() && VT.getSizeInBits() == 8)
19826     return SDValue();
19827
19828   SDValue N0 = N->getOperand(0);
19829   SDValue N1 = N->getOperand(1);
19830   SDLoc DL(N);
19831
19832   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19833   // and change it to SUB and CMOV.
19834   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19835       N0.getOpcode() == ISD::ADD &&
19836       N0.getOperand(1) == N1 &&
19837       N1.getOpcode() == ISD::SRA &&
19838       N1.getOperand(0) == N0.getOperand(0))
19839     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19840       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19841         // Generate SUB & CMOV.
19842         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19843                                   DAG.getConstant(0, VT), N0.getOperand(0));
19844
19845         SDValue Ops[] = { N0.getOperand(0), Neg,
19846                           DAG.getConstant(X86::COND_GE, MVT::i8),
19847                           SDValue(Neg.getNode(), 1) };
19848         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19849       }
19850   return SDValue();
19851 }
19852
19853 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19854 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19855                                  TargetLowering::DAGCombinerInfo &DCI,
19856                                  const X86Subtarget *Subtarget) {
19857   if (DCI.isBeforeLegalizeOps())
19858     return SDValue();
19859
19860   if (Subtarget->hasCMov()) {
19861     SDValue RV = performIntegerAbsCombine(N, DAG);
19862     if (RV.getNode())
19863       return RV;
19864   }
19865
19866   return SDValue();
19867 }
19868
19869 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19870 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19871                                   TargetLowering::DAGCombinerInfo &DCI,
19872                                   const X86Subtarget *Subtarget) {
19873   LoadSDNode *Ld = cast<LoadSDNode>(N);
19874   EVT RegVT = Ld->getValueType(0);
19875   EVT MemVT = Ld->getMemoryVT();
19876   SDLoc dl(Ld);
19877   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19878   unsigned RegSz = RegVT.getSizeInBits();
19879
19880   // On Sandybridge unaligned 256bit loads are inefficient.
19881   ISD::LoadExtType Ext = Ld->getExtensionType();
19882   unsigned Alignment = Ld->getAlignment();
19883   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19884   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19885       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19886     unsigned NumElems = RegVT.getVectorNumElements();
19887     if (NumElems < 2)
19888       return SDValue();
19889
19890     SDValue Ptr = Ld->getBasePtr();
19891     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19892
19893     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19894                                   NumElems/2);
19895     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19896                                 Ld->getPointerInfo(), Ld->isVolatile(),
19897                                 Ld->isNonTemporal(), Ld->isInvariant(),
19898                                 Alignment);
19899     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19900     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19901                                 Ld->getPointerInfo(), Ld->isVolatile(),
19902                                 Ld->isNonTemporal(), Ld->isInvariant(),
19903                                 std::min(16U, Alignment));
19904     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19905                              Load1.getValue(1),
19906                              Load2.getValue(1));
19907
19908     SDValue NewVec = DAG.getUNDEF(RegVT);
19909     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19910     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19911     return DCI.CombineTo(N, NewVec, TF, true);
19912   }
19913
19914   // If this is a vector EXT Load then attempt to optimize it using a
19915   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19916   // expansion is still better than scalar code.
19917   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19918   // emit a shuffle and a arithmetic shift.
19919   // TODO: It is possible to support ZExt by zeroing the undef values
19920   // during the shuffle phase or after the shuffle.
19921   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19922       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19923     assert(MemVT != RegVT && "Cannot extend to the same type");
19924     assert(MemVT.isVector() && "Must load a vector from memory");
19925
19926     unsigned NumElems = RegVT.getVectorNumElements();
19927     unsigned MemSz = MemVT.getSizeInBits();
19928     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19929
19930     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19931       return SDValue();
19932
19933     // All sizes must be a power of two.
19934     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19935       return SDValue();
19936
19937     // Attempt to load the original value using scalar loads.
19938     // Find the largest scalar type that divides the total loaded size.
19939     MVT SclrLoadTy = MVT::i8;
19940     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19941          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19942       MVT Tp = (MVT::SimpleValueType)tp;
19943       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19944         SclrLoadTy = Tp;
19945       }
19946     }
19947
19948     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19949     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19950         (64 <= MemSz))
19951       SclrLoadTy = MVT::f64;
19952
19953     // Calculate the number of scalar loads that we need to perform
19954     // in order to load our vector from memory.
19955     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19956     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19957       return SDValue();
19958
19959     unsigned loadRegZize = RegSz;
19960     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19961       loadRegZize /= 2;
19962
19963     // Represent our vector as a sequence of elements which are the
19964     // largest scalar that we can load.
19965     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19966       loadRegZize/SclrLoadTy.getSizeInBits());
19967
19968     // Represent the data using the same element type that is stored in
19969     // memory. In practice, we ''widen'' MemVT.
19970     EVT WideVecVT =
19971           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19972                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19973
19974     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19975       "Invalid vector type");
19976
19977     // We can't shuffle using an illegal type.
19978     if (!TLI.isTypeLegal(WideVecVT))
19979       return SDValue();
19980
19981     SmallVector<SDValue, 8> Chains;
19982     SDValue Ptr = Ld->getBasePtr();
19983     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19984                                         TLI.getPointerTy());
19985     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19986
19987     for (unsigned i = 0; i < NumLoads; ++i) {
19988       // Perform a single load.
19989       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19990                                        Ptr, Ld->getPointerInfo(),
19991                                        Ld->isVolatile(), Ld->isNonTemporal(),
19992                                        Ld->isInvariant(), Ld->getAlignment());
19993       Chains.push_back(ScalarLoad.getValue(1));
19994       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19995       // another round of DAGCombining.
19996       if (i == 0)
19997         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19998       else
19999         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
20000                           ScalarLoad, DAG.getIntPtrConstant(i));
20001
20002       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20003     }
20004
20005     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20006
20007     // Bitcast the loaded value to a vector of the original element type, in
20008     // the size of the target vector type.
20009     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
20010     unsigned SizeRatio = RegSz/MemSz;
20011
20012     if (Ext == ISD::SEXTLOAD) {
20013       // If we have SSE4.1 we can directly emit a VSEXT node.
20014       if (Subtarget->hasSSE41()) {
20015         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
20016         return DCI.CombineTo(N, Sext, TF, true);
20017       }
20018
20019       // Otherwise we'll shuffle the small elements in the high bits of the
20020       // larger type and perform an arithmetic shift. If the shift is not legal
20021       // it's better to scalarize.
20022       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
20023         return SDValue();
20024
20025       // Redistribute the loaded elements into the different locations.
20026       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20027       for (unsigned i = 0; i != NumElems; ++i)
20028         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
20029
20030       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20031                                            DAG.getUNDEF(WideVecVT),
20032                                            &ShuffleVec[0]);
20033
20034       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20035
20036       // Build the arithmetic shift.
20037       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
20038                      MemVT.getVectorElementType().getSizeInBits();
20039       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
20040                           DAG.getConstant(Amt, RegVT));
20041
20042       return DCI.CombineTo(N, Shuff, TF, true);
20043     }
20044
20045     // Redistribute the loaded elements into the different locations.
20046     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20047     for (unsigned i = 0; i != NumElems; ++i)
20048       ShuffleVec[i*SizeRatio] = i;
20049
20050     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
20051                                          DAG.getUNDEF(WideVecVT),
20052                                          &ShuffleVec[0]);
20053
20054     // Bitcast to the requested type.
20055     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
20056     // Replace the original load with the new sequence
20057     // and return the new chain.
20058     return DCI.CombineTo(N, Shuff, TF, true);
20059   }
20060
20061   return SDValue();
20062 }
20063
20064 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
20065 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
20066                                    const X86Subtarget *Subtarget) {
20067   StoreSDNode *St = cast<StoreSDNode>(N);
20068   EVT VT = St->getValue().getValueType();
20069   EVT StVT = St->getMemoryVT();
20070   SDLoc dl(St);
20071   SDValue StoredVal = St->getOperand(1);
20072   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20073
20074   // If we are saving a concatenation of two XMM registers, perform two stores.
20075   // On Sandy Bridge, 256-bit memory operations are executed by two
20076   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
20077   // memory  operation.
20078   unsigned Alignment = St->getAlignment();
20079   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
20080   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
20081       StVT == VT && !IsAligned) {
20082     unsigned NumElems = VT.getVectorNumElements();
20083     if (NumElems < 2)
20084       return SDValue();
20085
20086     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
20087     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
20088
20089     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
20090     SDValue Ptr0 = St->getBasePtr();
20091     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
20092
20093     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
20094                                 St->getPointerInfo(), St->isVolatile(),
20095                                 St->isNonTemporal(), Alignment);
20096     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
20097                                 St->getPointerInfo(), St->isVolatile(),
20098                                 St->isNonTemporal(),
20099                                 std::min(16U, Alignment));
20100     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
20101   }
20102
20103   // Optimize trunc store (of multiple scalars) to shuffle and store.
20104   // First, pack all of the elements in one place. Next, store to memory
20105   // in fewer chunks.
20106   if (St->isTruncatingStore() && VT.isVector()) {
20107     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20108     unsigned NumElems = VT.getVectorNumElements();
20109     assert(StVT != VT && "Cannot truncate to the same type");
20110     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
20111     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
20112
20113     // From, To sizes and ElemCount must be pow of two
20114     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
20115     // We are going to use the original vector elt for storing.
20116     // Accumulated smaller vector elements must be a multiple of the store size.
20117     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
20118
20119     unsigned SizeRatio  = FromSz / ToSz;
20120
20121     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
20122
20123     // Create a type on which we perform the shuffle
20124     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
20125             StVT.getScalarType(), NumElems*SizeRatio);
20126
20127     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
20128
20129     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
20130     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
20131     for (unsigned i = 0; i != NumElems; ++i)
20132       ShuffleVec[i] = i * SizeRatio;
20133
20134     // Can't shuffle using an illegal type.
20135     if (!TLI.isTypeLegal(WideVecVT))
20136       return SDValue();
20137
20138     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
20139                                          DAG.getUNDEF(WideVecVT),
20140                                          &ShuffleVec[0]);
20141     // At this point all of the data is stored at the bottom of the
20142     // register. We now need to save it to mem.
20143
20144     // Find the largest store unit
20145     MVT StoreType = MVT::i8;
20146     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
20147          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
20148       MVT Tp = (MVT::SimpleValueType)tp;
20149       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
20150         StoreType = Tp;
20151     }
20152
20153     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
20154     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
20155         (64 <= NumElems * ToSz))
20156       StoreType = MVT::f64;
20157
20158     // Bitcast the original vector into a vector of store-size units
20159     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
20160             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
20161     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
20162     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
20163     SmallVector<SDValue, 8> Chains;
20164     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
20165                                         TLI.getPointerTy());
20166     SDValue Ptr = St->getBasePtr();
20167
20168     // Perform one or more big stores into memory.
20169     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
20170       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
20171                                    StoreType, ShuffWide,
20172                                    DAG.getIntPtrConstant(i));
20173       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
20174                                 St->getPointerInfo(), St->isVolatile(),
20175                                 St->isNonTemporal(), St->getAlignment());
20176       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
20177       Chains.push_back(Ch);
20178     }
20179
20180     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
20181   }
20182
20183   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
20184   // the FP state in cases where an emms may be missing.
20185   // A preferable solution to the general problem is to figure out the right
20186   // places to insert EMMS.  This qualifies as a quick hack.
20187
20188   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
20189   if (VT.getSizeInBits() != 64)
20190     return SDValue();
20191
20192   const Function *F = DAG.getMachineFunction().getFunction();
20193   bool NoImplicitFloatOps = F->getAttributes().
20194     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
20195   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
20196                      && Subtarget->hasSSE2();
20197   if ((VT.isVector() ||
20198        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
20199       isa<LoadSDNode>(St->getValue()) &&
20200       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
20201       St->getChain().hasOneUse() && !St->isVolatile()) {
20202     SDNode* LdVal = St->getValue().getNode();
20203     LoadSDNode *Ld = nullptr;
20204     int TokenFactorIndex = -1;
20205     SmallVector<SDValue, 8> Ops;
20206     SDNode* ChainVal = St->getChain().getNode();
20207     // Must be a store of a load.  We currently handle two cases:  the load
20208     // is a direct child, and it's under an intervening TokenFactor.  It is
20209     // possible to dig deeper under nested TokenFactors.
20210     if (ChainVal == LdVal)
20211       Ld = cast<LoadSDNode>(St->getChain());
20212     else if (St->getValue().hasOneUse() &&
20213              ChainVal->getOpcode() == ISD::TokenFactor) {
20214       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
20215         if (ChainVal->getOperand(i).getNode() == LdVal) {
20216           TokenFactorIndex = i;
20217           Ld = cast<LoadSDNode>(St->getValue());
20218         } else
20219           Ops.push_back(ChainVal->getOperand(i));
20220       }
20221     }
20222
20223     if (!Ld || !ISD::isNormalLoad(Ld))
20224       return SDValue();
20225
20226     // If this is not the MMX case, i.e. we are just turning i64 load/store
20227     // into f64 load/store, avoid the transformation if there are multiple
20228     // uses of the loaded value.
20229     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
20230       return SDValue();
20231
20232     SDLoc LdDL(Ld);
20233     SDLoc StDL(N);
20234     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
20235     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
20236     // pair instead.
20237     if (Subtarget->is64Bit() || F64IsLegal) {
20238       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
20239       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
20240                                   Ld->getPointerInfo(), Ld->isVolatile(),
20241                                   Ld->isNonTemporal(), Ld->isInvariant(),
20242                                   Ld->getAlignment());
20243       SDValue NewChain = NewLd.getValue(1);
20244       if (TokenFactorIndex != -1) {
20245         Ops.push_back(NewChain);
20246         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20247       }
20248       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
20249                           St->getPointerInfo(),
20250                           St->isVolatile(), St->isNonTemporal(),
20251                           St->getAlignment());
20252     }
20253
20254     // Otherwise, lower to two pairs of 32-bit loads / stores.
20255     SDValue LoAddr = Ld->getBasePtr();
20256     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
20257                                  DAG.getConstant(4, MVT::i32));
20258
20259     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
20260                                Ld->getPointerInfo(),
20261                                Ld->isVolatile(), Ld->isNonTemporal(),
20262                                Ld->isInvariant(), Ld->getAlignment());
20263     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
20264                                Ld->getPointerInfo().getWithOffset(4),
20265                                Ld->isVolatile(), Ld->isNonTemporal(),
20266                                Ld->isInvariant(),
20267                                MinAlign(Ld->getAlignment(), 4));
20268
20269     SDValue NewChain = LoLd.getValue(1);
20270     if (TokenFactorIndex != -1) {
20271       Ops.push_back(LoLd);
20272       Ops.push_back(HiLd);
20273       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
20274     }
20275
20276     LoAddr = St->getBasePtr();
20277     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
20278                          DAG.getConstant(4, MVT::i32));
20279
20280     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
20281                                 St->getPointerInfo(),
20282                                 St->isVolatile(), St->isNonTemporal(),
20283                                 St->getAlignment());
20284     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
20285                                 St->getPointerInfo().getWithOffset(4),
20286                                 St->isVolatile(),
20287                                 St->isNonTemporal(),
20288                                 MinAlign(St->getAlignment(), 4));
20289     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
20290   }
20291   return SDValue();
20292 }
20293
20294 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
20295 /// and return the operands for the horizontal operation in LHS and RHS.  A
20296 /// horizontal operation performs the binary operation on successive elements
20297 /// of its first operand, then on successive elements of its second operand,
20298 /// returning the resulting values in a vector.  For example, if
20299 ///   A = < float a0, float a1, float a2, float a3 >
20300 /// and
20301 ///   B = < float b0, float b1, float b2, float b3 >
20302 /// then the result of doing a horizontal operation on A and B is
20303 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
20304 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
20305 /// A horizontal-op B, for some already available A and B, and if so then LHS is
20306 /// set to A, RHS to B, and the routine returns 'true'.
20307 /// Note that the binary operation should have the property that if one of the
20308 /// operands is UNDEF then the result is UNDEF.
20309 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
20310   // Look for the following pattern: if
20311   //   A = < float a0, float a1, float a2, float a3 >
20312   //   B = < float b0, float b1, float b2, float b3 >
20313   // and
20314   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
20315   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
20316   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
20317   // which is A horizontal-op B.
20318
20319   // At least one of the operands should be a vector shuffle.
20320   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
20321       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
20322     return false;
20323
20324   MVT VT = LHS.getSimpleValueType();
20325
20326   assert((VT.is128BitVector() || VT.is256BitVector()) &&
20327          "Unsupported vector type for horizontal add/sub");
20328
20329   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
20330   // operate independently on 128-bit lanes.
20331   unsigned NumElts = VT.getVectorNumElements();
20332   unsigned NumLanes = VT.getSizeInBits()/128;
20333   unsigned NumLaneElts = NumElts / NumLanes;
20334   assert((NumLaneElts % 2 == 0) &&
20335          "Vector type should have an even number of elements in each lane");
20336   unsigned HalfLaneElts = NumLaneElts/2;
20337
20338   // View LHS in the form
20339   //   LHS = VECTOR_SHUFFLE A, B, LMask
20340   // If LHS is not a shuffle then pretend it is the shuffle
20341   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
20342   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
20343   // type VT.
20344   SDValue A, B;
20345   SmallVector<int, 16> LMask(NumElts);
20346   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20347     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
20348       A = LHS.getOperand(0);
20349     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
20350       B = LHS.getOperand(1);
20351     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
20352     std::copy(Mask.begin(), Mask.end(), LMask.begin());
20353   } else {
20354     if (LHS.getOpcode() != ISD::UNDEF)
20355       A = LHS;
20356     for (unsigned i = 0; i != NumElts; ++i)
20357       LMask[i] = i;
20358   }
20359
20360   // Likewise, view RHS in the form
20361   //   RHS = VECTOR_SHUFFLE C, D, RMask
20362   SDValue C, D;
20363   SmallVector<int, 16> RMask(NumElts);
20364   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20365     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20366       C = RHS.getOperand(0);
20367     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20368       D = RHS.getOperand(1);
20369     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20370     std::copy(Mask.begin(), Mask.end(), RMask.begin());
20371   } else {
20372     if (RHS.getOpcode() != ISD::UNDEF)
20373       C = RHS;
20374     for (unsigned i = 0; i != NumElts; ++i)
20375       RMask[i] = i;
20376   }
20377
20378   // Check that the shuffles are both shuffling the same vectors.
20379   if (!(A == C && B == D) && !(A == D && B == C))
20380     return false;
20381
20382   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20383   if (!A.getNode() && !B.getNode())
20384     return false;
20385
20386   // If A and B occur in reverse order in RHS, then "swap" them (which means
20387   // rewriting the mask).
20388   if (A != C)
20389     CommuteVectorShuffleMask(RMask, NumElts);
20390
20391   // At this point LHS and RHS are equivalent to
20392   //   LHS = VECTOR_SHUFFLE A, B, LMask
20393   //   RHS = VECTOR_SHUFFLE A, B, RMask
20394   // Check that the masks correspond to performing a horizontal operation.
20395   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20396     for (unsigned i = 0; i != NumLaneElts; ++i) {
20397       int LIdx = LMask[i+l], RIdx = RMask[i+l];
20398
20399       // Ignore any UNDEF components.
20400       if (LIdx < 0 || RIdx < 0 ||
20401           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20402           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20403         continue;
20404
20405       // Check that successive elements are being operated on.  If not, this is
20406       // not a horizontal operation.
20407       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20408       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20409       if (!(LIdx == Index && RIdx == Index + 1) &&
20410           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20411         return false;
20412     }
20413   }
20414
20415   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20416   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20417   return true;
20418 }
20419
20420 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20421 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20422                                   const X86Subtarget *Subtarget) {
20423   EVT VT = N->getValueType(0);
20424   SDValue LHS = N->getOperand(0);
20425   SDValue RHS = N->getOperand(1);
20426
20427   // Try to synthesize horizontal adds from adds of shuffles.
20428   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20429        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20430       isHorizontalBinOp(LHS, RHS, true))
20431     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20432   return SDValue();
20433 }
20434
20435 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20436 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20437                                   const X86Subtarget *Subtarget) {
20438   EVT VT = N->getValueType(0);
20439   SDValue LHS = N->getOperand(0);
20440   SDValue RHS = N->getOperand(1);
20441
20442   // Try to synthesize horizontal subs from subs of shuffles.
20443   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20444        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20445       isHorizontalBinOp(LHS, RHS, false))
20446     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20447   return SDValue();
20448 }
20449
20450 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20451 /// X86ISD::FXOR nodes.
20452 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20453   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20454   // F[X]OR(0.0, x) -> x
20455   // F[X]OR(x, 0.0) -> x
20456   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20457     if (C->getValueAPF().isPosZero())
20458       return N->getOperand(1);
20459   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20460     if (C->getValueAPF().isPosZero())
20461       return N->getOperand(0);
20462   return SDValue();
20463 }
20464
20465 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20466 /// X86ISD::FMAX nodes.
20467 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20468   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20469
20470   // Only perform optimizations if UnsafeMath is used.
20471   if (!DAG.getTarget().Options.UnsafeFPMath)
20472     return SDValue();
20473
20474   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20475   // into FMINC and FMAXC, which are Commutative operations.
20476   unsigned NewOp = 0;
20477   switch (N->getOpcode()) {
20478     default: llvm_unreachable("unknown opcode");
20479     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20480     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20481   }
20482
20483   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20484                      N->getOperand(0), N->getOperand(1));
20485 }
20486
20487 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20488 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20489   // FAND(0.0, x) -> 0.0
20490   // FAND(x, 0.0) -> 0.0
20491   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20492     if (C->getValueAPF().isPosZero())
20493       return N->getOperand(0);
20494   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20495     if (C->getValueAPF().isPosZero())
20496       return N->getOperand(1);
20497   return SDValue();
20498 }
20499
20500 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20501 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20502   // FANDN(x, 0.0) -> 0.0
20503   // FANDN(0.0, x) -> x
20504   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20505     if (C->getValueAPF().isPosZero())
20506       return N->getOperand(1);
20507   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20508     if (C->getValueAPF().isPosZero())
20509       return N->getOperand(1);
20510   return SDValue();
20511 }
20512
20513 static SDValue PerformBTCombine(SDNode *N,
20514                                 SelectionDAG &DAG,
20515                                 TargetLowering::DAGCombinerInfo &DCI) {
20516   // BT ignores high bits in the bit index operand.
20517   SDValue Op1 = N->getOperand(1);
20518   if (Op1.hasOneUse()) {
20519     unsigned BitWidth = Op1.getValueSizeInBits();
20520     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20521     APInt KnownZero, KnownOne;
20522     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20523                                           !DCI.isBeforeLegalizeOps());
20524     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20525     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20526         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20527       DCI.CommitTargetLoweringOpt(TLO);
20528   }
20529   return SDValue();
20530 }
20531
20532 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20533   SDValue Op = N->getOperand(0);
20534   if (Op.getOpcode() == ISD::BITCAST)
20535     Op = Op.getOperand(0);
20536   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20537   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20538       VT.getVectorElementType().getSizeInBits() ==
20539       OpVT.getVectorElementType().getSizeInBits()) {
20540     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20541   }
20542   return SDValue();
20543 }
20544
20545 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20546                                                const X86Subtarget *Subtarget) {
20547   EVT VT = N->getValueType(0);
20548   if (!VT.isVector())
20549     return SDValue();
20550
20551   SDValue N0 = N->getOperand(0);
20552   SDValue N1 = N->getOperand(1);
20553   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20554   SDLoc dl(N);
20555
20556   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20557   // both SSE and AVX2 since there is no sign-extended shift right
20558   // operation on a vector with 64-bit elements.
20559   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20560   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20561   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20562       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20563     SDValue N00 = N0.getOperand(0);
20564
20565     // EXTLOAD has a better solution on AVX2,
20566     // it may be replaced with X86ISD::VSEXT node.
20567     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20568       if (!ISD::isNormalLoad(N00.getNode()))
20569         return SDValue();
20570
20571     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20572         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20573                                   N00, N1);
20574       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20575     }
20576   }
20577   return SDValue();
20578 }
20579
20580 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20581                                   TargetLowering::DAGCombinerInfo &DCI,
20582                                   const X86Subtarget *Subtarget) {
20583   if (!DCI.isBeforeLegalizeOps())
20584     return SDValue();
20585
20586   if (!Subtarget->hasFp256())
20587     return SDValue();
20588
20589   EVT VT = N->getValueType(0);
20590   if (VT.isVector() && VT.getSizeInBits() == 256) {
20591     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20592     if (R.getNode())
20593       return R;
20594   }
20595
20596   return SDValue();
20597 }
20598
20599 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20600                                  const X86Subtarget* Subtarget) {
20601   SDLoc dl(N);
20602   EVT VT = N->getValueType(0);
20603
20604   // Let legalize expand this if it isn't a legal type yet.
20605   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20606     return SDValue();
20607
20608   EVT ScalarVT = VT.getScalarType();
20609   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20610       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20611     return SDValue();
20612
20613   SDValue A = N->getOperand(0);
20614   SDValue B = N->getOperand(1);
20615   SDValue C = N->getOperand(2);
20616
20617   bool NegA = (A.getOpcode() == ISD::FNEG);
20618   bool NegB = (B.getOpcode() == ISD::FNEG);
20619   bool NegC = (C.getOpcode() == ISD::FNEG);
20620
20621   // Negative multiplication when NegA xor NegB
20622   bool NegMul = (NegA != NegB);
20623   if (NegA)
20624     A = A.getOperand(0);
20625   if (NegB)
20626     B = B.getOperand(0);
20627   if (NegC)
20628     C = C.getOperand(0);
20629
20630   unsigned Opcode;
20631   if (!NegMul)
20632     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20633   else
20634     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20635
20636   return DAG.getNode(Opcode, dl, VT, A, B, C);
20637 }
20638
20639 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20640                                   TargetLowering::DAGCombinerInfo &DCI,
20641                                   const X86Subtarget *Subtarget) {
20642   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20643   //           (and (i32 x86isd::setcc_carry), 1)
20644   // This eliminates the zext. This transformation is necessary because
20645   // ISD::SETCC is always legalized to i8.
20646   SDLoc dl(N);
20647   SDValue N0 = N->getOperand(0);
20648   EVT VT = N->getValueType(0);
20649
20650   if (N0.getOpcode() == ISD::AND &&
20651       N0.hasOneUse() &&
20652       N0.getOperand(0).hasOneUse()) {
20653     SDValue N00 = N0.getOperand(0);
20654     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20655       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20656       if (!C || C->getZExtValue() != 1)
20657         return SDValue();
20658       return DAG.getNode(ISD::AND, dl, VT,
20659                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20660                                      N00.getOperand(0), N00.getOperand(1)),
20661                          DAG.getConstant(1, VT));
20662     }
20663   }
20664
20665   if (N0.getOpcode() == ISD::TRUNCATE &&
20666       N0.hasOneUse() &&
20667       N0.getOperand(0).hasOneUse()) {
20668     SDValue N00 = N0.getOperand(0);
20669     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20670       return DAG.getNode(ISD::AND, dl, VT,
20671                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20672                                      N00.getOperand(0), N00.getOperand(1)),
20673                          DAG.getConstant(1, VT));
20674     }
20675   }
20676   if (VT.is256BitVector()) {
20677     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20678     if (R.getNode())
20679       return R;
20680   }
20681
20682   return SDValue();
20683 }
20684
20685 // Optimize x == -y --> x+y == 0
20686 //          x != -y --> x+y != 0
20687 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20688                                       const X86Subtarget* Subtarget) {
20689   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20690   SDValue LHS = N->getOperand(0);
20691   SDValue RHS = N->getOperand(1);
20692   EVT VT = N->getValueType(0);
20693   SDLoc DL(N);
20694
20695   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20696     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20697       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20698         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20699                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20700         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20701                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20702       }
20703   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20705       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20706         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20707                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20708         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20709                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20710       }
20711
20712   if (VT.getScalarType() == MVT::i1) {
20713     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20714       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20715     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20716     if (!IsSEXT0 && !IsVZero0)
20717       return SDValue();
20718     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20719       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20720     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20721
20722     if (!IsSEXT1 && !IsVZero1)
20723       return SDValue();
20724
20725     if (IsSEXT0 && IsVZero1) {
20726       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20727       if (CC == ISD::SETEQ)
20728         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20729       return LHS.getOperand(0);
20730     }
20731     if (IsSEXT1 && IsVZero0) {
20732       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20733       if (CC == ISD::SETEQ)
20734         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20735       return RHS.getOperand(0);
20736     }
20737   }
20738
20739   return SDValue();
20740 }
20741
20742 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20743                                       const X86Subtarget *Subtarget) {
20744   SDLoc dl(N);
20745   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20746   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20747          "X86insertps is only defined for v4x32");
20748
20749   SDValue Ld = N->getOperand(1);
20750   if (MayFoldLoad(Ld)) {
20751     // Extract the countS bits from the immediate so we can get the proper
20752     // address when narrowing the vector load to a specific element.
20753     // When the second source op is a memory address, interps doesn't use
20754     // countS and just gets an f32 from that address.
20755     unsigned DestIndex =
20756         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20757     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20758   } else
20759     return SDValue();
20760
20761   // Create this as a scalar to vector to match the instruction pattern.
20762   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20763   // countS bits are ignored when loading from memory on insertps, which
20764   // means we don't need to explicitly set them to 0.
20765   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20766                      LoadScalarToVector, N->getOperand(2));
20767 }
20768
20769 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20770 // as "sbb reg,reg", since it can be extended without zext and produces
20771 // an all-ones bit which is more useful than 0/1 in some cases.
20772 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20773                                MVT VT) {
20774   if (VT == MVT::i8)
20775     return DAG.getNode(ISD::AND, DL, VT,
20776                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20777                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20778                        DAG.getConstant(1, VT));
20779   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20780   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20781                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20782                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20783 }
20784
20785 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20786 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20787                                    TargetLowering::DAGCombinerInfo &DCI,
20788                                    const X86Subtarget *Subtarget) {
20789   SDLoc DL(N);
20790   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20791   SDValue EFLAGS = N->getOperand(1);
20792
20793   if (CC == X86::COND_A) {
20794     // Try to convert COND_A into COND_B in an attempt to facilitate
20795     // materializing "setb reg".
20796     //
20797     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20798     // cannot take an immediate as its first operand.
20799     //
20800     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20801         EFLAGS.getValueType().isInteger() &&
20802         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20803       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20804                                    EFLAGS.getNode()->getVTList(),
20805                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20806       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20807       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20808     }
20809   }
20810
20811   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20812   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20813   // cases.
20814   if (CC == X86::COND_B)
20815     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20816
20817   SDValue Flags;
20818
20819   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20820   if (Flags.getNode()) {
20821     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20822     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20823   }
20824
20825   return SDValue();
20826 }
20827
20828 // Optimize branch condition evaluation.
20829 //
20830 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20831                                     TargetLowering::DAGCombinerInfo &DCI,
20832                                     const X86Subtarget *Subtarget) {
20833   SDLoc DL(N);
20834   SDValue Chain = N->getOperand(0);
20835   SDValue Dest = N->getOperand(1);
20836   SDValue EFLAGS = N->getOperand(3);
20837   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20838
20839   SDValue Flags;
20840
20841   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20842   if (Flags.getNode()) {
20843     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20844     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20845                        Flags);
20846   }
20847
20848   return SDValue();
20849 }
20850
20851 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20852                                         const X86TargetLowering *XTLI) {
20853   SDValue Op0 = N->getOperand(0);
20854   EVT InVT = Op0->getValueType(0);
20855
20856   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20857   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20858     SDLoc dl(N);
20859     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20860     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20861     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20862   }
20863
20864   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20865   // a 32-bit target where SSE doesn't support i64->FP operations.
20866   if (Op0.getOpcode() == ISD::LOAD) {
20867     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20868     EVT VT = Ld->getValueType(0);
20869     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20870         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20871         !XTLI->getSubtarget()->is64Bit() &&
20872         VT == MVT::i64) {
20873       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20874                                           Ld->getChain(), Op0, DAG);
20875       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20876       return FILDChain;
20877     }
20878   }
20879   return SDValue();
20880 }
20881
20882 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20883 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20884                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20885   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20886   // the result is either zero or one (depending on the input carry bit).
20887   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20888   if (X86::isZeroNode(N->getOperand(0)) &&
20889       X86::isZeroNode(N->getOperand(1)) &&
20890       // We don't have a good way to replace an EFLAGS use, so only do this when
20891       // dead right now.
20892       SDValue(N, 1).use_empty()) {
20893     SDLoc DL(N);
20894     EVT VT = N->getValueType(0);
20895     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20896     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20897                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20898                                            DAG.getConstant(X86::COND_B,MVT::i8),
20899                                            N->getOperand(2)),
20900                                DAG.getConstant(1, VT));
20901     return DCI.CombineTo(N, Res1, CarryOut);
20902   }
20903
20904   return SDValue();
20905 }
20906
20907 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20908 //      (add Y, (setne X, 0)) -> sbb -1, Y
20909 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20910 //      (sub (setne X, 0), Y) -> adc -1, Y
20911 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20912   SDLoc DL(N);
20913
20914   // Look through ZExts.
20915   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20916   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20917     return SDValue();
20918
20919   SDValue SetCC = Ext.getOperand(0);
20920   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20921     return SDValue();
20922
20923   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20924   if (CC != X86::COND_E && CC != X86::COND_NE)
20925     return SDValue();
20926
20927   SDValue Cmp = SetCC.getOperand(1);
20928   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20929       !X86::isZeroNode(Cmp.getOperand(1)) ||
20930       !Cmp.getOperand(0).getValueType().isInteger())
20931     return SDValue();
20932
20933   SDValue CmpOp0 = Cmp.getOperand(0);
20934   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20935                                DAG.getConstant(1, CmpOp0.getValueType()));
20936
20937   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20938   if (CC == X86::COND_NE)
20939     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20940                        DL, OtherVal.getValueType(), OtherVal,
20941                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20942   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20943                      DL, OtherVal.getValueType(), OtherVal,
20944                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20945 }
20946
20947 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20948 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20949                                  const X86Subtarget *Subtarget) {
20950   EVT VT = N->getValueType(0);
20951   SDValue Op0 = N->getOperand(0);
20952   SDValue Op1 = N->getOperand(1);
20953
20954   // Try to synthesize horizontal adds from adds of shuffles.
20955   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20956        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20957       isHorizontalBinOp(Op0, Op1, true))
20958     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20959
20960   return OptimizeConditionalInDecrement(N, DAG);
20961 }
20962
20963 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20964                                  const X86Subtarget *Subtarget) {
20965   SDValue Op0 = N->getOperand(0);
20966   SDValue Op1 = N->getOperand(1);
20967
20968   // X86 can't encode an immediate LHS of a sub. See if we can push the
20969   // negation into a preceding instruction.
20970   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20971     // If the RHS of the sub is a XOR with one use and a constant, invert the
20972     // immediate. Then add one to the LHS of the sub so we can turn
20973     // X-Y -> X+~Y+1, saving one register.
20974     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20975         isa<ConstantSDNode>(Op1.getOperand(1))) {
20976       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20977       EVT VT = Op0.getValueType();
20978       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20979                                    Op1.getOperand(0),
20980                                    DAG.getConstant(~XorC, VT));
20981       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20982                          DAG.getConstant(C->getAPIntValue()+1, VT));
20983     }
20984   }
20985
20986   // Try to synthesize horizontal adds from adds of shuffles.
20987   EVT VT = N->getValueType(0);
20988   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20989        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20990       isHorizontalBinOp(Op0, Op1, true))
20991     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20992
20993   return OptimizeConditionalInDecrement(N, DAG);
20994 }
20995
20996 /// performVZEXTCombine - Performs build vector combines
20997 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20998                                         TargetLowering::DAGCombinerInfo &DCI,
20999                                         const X86Subtarget *Subtarget) {
21000   // (vzext (bitcast (vzext (x)) -> (vzext x)
21001   SDValue In = N->getOperand(0);
21002   while (In.getOpcode() == ISD::BITCAST)
21003     In = In.getOperand(0);
21004
21005   if (In.getOpcode() != X86ISD::VZEXT)
21006     return SDValue();
21007
21008   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
21009                      In.getOperand(0));
21010 }
21011
21012 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
21013                                              DAGCombinerInfo &DCI) const {
21014   SelectionDAG &DAG = DCI.DAG;
21015   switch (N->getOpcode()) {
21016   default: break;
21017   case ISD::EXTRACT_VECTOR_ELT:
21018     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
21019   case ISD::VSELECT:
21020   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
21021   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
21022   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
21023   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
21024   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
21025   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
21026   case ISD::SHL:
21027   case ISD::SRA:
21028   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
21029   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
21030   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
21031   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
21032   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
21033   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
21034   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
21035   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
21036   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
21037   case X86ISD::FXOR:
21038   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
21039   case X86ISD::FMIN:
21040   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
21041   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
21042   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
21043   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
21044   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
21045   case ISD::ANY_EXTEND:
21046   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
21047   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
21048   case ISD::SIGN_EXTEND_INREG:
21049     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
21050   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
21051   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
21052   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
21053   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
21054   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
21055   case X86ISD::SHUFP:       // Handle all target specific shuffles
21056   case X86ISD::PALIGNR:
21057   case X86ISD::UNPCKH:
21058   case X86ISD::UNPCKL:
21059   case X86ISD::MOVHLPS:
21060   case X86ISD::MOVLHPS:
21061   case X86ISD::PSHUFD:
21062   case X86ISD::PSHUFHW:
21063   case X86ISD::PSHUFLW:
21064   case X86ISD::MOVSS:
21065   case X86ISD::MOVSD:
21066   case X86ISD::VPERMILP:
21067   case X86ISD::VPERM2X128:
21068   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
21069   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
21070   case ISD::INTRINSIC_WO_CHAIN:
21071     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
21072   case X86ISD::INSERTPS:
21073     return PerformINSERTPSCombine(N, DAG, Subtarget);
21074   case ISD::BUILD_VECTOR: return PerformBUILD_VECTORCombine(N, DAG, Subtarget);
21075   }
21076
21077   return SDValue();
21078 }
21079
21080 /// isTypeDesirableForOp - Return true if the target has native support for
21081 /// the specified value type and it is 'desirable' to use the type for the
21082 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
21083 /// instruction encodings are longer and some i16 instructions are slow.
21084 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
21085   if (!isTypeLegal(VT))
21086     return false;
21087   if (VT != MVT::i16)
21088     return true;
21089
21090   switch (Opc) {
21091   default:
21092     return true;
21093   case ISD::LOAD:
21094   case ISD::SIGN_EXTEND:
21095   case ISD::ZERO_EXTEND:
21096   case ISD::ANY_EXTEND:
21097   case ISD::SHL:
21098   case ISD::SRL:
21099   case ISD::SUB:
21100   case ISD::ADD:
21101   case ISD::MUL:
21102   case ISD::AND:
21103   case ISD::OR:
21104   case ISD::XOR:
21105     return false;
21106   }
21107 }
21108
21109 /// IsDesirableToPromoteOp - This method query the target whether it is
21110 /// beneficial for dag combiner to promote the specified node. If true, it
21111 /// should return the desired promotion type by reference.
21112 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
21113   EVT VT = Op.getValueType();
21114   if (VT != MVT::i16)
21115     return false;
21116
21117   bool Promote = false;
21118   bool Commute = false;
21119   switch (Op.getOpcode()) {
21120   default: break;
21121   case ISD::LOAD: {
21122     LoadSDNode *LD = cast<LoadSDNode>(Op);
21123     // If the non-extending load has a single use and it's not live out, then it
21124     // might be folded.
21125     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
21126                                                      Op.hasOneUse()*/) {
21127       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
21128              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
21129         // The only case where we'd want to promote LOAD (rather then it being
21130         // promoted as an operand is when it's only use is liveout.
21131         if (UI->getOpcode() != ISD::CopyToReg)
21132           return false;
21133       }
21134     }
21135     Promote = true;
21136     break;
21137   }
21138   case ISD::SIGN_EXTEND:
21139   case ISD::ZERO_EXTEND:
21140   case ISD::ANY_EXTEND:
21141     Promote = true;
21142     break;
21143   case ISD::SHL:
21144   case ISD::SRL: {
21145     SDValue N0 = Op.getOperand(0);
21146     // Look out for (store (shl (load), x)).
21147     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
21148       return false;
21149     Promote = true;
21150     break;
21151   }
21152   case ISD::ADD:
21153   case ISD::MUL:
21154   case ISD::AND:
21155   case ISD::OR:
21156   case ISD::XOR:
21157     Commute = true;
21158     // fallthrough
21159   case ISD::SUB: {
21160     SDValue N0 = Op.getOperand(0);
21161     SDValue N1 = Op.getOperand(1);
21162     if (!Commute && MayFoldLoad(N1))
21163       return false;
21164     // Avoid disabling potential load folding opportunities.
21165     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
21166       return false;
21167     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
21168       return false;
21169     Promote = true;
21170   }
21171   }
21172
21173   PVT = MVT::i32;
21174   return Promote;
21175 }
21176
21177 //===----------------------------------------------------------------------===//
21178 //                           X86 Inline Assembly Support
21179 //===----------------------------------------------------------------------===//
21180
21181 namespace {
21182   // Helper to match a string separated by whitespace.
21183   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
21184     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
21185
21186     for (unsigned i = 0, e = args.size(); i != e; ++i) {
21187       StringRef piece(*args[i]);
21188       if (!s.startswith(piece)) // Check if the piece matches.
21189         return false;
21190
21191       s = s.substr(piece.size());
21192       StringRef::size_type pos = s.find_first_not_of(" \t");
21193       if (pos == 0) // We matched a prefix.
21194         return false;
21195
21196       s = s.substr(pos);
21197     }
21198
21199     return s.empty();
21200   }
21201   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
21202 }
21203
21204 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
21205
21206   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
21207     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
21208         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
21209         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
21210
21211       if (AsmPieces.size() == 3)
21212         return true;
21213       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
21214         return true;
21215     }
21216   }
21217   return false;
21218 }
21219
21220 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
21221   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
21222
21223   std::string AsmStr = IA->getAsmString();
21224
21225   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
21226   if (!Ty || Ty->getBitWidth() % 16 != 0)
21227     return false;
21228
21229   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
21230   SmallVector<StringRef, 4> AsmPieces;
21231   SplitString(AsmStr, AsmPieces, ";\n");
21232
21233   switch (AsmPieces.size()) {
21234   default: return false;
21235   case 1:
21236     // FIXME: this should verify that we are targeting a 486 or better.  If not,
21237     // we will turn this bswap into something that will be lowered to logical
21238     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
21239     // lower so don't worry about this.
21240     // bswap $0
21241     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
21242         matchAsm(AsmPieces[0], "bswapl", "$0") ||
21243         matchAsm(AsmPieces[0], "bswapq", "$0") ||
21244         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
21245         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
21246         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
21247       // No need to check constraints, nothing other than the equivalent of
21248       // "=r,0" would be valid here.
21249       return IntrinsicLowering::LowerToByteSwap(CI);
21250     }
21251
21252     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
21253     if (CI->getType()->isIntegerTy(16) &&
21254         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21255         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
21256          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
21257       AsmPieces.clear();
21258       const std::string &ConstraintsStr = IA->getConstraintString();
21259       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21260       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21261       if (clobbersFlagRegisters(AsmPieces))
21262         return IntrinsicLowering::LowerToByteSwap(CI);
21263     }
21264     break;
21265   case 3:
21266     if (CI->getType()->isIntegerTy(32) &&
21267         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
21268         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
21269         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
21270         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
21271       AsmPieces.clear();
21272       const std::string &ConstraintsStr = IA->getConstraintString();
21273       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
21274       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
21275       if (clobbersFlagRegisters(AsmPieces))
21276         return IntrinsicLowering::LowerToByteSwap(CI);
21277     }
21278
21279     if (CI->getType()->isIntegerTy(64)) {
21280       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
21281       if (Constraints.size() >= 2 &&
21282           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
21283           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
21284         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
21285         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
21286             matchAsm(AsmPieces[1], "bswap", "%edx") &&
21287             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
21288           return IntrinsicLowering::LowerToByteSwap(CI);
21289       }
21290     }
21291     break;
21292   }
21293   return false;
21294 }
21295
21296 /// getConstraintType - Given a constraint letter, return the type of
21297 /// constraint it is for this target.
21298 X86TargetLowering::ConstraintType
21299 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
21300   if (Constraint.size() == 1) {
21301     switch (Constraint[0]) {
21302     case 'R':
21303     case 'q':
21304     case 'Q':
21305     case 'f':
21306     case 't':
21307     case 'u':
21308     case 'y':
21309     case 'x':
21310     case 'Y':
21311     case 'l':
21312       return C_RegisterClass;
21313     case 'a':
21314     case 'b':
21315     case 'c':
21316     case 'd':
21317     case 'S':
21318     case 'D':
21319     case 'A':
21320       return C_Register;
21321     case 'I':
21322     case 'J':
21323     case 'K':
21324     case 'L':
21325     case 'M':
21326     case 'N':
21327     case 'G':
21328     case 'C':
21329     case 'e':
21330     case 'Z':
21331       return C_Other;
21332     default:
21333       break;
21334     }
21335   }
21336   return TargetLowering::getConstraintType(Constraint);
21337 }
21338
21339 /// Examine constraint type and operand type and determine a weight value.
21340 /// This object must already have been set up with the operand type
21341 /// and the current alternative constraint selected.
21342 TargetLowering::ConstraintWeight
21343   X86TargetLowering::getSingleConstraintMatchWeight(
21344     AsmOperandInfo &info, const char *constraint) const {
21345   ConstraintWeight weight = CW_Invalid;
21346   Value *CallOperandVal = info.CallOperandVal;
21347     // If we don't have a value, we can't do a match,
21348     // but allow it at the lowest weight.
21349   if (!CallOperandVal)
21350     return CW_Default;
21351   Type *type = CallOperandVal->getType();
21352   // Look at the constraint type.
21353   switch (*constraint) {
21354   default:
21355     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
21356   case 'R':
21357   case 'q':
21358   case 'Q':
21359   case 'a':
21360   case 'b':
21361   case 'c':
21362   case 'd':
21363   case 'S':
21364   case 'D':
21365   case 'A':
21366     if (CallOperandVal->getType()->isIntegerTy())
21367       weight = CW_SpecificReg;
21368     break;
21369   case 'f':
21370   case 't':
21371   case 'u':
21372     if (type->isFloatingPointTy())
21373       weight = CW_SpecificReg;
21374     break;
21375   case 'y':
21376     if (type->isX86_MMXTy() && Subtarget->hasMMX())
21377       weight = CW_SpecificReg;
21378     break;
21379   case 'x':
21380   case 'Y':
21381     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21382         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21383       weight = CW_Register;
21384     break;
21385   case 'I':
21386     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21387       if (C->getZExtValue() <= 31)
21388         weight = CW_Constant;
21389     }
21390     break;
21391   case 'J':
21392     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21393       if (C->getZExtValue() <= 63)
21394         weight = CW_Constant;
21395     }
21396     break;
21397   case 'K':
21398     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21399       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21400         weight = CW_Constant;
21401     }
21402     break;
21403   case 'L':
21404     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21405       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21406         weight = CW_Constant;
21407     }
21408     break;
21409   case 'M':
21410     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21411       if (C->getZExtValue() <= 3)
21412         weight = CW_Constant;
21413     }
21414     break;
21415   case 'N':
21416     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21417       if (C->getZExtValue() <= 0xff)
21418         weight = CW_Constant;
21419     }
21420     break;
21421   case 'G':
21422   case 'C':
21423     if (dyn_cast<ConstantFP>(CallOperandVal)) {
21424       weight = CW_Constant;
21425     }
21426     break;
21427   case 'e':
21428     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21429       if ((C->getSExtValue() >= -0x80000000LL) &&
21430           (C->getSExtValue() <= 0x7fffffffLL))
21431         weight = CW_Constant;
21432     }
21433     break;
21434   case 'Z':
21435     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21436       if (C->getZExtValue() <= 0xffffffff)
21437         weight = CW_Constant;
21438     }
21439     break;
21440   }
21441   return weight;
21442 }
21443
21444 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21445 /// with another that has more specific requirements based on the type of the
21446 /// corresponding operand.
21447 const char *X86TargetLowering::
21448 LowerXConstraint(EVT ConstraintVT) const {
21449   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21450   // 'f' like normal targets.
21451   if (ConstraintVT.isFloatingPoint()) {
21452     if (Subtarget->hasSSE2())
21453       return "Y";
21454     if (Subtarget->hasSSE1())
21455       return "x";
21456   }
21457
21458   return TargetLowering::LowerXConstraint(ConstraintVT);
21459 }
21460
21461 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21462 /// vector.  If it is invalid, don't add anything to Ops.
21463 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21464                                                      std::string &Constraint,
21465                                                      std::vector<SDValue>&Ops,
21466                                                      SelectionDAG &DAG) const {
21467   SDValue Result;
21468
21469   // Only support length 1 constraints for now.
21470   if (Constraint.length() > 1) return;
21471
21472   char ConstraintLetter = Constraint[0];
21473   switch (ConstraintLetter) {
21474   default: break;
21475   case 'I':
21476     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21477       if (C->getZExtValue() <= 31) {
21478         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21479         break;
21480       }
21481     }
21482     return;
21483   case 'J':
21484     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21485       if (C->getZExtValue() <= 63) {
21486         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21487         break;
21488       }
21489     }
21490     return;
21491   case 'K':
21492     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21493       if (isInt<8>(C->getSExtValue())) {
21494         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21495         break;
21496       }
21497     }
21498     return;
21499   case 'N':
21500     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21501       if (C->getZExtValue() <= 255) {
21502         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21503         break;
21504       }
21505     }
21506     return;
21507   case 'e': {
21508     // 32-bit signed value
21509     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21510       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21511                                            C->getSExtValue())) {
21512         // Widen to 64 bits here to get it sign extended.
21513         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21514         break;
21515       }
21516     // FIXME gcc accepts some relocatable values here too, but only in certain
21517     // memory models; it's complicated.
21518     }
21519     return;
21520   }
21521   case 'Z': {
21522     // 32-bit unsigned value
21523     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21524       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21525                                            C->getZExtValue())) {
21526         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21527         break;
21528       }
21529     }
21530     // FIXME gcc accepts some relocatable values here too, but only in certain
21531     // memory models; it's complicated.
21532     return;
21533   }
21534   case 'i': {
21535     // Literal immediates are always ok.
21536     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21537       // Widen to 64 bits here to get it sign extended.
21538       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21539       break;
21540     }
21541
21542     // In any sort of PIC mode addresses need to be computed at runtime by
21543     // adding in a register or some sort of table lookup.  These can't
21544     // be used as immediates.
21545     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21546       return;
21547
21548     // If we are in non-pic codegen mode, we allow the address of a global (with
21549     // an optional displacement) to be used with 'i'.
21550     GlobalAddressSDNode *GA = nullptr;
21551     int64_t Offset = 0;
21552
21553     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21554     while (1) {
21555       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21556         Offset += GA->getOffset();
21557         break;
21558       } else if (Op.getOpcode() == ISD::ADD) {
21559         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21560           Offset += C->getZExtValue();
21561           Op = Op.getOperand(0);
21562           continue;
21563         }
21564       } else if (Op.getOpcode() == ISD::SUB) {
21565         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21566           Offset += -C->getZExtValue();
21567           Op = Op.getOperand(0);
21568           continue;
21569         }
21570       }
21571
21572       // Otherwise, this isn't something we can handle, reject it.
21573       return;
21574     }
21575
21576     const GlobalValue *GV = GA->getGlobal();
21577     // If we require an extra load to get this address, as in PIC mode, we
21578     // can't accept it.
21579     if (isGlobalStubReference(
21580             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
21581       return;
21582
21583     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21584                                         GA->getValueType(0), Offset);
21585     break;
21586   }
21587   }
21588
21589   if (Result.getNode()) {
21590     Ops.push_back(Result);
21591     return;
21592   }
21593   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21594 }
21595
21596 std::pair<unsigned, const TargetRegisterClass*>
21597 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21598                                                 MVT VT) const {
21599   // First, see if this is a constraint that directly corresponds to an LLVM
21600   // register class.
21601   if (Constraint.size() == 1) {
21602     // GCC Constraint Letters
21603     switch (Constraint[0]) {
21604     default: break;
21605       // TODO: Slight differences here in allocation order and leaving
21606       // RIP in the class. Do they matter any more here than they do
21607       // in the normal allocation?
21608     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21609       if (Subtarget->is64Bit()) {
21610         if (VT == MVT::i32 || VT == MVT::f32)
21611           return std::make_pair(0U, &X86::GR32RegClass);
21612         if (VT == MVT::i16)
21613           return std::make_pair(0U, &X86::GR16RegClass);
21614         if (VT == MVT::i8 || VT == MVT::i1)
21615           return std::make_pair(0U, &X86::GR8RegClass);
21616         if (VT == MVT::i64 || VT == MVT::f64)
21617           return std::make_pair(0U, &X86::GR64RegClass);
21618         break;
21619       }
21620       // 32-bit fallthrough
21621     case 'Q':   // Q_REGS
21622       if (VT == MVT::i32 || VT == MVT::f32)
21623         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21624       if (VT == MVT::i16)
21625         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21626       if (VT == MVT::i8 || VT == MVT::i1)
21627         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21628       if (VT == MVT::i64)
21629         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21630       break;
21631     case 'r':   // GENERAL_REGS
21632     case 'l':   // INDEX_REGS
21633       if (VT == MVT::i8 || VT == MVT::i1)
21634         return std::make_pair(0U, &X86::GR8RegClass);
21635       if (VT == MVT::i16)
21636         return std::make_pair(0U, &X86::GR16RegClass);
21637       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21638         return std::make_pair(0U, &X86::GR32RegClass);
21639       return std::make_pair(0U, &X86::GR64RegClass);
21640     case 'R':   // LEGACY_REGS
21641       if (VT == MVT::i8 || VT == MVT::i1)
21642         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21643       if (VT == MVT::i16)
21644         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21645       if (VT == MVT::i32 || !Subtarget->is64Bit())
21646         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21647       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21648     case 'f':  // FP Stack registers.
21649       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21650       // value to the correct fpstack register class.
21651       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21652         return std::make_pair(0U, &X86::RFP32RegClass);
21653       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21654         return std::make_pair(0U, &X86::RFP64RegClass);
21655       return std::make_pair(0U, &X86::RFP80RegClass);
21656     case 'y':   // MMX_REGS if MMX allowed.
21657       if (!Subtarget->hasMMX()) break;
21658       return std::make_pair(0U, &X86::VR64RegClass);
21659     case 'Y':   // SSE_REGS if SSE2 allowed
21660       if (!Subtarget->hasSSE2()) break;
21661       // FALL THROUGH.
21662     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21663       if (!Subtarget->hasSSE1()) break;
21664
21665       switch (VT.SimpleTy) {
21666       default: break;
21667       // Scalar SSE types.
21668       case MVT::f32:
21669       case MVT::i32:
21670         return std::make_pair(0U, &X86::FR32RegClass);
21671       case MVT::f64:
21672       case MVT::i64:
21673         return std::make_pair(0U, &X86::FR64RegClass);
21674       // Vector types.
21675       case MVT::v16i8:
21676       case MVT::v8i16:
21677       case MVT::v4i32:
21678       case MVT::v2i64:
21679       case MVT::v4f32:
21680       case MVT::v2f64:
21681         return std::make_pair(0U, &X86::VR128RegClass);
21682       // AVX types.
21683       case MVT::v32i8:
21684       case MVT::v16i16:
21685       case MVT::v8i32:
21686       case MVT::v4i64:
21687       case MVT::v8f32:
21688       case MVT::v4f64:
21689         return std::make_pair(0U, &X86::VR256RegClass);
21690       case MVT::v8f64:
21691       case MVT::v16f32:
21692       case MVT::v16i32:
21693       case MVT::v8i64:
21694         return std::make_pair(0U, &X86::VR512RegClass);
21695       }
21696       break;
21697     }
21698   }
21699
21700   // Use the default implementation in TargetLowering to convert the register
21701   // constraint into a member of a register class.
21702   std::pair<unsigned, const TargetRegisterClass*> Res;
21703   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21704
21705   // Not found as a standard register?
21706   if (!Res.second) {
21707     // Map st(0) -> st(7) -> ST0
21708     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21709         tolower(Constraint[1]) == 's' &&
21710         tolower(Constraint[2]) == 't' &&
21711         Constraint[3] == '(' &&
21712         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21713         Constraint[5] == ')' &&
21714         Constraint[6] == '}') {
21715
21716       Res.first = X86::ST0+Constraint[4]-'0';
21717       Res.second = &X86::RFP80RegClass;
21718       return Res;
21719     }
21720
21721     // GCC allows "st(0)" to be called just plain "st".
21722     if (StringRef("{st}").equals_lower(Constraint)) {
21723       Res.first = X86::ST0;
21724       Res.second = &X86::RFP80RegClass;
21725       return Res;
21726     }
21727
21728     // flags -> EFLAGS
21729     if (StringRef("{flags}").equals_lower(Constraint)) {
21730       Res.first = X86::EFLAGS;
21731       Res.second = &X86::CCRRegClass;
21732       return Res;
21733     }
21734
21735     // 'A' means EAX + EDX.
21736     if (Constraint == "A") {
21737       Res.first = X86::EAX;
21738       Res.second = &X86::GR32_ADRegClass;
21739       return Res;
21740     }
21741     return Res;
21742   }
21743
21744   // Otherwise, check to see if this is a register class of the wrong value
21745   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21746   // turn into {ax},{dx}.
21747   if (Res.second->hasType(VT))
21748     return Res;   // Correct type already, nothing to do.
21749
21750   // All of the single-register GCC register classes map their values onto
21751   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21752   // really want an 8-bit or 32-bit register, map to the appropriate register
21753   // class and return the appropriate register.
21754   if (Res.second == &X86::GR16RegClass) {
21755     if (VT == MVT::i8 || VT == MVT::i1) {
21756       unsigned DestReg = 0;
21757       switch (Res.first) {
21758       default: break;
21759       case X86::AX: DestReg = X86::AL; break;
21760       case X86::DX: DestReg = X86::DL; break;
21761       case X86::CX: DestReg = X86::CL; break;
21762       case X86::BX: DestReg = X86::BL; break;
21763       }
21764       if (DestReg) {
21765         Res.first = DestReg;
21766         Res.second = &X86::GR8RegClass;
21767       }
21768     } else if (VT == MVT::i32 || VT == MVT::f32) {
21769       unsigned DestReg = 0;
21770       switch (Res.first) {
21771       default: break;
21772       case X86::AX: DestReg = X86::EAX; break;
21773       case X86::DX: DestReg = X86::EDX; break;
21774       case X86::CX: DestReg = X86::ECX; break;
21775       case X86::BX: DestReg = X86::EBX; break;
21776       case X86::SI: DestReg = X86::ESI; break;
21777       case X86::DI: DestReg = X86::EDI; break;
21778       case X86::BP: DestReg = X86::EBP; break;
21779       case X86::SP: DestReg = X86::ESP; break;
21780       }
21781       if (DestReg) {
21782         Res.first = DestReg;
21783         Res.second = &X86::GR32RegClass;
21784       }
21785     } else if (VT == MVT::i64 || VT == MVT::f64) {
21786       unsigned DestReg = 0;
21787       switch (Res.first) {
21788       default: break;
21789       case X86::AX: DestReg = X86::RAX; break;
21790       case X86::DX: DestReg = X86::RDX; break;
21791       case X86::CX: DestReg = X86::RCX; break;
21792       case X86::BX: DestReg = X86::RBX; break;
21793       case X86::SI: DestReg = X86::RSI; break;
21794       case X86::DI: DestReg = X86::RDI; break;
21795       case X86::BP: DestReg = X86::RBP; break;
21796       case X86::SP: DestReg = X86::RSP; break;
21797       }
21798       if (DestReg) {
21799         Res.first = DestReg;
21800         Res.second = &X86::GR64RegClass;
21801       }
21802     }
21803   } else if (Res.second == &X86::FR32RegClass ||
21804              Res.second == &X86::FR64RegClass ||
21805              Res.second == &X86::VR128RegClass ||
21806              Res.second == &X86::VR256RegClass ||
21807              Res.second == &X86::FR32XRegClass ||
21808              Res.second == &X86::FR64XRegClass ||
21809              Res.second == &X86::VR128XRegClass ||
21810              Res.second == &X86::VR256XRegClass ||
21811              Res.second == &X86::VR512RegClass) {
21812     // Handle references to XMM physical registers that got mapped into the
21813     // wrong class.  This can happen with constraints like {xmm0} where the
21814     // target independent register mapper will just pick the first match it can
21815     // find, ignoring the required type.
21816
21817     if (VT == MVT::f32 || VT == MVT::i32)
21818       Res.second = &X86::FR32RegClass;
21819     else if (VT == MVT::f64 || VT == MVT::i64)
21820       Res.second = &X86::FR64RegClass;
21821     else if (X86::VR128RegClass.hasType(VT))
21822       Res.second = &X86::VR128RegClass;
21823     else if (X86::VR256RegClass.hasType(VT))
21824       Res.second = &X86::VR256RegClass;
21825     else if (X86::VR512RegClass.hasType(VT))
21826       Res.second = &X86::VR512RegClass;
21827   }
21828
21829   return Res;
21830 }
21831
21832 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21833                                             Type *Ty) const {
21834   // Scaling factors are not free at all.
21835   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21836   // will take 2 allocations in the out of order engine instead of 1
21837   // for plain addressing mode, i.e. inst (reg1).
21838   // E.g.,
21839   // vaddps (%rsi,%drx), %ymm0, %ymm1
21840   // Requires two allocations (one for the load, one for the computation)
21841   // whereas:
21842   // vaddps (%rsi), %ymm0, %ymm1
21843   // Requires just 1 allocation, i.e., freeing allocations for other operations
21844   // and having less micro operations to execute.
21845   //
21846   // For some X86 architectures, this is even worse because for instance for
21847   // stores, the complex addressing mode forces the instruction to use the
21848   // "load" ports instead of the dedicated "store" port.
21849   // E.g., on Haswell:
21850   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21851   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21852   if (isLegalAddressingMode(AM, Ty))
21853     // Scale represents reg2 * scale, thus account for 1
21854     // as soon as we use a second register.
21855     return AM.Scale != 0;
21856   return -1;
21857 }
21858
21859 bool X86TargetLowering::isTargetFTOL() const {
21860   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
21861 }