Have the TLOF creation take a Triple rather than needing a subtarget.
[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 X86TargetLowering::X86TargetLowering(X86TargetMachine &TM)
200   : TargetLowering(TM, createTLOF(Triple(TM.getTargetTriple()))) {
201   Subtarget = &TM.getSubtarget<X86Subtarget>();
202   X86ScalarSSEf64 = Subtarget->hasSSE2();
203   X86ScalarSSEf32 = Subtarget->hasSSE1();
204   TD = getDataLayout();
205
206   resetOperationActions();
207 }
208
209 void X86TargetLowering::resetOperationActions() {
210   const TargetMachine &TM = getTargetMachine();
211   static bool FirstTimeThrough = true;
212
213   // If none of the target options have changed, then we don't need to reset the
214   // operation actions.
215   if (!FirstTimeThrough && TO == TM.Options) return;
216
217   if (!FirstTimeThrough) {
218     // Reinitialize the actions.
219     initActions();
220     FirstTimeThrough = false;
221   }
222
223   TO = TM.Options;
224
225   // Set up the TargetLowering object.
226   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
227
228   // X86 is weird, it always uses i8 for shift amounts and setcc results.
229   setBooleanContents(ZeroOrOneBooleanContent);
230   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
231   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232
233   // For 64-bit since we have so many registers use the ILP scheduler, for
234   // 32-bit code use the register pressure specific scheduling.
235   // For Atom, always use ILP scheduling.
236   if (Subtarget->isAtom())
237     setSchedulingPreference(Sched::ILP);
238   else if (Subtarget->is64Bit())
239     setSchedulingPreference(Sched::ILP);
240   else
241     setSchedulingPreference(Sched::RegPressure);
242   const X86RegisterInfo *RegInfo =
243     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
244   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
245
246   // Bypass expensive divides on Atom when compiling with O2
247   if (Subtarget->hasSlowDivide() && TM.getOptLevel() >= CodeGenOpt::Default) {
248     addBypassSlowDiv(32, 8);
249     if (Subtarget->is64Bit())
250       addBypassSlowDiv(64, 16);
251   }
252
253   if (Subtarget->isTargetKnownWindowsMSVC()) {
254     // Setup Windows compiler runtime calls.
255     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
256     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
257     setLibcallName(RTLIB::SREM_I64, "_allrem");
258     setLibcallName(RTLIB::UREM_I64, "_aullrem");
259     setLibcallName(RTLIB::MUL_I64, "_allmul");
260     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
261     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
262     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
263     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
264     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
265
266     // The _ftol2 runtime function has an unusual calling conv, which
267     // is modeled by a special pseudo-instruction.
268     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
269     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
270     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
271     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
272   }
273
274   if (Subtarget->isTargetDarwin()) {
275     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
276     setUseUnderscoreSetJmp(false);
277     setUseUnderscoreLongJmp(false);
278   } else if (Subtarget->isTargetWindowsGNU()) {
279     // MS runtime is weird: it exports _setjmp, but longjmp!
280     setUseUnderscoreSetJmp(true);
281     setUseUnderscoreLongJmp(false);
282   } else {
283     setUseUnderscoreSetJmp(true);
284     setUseUnderscoreLongJmp(true);
285   }
286
287   // Set up the register classes.
288   addRegisterClass(MVT::i8, &X86::GR8RegClass);
289   addRegisterClass(MVT::i16, &X86::GR16RegClass);
290   addRegisterClass(MVT::i32, &X86::GR32RegClass);
291   if (Subtarget->is64Bit())
292     addRegisterClass(MVT::i64, &X86::GR64RegClass);
293
294   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
295
296   // We don't accept any truncstore of integer registers.
297   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
298   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
299   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
300   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
301   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
302   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
303
304   // SETOEQ and SETUNE require checking two conditions.
305   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
306   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
307   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
308   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
309   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
310   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
311
312   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
313   // operation.
314   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
315   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
316   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
317
318   if (Subtarget->is64Bit()) {
319     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
320     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
321   } else if (!TM.Options.UseSoftFloat) {
322     // We have an algorithm for SSE2->double, and we turn this into a
323     // 64-bit FILD followed by conditional FADD for other targets.
324     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
325     // We have an algorithm for SSE2, and we turn this into a 64-bit
326     // FILD for other targets.
327     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
328   }
329
330   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
331   // this operation.
332   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
333   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
334
335   if (!TM.Options.UseSoftFloat) {
336     // SSE has no i16 to fp conversion, only i32
337     if (X86ScalarSSEf32) {
338       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
339       // f32 and f64 cases are Legal, f80 case is not
340       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
341     } else {
342       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
343       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
344     }
345   } else {
346     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
347     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
348   }
349
350   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
351   // are Legal, f80 is custom lowered.
352   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
353   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
354
355   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
356   // this operation.
357   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
358   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
359
360   if (X86ScalarSSEf32) {
361     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
362     // f32 and f64 cases are Legal, f80 case is not
363     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
364   } else {
365     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
366     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
367   }
368
369   // Handle FP_TO_UINT by promoting the destination to a larger signed
370   // conversion.
371   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
372   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
373   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
374
375   if (Subtarget->is64Bit()) {
376     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
377     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
378   } else if (!TM.Options.UseSoftFloat) {
379     // Since AVX is a superset of SSE3, only check for SSE here.
380     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
381       // Expand FP_TO_UINT into a select.
382       // FIXME: We would like to use a Custom expander here eventually to do
383       // the optimal thing for SSE vs. the default expansion in the legalizer.
384       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
385     else
386       // With SSE3 we can use fisttpll to convert to a signed i64; without
387       // SSE, we're stuck with a fistpll.
388       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
389   }
390
391   if (isTargetFTOL()) {
392     // Use the _ftol2 runtime function, which has a pseudo-instruction
393     // to handle its weird calling convention.
394     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
395   }
396
397   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
398   if (!X86ScalarSSEf64) {
399     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
400     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
401     if (Subtarget->is64Bit()) {
402       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
403       // Without SSE, i64->f64 goes through memory.
404       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
405     }
406   }
407
408   // Scalar integer divide and remainder are lowered to use operations that
409   // produce two results, to match the available instructions. This exposes
410   // the two-result form to trivial CSE, which is able to combine x/y and x%y
411   // into a single instruction.
412   //
413   // Scalar integer multiply-high is also lowered to use two-result
414   // operations, to match the available instructions. However, plain multiply
415   // (low) operations are left as Legal, as there are single-result
416   // instructions for this in x86. Using the two-result multiply instructions
417   // when both high and low results are needed must be arranged by dagcombine.
418   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
419     MVT VT = IntVTs[i];
420     setOperationAction(ISD::MULHS, VT, Expand);
421     setOperationAction(ISD::MULHU, VT, Expand);
422     setOperationAction(ISD::SDIV, VT, Expand);
423     setOperationAction(ISD::UDIV, VT, Expand);
424     setOperationAction(ISD::SREM, VT, Expand);
425     setOperationAction(ISD::UREM, VT, Expand);
426
427     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
428     setOperationAction(ISD::ADDC, VT, Custom);
429     setOperationAction(ISD::ADDE, VT, Custom);
430     setOperationAction(ISD::SUBC, VT, Custom);
431     setOperationAction(ISD::SUBE, VT, Custom);
432   }
433
434   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
435   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
436   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
437   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
438   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
439   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
440   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
441   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
442   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
443   setOperationAction(ISD::SELECT_CC        , MVT::Other, Expand);
444   if (Subtarget->is64Bit())
445     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
446   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
447   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
448   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
449   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
450   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
451   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
452   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
453   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
454
455   // Promote the i8 variants and force them on up to i32 which has a shorter
456   // encoding.
457   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
458   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
459   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
460   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
461   if (Subtarget->hasBMI()) {
462     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
463     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
464     if (Subtarget->is64Bit())
465       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
466   } else {
467     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
468     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
469     if (Subtarget->is64Bit())
470       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
471   }
472
473   if (Subtarget->hasLZCNT()) {
474     // When promoting the i8 variants, force them to i32 for a shorter
475     // encoding.
476     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
477     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
478     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
479     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
480     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
482     if (Subtarget->is64Bit())
483       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
484   } else {
485     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
486     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
487     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
488     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
489     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
490     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
491     if (Subtarget->is64Bit()) {
492       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
493       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
494     }
495   }
496
497   if (Subtarget->hasPOPCNT()) {
498     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
499   } else {
500     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
501     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
502     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
503     if (Subtarget->is64Bit())
504       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
505   }
506
507   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
508
509   if (!Subtarget->hasMOVBE())
510     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
511
512   // These should be promoted to a larger select which is supported.
513   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
514   // X86 wants to expand cmov itself.
515   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
516   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
517   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
518   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
519   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
520   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
521   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
522   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
523   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
524   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
525   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
526   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
527   if (Subtarget->is64Bit()) {
528     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
529     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
530   }
531   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
532   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
533   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
534   // support continuation, user-level threading, and etc.. As a result, no
535   // other SjLj exception interfaces are implemented and please don't build
536   // your own exception handling based on them.
537   // LLVM/Clang supports zero-cost DWARF exception handling.
538   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
539   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
540
541   // Darwin ABI issue.
542   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
543   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
544   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
545   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
546   if (Subtarget->is64Bit())
547     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
548   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
549   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
550   if (Subtarget->is64Bit()) {
551     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
552     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
553     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
554     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
555     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
556   }
557   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
558   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
559   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
560   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
561   if (Subtarget->is64Bit()) {
562     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
563     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
564     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
565   }
566
567   if (Subtarget->hasSSE1())
568     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
569
570   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
571
572   // Expand certain atomics
573   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
574     MVT VT = IntVTs[i];
575     setOperationAction(ISD::ATOMIC_CMP_SWAP, VT, Custom);
576     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
577     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
578   }
579
580   if (!Subtarget->is64Bit()) {
581     setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Custom);
582     setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, Custom);
583     setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
584     setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
585     setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, Custom);
586     setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, Custom);
587     setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i64, Custom);
588     setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, Custom);
589     setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i64, Custom);
590     setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i64, Custom);
591     setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i64, Custom);
592     setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i64, Custom);
593   }
594
595   if (Subtarget->hasCmpxchg16b()) {
596     setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
597   }
598
599   // FIXME - use subtarget debug flags
600   if (!Subtarget->isTargetDarwin() &&
601       !Subtarget->isTargetELF() &&
602       !Subtarget->isTargetCygMing()) {
603     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
604   }
605
606   if (Subtarget->is64Bit()) {
607     setExceptionPointerRegister(X86::RAX);
608     setExceptionSelectorRegister(X86::RDX);
609   } else {
610     setExceptionPointerRegister(X86::EAX);
611     setExceptionSelectorRegister(X86::EDX);
612   }
613   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
614   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
615
616   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
617   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
618
619   setOperationAction(ISD::TRAP, MVT::Other, Legal);
620   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
621
622   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
623   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
624   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
625   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
626     // TargetInfo::X86_64ABIBuiltinVaList
627     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
628     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
629   } else {
630     // TargetInfo::CharPtrBuiltinVaList
631     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
632     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
633   }
634
635   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
636   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
637
638   setOperationAction(ISD::DYNAMIC_STACKALLOC, Subtarget->is64Bit() ?
639                      MVT::i64 : MVT::i32, Custom);
640
641   if (!TM.Options.UseSoftFloat && X86ScalarSSEf64) {
642     // f32 and f64 use SSE.
643     // Set up the FP register classes.
644     addRegisterClass(MVT::f32, &X86::FR32RegClass);
645     addRegisterClass(MVT::f64, &X86::FR64RegClass);
646
647     // Use ANDPD to simulate FABS.
648     setOperationAction(ISD::FABS , MVT::f64, Custom);
649     setOperationAction(ISD::FABS , MVT::f32, Custom);
650
651     // Use XORP to simulate FNEG.
652     setOperationAction(ISD::FNEG , MVT::f64, Custom);
653     setOperationAction(ISD::FNEG , MVT::f32, Custom);
654
655     // Use ANDPD and ORPD to simulate FCOPYSIGN.
656     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
657     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
658
659     // Lower this to FGETSIGNx86 plus an AND.
660     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
661     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
662
663     // We don't support sin/cos/fmod
664     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
665     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
666     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
667     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
668     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
669     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
670
671     // Expand FP immediates into loads from the stack, except for the special
672     // cases we handle.
673     addLegalFPImmediate(APFloat(+0.0)); // xorpd
674     addLegalFPImmediate(APFloat(+0.0f)); // xorps
675   } else if (!TM.Options.UseSoftFloat && X86ScalarSSEf32) {
676     // Use SSE for f32, x87 for f64.
677     // Set up the FP register classes.
678     addRegisterClass(MVT::f32, &X86::FR32RegClass);
679     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
680
681     // Use ANDPS to simulate FABS.
682     setOperationAction(ISD::FABS , MVT::f32, Custom);
683
684     // Use XORP to simulate FNEG.
685     setOperationAction(ISD::FNEG , MVT::f32, Custom);
686
687     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
688
689     // Use ANDPS and ORPS to simulate FCOPYSIGN.
690     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
691     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
692
693     // We don't support sin/cos/fmod
694     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
695     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
696     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
697
698     // Special cases we handle for FP constants.
699     addLegalFPImmediate(APFloat(+0.0f)); // xorps
700     addLegalFPImmediate(APFloat(+0.0)); // FLD0
701     addLegalFPImmediate(APFloat(+1.0)); // FLD1
702     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
703     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
704
705     if (!TM.Options.UnsafeFPMath) {
706       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
707       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
708       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
709     }
710   } else if (!TM.Options.UseSoftFloat) {
711     // f32 and f64 in x87.
712     // Set up the FP register classes.
713     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
714     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
715
716     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
717     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
718     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
719     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
720
721     if (!TM.Options.UnsafeFPMath) {
722       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
723       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
724       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
725       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
726       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
727       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
728     }
729     addLegalFPImmediate(APFloat(+0.0)); // FLD0
730     addLegalFPImmediate(APFloat(+1.0)); // FLD1
731     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
732     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
733     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
734     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
735     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
736     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
737   }
738
739   // We don't support FMA.
740   setOperationAction(ISD::FMA, MVT::f64, Expand);
741   setOperationAction(ISD::FMA, MVT::f32, Expand);
742
743   // Long double always uses X87.
744   if (!TM.Options.UseSoftFloat) {
745     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
746     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
747     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
748     {
749       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
750       addLegalFPImmediate(TmpFlt);  // FLD0
751       TmpFlt.changeSign();
752       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
753
754       bool ignored;
755       APFloat TmpFlt2(+1.0);
756       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
757                       &ignored);
758       addLegalFPImmediate(TmpFlt2);  // FLD1
759       TmpFlt2.changeSign();
760       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
761     }
762
763     if (!TM.Options.UnsafeFPMath) {
764       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
765       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
766       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
767     }
768
769     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
770     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
771     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
772     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
773     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
774     setOperationAction(ISD::FMA, MVT::f80, Expand);
775   }
776
777   // Always use a library call for pow.
778   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
779   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
780   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
781
782   setOperationAction(ISD::FLOG, MVT::f80, Expand);
783   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
784   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
785   setOperationAction(ISD::FEXP, MVT::f80, Expand);
786   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
787
788   // First set operation action for all vector types to either promote
789   // (for widening) or expand (for scalarization). Then we will selectively
790   // turn on ones that can be effectively codegen'd.
791   for (int i = MVT::FIRST_VECTOR_VALUETYPE;
792            i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
793     MVT VT = (MVT::SimpleValueType)i;
794     setOperationAction(ISD::ADD , VT, Expand);
795     setOperationAction(ISD::SUB , VT, Expand);
796     setOperationAction(ISD::FADD, VT, Expand);
797     setOperationAction(ISD::FNEG, VT, Expand);
798     setOperationAction(ISD::FSUB, VT, Expand);
799     setOperationAction(ISD::MUL , VT, Expand);
800     setOperationAction(ISD::FMUL, VT, Expand);
801     setOperationAction(ISD::SDIV, VT, Expand);
802     setOperationAction(ISD::UDIV, VT, Expand);
803     setOperationAction(ISD::FDIV, VT, Expand);
804     setOperationAction(ISD::SREM, VT, Expand);
805     setOperationAction(ISD::UREM, VT, Expand);
806     setOperationAction(ISD::LOAD, VT, Expand);
807     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
808     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
809     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
810     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
811     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
812     setOperationAction(ISD::FABS, VT, Expand);
813     setOperationAction(ISD::FSIN, VT, Expand);
814     setOperationAction(ISD::FSINCOS, VT, Expand);
815     setOperationAction(ISD::FCOS, VT, Expand);
816     setOperationAction(ISD::FSINCOS, VT, Expand);
817     setOperationAction(ISD::FREM, VT, Expand);
818     setOperationAction(ISD::FMA,  VT, Expand);
819     setOperationAction(ISD::FPOWI, VT, Expand);
820     setOperationAction(ISD::FSQRT, VT, Expand);
821     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
822     setOperationAction(ISD::FFLOOR, VT, Expand);
823     setOperationAction(ISD::FCEIL, VT, Expand);
824     setOperationAction(ISD::FTRUNC, VT, Expand);
825     setOperationAction(ISD::FRINT, VT, Expand);
826     setOperationAction(ISD::FNEARBYINT, VT, Expand);
827     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
828     setOperationAction(ISD::MULHS, VT, Expand);
829     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
830     setOperationAction(ISD::MULHU, VT, Expand);
831     setOperationAction(ISD::SDIVREM, VT, Expand);
832     setOperationAction(ISD::UDIVREM, VT, Expand);
833     setOperationAction(ISD::FPOW, VT, Expand);
834     setOperationAction(ISD::CTPOP, VT, Expand);
835     setOperationAction(ISD::CTTZ, VT, Expand);
836     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
837     setOperationAction(ISD::CTLZ, VT, Expand);
838     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
839     setOperationAction(ISD::SHL, VT, Expand);
840     setOperationAction(ISD::SRA, VT, Expand);
841     setOperationAction(ISD::SRL, VT, Expand);
842     setOperationAction(ISD::ROTL, VT, Expand);
843     setOperationAction(ISD::ROTR, VT, Expand);
844     setOperationAction(ISD::BSWAP, VT, Expand);
845     setOperationAction(ISD::SETCC, VT, Expand);
846     setOperationAction(ISD::FLOG, VT, Expand);
847     setOperationAction(ISD::FLOG2, VT, Expand);
848     setOperationAction(ISD::FLOG10, VT, Expand);
849     setOperationAction(ISD::FEXP, VT, Expand);
850     setOperationAction(ISD::FEXP2, VT, Expand);
851     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
852     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
853     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
854     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
855     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
856     setOperationAction(ISD::TRUNCATE, VT, Expand);
857     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
858     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
859     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
860     setOperationAction(ISD::VSELECT, VT, Expand);
861     for (int InnerVT = MVT::FIRST_VECTOR_VALUETYPE;
862              InnerVT <= MVT::LAST_VECTOR_VALUETYPE; ++InnerVT)
863       setTruncStoreAction(VT,
864                           (MVT::SimpleValueType)InnerVT, Expand);
865     setLoadExtAction(ISD::SEXTLOAD, VT, Expand);
866     setLoadExtAction(ISD::ZEXTLOAD, VT, Expand);
867     setLoadExtAction(ISD::EXTLOAD, VT, Expand);
868   }
869
870   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
871   // with -msoft-float, disable use of MMX as well.
872   if (!TM.Options.UseSoftFloat && Subtarget->hasMMX()) {
873     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
874     // No operations on x86mmx supported, everything uses intrinsics.
875   }
876
877   // MMX-sized vectors (other than x86mmx) are expected to be expanded
878   // into smaller operations.
879   setOperationAction(ISD::MULHS,              MVT::v8i8,  Expand);
880   setOperationAction(ISD::MULHS,              MVT::v4i16, Expand);
881   setOperationAction(ISD::MULHS,              MVT::v2i32, Expand);
882   setOperationAction(ISD::MULHS,              MVT::v1i64, Expand);
883   setOperationAction(ISD::AND,                MVT::v8i8,  Expand);
884   setOperationAction(ISD::AND,                MVT::v4i16, Expand);
885   setOperationAction(ISD::AND,                MVT::v2i32, Expand);
886   setOperationAction(ISD::AND,                MVT::v1i64, Expand);
887   setOperationAction(ISD::OR,                 MVT::v8i8,  Expand);
888   setOperationAction(ISD::OR,                 MVT::v4i16, Expand);
889   setOperationAction(ISD::OR,                 MVT::v2i32, Expand);
890   setOperationAction(ISD::OR,                 MVT::v1i64, Expand);
891   setOperationAction(ISD::XOR,                MVT::v8i8,  Expand);
892   setOperationAction(ISD::XOR,                MVT::v4i16, Expand);
893   setOperationAction(ISD::XOR,                MVT::v2i32, Expand);
894   setOperationAction(ISD::XOR,                MVT::v1i64, Expand);
895   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i8,  Expand);
896   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v4i16, Expand);
897   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v2i32, Expand);
898   setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v1i64, Expand);
899   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
900   setOperationAction(ISD::SELECT,             MVT::v8i8,  Expand);
901   setOperationAction(ISD::SELECT,             MVT::v4i16, Expand);
902   setOperationAction(ISD::SELECT,             MVT::v2i32, Expand);
903   setOperationAction(ISD::SELECT,             MVT::v1i64, Expand);
904   setOperationAction(ISD::BITCAST,            MVT::v8i8,  Expand);
905   setOperationAction(ISD::BITCAST,            MVT::v4i16, Expand);
906   setOperationAction(ISD::BITCAST,            MVT::v2i32, Expand);
907   setOperationAction(ISD::BITCAST,            MVT::v1i64, Expand);
908
909   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE1()) {
910     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
911
912     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
913     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
914     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
915     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
916     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
917     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
918     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
919     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
920     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
921     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
922     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
923     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
924   }
925
926   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE2()) {
927     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
928
929     // FIXME: Unfortunately -soft-float and -no-implicit-float means XMM
930     // registers cannot be used even for integer operations.
931     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
932     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
933     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
934     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
935
936     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
937     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
938     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
939     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
940     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
941     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
942     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
943     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
944     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
945     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
946     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
947     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
948     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
949     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
950     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
951     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
952     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
953     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
954     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
955     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
956     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
957     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
958
959     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
960     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
961     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
962     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
963
964     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
965     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
966     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
967     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
968     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
969
970     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
971     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
972       MVT VT = (MVT::SimpleValueType)i;
973       // Do not attempt to custom lower non-power-of-2 vectors
974       if (!isPowerOf2_32(VT.getVectorNumElements()))
975         continue;
976       // Do not attempt to custom lower non-128-bit vectors
977       if (!VT.is128BitVector())
978         continue;
979       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
980       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
981       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
982     }
983
984     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
985     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
986     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
987     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
988     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
989     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
990
991     if (Subtarget->is64Bit()) {
992       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
993       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
994     }
995
996     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
997     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
998       MVT VT = (MVT::SimpleValueType)i;
999
1000       // Do not attempt to promote non-128-bit vectors
1001       if (!VT.is128BitVector())
1002         continue;
1003
1004       setOperationAction(ISD::AND,    VT, Promote);
1005       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
1006       setOperationAction(ISD::OR,     VT, Promote);
1007       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
1008       setOperationAction(ISD::XOR,    VT, Promote);
1009       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
1010       setOperationAction(ISD::LOAD,   VT, Promote);
1011       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
1012       setOperationAction(ISD::SELECT, VT, Promote);
1013       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
1014     }
1015
1016     setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1017
1018     // Custom lower v2i64 and v2f64 selects.
1019     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
1020     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
1021     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
1022     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
1023
1024     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
1025     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
1026
1027     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
1028     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
1029     // As there is no 64-bit GPR available, we need build a special custom
1030     // sequence to convert from v2i32 to v2f32.
1031     if (!Subtarget->is64Bit())
1032       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
1033
1034     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
1035     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
1036
1037     setLoadExtAction(ISD::EXTLOAD,              MVT::v2f32, Legal);
1038
1039     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
1040     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
1041     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
1042   }
1043
1044   if (!TM.Options.UseSoftFloat && Subtarget->hasSSE41()) {
1045     setOperationAction(ISD::FFLOOR,             MVT::f32,   Legal);
1046     setOperationAction(ISD::FCEIL,              MVT::f32,   Legal);
1047     setOperationAction(ISD::FTRUNC,             MVT::f32,   Legal);
1048     setOperationAction(ISD::FRINT,              MVT::f32,   Legal);
1049     setOperationAction(ISD::FNEARBYINT,         MVT::f32,   Legal);
1050     setOperationAction(ISD::FFLOOR,             MVT::f64,   Legal);
1051     setOperationAction(ISD::FCEIL,              MVT::f64,   Legal);
1052     setOperationAction(ISD::FTRUNC,             MVT::f64,   Legal);
1053     setOperationAction(ISD::FRINT,              MVT::f64,   Legal);
1054     setOperationAction(ISD::FNEARBYINT,         MVT::f64,   Legal);
1055
1056     setOperationAction(ISD::FFLOOR,             MVT::v4f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v4f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v4f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v4f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v4f32, Legal);
1061     setOperationAction(ISD::FFLOOR,             MVT::v2f64, Legal);
1062     setOperationAction(ISD::FCEIL,              MVT::v2f64, Legal);
1063     setOperationAction(ISD::FTRUNC,             MVT::v2f64, Legal);
1064     setOperationAction(ISD::FRINT,              MVT::v2f64, Legal);
1065     setOperationAction(ISD::FNEARBYINT,         MVT::v2f64, Legal);
1066
1067     // FIXME: Do we need to handle scalar-to-vector here?
1068     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
1069
1070     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
1071     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
1072     setOperationAction(ISD::VSELECT,            MVT::v4i32, Custom);
1073     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
1074     setOperationAction(ISD::VSELECT,            MVT::v8i16, Custom);
1075     // There is no BLENDI for byte vectors. We don't need to custom lower
1076     // some vselects for now.
1077     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
1078
1079     // i8 and i16 vectors are custom , because the source register and source
1080     // source memory operand types are not the same width.  f32 vectors are
1081     // custom since the immediate controlling the insert encodes additional
1082     // information.
1083     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
1084     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
1085     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
1086     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
1087
1088     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1089     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1090     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1091     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1092
1093     // FIXME: these should be Legal but thats only for the case where
1094     // the index is constant.  For now custom expand to deal with that.
1095     if (Subtarget->is64Bit()) {
1096       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1097       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1098     }
1099   }
1100
1101   if (Subtarget->hasSSE2()) {
1102     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1103     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1104
1105     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1106     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1107
1108     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1109     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1110
1111     // In the customized shift lowering, the legal cases in AVX2 will be
1112     // recognized.
1113     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1114     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1115
1116     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1117     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1118
1119     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1120   }
1121
1122   if (!TM.Options.UseSoftFloat && Subtarget->hasFp256()) {
1123     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1124     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1125     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1126     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1127     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1128     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1129
1130     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1131     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1132     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1133
1134     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1135     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1136     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1137     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1138     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1139     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1140     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1141     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1142     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1143     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1144     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1145     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1146
1147     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1148     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1149     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1150     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1151     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1152     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1153     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1154     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1155     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1156     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1157     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1158     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1159
1160     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1161     // even though v8i16 is a legal type.
1162     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1163     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1164     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1165
1166     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1167     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1168     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1169
1170     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1171     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1172
1173     setLoadExtAction(ISD::EXTLOAD,              MVT::v4f32, Legal);
1174
1175     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1176     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1177
1178     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1179     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1180
1181     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1182     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1183
1184     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1185     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1186     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1187     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1188
1189     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1190     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1191     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1192
1193     setOperationAction(ISD::VSELECT,           MVT::v4f64, Custom);
1194     setOperationAction(ISD::VSELECT,           MVT::v4i64, Custom);
1195     setOperationAction(ISD::VSELECT,           MVT::v8i32, Custom);
1196     setOperationAction(ISD::VSELECT,           MVT::v8f32, Custom);
1197
1198     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1199     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1200     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1201     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1202     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1203     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1204     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1205     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1206     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1207     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1208     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1209     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1210
1211     if (Subtarget->hasFMA() || Subtarget->hasFMA4()) {
1212       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1213       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1214       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1215       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1216       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1217       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1218     }
1219
1220     if (Subtarget->hasInt256()) {
1221       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1222       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1223       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1224       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1225
1226       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1227       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1228       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1229       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1230
1231       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1232       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1233       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1234       // Don't lower v32i8 because there is no 128-bit byte mul
1235
1236       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1237       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1238       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1239       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1240
1241       setOperationAction(ISD::VSELECT,         MVT::v16i16, Custom);
1242       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1243     } else {
1244       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1245       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1246       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1247       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1248
1249       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1250       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1251       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1252       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1253
1254       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1255       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1256       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1257       // Don't lower v32i8 because there is no 128-bit byte mul
1258     }
1259
1260     // In the customized shift lowering, the legal cases in AVX2 will be
1261     // recognized.
1262     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1263     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1264
1265     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1266     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1267
1268     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1269
1270     // Custom lower several nodes for 256-bit types.
1271     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1272              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1273       MVT VT = (MVT::SimpleValueType)i;
1274
1275       // Extract subvector is special because the value type
1276       // (result) is 128-bit but the source is 256-bit wide.
1277       if (VT.is128BitVector())
1278         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1279
1280       // Do not attempt to custom lower other non-256-bit vectors
1281       if (!VT.is256BitVector())
1282         continue;
1283
1284       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1285       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1286       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1287       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1288       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1289       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1290       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1291     }
1292
1293     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1294     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1295       MVT VT = (MVT::SimpleValueType)i;
1296
1297       // Do not attempt to promote non-256-bit vectors
1298       if (!VT.is256BitVector())
1299         continue;
1300
1301       setOperationAction(ISD::AND,    VT, Promote);
1302       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1303       setOperationAction(ISD::OR,     VT, Promote);
1304       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1305       setOperationAction(ISD::XOR,    VT, Promote);
1306       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1307       setOperationAction(ISD::LOAD,   VT, Promote);
1308       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1309       setOperationAction(ISD::SELECT, VT, Promote);
1310       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1311     }
1312   }
1313
1314   if (!TM.Options.UseSoftFloat && Subtarget->hasAVX512()) {
1315     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1316     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1317     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1318     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1319
1320     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1321     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1322     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1323
1324     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1325     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1326     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1327     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1328     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1329     setLoadExtAction(ISD::EXTLOAD,              MVT::v8f32, Legal);
1330     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1331     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1332     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1333     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1334     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1335
1336     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1337     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1338     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1339     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1340     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1341     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1342
1343     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1344     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1345     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1346     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1347     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1348     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1349     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1350     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1351
1352     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1353     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1354     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1355     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1356     if (Subtarget->is64Bit()) {
1357       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1358       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1359       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1360       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1361     }
1362     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1363     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1364     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1365     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1366     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1367     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1368     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1369     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1370     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1371     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1372
1373     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1374     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1375     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1376     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1377     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1378     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1379     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1380     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1381     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1382     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1383     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1384     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1385     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1386
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1390     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1391     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1,    Custom);
1392     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1393
1394     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1395     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1396
1397     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1398
1399     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1400     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1401     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1402     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1403     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1404     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1405     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1407     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1408
1409     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1410     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1411
1412     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1413     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1414
1415     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1416
1417     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1418     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1419
1420     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1421     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1422
1423     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1424     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1425
1426     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1427     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1428     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1429     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1430     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1431     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1432
1433     // Custom lower several nodes.
1434     for (int i = MVT::FIRST_VECTOR_VALUETYPE;
1435              i <= MVT::LAST_VECTOR_VALUETYPE; ++i) {
1436       MVT VT = (MVT::SimpleValueType)i;
1437
1438       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1439       // Extract subvector is special because the value type
1440       // (result) is 256/128-bit but the source is 512-bit wide.
1441       if (VT.is128BitVector() || VT.is256BitVector())
1442         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1443
1444       if (VT.getVectorElementType() == MVT::i1)
1445         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1446
1447       // Do not attempt to custom lower other non-512-bit vectors
1448       if (!VT.is512BitVector())
1449         continue;
1450
1451       if ( EltSize >= 32) {
1452         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1453         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1454         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1455         setOperationAction(ISD::VSELECT,             VT, Legal);
1456         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1457         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1458         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1459       }
1460     }
1461     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1462       MVT VT = (MVT::SimpleValueType)i;
1463
1464       // Do not attempt to promote non-256-bit vectors
1465       if (!VT.is512BitVector())
1466         continue;
1467
1468       setOperationAction(ISD::SELECT, VT, Promote);
1469       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1470     }
1471   }// has  AVX-512
1472
1473   // SIGN_EXTEND_INREGs are evaluated by the extend type. Handle the expansion
1474   // of this type with custom code.
1475   for (int VT = MVT::FIRST_VECTOR_VALUETYPE;
1476            VT != MVT::LAST_VECTOR_VALUETYPE; VT++) {
1477     setOperationAction(ISD::SIGN_EXTEND_INREG, (MVT::SimpleValueType)VT,
1478                        Custom);
1479   }
1480
1481   // We want to custom lower some of our intrinsics.
1482   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1483   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1484   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1485   if (!Subtarget->is64Bit())
1486     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1487
1488   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1489   // handle type legalization for these operations here.
1490   //
1491   // FIXME: We really should do custom legalization for addition and
1492   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1493   // than generic legalization for 64-bit multiplication-with-overflow, though.
1494   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1495     // Add/Sub/Mul with overflow operations are custom lowered.
1496     MVT VT = IntVTs[i];
1497     setOperationAction(ISD::SADDO, VT, Custom);
1498     setOperationAction(ISD::UADDO, VT, Custom);
1499     setOperationAction(ISD::SSUBO, VT, Custom);
1500     setOperationAction(ISD::USUBO, VT, Custom);
1501     setOperationAction(ISD::SMULO, VT, Custom);
1502     setOperationAction(ISD::UMULO, VT, Custom);
1503   }
1504
1505   // There are no 8-bit 3-address imul/mul instructions
1506   setOperationAction(ISD::SMULO, MVT::i8, Expand);
1507   setOperationAction(ISD::UMULO, MVT::i8, Expand);
1508
1509   if (!Subtarget->is64Bit()) {
1510     // These libcalls are not available in 32-bit.
1511     setLibcallName(RTLIB::SHL_I128, nullptr);
1512     setLibcallName(RTLIB::SRL_I128, nullptr);
1513     setLibcallName(RTLIB::SRA_I128, nullptr);
1514   }
1515
1516   // Combine sin / cos into one node or libcall if possible.
1517   if (Subtarget->hasSinCos()) {
1518     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1519     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1520     if (Subtarget->isTargetDarwin()) {
1521       // For MacOSX, we don't want to the normal expansion of a libcall to
1522       // sincos. We want to issue a libcall to __sincos_stret to avoid memory
1523       // traffic.
1524       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1525       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1526     }
1527   }
1528
1529   if (Subtarget->isTargetWin64()) {
1530     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1531     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1532     setOperationAction(ISD::SREM, MVT::i128, Custom);
1533     setOperationAction(ISD::UREM, MVT::i128, Custom);
1534     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1535     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1536   }
1537
1538   // We have target-specific dag combine patterns for the following nodes:
1539   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1540   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1541   setTargetDAGCombine(ISD::VSELECT);
1542   setTargetDAGCombine(ISD::SELECT);
1543   setTargetDAGCombine(ISD::SHL);
1544   setTargetDAGCombine(ISD::SRA);
1545   setTargetDAGCombine(ISD::SRL);
1546   setTargetDAGCombine(ISD::OR);
1547   setTargetDAGCombine(ISD::AND);
1548   setTargetDAGCombine(ISD::ADD);
1549   setTargetDAGCombine(ISD::FADD);
1550   setTargetDAGCombine(ISD::FSUB);
1551   setTargetDAGCombine(ISD::FMA);
1552   setTargetDAGCombine(ISD::SUB);
1553   setTargetDAGCombine(ISD::LOAD);
1554   setTargetDAGCombine(ISD::STORE);
1555   setTargetDAGCombine(ISD::ZERO_EXTEND);
1556   setTargetDAGCombine(ISD::ANY_EXTEND);
1557   setTargetDAGCombine(ISD::SIGN_EXTEND);
1558   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1559   setTargetDAGCombine(ISD::TRUNCATE);
1560   setTargetDAGCombine(ISD::SINT_TO_FP);
1561   setTargetDAGCombine(ISD::SETCC);
1562   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1563   if (Subtarget->is64Bit())
1564     setTargetDAGCombine(ISD::MUL);
1565   setTargetDAGCombine(ISD::XOR);
1566
1567   computeRegisterProperties();
1568
1569   // On Darwin, -Os means optimize for size without hurting performance,
1570   // do not reduce the limit.
1571   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1572   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1573   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1574   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1575   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1576   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1577   setPrefLoopAlignment(4); // 2^4 bytes.
1578
1579   // Predictable cmov don't hurt on atom because it's in-order.
1580   PredictableSelectIsExpensive = !Subtarget->isAtom();
1581
1582   setPrefFunctionAlignment(4); // 2^4 bytes.
1583 }
1584
1585 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1586   if (!VT.isVector())
1587     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1588
1589   if (Subtarget->hasAVX512())
1590     switch(VT.getVectorNumElements()) {
1591     case  8: return MVT::v8i1;
1592     case 16: return MVT::v16i1;
1593   }
1594
1595   return VT.changeVectorElementTypeToInteger();
1596 }
1597
1598 /// getMaxByValAlign - Helper for getByValTypeAlignment to determine
1599 /// the desired ByVal argument alignment.
1600 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1601   if (MaxAlign == 16)
1602     return;
1603   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1604     if (VTy->getBitWidth() == 128)
1605       MaxAlign = 16;
1606   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1607     unsigned EltAlign = 0;
1608     getMaxByValAlign(ATy->getElementType(), EltAlign);
1609     if (EltAlign > MaxAlign)
1610       MaxAlign = EltAlign;
1611   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1612     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1613       unsigned EltAlign = 0;
1614       getMaxByValAlign(STy->getElementType(i), EltAlign);
1615       if (EltAlign > MaxAlign)
1616         MaxAlign = EltAlign;
1617       if (MaxAlign == 16)
1618         break;
1619     }
1620   }
1621 }
1622
1623 /// getByValTypeAlignment - Return the desired alignment for ByVal aggregate
1624 /// function arguments in the caller parameter area. For X86, aggregates
1625 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1626 /// are at 4-byte boundaries.
1627 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1628   if (Subtarget->is64Bit()) {
1629     // Max of 8 and alignment of type.
1630     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1631     if (TyAlign > 8)
1632       return TyAlign;
1633     return 8;
1634   }
1635
1636   unsigned Align = 4;
1637   if (Subtarget->hasSSE1())
1638     getMaxByValAlign(Ty, Align);
1639   return Align;
1640 }
1641
1642 /// getOptimalMemOpType - Returns the target specific optimal type for load
1643 /// and store operations as a result of memset, memcpy, and memmove
1644 /// lowering. If DstAlign is zero that means it's safe to destination
1645 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1646 /// means there isn't a need to check it against alignment requirement,
1647 /// probably because the source does not need to be loaded. If 'IsMemset' is
1648 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1649 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1650 /// source is constant so it does not need to be loaded.
1651 /// It returns EVT::Other if the type should be determined using generic
1652 /// target-independent logic.
1653 EVT
1654 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1655                                        unsigned DstAlign, unsigned SrcAlign,
1656                                        bool IsMemset, bool ZeroMemset,
1657                                        bool MemcpyStrSrc,
1658                                        MachineFunction &MF) const {
1659   const Function *F = MF.getFunction();
1660   if ((!IsMemset || ZeroMemset) &&
1661       !F->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
1662                                        Attribute::NoImplicitFloat)) {
1663     if (Size >= 16 &&
1664         (Subtarget->isUnalignedMemAccessFast() ||
1665          ((DstAlign == 0 || DstAlign >= 16) &&
1666           (SrcAlign == 0 || SrcAlign >= 16)))) {
1667       if (Size >= 32) {
1668         if (Subtarget->hasInt256())
1669           return MVT::v8i32;
1670         if (Subtarget->hasFp256())
1671           return MVT::v8f32;
1672       }
1673       if (Subtarget->hasSSE2())
1674         return MVT::v4i32;
1675       if (Subtarget->hasSSE1())
1676         return MVT::v4f32;
1677     } else if (!MemcpyStrSrc && Size >= 8 &&
1678                !Subtarget->is64Bit() &&
1679                Subtarget->hasSSE2()) {
1680       // Do not use f64 to lower memcpy if source is string constant. It's
1681       // better to use i32 to avoid the loads.
1682       return MVT::f64;
1683     }
1684   }
1685   if (Subtarget->is64Bit() && Size >= 8)
1686     return MVT::i64;
1687   return MVT::i32;
1688 }
1689
1690 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1691   if (VT == MVT::f32)
1692     return X86ScalarSSEf32;
1693   else if (VT == MVT::f64)
1694     return X86ScalarSSEf64;
1695   return true;
1696 }
1697
1698 bool
1699 X86TargetLowering::allowsUnalignedMemoryAccesses(EVT VT,
1700                                                  unsigned,
1701                                                  bool *Fast) const {
1702   if (Fast)
1703     *Fast = Subtarget->isUnalignedMemAccessFast();
1704   return true;
1705 }
1706
1707 /// getJumpTableEncoding - Return the entry encoding for a jump table in the
1708 /// current function.  The returned value is a member of the
1709 /// MachineJumpTableInfo::JTEntryKind enum.
1710 unsigned X86TargetLowering::getJumpTableEncoding() const {
1711   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1712   // symbol.
1713   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1714       Subtarget->isPICStyleGOT())
1715     return MachineJumpTableInfo::EK_Custom32;
1716
1717   // Otherwise, use the normal jump table encoding heuristics.
1718   return TargetLowering::getJumpTableEncoding();
1719 }
1720
1721 const MCExpr *
1722 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1723                                              const MachineBasicBlock *MBB,
1724                                              unsigned uid,MCContext &Ctx) const{
1725   assert(getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1726          Subtarget->isPICStyleGOT());
1727   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1728   // entries.
1729   return MCSymbolRefExpr::Create(MBB->getSymbol(),
1730                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1731 }
1732
1733 /// getPICJumpTableRelocaBase - Returns relocation base for the given PIC
1734 /// jumptable.
1735 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1736                                                     SelectionDAG &DAG) const {
1737   if (!Subtarget->is64Bit())
1738     // This doesn't have SDLoc associated with it, but is not really the
1739     // same as a Register.
1740     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1741   return Table;
1742 }
1743
1744 /// getPICJumpTableRelocBaseExpr - This returns the relocation base for the
1745 /// given PIC jumptable, the same as getPICJumpTableRelocBase, but as an
1746 /// MCExpr.
1747 const MCExpr *X86TargetLowering::
1748 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1749                              MCContext &Ctx) const {
1750   // X86-64 uses RIP relative addressing based on the jump table label.
1751   if (Subtarget->isPICStyleRIPRel())
1752     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1753
1754   // Otherwise, the reference is relative to the PIC base.
1755   return MCSymbolRefExpr::Create(MF->getPICBaseSymbol(), Ctx);
1756 }
1757
1758 // FIXME: Why this routine is here? Move to RegInfo!
1759 std::pair<const TargetRegisterClass*, uint8_t>
1760 X86TargetLowering::findRepresentativeClass(MVT VT) const{
1761   const TargetRegisterClass *RRC = nullptr;
1762   uint8_t Cost = 1;
1763   switch (VT.SimpleTy) {
1764   default:
1765     return TargetLowering::findRepresentativeClass(VT);
1766   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1767     RRC = Subtarget->is64Bit() ?
1768       (const TargetRegisterClass*)&X86::GR64RegClass :
1769       (const TargetRegisterClass*)&X86::GR32RegClass;
1770     break;
1771   case MVT::x86mmx:
1772     RRC = &X86::VR64RegClass;
1773     break;
1774   case MVT::f32: case MVT::f64:
1775   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1776   case MVT::v4f32: case MVT::v2f64:
1777   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1778   case MVT::v4f64:
1779     RRC = &X86::VR128RegClass;
1780     break;
1781   }
1782   return std::make_pair(RRC, Cost);
1783 }
1784
1785 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1786                                                unsigned &Offset) const {
1787   if (!Subtarget->isTargetLinux())
1788     return false;
1789
1790   if (Subtarget->is64Bit()) {
1791     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1792     Offset = 0x28;
1793     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1794       AddressSpace = 256;
1795     else
1796       AddressSpace = 257;
1797   } else {
1798     // %gs:0x14 on i386
1799     Offset = 0x14;
1800     AddressSpace = 256;
1801   }
1802   return true;
1803 }
1804
1805 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1806                                             unsigned DestAS) const {
1807   assert(SrcAS != DestAS && "Expected different address spaces!");
1808
1809   return SrcAS < 256 && DestAS < 256;
1810 }
1811
1812 //===----------------------------------------------------------------------===//
1813 //               Return Value Calling Convention Implementation
1814 //===----------------------------------------------------------------------===//
1815
1816 #include "X86GenCallingConv.inc"
1817
1818 bool
1819 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1820                                   MachineFunction &MF, bool isVarArg,
1821                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1822                         LLVMContext &Context) const {
1823   SmallVector<CCValAssign, 16> RVLocs;
1824   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1825                  RVLocs, Context);
1826   return CCInfo.CheckReturn(Outs, RetCC_X86);
1827 }
1828
1829 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1830   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1831   return ScratchRegs;
1832 }
1833
1834 SDValue
1835 X86TargetLowering::LowerReturn(SDValue Chain,
1836                                CallingConv::ID CallConv, bool isVarArg,
1837                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1838                                const SmallVectorImpl<SDValue> &OutVals,
1839                                SDLoc dl, SelectionDAG &DAG) const {
1840   MachineFunction &MF = DAG.getMachineFunction();
1841   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1842
1843   SmallVector<CCValAssign, 16> RVLocs;
1844   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
1845                  RVLocs, *DAG.getContext());
1846   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
1847
1848   SDValue Flag;
1849   SmallVector<SDValue, 6> RetOps;
1850   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1851   // Operand #1 = Bytes To Pop
1852   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(),
1853                    MVT::i16));
1854
1855   // Copy the result values into the output registers.
1856   for (unsigned i = 0; i != RVLocs.size(); ++i) {
1857     CCValAssign &VA = RVLocs[i];
1858     assert(VA.isRegLoc() && "Can only return in registers!");
1859     SDValue ValToCopy = OutVals[i];
1860     EVT ValVT = ValToCopy.getValueType();
1861
1862     // Promote values to the appropriate types
1863     if (VA.getLocInfo() == CCValAssign::SExt)
1864       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
1865     else if (VA.getLocInfo() == CCValAssign::ZExt)
1866       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
1867     else if (VA.getLocInfo() == CCValAssign::AExt)
1868       ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
1869     else if (VA.getLocInfo() == CCValAssign::BCvt)
1870       ValToCopy = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), ValToCopy);
1871
1872     assert(VA.getLocInfo() != CCValAssign::FPExt &&
1873            "Unexpected FP-extend for return value.");  
1874
1875     // If this is x86-64, and we disabled SSE, we can't return FP values,
1876     // or SSE or MMX vectors.
1877     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
1878          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
1879           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
1880       report_fatal_error("SSE register return with SSE disabled");
1881     }
1882     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
1883     // llvm-gcc has never done it right and no one has noticed, so this
1884     // should be OK for now.
1885     if (ValVT == MVT::f64 &&
1886         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
1887       report_fatal_error("SSE2 register return with SSE2 disabled");
1888
1889     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
1890     // the RET instruction and handled by the FP Stackifier.
1891     if (VA.getLocReg() == X86::ST0 ||
1892         VA.getLocReg() == X86::ST1) {
1893       // If this is a copy from an xmm register to ST(0), use an FPExtend to
1894       // change the value to the FP stack register class.
1895       if (isScalarFPTypeInSSEReg(VA.getValVT()))
1896         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
1897       RetOps.push_back(ValToCopy);
1898       // Don't emit a copytoreg.
1899       continue;
1900     }
1901
1902     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
1903     // which is returned in RAX / RDX.
1904     if (Subtarget->is64Bit()) {
1905       if (ValVT == MVT::x86mmx) {
1906         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
1907           ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::i64, ValToCopy);
1908           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
1909                                   ValToCopy);
1910           // If we don't have SSE2 available, convert to v4f32 so the generated
1911           // register is legal.
1912           if (!Subtarget->hasSSE2())
1913             ValToCopy = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32,ValToCopy);
1914         }
1915       }
1916     }
1917
1918     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
1919     Flag = Chain.getValue(1);
1920     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
1921   }
1922
1923   // The x86-64 ABIs require that for returning structs by value we copy
1924   // the sret argument into %rax/%eax (depending on ABI) for the return.
1925   // Win32 requires us to put the sret argument to %eax as well.
1926   // We saved the argument into a virtual register in the entry block,
1927   // so now we copy the value out and into %rax/%eax.
1928   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr() &&
1929       (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC())) {
1930     MachineFunction &MF = DAG.getMachineFunction();
1931     X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1932     unsigned Reg = FuncInfo->getSRetReturnReg();
1933     assert(Reg &&
1934            "SRetReturnReg should have been set in LowerFormalArguments().");
1935     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
1936
1937     unsigned RetValReg
1938         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
1939           X86::RAX : X86::EAX;
1940     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
1941     Flag = Chain.getValue(1);
1942
1943     // RAX/EAX now acts like a return value.
1944     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
1945   }
1946
1947   RetOps[0] = Chain;  // Update chain.
1948
1949   // Add the flag if we have it.
1950   if (Flag.getNode())
1951     RetOps.push_back(Flag);
1952
1953   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
1954 }
1955
1956 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
1957   if (N->getNumValues() != 1)
1958     return false;
1959   if (!N->hasNUsesOfValue(1, 0))
1960     return false;
1961
1962   SDValue TCChain = Chain;
1963   SDNode *Copy = *N->use_begin();
1964   if (Copy->getOpcode() == ISD::CopyToReg) {
1965     // If the copy has a glue operand, we conservatively assume it isn't safe to
1966     // perform a tail call.
1967     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
1968       return false;
1969     TCChain = Copy->getOperand(0);
1970   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
1971     return false;
1972
1973   bool HasRet = false;
1974   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
1975        UI != UE; ++UI) {
1976     if (UI->getOpcode() != X86ISD::RET_FLAG)
1977       return false;
1978     HasRet = true;
1979   }
1980
1981   if (!HasRet)
1982     return false;
1983
1984   Chain = TCChain;
1985   return true;
1986 }
1987
1988 MVT
1989 X86TargetLowering::getTypeForExtArgOrReturn(MVT VT,
1990                                             ISD::NodeType ExtendKind) const {
1991   MVT ReturnMVT;
1992   // TODO: Is this also valid on 32-bit?
1993   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
1994     ReturnMVT = MVT::i8;
1995   else
1996     ReturnMVT = MVT::i32;
1997
1998   MVT MinVT = getRegisterType(ReturnMVT);
1999   return VT.bitsLT(MinVT) ? MinVT : VT;
2000 }
2001
2002 /// LowerCallResult - Lower the result values of a call into the
2003 /// appropriate copies out of appropriate physical registers.
2004 ///
2005 SDValue
2006 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2007                                    CallingConv::ID CallConv, bool isVarArg,
2008                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2009                                    SDLoc dl, SelectionDAG &DAG,
2010                                    SmallVectorImpl<SDValue> &InVals) const {
2011
2012   // Assign locations to each value returned by this call.
2013   SmallVector<CCValAssign, 16> RVLocs;
2014   bool Is64Bit = Subtarget->is64Bit();
2015   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2016                  getTargetMachine(), RVLocs, *DAG.getContext());
2017   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2018
2019   // Copy all of the result registers out of their specified physreg.
2020   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2021     CCValAssign &VA = RVLocs[i];
2022     EVT CopyVT = VA.getValVT();
2023
2024     // If this is x86-64, and we disabled SSE, we can't return FP values
2025     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2026         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2027       report_fatal_error("SSE register return with SSE disabled");
2028     }
2029
2030     SDValue Val;
2031
2032     // If this is a call to a function that returns an fp value on the floating
2033     // point stack, we must guarantee the value is popped from the stack, so
2034     // a CopyFromReg is not good enough - the copy instruction may be eliminated
2035     // if the return value is not used. We use the FpPOP_RETVAL instruction
2036     // instead.
2037     if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1) {
2038       // If we prefer to use the value in xmm registers, copy it out as f80 and
2039       // use a truncate to move it from fp stack reg to xmm reg.
2040       if (isScalarFPTypeInSSEReg(VA.getValVT())) CopyVT = MVT::f80;
2041       SDValue Ops[] = { Chain, InFlag };
2042       Chain = SDValue(DAG.getMachineNode(X86::FpPOP_RETVAL, dl, CopyVT,
2043                                          MVT::Other, MVT::Glue, Ops), 1);
2044       Val = Chain.getValue(0);
2045
2046       // Round the f80 to the right size, which also moves it to the appropriate
2047       // xmm register.
2048       if (CopyVT != VA.getValVT())
2049         Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2050                           // This truncation won't change the value.
2051                           DAG.getIntPtrConstant(1));
2052     } else {
2053       Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2054                                  CopyVT, InFlag).getValue(1);
2055       Val = Chain.getValue(0);
2056     }
2057     InFlag = Chain.getValue(2);
2058     InVals.push_back(Val);
2059   }
2060
2061   return Chain;
2062 }
2063
2064 //===----------------------------------------------------------------------===//
2065 //                C & StdCall & Fast Calling Convention implementation
2066 //===----------------------------------------------------------------------===//
2067 //  StdCall calling convention seems to be standard for many Windows' API
2068 //  routines and around. It differs from C calling convention just a little:
2069 //  callee should clean up the stack, not caller. Symbols should be also
2070 //  decorated in some fancy way :) It doesn't support any vector arguments.
2071 //  For info on fast calling convention see Fast Calling Convention (tail call)
2072 //  implementation LowerX86_32FastCCCallTo.
2073
2074 /// CallIsStructReturn - Determines whether a call uses struct return
2075 /// semantics.
2076 enum StructReturnType {
2077   NotStructReturn,
2078   RegStructReturn,
2079   StackStructReturn
2080 };
2081 static StructReturnType
2082 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2083   if (Outs.empty())
2084     return NotStructReturn;
2085
2086   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2087   if (!Flags.isSRet())
2088     return NotStructReturn;
2089   if (Flags.isInReg())
2090     return RegStructReturn;
2091   return StackStructReturn;
2092 }
2093
2094 /// ArgsAreStructReturn - Determines whether a function uses struct
2095 /// return semantics.
2096 static StructReturnType
2097 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2098   if (Ins.empty())
2099     return NotStructReturn;
2100
2101   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2102   if (!Flags.isSRet())
2103     return NotStructReturn;
2104   if (Flags.isInReg())
2105     return RegStructReturn;
2106   return StackStructReturn;
2107 }
2108
2109 /// CreateCopyOfByValArgument - Make a copy of an aggregate at address specified
2110 /// by "Src" to address "Dst" with size and alignment information specified by
2111 /// the specific parameter attribute. The copy will be passed as a byval
2112 /// function parameter.
2113 static SDValue
2114 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2115                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2116                           SDLoc dl) {
2117   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), MVT::i32);
2118
2119   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2120                        /*isVolatile*/false, /*AlwaysInline=*/true,
2121                        MachinePointerInfo(), MachinePointerInfo());
2122 }
2123
2124 /// IsTailCallConvention - Return true if the calling convention is one that
2125 /// supports tail call optimization.
2126 static bool IsTailCallConvention(CallingConv::ID CC) {
2127   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2128           CC == CallingConv::HiPE);
2129 }
2130
2131 /// \brief Return true if the calling convention is a C calling convention.
2132 static bool IsCCallConvention(CallingConv::ID CC) {
2133   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2134           CC == CallingConv::X86_64_SysV);
2135 }
2136
2137 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2138   if (!CI->isTailCall() || getTargetMachine().Options.DisableTailCalls)
2139     return false;
2140
2141   CallSite CS(CI);
2142   CallingConv::ID CalleeCC = CS.getCallingConv();
2143   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2144     return false;
2145
2146   return true;
2147 }
2148
2149 /// FuncIsMadeTailCallSafe - Return true if the function is being made into
2150 /// a tailcall target by changing its ABI.
2151 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2152                                    bool GuaranteedTailCallOpt) {
2153   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2154 }
2155
2156 SDValue
2157 X86TargetLowering::LowerMemArgument(SDValue Chain,
2158                                     CallingConv::ID CallConv,
2159                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2160                                     SDLoc dl, SelectionDAG &DAG,
2161                                     const CCValAssign &VA,
2162                                     MachineFrameInfo *MFI,
2163                                     unsigned i) const {
2164   // Create the nodes corresponding to a load from this parameter slot.
2165   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2166   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(CallConv,
2167                               getTargetMachine().Options.GuaranteedTailCallOpt);
2168   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2169   EVT ValVT;
2170
2171   // If value is passed by pointer we have address passed instead of the value
2172   // itself.
2173   if (VA.getLocInfo() == CCValAssign::Indirect)
2174     ValVT = VA.getLocVT();
2175   else
2176     ValVT = VA.getValVT();
2177
2178   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2179   // changed with more analysis.
2180   // In case of tail call optimization mark all arguments mutable. Since they
2181   // could be overwritten by lowering of arguments in case of a tail call.
2182   if (Flags.isByVal()) {
2183     unsigned Bytes = Flags.getByValSize();
2184     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2185     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2186     return DAG.getFrameIndex(FI, getPointerTy());
2187   } else {
2188     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2189                                     VA.getLocMemOffset(), isImmutable);
2190     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2191     return DAG.getLoad(ValVT, dl, Chain, FIN,
2192                        MachinePointerInfo::getFixedStack(FI),
2193                        false, false, false, 0);
2194   }
2195 }
2196
2197 SDValue
2198 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2199                                         CallingConv::ID CallConv,
2200                                         bool isVarArg,
2201                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2202                                         SDLoc dl,
2203                                         SelectionDAG &DAG,
2204                                         SmallVectorImpl<SDValue> &InVals)
2205                                           const {
2206   MachineFunction &MF = DAG.getMachineFunction();
2207   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2208
2209   const Function* Fn = MF.getFunction();
2210   if (Fn->hasExternalLinkage() &&
2211       Subtarget->isTargetCygMing() &&
2212       Fn->getName() == "main")
2213     FuncInfo->setForceFramePointer(true);
2214
2215   MachineFrameInfo *MFI = MF.getFrameInfo();
2216   bool Is64Bit = Subtarget->is64Bit();
2217   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2218
2219   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2220          "Var args not supported with calling convention fastcc, ghc or hipe");
2221
2222   // Assign locations to all of the incoming arguments.
2223   SmallVector<CCValAssign, 16> ArgLocs;
2224   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2225                  ArgLocs, *DAG.getContext());
2226
2227   // Allocate shadow area for Win64
2228   if (IsWin64)
2229     CCInfo.AllocateStack(32, 8);
2230
2231   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2232
2233   unsigned LastVal = ~0U;
2234   SDValue ArgValue;
2235   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2236     CCValAssign &VA = ArgLocs[i];
2237     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2238     // places.
2239     assert(VA.getValNo() != LastVal &&
2240            "Don't support value assigned to multiple locs yet");
2241     (void)LastVal;
2242     LastVal = VA.getValNo();
2243
2244     if (VA.isRegLoc()) {
2245       EVT RegVT = VA.getLocVT();
2246       const TargetRegisterClass *RC;
2247       if (RegVT == MVT::i32)
2248         RC = &X86::GR32RegClass;
2249       else if (Is64Bit && RegVT == MVT::i64)
2250         RC = &X86::GR64RegClass;
2251       else if (RegVT == MVT::f32)
2252         RC = &X86::FR32RegClass;
2253       else if (RegVT == MVT::f64)
2254         RC = &X86::FR64RegClass;
2255       else if (RegVT.is512BitVector())
2256         RC = &X86::VR512RegClass;
2257       else if (RegVT.is256BitVector())
2258         RC = &X86::VR256RegClass;
2259       else if (RegVT.is128BitVector())
2260         RC = &X86::VR128RegClass;
2261       else if (RegVT == MVT::x86mmx)
2262         RC = &X86::VR64RegClass;
2263       else if (RegVT == MVT::i1)
2264         RC = &X86::VK1RegClass;
2265       else if (RegVT == MVT::v8i1)
2266         RC = &X86::VK8RegClass;
2267       else if (RegVT == MVT::v16i1)
2268         RC = &X86::VK16RegClass;
2269       else
2270         llvm_unreachable("Unknown argument type!");
2271
2272       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2273       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2274
2275       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2276       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2277       // right size.
2278       if (VA.getLocInfo() == CCValAssign::SExt)
2279         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2280                                DAG.getValueType(VA.getValVT()));
2281       else if (VA.getLocInfo() == CCValAssign::ZExt)
2282         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2283                                DAG.getValueType(VA.getValVT()));
2284       else if (VA.getLocInfo() == CCValAssign::BCvt)
2285         ArgValue = DAG.getNode(ISD::BITCAST, dl, VA.getValVT(), ArgValue);
2286
2287       if (VA.isExtInLoc()) {
2288         // Handle MMX values passed in XMM regs.
2289         if (RegVT.isVector())
2290           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2291         else
2292           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2293       }
2294     } else {
2295       assert(VA.isMemLoc());
2296       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2297     }
2298
2299     // If value is passed via pointer - do a load.
2300     if (VA.getLocInfo() == CCValAssign::Indirect)
2301       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2302                              MachinePointerInfo(), false, false, false, 0);
2303
2304     InVals.push_back(ArgValue);
2305   }
2306
2307   if (Subtarget->is64Bit() || Subtarget->isTargetKnownWindowsMSVC()) {
2308     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2309       // The x86-64 ABIs require that for returning structs by value we copy
2310       // the sret argument into %rax/%eax (depending on ABI) for the return.
2311       // Win32 requires us to put the sret argument to %eax as well.
2312       // Save the argument into a virtual register so that we can access it
2313       // from the return points.
2314       if (Ins[i].Flags.isSRet()) {
2315         unsigned Reg = FuncInfo->getSRetReturnReg();
2316         if (!Reg) {
2317           MVT PtrTy = getPointerTy();
2318           Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2319           FuncInfo->setSRetReturnReg(Reg);
2320         }
2321         SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2322         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2323         break;
2324       }
2325     }
2326   }
2327
2328   unsigned StackSize = CCInfo.getNextStackOffset();
2329   // Align stack specially for tail calls.
2330   if (FuncIsMadeTailCallSafe(CallConv,
2331                              MF.getTarget().Options.GuaranteedTailCallOpt))
2332     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2333
2334   // If the function takes variable number of arguments, make a frame index for
2335   // the start of the first vararg value... for expansion of llvm.va_start.
2336   if (isVarArg) {
2337     if (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2338                     CallConv != CallingConv::X86_ThisCall)) {
2339       FuncInfo->setVarArgsFrameIndex(MFI->CreateFixedObject(1, StackSize,true));
2340     }
2341     if (Is64Bit) {
2342       unsigned TotalNumIntRegs = 0, TotalNumXMMRegs = 0;
2343
2344       // FIXME: We should really autogenerate these arrays
2345       static const MCPhysReg GPR64ArgRegsWin64[] = {
2346         X86::RCX, X86::RDX, X86::R8,  X86::R9
2347       };
2348       static const MCPhysReg GPR64ArgRegs64Bit[] = {
2349         X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2350       };
2351       static const MCPhysReg XMMArgRegs64Bit[] = {
2352         X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2353         X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2354       };
2355       const MCPhysReg *GPR64ArgRegs;
2356       unsigned NumXMMRegs = 0;
2357
2358       if (IsWin64) {
2359         // The XMM registers which might contain var arg parameters are shadowed
2360         // in their paired GPR.  So we only need to save the GPR to their home
2361         // slots.
2362         TotalNumIntRegs = 4;
2363         GPR64ArgRegs = GPR64ArgRegsWin64;
2364       } else {
2365         TotalNumIntRegs = 6; TotalNumXMMRegs = 8;
2366         GPR64ArgRegs = GPR64ArgRegs64Bit;
2367
2368         NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs64Bit,
2369                                                 TotalNumXMMRegs);
2370       }
2371       unsigned NumIntRegs = CCInfo.getFirstUnallocated(GPR64ArgRegs,
2372                                                        TotalNumIntRegs);
2373
2374       bool NoImplicitFloatOps = Fn->getAttributes().
2375         hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
2376       assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2377              "SSE register cannot be used when SSE is disabled!");
2378       assert(!(NumXMMRegs && MF.getTarget().Options.UseSoftFloat &&
2379                NoImplicitFloatOps) &&
2380              "SSE register cannot be used when SSE is disabled!");
2381       if (MF.getTarget().Options.UseSoftFloat || NoImplicitFloatOps ||
2382           !Subtarget->hasSSE1())
2383         // Kernel mode asks for SSE to be disabled, so don't push them
2384         // on the stack.
2385         TotalNumXMMRegs = 0;
2386
2387       if (IsWin64) {
2388         const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
2389         // Get to the caller-allocated home save location.  Add 8 to account
2390         // for the return address.
2391         int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2392         FuncInfo->setRegSaveFrameIndex(
2393           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2394         // Fixup to set vararg frame on shadow area (4 x i64).
2395         if (NumIntRegs < 4)
2396           FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2397       } else {
2398         // For X86-64, if there are vararg parameters that are passed via
2399         // registers, then we must store them to their spots on the stack so
2400         // they may be loaded by deferencing the result of va_next.
2401         FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2402         FuncInfo->setVarArgsFPOffset(TotalNumIntRegs * 8 + NumXMMRegs * 16);
2403         FuncInfo->setRegSaveFrameIndex(
2404           MFI->CreateStackObject(TotalNumIntRegs * 8 + TotalNumXMMRegs * 16, 16,
2405                                false));
2406       }
2407
2408       // Store the integer parameter registers.
2409       SmallVector<SDValue, 8> MemOps;
2410       SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2411                                         getPointerTy());
2412       unsigned Offset = FuncInfo->getVarArgsGPOffset();
2413       for (; NumIntRegs != TotalNumIntRegs; ++NumIntRegs) {
2414         SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2415                                   DAG.getIntPtrConstant(Offset));
2416         unsigned VReg = MF.addLiveIn(GPR64ArgRegs[NumIntRegs],
2417                                      &X86::GR64RegClass);
2418         SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i64);
2419         SDValue Store =
2420           DAG.getStore(Val.getValue(1), dl, Val, FIN,
2421                        MachinePointerInfo::getFixedStack(
2422                          FuncInfo->getRegSaveFrameIndex(), Offset),
2423                        false, false, 0);
2424         MemOps.push_back(Store);
2425         Offset += 8;
2426       }
2427
2428       if (TotalNumXMMRegs != 0 && NumXMMRegs != TotalNumXMMRegs) {
2429         // Now store the XMM (fp + vector) parameter registers.
2430         SmallVector<SDValue, 11> SaveXMMOps;
2431         SaveXMMOps.push_back(Chain);
2432
2433         unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2434         SDValue ALVal = DAG.getCopyFromReg(DAG.getEntryNode(), dl, AL, MVT::i8);
2435         SaveXMMOps.push_back(ALVal);
2436
2437         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2438                                FuncInfo->getRegSaveFrameIndex()));
2439         SaveXMMOps.push_back(DAG.getIntPtrConstant(
2440                                FuncInfo->getVarArgsFPOffset()));
2441
2442         for (; NumXMMRegs != TotalNumXMMRegs; ++NumXMMRegs) {
2443           unsigned VReg = MF.addLiveIn(XMMArgRegs64Bit[NumXMMRegs],
2444                                        &X86::VR128RegClass);
2445           SDValue Val = DAG.getCopyFromReg(Chain, dl, VReg, MVT::v4f32);
2446           SaveXMMOps.push_back(Val);
2447         }
2448         MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2449                                      MVT::Other, SaveXMMOps));
2450       }
2451
2452       if (!MemOps.empty())
2453         Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2454     }
2455   }
2456
2457   // Some CCs need callee pop.
2458   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2459                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2460     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2461   } else {
2462     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2463     // If this is an sret function, the return should pop the hidden pointer.
2464     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2465         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2466         argsAreStructReturn(Ins) == StackStructReturn)
2467       FuncInfo->setBytesToPopOnReturn(4);
2468   }
2469
2470   if (!Is64Bit) {
2471     // RegSaveFrameIndex is X86-64 only.
2472     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2473     if (CallConv == CallingConv::X86_FastCall ||
2474         CallConv == CallingConv::X86_ThisCall)
2475       // fastcc functions can't have varargs.
2476       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2477   }
2478
2479   FuncInfo->setArgumentStackSize(StackSize);
2480
2481   return Chain;
2482 }
2483
2484 SDValue
2485 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2486                                     SDValue StackPtr, SDValue Arg,
2487                                     SDLoc dl, SelectionDAG &DAG,
2488                                     const CCValAssign &VA,
2489                                     ISD::ArgFlagsTy Flags) const {
2490   unsigned LocMemOffset = VA.getLocMemOffset();
2491   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset);
2492   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2493   if (Flags.isByVal())
2494     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2495
2496   return DAG.getStore(Chain, dl, Arg, PtrOff,
2497                       MachinePointerInfo::getStack(LocMemOffset),
2498                       false, false, 0);
2499 }
2500
2501 /// EmitTailCallLoadRetAddr - Emit a load of return address if tail call
2502 /// optimization is performed and it is required.
2503 SDValue
2504 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2505                                            SDValue &OutRetAddr, SDValue Chain,
2506                                            bool IsTailCall, bool Is64Bit,
2507                                            int FPDiff, SDLoc dl) const {
2508   // Adjust the Return address stack slot.
2509   EVT VT = getPointerTy();
2510   OutRetAddr = getReturnAddressFrameIndex(DAG);
2511
2512   // Load the "old" Return address.
2513   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2514                            false, false, false, 0);
2515   return SDValue(OutRetAddr.getNode(), 1);
2516 }
2517
2518 /// EmitTailCallStoreRetAddr - Emit a store of the return address if tail call
2519 /// optimization is performed and it is required (FPDiff!=0).
2520 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2521                                         SDValue Chain, SDValue RetAddrFrIdx,
2522                                         EVT PtrVT, unsigned SlotSize,
2523                                         int FPDiff, SDLoc dl) {
2524   // Store the return address to the appropriate stack slot.
2525   if (!FPDiff) return Chain;
2526   // Calculate the new stack slot for the return address.
2527   int NewReturnAddrFI =
2528     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2529                                          false);
2530   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2531   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2532                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2533                        false, false, 0);
2534   return Chain;
2535 }
2536
2537 SDValue
2538 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2539                              SmallVectorImpl<SDValue> &InVals) const {
2540   SelectionDAG &DAG                     = CLI.DAG;
2541   SDLoc &dl                             = CLI.DL;
2542   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2543   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2544   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2545   SDValue Chain                         = CLI.Chain;
2546   SDValue Callee                        = CLI.Callee;
2547   CallingConv::ID CallConv              = CLI.CallConv;
2548   bool &isTailCall                      = CLI.IsTailCall;
2549   bool isVarArg                         = CLI.IsVarArg;
2550
2551   MachineFunction &MF = DAG.getMachineFunction();
2552   bool Is64Bit        = Subtarget->is64Bit();
2553   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2554   StructReturnType SR = callIsStructReturn(Outs);
2555   bool IsSibcall      = false;
2556
2557   if (MF.getTarget().Options.DisableTailCalls)
2558     isTailCall = false;
2559
2560   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2561   if (IsMustTail) {
2562     // Force this to be a tail call.  The verifier rules are enough to ensure
2563     // that we can lower this successfully without moving the return address
2564     // around.
2565     isTailCall = true;
2566   } else if (isTailCall) {
2567     // Check if it's really possible to do a tail call.
2568     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2569                     isVarArg, SR != NotStructReturn,
2570                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2571                     Outs, OutVals, Ins, DAG);
2572
2573     // Sibcalls are automatically detected tailcalls which do not require
2574     // ABI changes.
2575     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2576       IsSibcall = true;
2577
2578     if (isTailCall)
2579       ++NumTailCalls;
2580   }
2581
2582   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2583          "Var args not supported with calling convention fastcc, ghc or hipe");
2584
2585   // Analyze operands of the call, assigning locations to each operand.
2586   SmallVector<CCValAssign, 16> ArgLocs;
2587   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
2588                  ArgLocs, *DAG.getContext());
2589
2590   // Allocate shadow area for Win64
2591   if (IsWin64)
2592     CCInfo.AllocateStack(32, 8);
2593
2594   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2595
2596   // Get a count of how many bytes are to be pushed on the stack.
2597   unsigned NumBytes = CCInfo.getNextStackOffset();
2598   if (IsSibcall)
2599     // This is a sibcall. The memory operands are available in caller's
2600     // own caller's stack.
2601     NumBytes = 0;
2602   else if (getTargetMachine().Options.GuaranteedTailCallOpt &&
2603            IsTailCallConvention(CallConv))
2604     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2605
2606   int FPDiff = 0;
2607   if (isTailCall && !IsSibcall && !IsMustTail) {
2608     // Lower arguments at fp - stackoffset + fpdiff.
2609     X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2610     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2611
2612     FPDiff = NumBytesCallerPushed - NumBytes;
2613
2614     // Set the delta of movement of the returnaddr stackslot.
2615     // But only set if delta is greater than previous delta.
2616     if (FPDiff < X86Info->getTCReturnAddrDelta())
2617       X86Info->setTCReturnAddrDelta(FPDiff);
2618   }
2619
2620   unsigned NumBytesToPush = NumBytes;
2621   unsigned NumBytesToPop = NumBytes;
2622
2623   // If we have an inalloca argument, all stack space has already been allocated
2624   // for us and be right at the top of the stack.  We don't support multiple
2625   // arguments passed in memory when using inalloca.
2626   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2627     NumBytesToPush = 0;
2628     assert(ArgLocs.back().getLocMemOffset() == 0 &&
2629            "an inalloca argument must be the only memory argument");
2630   }
2631
2632   if (!IsSibcall)
2633     Chain = DAG.getCALLSEQ_START(
2634         Chain, DAG.getIntPtrConstant(NumBytesToPush, true), dl);
2635
2636   SDValue RetAddrFrIdx;
2637   // Load return address for tail calls.
2638   if (isTailCall && FPDiff)
2639     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2640                                     Is64Bit, FPDiff, dl);
2641
2642   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2643   SmallVector<SDValue, 8> MemOpChains;
2644   SDValue StackPtr;
2645
2646   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2647   // of tail call optimization arguments are handle later.
2648   const X86RegisterInfo *RegInfo =
2649     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
2650   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2651     // Skip inalloca arguments, they have already been written.
2652     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2653     if (Flags.isInAlloca())
2654       continue;
2655
2656     CCValAssign &VA = ArgLocs[i];
2657     EVT RegVT = VA.getLocVT();
2658     SDValue Arg = OutVals[i];
2659     bool isByVal = Flags.isByVal();
2660
2661     // Promote the value if needed.
2662     switch (VA.getLocInfo()) {
2663     default: llvm_unreachable("Unknown loc info!");
2664     case CCValAssign::Full: break;
2665     case CCValAssign::SExt:
2666       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2667       break;
2668     case CCValAssign::ZExt:
2669       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2670       break;
2671     case CCValAssign::AExt:
2672       if (RegVT.is128BitVector()) {
2673         // Special case: passing MMX values in XMM registers.
2674         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i64, Arg);
2675         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2676         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2677       } else
2678         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2679       break;
2680     case CCValAssign::BCvt:
2681       Arg = DAG.getNode(ISD::BITCAST, dl, RegVT, Arg);
2682       break;
2683     case CCValAssign::Indirect: {
2684       // Store the argument.
2685       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2686       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2687       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2688                            MachinePointerInfo::getFixedStack(FI),
2689                            false, false, 0);
2690       Arg = SpillSlot;
2691       break;
2692     }
2693     }
2694
2695     if (VA.isRegLoc()) {
2696       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2697       if (isVarArg && IsWin64) {
2698         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2699         // shadow reg if callee is a varargs function.
2700         unsigned ShadowReg = 0;
2701         switch (VA.getLocReg()) {
2702         case X86::XMM0: ShadowReg = X86::RCX; break;
2703         case X86::XMM1: ShadowReg = X86::RDX; break;
2704         case X86::XMM2: ShadowReg = X86::R8; break;
2705         case X86::XMM3: ShadowReg = X86::R9; break;
2706         }
2707         if (ShadowReg)
2708           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2709       }
2710     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2711       assert(VA.isMemLoc());
2712       if (!StackPtr.getNode())
2713         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
2714                                       getPointerTy());
2715       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
2716                                              dl, DAG, VA, Flags));
2717     }
2718   }
2719
2720   if (!MemOpChains.empty())
2721     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
2722
2723   if (Subtarget->isPICStyleGOT()) {
2724     // ELF / PIC requires GOT in the EBX register before function calls via PLT
2725     // GOT pointer.
2726     if (!isTailCall) {
2727       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
2728                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
2729     } else {
2730       // If we are tail calling and generating PIC/GOT style code load the
2731       // address of the callee into ECX. The value in ecx is used as target of
2732       // the tail jump. This is done to circumvent the ebx/callee-saved problem
2733       // for tail calls on PIC/GOT architectures. Normally we would just put the
2734       // address of GOT into ebx and then call target@PLT. But for tail calls
2735       // ebx would be restored (since ebx is callee saved) before jumping to the
2736       // target@PLT.
2737
2738       // Note: The actual moving to ECX is done further down.
2739       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2740       if (G && !G->getGlobal()->hasHiddenVisibility() &&
2741           !G->getGlobal()->hasProtectedVisibility())
2742         Callee = LowerGlobalAddress(Callee, DAG);
2743       else if (isa<ExternalSymbolSDNode>(Callee))
2744         Callee = LowerExternalSymbol(Callee, DAG);
2745     }
2746   }
2747
2748   if (Is64Bit && isVarArg && !IsWin64) {
2749     // From AMD64 ABI document:
2750     // For calls that may call functions that use varargs or stdargs
2751     // (prototype-less calls or calls to functions containing ellipsis (...) in
2752     // the declaration) %al is used as hidden argument to specify the number
2753     // of SSE registers used. The contents of %al do not need to match exactly
2754     // the number of registers, but must be an ubound on the number of SSE
2755     // registers used and is in the range 0 - 8 inclusive.
2756
2757     // Count the number of XMM registers allocated.
2758     static const MCPhysReg XMMArgRegs[] = {
2759       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2760       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2761     };
2762     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs, 8);
2763     assert((Subtarget->hasSSE1() || !NumXMMRegs)
2764            && "SSE registers cannot be used when SSE is disabled");
2765
2766     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
2767                                         DAG.getConstant(NumXMMRegs, MVT::i8)));
2768   }
2769
2770   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
2771   // don't need this because the eligibility check rejects calls that require
2772   // shuffling arguments passed in memory.
2773   if (!IsSibcall && isTailCall) {
2774     // Force all the incoming stack arguments to be loaded from the stack
2775     // before any new outgoing arguments are stored to the stack, because the
2776     // outgoing stack slots may alias the incoming argument stack slots, and
2777     // the alias isn't otherwise explicit. This is slightly more conservative
2778     // than necessary, because it means that each store effectively depends
2779     // on every argument instead of just those arguments it would clobber.
2780     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
2781
2782     SmallVector<SDValue, 8> MemOpChains2;
2783     SDValue FIN;
2784     int FI = 0;
2785     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2786       CCValAssign &VA = ArgLocs[i];
2787       if (VA.isRegLoc())
2788         continue;
2789       assert(VA.isMemLoc());
2790       SDValue Arg = OutVals[i];
2791       ISD::ArgFlagsTy Flags = Outs[i].Flags;
2792       // Skip inalloca arguments.  They don't require any work.
2793       if (Flags.isInAlloca())
2794         continue;
2795       // Create frame index.
2796       int32_t Offset = VA.getLocMemOffset()+FPDiff;
2797       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
2798       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
2799       FIN = DAG.getFrameIndex(FI, getPointerTy());
2800
2801       if (Flags.isByVal()) {
2802         // Copy relative to framepointer.
2803         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset());
2804         if (!StackPtr.getNode())
2805           StackPtr = DAG.getCopyFromReg(Chain, dl,
2806                                         RegInfo->getStackRegister(),
2807                                         getPointerTy());
2808         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
2809
2810         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
2811                                                          ArgChain,
2812                                                          Flags, DAG, dl));
2813       } else {
2814         // Store relative to framepointer.
2815         MemOpChains2.push_back(
2816           DAG.getStore(ArgChain, dl, Arg, FIN,
2817                        MachinePointerInfo::getFixedStack(FI),
2818                        false, false, 0));
2819       }
2820     }
2821
2822     if (!MemOpChains2.empty())
2823       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
2824
2825     // Store the return address to the appropriate stack slot.
2826     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
2827                                      getPointerTy(), RegInfo->getSlotSize(),
2828                                      FPDiff, dl);
2829   }
2830
2831   // Build a sequence of copy-to-reg nodes chained together with token chain
2832   // and flag operands which copy the outgoing args into registers.
2833   SDValue InFlag;
2834   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2835     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2836                              RegsToPass[i].second, InFlag);
2837     InFlag = Chain.getValue(1);
2838   }
2839
2840   if (getTargetMachine().getCodeModel() == CodeModel::Large) {
2841     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
2842     // In the 64-bit large code model, we have to make all calls
2843     // through a register, since the call instruction's 32-bit
2844     // pc-relative offset may not be large enough to hold the whole
2845     // address.
2846   } else if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2847     // If the callee is a GlobalAddress node (quite common, every direct call
2848     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
2849     // it.
2850
2851     // We should use extra load for direct calls to dllimported functions in
2852     // non-JIT mode.
2853     const GlobalValue *GV = G->getGlobal();
2854     if (!GV->hasDLLImportStorageClass()) {
2855       unsigned char OpFlags = 0;
2856       bool ExtraLoad = false;
2857       unsigned WrapperKind = ISD::DELETED_NODE;
2858
2859       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
2860       // external symbols most go through the PLT in PIC mode.  If the symbol
2861       // has hidden or protected visibility, or if it is static or local, then
2862       // we don't need to use the PLT - we can directly call it.
2863       if (Subtarget->isTargetELF() &&
2864           getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
2865           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
2866         OpFlags = X86II::MO_PLT;
2867       } else if (Subtarget->isPICStyleStubAny() &&
2868                  (GV->isDeclaration() || GV->isWeakForLinker()) &&
2869                  (!Subtarget->getTargetTriple().isMacOSX() ||
2870                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2871         // PC-relative references to external symbols should go through $stub,
2872         // unless we're building with the leopard linker or later, which
2873         // automatically synthesizes these stubs.
2874         OpFlags = X86II::MO_DARWIN_STUB;
2875       } else if (Subtarget->isPICStyleRIPRel() &&
2876                  isa<Function>(GV) &&
2877                  cast<Function>(GV)->getAttributes().
2878                    hasAttribute(AttributeSet::FunctionIndex,
2879                                 Attribute::NonLazyBind)) {
2880         // If the function is marked as non-lazy, generate an indirect call
2881         // which loads from the GOT directly. This avoids runtime overhead
2882         // at the cost of eager binding (and one extra byte of encoding).
2883         OpFlags = X86II::MO_GOTPCREL;
2884         WrapperKind = X86ISD::WrapperRIP;
2885         ExtraLoad = true;
2886       }
2887
2888       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
2889                                           G->getOffset(), OpFlags);
2890
2891       // Add a wrapper if needed.
2892       if (WrapperKind != ISD::DELETED_NODE)
2893         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
2894       // Add extra indirection if needed.
2895       if (ExtraLoad)
2896         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
2897                              MachinePointerInfo::getGOT(),
2898                              false, false, false, 0);
2899     }
2900   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2901     unsigned char OpFlags = 0;
2902
2903     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
2904     // external symbols should go through the PLT.
2905     if (Subtarget->isTargetELF() &&
2906         getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2907       OpFlags = X86II::MO_PLT;
2908     } else if (Subtarget->isPICStyleStubAny() &&
2909                (!Subtarget->getTargetTriple().isMacOSX() ||
2910                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
2911       // PC-relative references to external symbols should go through $stub,
2912       // unless we're building with the leopard linker or later, which
2913       // automatically synthesizes these stubs.
2914       OpFlags = X86II::MO_DARWIN_STUB;
2915     }
2916
2917     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2918                                          OpFlags);
2919   }
2920
2921   // Returns a chain & a flag for retval copy to use.
2922   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2923   SmallVector<SDValue, 8> Ops;
2924
2925   if (!IsSibcall && isTailCall) {
2926     Chain = DAG.getCALLSEQ_END(Chain,
2927                                DAG.getIntPtrConstant(NumBytesToPop, true),
2928                                DAG.getIntPtrConstant(0, true), InFlag, dl);
2929     InFlag = Chain.getValue(1);
2930   }
2931
2932   Ops.push_back(Chain);
2933   Ops.push_back(Callee);
2934
2935   if (isTailCall)
2936     Ops.push_back(DAG.getConstant(FPDiff, MVT::i32));
2937
2938   // Add argument registers to the end of the list so that they are known live
2939   // into the call.
2940   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2941     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2942                                   RegsToPass[i].second.getValueType()));
2943
2944   // Add a register mask operand representing the call-preserved registers.
2945   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2946   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2947   assert(Mask && "Missing call preserved mask for calling convention");
2948   Ops.push_back(DAG.getRegisterMask(Mask));
2949
2950   if (InFlag.getNode())
2951     Ops.push_back(InFlag);
2952
2953   if (isTailCall) {
2954     // We used to do:
2955     //// If this is the first return lowered for this function, add the regs
2956     //// to the liveout set for the function.
2957     // This isn't right, although it's probably harmless on x86; liveouts
2958     // should be computed from returns not tail calls.  Consider a void
2959     // function making a tail call to a function returning int.
2960     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
2961   }
2962
2963   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
2964   InFlag = Chain.getValue(1);
2965
2966   // Create the CALLSEQ_END node.
2967   unsigned NumBytesForCalleeToPop;
2968   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2969                        getTargetMachine().Options.GuaranteedTailCallOpt))
2970     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
2971   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2972            !Subtarget->getTargetTriple().isOSMSVCRT() &&
2973            SR == StackStructReturn)
2974     // If this is a call to a struct-return function, the callee
2975     // pops the hidden struct pointer, so we have to push it back.
2976     // This is common for Darwin/X86, Linux & Mingw32 targets.
2977     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
2978     NumBytesForCalleeToPop = 4;
2979   else
2980     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
2981
2982   // Returns a flag for retval copy to use.
2983   if (!IsSibcall) {
2984     Chain = DAG.getCALLSEQ_END(Chain,
2985                                DAG.getIntPtrConstant(NumBytesToPop, true),
2986                                DAG.getIntPtrConstant(NumBytesForCalleeToPop,
2987                                                      true),
2988                                InFlag, dl);
2989     InFlag = Chain.getValue(1);
2990   }
2991
2992   // Handle result values, copying them out of physregs into vregs that we
2993   // return.
2994   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2995                          Ins, dl, DAG, InVals);
2996 }
2997
2998 //===----------------------------------------------------------------------===//
2999 //                Fast Calling Convention (tail call) implementation
3000 //===----------------------------------------------------------------------===//
3001
3002 //  Like std call, callee cleans arguments, convention except that ECX is
3003 //  reserved for storing the tail called function address. Only 2 registers are
3004 //  free for argument passing (inreg). Tail call optimization is performed
3005 //  provided:
3006 //                * tailcallopt is enabled
3007 //                * caller/callee are fastcc
3008 //  On X86_64 architecture with GOT-style position independent code only local
3009 //  (within module) calls are supported at the moment.
3010 //  To keep the stack aligned according to platform abi the function
3011 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3012 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3013 //  If a tail called function callee has more arguments than the caller the
3014 //  caller needs to make sure that there is room to move the RETADDR to. This is
3015 //  achieved by reserving an area the size of the argument delta right after the
3016 //  original REtADDR, but before the saved framepointer or the spilled registers
3017 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3018 //  stack layout:
3019 //    arg1
3020 //    arg2
3021 //    RETADDR
3022 //    [ new RETADDR
3023 //      move area ]
3024 //    (possible EBP)
3025 //    ESI
3026 //    EDI
3027 //    local1 ..
3028
3029 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3030 /// for a 16 byte align requirement.
3031 unsigned
3032 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3033                                                SelectionDAG& DAG) const {
3034   MachineFunction &MF = DAG.getMachineFunction();
3035   const TargetMachine &TM = MF.getTarget();
3036   const X86RegisterInfo *RegInfo =
3037     static_cast<const X86RegisterInfo*>(TM.getRegisterInfo());
3038   const TargetFrameLowering &TFI = *TM.getFrameLowering();
3039   unsigned StackAlignment = TFI.getStackAlignment();
3040   uint64_t AlignMask = StackAlignment - 1;
3041   int64_t Offset = StackSize;
3042   unsigned SlotSize = RegInfo->getSlotSize();
3043   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3044     // Number smaller than 12 so just add the difference.
3045     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3046   } else {
3047     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3048     Offset = ((~AlignMask) & Offset) + StackAlignment +
3049       (StackAlignment-SlotSize);
3050   }
3051   return Offset;
3052 }
3053
3054 /// MatchingStackOffset - Return true if the given stack call argument is
3055 /// already available in the same position (relatively) of the caller's
3056 /// incoming argument stack.
3057 static
3058 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3059                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3060                          const X86InstrInfo *TII) {
3061   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3062   int FI = INT_MAX;
3063   if (Arg.getOpcode() == ISD::CopyFromReg) {
3064     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3065     if (!TargetRegisterInfo::isVirtualRegister(VR))
3066       return false;
3067     MachineInstr *Def = MRI->getVRegDef(VR);
3068     if (!Def)
3069       return false;
3070     if (!Flags.isByVal()) {
3071       if (!TII->isLoadFromStackSlot(Def, FI))
3072         return false;
3073     } else {
3074       unsigned Opcode = Def->getOpcode();
3075       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r) &&
3076           Def->getOperand(1).isFI()) {
3077         FI = Def->getOperand(1).getIndex();
3078         Bytes = Flags.getByValSize();
3079       } else
3080         return false;
3081     }
3082   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3083     if (Flags.isByVal())
3084       // ByVal argument is passed in as a pointer but it's now being
3085       // dereferenced. e.g.
3086       // define @foo(%struct.X* %A) {
3087       //   tail call @bar(%struct.X* byval %A)
3088       // }
3089       return false;
3090     SDValue Ptr = Ld->getBasePtr();
3091     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3092     if (!FINode)
3093       return false;
3094     FI = FINode->getIndex();
3095   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3096     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3097     FI = FINode->getIndex();
3098     Bytes = Flags.getByValSize();
3099   } else
3100     return false;
3101
3102   assert(FI != INT_MAX);
3103   if (!MFI->isFixedObjectIndex(FI))
3104     return false;
3105   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3106 }
3107
3108 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3109 /// for tail call optimization. Targets which want to do tail call
3110 /// optimization should implement this function.
3111 bool
3112 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3113                                                      CallingConv::ID CalleeCC,
3114                                                      bool isVarArg,
3115                                                      bool isCalleeStructRet,
3116                                                      bool isCallerStructRet,
3117                                                      Type *RetTy,
3118                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3119                                     const SmallVectorImpl<SDValue> &OutVals,
3120                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3121                                                      SelectionDAG &DAG) const {
3122   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3123     return false;
3124
3125   // If -tailcallopt is specified, make fastcc functions tail-callable.
3126   const MachineFunction &MF = DAG.getMachineFunction();
3127   const Function *CallerF = MF.getFunction();
3128
3129   // If the function return type is x86_fp80 and the callee return type is not,
3130   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3131   // perform a tailcall optimization here.
3132   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3133     return false;
3134
3135   CallingConv::ID CallerCC = CallerF->getCallingConv();
3136   bool CCMatch = CallerCC == CalleeCC;
3137   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3138   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3139
3140   if (getTargetMachine().Options.GuaranteedTailCallOpt) {
3141     if (IsTailCallConvention(CalleeCC) && CCMatch)
3142       return true;
3143     return false;
3144   }
3145
3146   // Look for obvious safe cases to perform tail call optimization that do not
3147   // require ABI changes. This is what gcc calls sibcall.
3148
3149   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3150   // emit a special epilogue.
3151   const X86RegisterInfo *RegInfo =
3152     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3153   if (RegInfo->needsStackRealignment(MF))
3154     return false;
3155
3156   // Also avoid sibcall optimization if either caller or callee uses struct
3157   // return semantics.
3158   if (isCalleeStructRet || isCallerStructRet)
3159     return false;
3160
3161   // An stdcall/thiscall caller is expected to clean up its arguments; the
3162   // callee isn't going to do that.
3163   // FIXME: this is more restrictive than needed. We could produce a tailcall
3164   // when the stack adjustment matches. For example, with a thiscall that takes
3165   // only one argument.
3166   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3167                    CallerCC == CallingConv::X86_ThisCall))
3168     return false;
3169
3170   // Do not sibcall optimize vararg calls unless all arguments are passed via
3171   // registers.
3172   if (isVarArg && !Outs.empty()) {
3173
3174     // Optimizing for varargs on Win64 is unlikely to be safe without
3175     // additional testing.
3176     if (IsCalleeWin64 || IsCallerWin64)
3177       return false;
3178
3179     SmallVector<CCValAssign, 16> ArgLocs;
3180     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3181                    getTargetMachine(), ArgLocs, *DAG.getContext());
3182
3183     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3184     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3185       if (!ArgLocs[i].isRegLoc())
3186         return false;
3187   }
3188
3189   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3190   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3191   // this into a sibcall.
3192   bool Unused = false;
3193   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3194     if (!Ins[i].Used) {
3195       Unused = true;
3196       break;
3197     }
3198   }
3199   if (Unused) {
3200     SmallVector<CCValAssign, 16> RVLocs;
3201     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(),
3202                    getTargetMachine(), RVLocs, *DAG.getContext());
3203     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3204     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3205       CCValAssign &VA = RVLocs[i];
3206       if (VA.getLocReg() == X86::ST0 || VA.getLocReg() == X86::ST1)
3207         return false;
3208     }
3209   }
3210
3211   // If the calling conventions do not match, then we'd better make sure the
3212   // results are returned in the same way as what the caller expects.
3213   if (!CCMatch) {
3214     SmallVector<CCValAssign, 16> RVLocs1;
3215     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(),
3216                     getTargetMachine(), RVLocs1, *DAG.getContext());
3217     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3218
3219     SmallVector<CCValAssign, 16> RVLocs2;
3220     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(),
3221                     getTargetMachine(), RVLocs2, *DAG.getContext());
3222     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3223
3224     if (RVLocs1.size() != RVLocs2.size())
3225       return false;
3226     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3227       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3228         return false;
3229       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3230         return false;
3231       if (RVLocs1[i].isRegLoc()) {
3232         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3233           return false;
3234       } else {
3235         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3236           return false;
3237       }
3238     }
3239   }
3240
3241   // If the callee takes no arguments then go on to check the results of the
3242   // call.
3243   if (!Outs.empty()) {
3244     // Check if stack adjustment is needed. For now, do not do this if any
3245     // argument is passed on the stack.
3246     SmallVector<CCValAssign, 16> ArgLocs;
3247     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(),
3248                    getTargetMachine(), ArgLocs, *DAG.getContext());
3249
3250     // Allocate shadow area for Win64
3251     if (IsCalleeWin64)
3252       CCInfo.AllocateStack(32, 8);
3253
3254     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3255     if (CCInfo.getNextStackOffset()) {
3256       MachineFunction &MF = DAG.getMachineFunction();
3257       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3258         return false;
3259
3260       // Check if the arguments are already laid out in the right way as
3261       // the caller's fixed stack objects.
3262       MachineFrameInfo *MFI = MF.getFrameInfo();
3263       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3264       const X86InstrInfo *TII =
3265         ((const X86TargetMachine&)getTargetMachine()).getInstrInfo();
3266       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3267         CCValAssign &VA = ArgLocs[i];
3268         SDValue Arg = OutVals[i];
3269         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3270         if (VA.getLocInfo() == CCValAssign::Indirect)
3271           return false;
3272         if (!VA.isRegLoc()) {
3273           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3274                                    MFI, MRI, TII))
3275             return false;
3276         }
3277       }
3278     }
3279
3280     // If the tailcall address may be in a register, then make sure it's
3281     // possible to register allocate for it. In 32-bit, the call address can
3282     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3283     // callee-saved registers are restored. These happen to be the same
3284     // registers used to pass 'inreg' arguments so watch out for those.
3285     if (!Subtarget->is64Bit() &&
3286         ((!isa<GlobalAddressSDNode>(Callee) &&
3287           !isa<ExternalSymbolSDNode>(Callee)) ||
3288          getTargetMachine().getRelocationModel() == Reloc::PIC_)) {
3289       unsigned NumInRegs = 0;
3290       // In PIC we need an extra register to formulate the address computation
3291       // for the callee.
3292       unsigned MaxInRegs =
3293           (getTargetMachine().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3294
3295       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3296         CCValAssign &VA = ArgLocs[i];
3297         if (!VA.isRegLoc())
3298           continue;
3299         unsigned Reg = VA.getLocReg();
3300         switch (Reg) {
3301         default: break;
3302         case X86::EAX: case X86::EDX: case X86::ECX:
3303           if (++NumInRegs == MaxInRegs)
3304             return false;
3305           break;
3306         }
3307       }
3308     }
3309   }
3310
3311   return true;
3312 }
3313
3314 FastISel *
3315 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3316                                   const TargetLibraryInfo *libInfo) const {
3317   return X86::createFastISel(funcInfo, libInfo);
3318 }
3319
3320 //===----------------------------------------------------------------------===//
3321 //                           Other Lowering Hooks
3322 //===----------------------------------------------------------------------===//
3323
3324 static bool MayFoldLoad(SDValue Op) {
3325   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3326 }
3327
3328 static bool MayFoldIntoStore(SDValue Op) {
3329   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3330 }
3331
3332 static bool isTargetShuffle(unsigned Opcode) {
3333   switch(Opcode) {
3334   default: return false;
3335   case X86ISD::PSHUFD:
3336   case X86ISD::PSHUFHW:
3337   case X86ISD::PSHUFLW:
3338   case X86ISD::SHUFP:
3339   case X86ISD::PALIGNR:
3340   case X86ISD::MOVLHPS:
3341   case X86ISD::MOVLHPD:
3342   case X86ISD::MOVHLPS:
3343   case X86ISD::MOVLPS:
3344   case X86ISD::MOVLPD:
3345   case X86ISD::MOVSHDUP:
3346   case X86ISD::MOVSLDUP:
3347   case X86ISD::MOVDDUP:
3348   case X86ISD::MOVSS:
3349   case X86ISD::MOVSD:
3350   case X86ISD::UNPCKL:
3351   case X86ISD::UNPCKH:
3352   case X86ISD::VPERMILP:
3353   case X86ISD::VPERM2X128:
3354   case X86ISD::VPERMI:
3355     return true;
3356   }
3357 }
3358
3359 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3360                                     SDValue V1, SelectionDAG &DAG) {
3361   switch(Opc) {
3362   default: llvm_unreachable("Unknown x86 shuffle node");
3363   case X86ISD::MOVSHDUP:
3364   case X86ISD::MOVSLDUP:
3365   case X86ISD::MOVDDUP:
3366     return DAG.getNode(Opc, dl, VT, V1);
3367   }
3368 }
3369
3370 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3371                                     SDValue V1, unsigned TargetMask,
3372                                     SelectionDAG &DAG) {
3373   switch(Opc) {
3374   default: llvm_unreachable("Unknown x86 shuffle node");
3375   case X86ISD::PSHUFD:
3376   case X86ISD::PSHUFHW:
3377   case X86ISD::PSHUFLW:
3378   case X86ISD::VPERMILP:
3379   case X86ISD::VPERMI:
3380     return DAG.getNode(Opc, dl, VT, V1, DAG.getConstant(TargetMask, MVT::i8));
3381   }
3382 }
3383
3384 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3385                                     SDValue V1, SDValue V2, unsigned TargetMask,
3386                                     SelectionDAG &DAG) {
3387   switch(Opc) {
3388   default: llvm_unreachable("Unknown x86 shuffle node");
3389   case X86ISD::PALIGNR:
3390   case X86ISD::SHUFP:
3391   case X86ISD::VPERM2X128:
3392     return DAG.getNode(Opc, dl, VT, V1, V2,
3393                        DAG.getConstant(TargetMask, MVT::i8));
3394   }
3395 }
3396
3397 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3398                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3399   switch(Opc) {
3400   default: llvm_unreachable("Unknown x86 shuffle node");
3401   case X86ISD::MOVLHPS:
3402   case X86ISD::MOVLHPD:
3403   case X86ISD::MOVHLPS:
3404   case X86ISD::MOVLPS:
3405   case X86ISD::MOVLPD:
3406   case X86ISD::MOVSS:
3407   case X86ISD::MOVSD:
3408   case X86ISD::UNPCKL:
3409   case X86ISD::UNPCKH:
3410     return DAG.getNode(Opc, dl, VT, V1, V2);
3411   }
3412 }
3413
3414 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3415   MachineFunction &MF = DAG.getMachineFunction();
3416   const X86RegisterInfo *RegInfo =
3417     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
3418   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3419   int ReturnAddrIndex = FuncInfo->getRAIndex();
3420
3421   if (ReturnAddrIndex == 0) {
3422     // Set up a frame object for the return address.
3423     unsigned SlotSize = RegInfo->getSlotSize();
3424     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3425                                                            -(int64_t)SlotSize,
3426                                                            false);
3427     FuncInfo->setRAIndex(ReturnAddrIndex);
3428   }
3429
3430   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3431 }
3432
3433 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3434                                        bool hasSymbolicDisplacement) {
3435   // Offset should fit into 32 bit immediate field.
3436   if (!isInt<32>(Offset))
3437     return false;
3438
3439   // If we don't have a symbolic displacement - we don't have any extra
3440   // restrictions.
3441   if (!hasSymbolicDisplacement)
3442     return true;
3443
3444   // FIXME: Some tweaks might be needed for medium code model.
3445   if (M != CodeModel::Small && M != CodeModel::Kernel)
3446     return false;
3447
3448   // For small code model we assume that latest object is 16MB before end of 31
3449   // bits boundary. We may also accept pretty large negative constants knowing
3450   // that all objects are in the positive half of address space.
3451   if (M == CodeModel::Small && Offset < 16*1024*1024)
3452     return true;
3453
3454   // For kernel code model we know that all object resist in the negative half
3455   // of 32bits address space. We may not accept negative offsets, since they may
3456   // be just off and we may accept pretty large positive ones.
3457   if (M == CodeModel::Kernel && Offset > 0)
3458     return true;
3459
3460   return false;
3461 }
3462
3463 /// isCalleePop - Determines whether the callee is required to pop its
3464 /// own arguments. Callee pop is necessary to support tail calls.
3465 bool X86::isCalleePop(CallingConv::ID CallingConv,
3466                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3467   if (IsVarArg)
3468     return false;
3469
3470   switch (CallingConv) {
3471   default:
3472     return false;
3473   case CallingConv::X86_StdCall:
3474     return !is64Bit;
3475   case CallingConv::X86_FastCall:
3476     return !is64Bit;
3477   case CallingConv::X86_ThisCall:
3478     return !is64Bit;
3479   case CallingConv::Fast:
3480     return TailCallOpt;
3481   case CallingConv::GHC:
3482     return TailCallOpt;
3483   case CallingConv::HiPE:
3484     return TailCallOpt;
3485   }
3486 }
3487
3488 /// \brief Return true if the condition is an unsigned comparison operation.
3489 static bool isX86CCUnsigned(unsigned X86CC) {
3490   switch (X86CC) {
3491   default: llvm_unreachable("Invalid integer condition!");
3492   case X86::COND_E:     return true;
3493   case X86::COND_G:     return false;
3494   case X86::COND_GE:    return false;
3495   case X86::COND_L:     return false;
3496   case X86::COND_LE:    return false;
3497   case X86::COND_NE:    return true;
3498   case X86::COND_B:     return true;
3499   case X86::COND_A:     return true;
3500   case X86::COND_BE:    return true;
3501   case X86::COND_AE:    return true;
3502   }
3503   llvm_unreachable("covered switch fell through?!");
3504 }
3505
3506 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3507 /// specific condition code, returning the condition code and the LHS/RHS of the
3508 /// comparison to make.
3509 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, bool isFP,
3510                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3511   if (!isFP) {
3512     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3513       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3514         // X > -1   -> X == 0, jump !sign.
3515         RHS = DAG.getConstant(0, RHS.getValueType());
3516         return X86::COND_NS;
3517       }
3518       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3519         // X < 0   -> X == 0, jump on sign.
3520         return X86::COND_S;
3521       }
3522       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3523         // X < 1   -> X <= 0
3524         RHS = DAG.getConstant(0, RHS.getValueType());
3525         return X86::COND_LE;
3526       }
3527     }
3528
3529     switch (SetCCOpcode) {
3530     default: llvm_unreachable("Invalid integer condition!");
3531     case ISD::SETEQ:  return X86::COND_E;
3532     case ISD::SETGT:  return X86::COND_G;
3533     case ISD::SETGE:  return X86::COND_GE;
3534     case ISD::SETLT:  return X86::COND_L;
3535     case ISD::SETLE:  return X86::COND_LE;
3536     case ISD::SETNE:  return X86::COND_NE;
3537     case ISD::SETULT: return X86::COND_B;
3538     case ISD::SETUGT: return X86::COND_A;
3539     case ISD::SETULE: return X86::COND_BE;
3540     case ISD::SETUGE: return X86::COND_AE;
3541     }
3542   }
3543
3544   // First determine if it is required or is profitable to flip the operands.
3545
3546   // If LHS is a foldable load, but RHS is not, flip the condition.
3547   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3548       !ISD::isNON_EXTLoad(RHS.getNode())) {
3549     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3550     std::swap(LHS, RHS);
3551   }
3552
3553   switch (SetCCOpcode) {
3554   default: break;
3555   case ISD::SETOLT:
3556   case ISD::SETOLE:
3557   case ISD::SETUGT:
3558   case ISD::SETUGE:
3559     std::swap(LHS, RHS);
3560     break;
3561   }
3562
3563   // On a floating point condition, the flags are set as follows:
3564   // ZF  PF  CF   op
3565   //  0 | 0 | 0 | X > Y
3566   //  0 | 0 | 1 | X < Y
3567   //  1 | 0 | 0 | X == Y
3568   //  1 | 1 | 1 | unordered
3569   switch (SetCCOpcode) {
3570   default: llvm_unreachable("Condcode should be pre-legalized away");
3571   case ISD::SETUEQ:
3572   case ISD::SETEQ:   return X86::COND_E;
3573   case ISD::SETOLT:              // flipped
3574   case ISD::SETOGT:
3575   case ISD::SETGT:   return X86::COND_A;
3576   case ISD::SETOLE:              // flipped
3577   case ISD::SETOGE:
3578   case ISD::SETGE:   return X86::COND_AE;
3579   case ISD::SETUGT:              // flipped
3580   case ISD::SETULT:
3581   case ISD::SETLT:   return X86::COND_B;
3582   case ISD::SETUGE:              // flipped
3583   case ISD::SETULE:
3584   case ISD::SETLE:   return X86::COND_BE;
3585   case ISD::SETONE:
3586   case ISD::SETNE:   return X86::COND_NE;
3587   case ISD::SETUO:   return X86::COND_P;
3588   case ISD::SETO:    return X86::COND_NP;
3589   case ISD::SETOEQ:
3590   case ISD::SETUNE:  return X86::COND_INVALID;
3591   }
3592 }
3593
3594 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3595 /// code. Current x86 isa includes the following FP cmov instructions:
3596 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3597 static bool hasFPCMov(unsigned X86CC) {
3598   switch (X86CC) {
3599   default:
3600     return false;
3601   case X86::COND_B:
3602   case X86::COND_BE:
3603   case X86::COND_E:
3604   case X86::COND_P:
3605   case X86::COND_A:
3606   case X86::COND_AE:
3607   case X86::COND_NE:
3608   case X86::COND_NP:
3609     return true;
3610   }
3611 }
3612
3613 /// isFPImmLegal - Returns true if the target can instruction select the
3614 /// specified FP immediate natively. If false, the legalizer will
3615 /// materialize the FP immediate as a load from a constant pool.
3616 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3617   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3618     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3619       return true;
3620   }
3621   return false;
3622 }
3623
3624 /// \brief Returns true if it is beneficial to convert a load of a constant
3625 /// to just the constant itself.
3626 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3627                                                           Type *Ty) const {
3628   assert(Ty->isIntegerTy());
3629
3630   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3631   if (BitSize == 0 || BitSize > 64)
3632     return false;
3633   return true;
3634 }
3635
3636 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3637 /// the specified range (L, H].
3638 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3639   return (Val < 0) || (Val >= Low && Val < Hi);
3640 }
3641
3642 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3643 /// specified value.
3644 static bool isUndefOrEqual(int Val, int CmpVal) {
3645   return (Val < 0 || Val == CmpVal);
3646 }
3647
3648 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3649 /// from position Pos and ending in Pos+Size, falls within the specified
3650 /// sequential range (L, L+Pos]. or is undef.
3651 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3652                                        unsigned Pos, unsigned Size, int Low) {
3653   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3654     if (!isUndefOrEqual(Mask[i], Low))
3655       return false;
3656   return true;
3657 }
3658
3659 /// isPSHUFDMask - Return true if the node specifies a shuffle of elements that
3660 /// is suitable for input to PSHUFD or PSHUFW.  That is, it doesn't reference
3661 /// the second operand.
3662 static bool isPSHUFDMask(ArrayRef<int> Mask, MVT VT) {
3663   if (VT == MVT::v4f32 || VT == MVT::v4i32 )
3664     return (Mask[0] < 4 && Mask[1] < 4 && Mask[2] < 4 && Mask[3] < 4);
3665   if (VT == MVT::v2f64 || VT == MVT::v2i64)
3666     return (Mask[0] < 2 && Mask[1] < 2);
3667   return false;
3668 }
3669
3670 /// isPSHUFHWMask - Return true if the node specifies a shuffle of elements that
3671 /// is suitable for input to PSHUFHW.
3672 static bool isPSHUFHWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3673   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3674     return false;
3675
3676   // Lower quadword copied in order or undef.
3677   if (!isSequentialOrUndefInRange(Mask, 0, 4, 0))
3678     return false;
3679
3680   // Upper quadword shuffled.
3681   for (unsigned i = 4; i != 8; ++i)
3682     if (!isUndefOrInRange(Mask[i], 4, 8))
3683       return false;
3684
3685   if (VT == MVT::v16i16) {
3686     // Lower quadword copied in order or undef.
3687     if (!isSequentialOrUndefInRange(Mask, 8, 4, 8))
3688       return false;
3689
3690     // Upper quadword shuffled.
3691     for (unsigned i = 12; i != 16; ++i)
3692       if (!isUndefOrInRange(Mask[i], 12, 16))
3693         return false;
3694   }
3695
3696   return true;
3697 }
3698
3699 /// isPSHUFLWMask - Return true if the node specifies a shuffle of elements that
3700 /// is suitable for input to PSHUFLW.
3701 static bool isPSHUFLWMask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
3702   if (VT != MVT::v8i16 && (!HasInt256 || VT != MVT::v16i16))
3703     return false;
3704
3705   // Upper quadword copied in order.
3706   if (!isSequentialOrUndefInRange(Mask, 4, 4, 4))
3707     return false;
3708
3709   // Lower quadword shuffled.
3710   for (unsigned i = 0; i != 4; ++i)
3711     if (!isUndefOrInRange(Mask[i], 0, 4))
3712       return false;
3713
3714   if (VT == MVT::v16i16) {
3715     // Upper quadword copied in order.
3716     if (!isSequentialOrUndefInRange(Mask, 12, 4, 12))
3717       return false;
3718
3719     // Lower quadword shuffled.
3720     for (unsigned i = 8; i != 12; ++i)
3721       if (!isUndefOrInRange(Mask[i], 8, 12))
3722         return false;
3723   }
3724
3725   return true;
3726 }
3727
3728 /// isPALIGNRMask - Return true if the node specifies a shuffle of elements that
3729 /// is suitable for input to PALIGNR.
3730 static bool isPALIGNRMask(ArrayRef<int> Mask, MVT VT,
3731                           const X86Subtarget *Subtarget) {
3732   if ((VT.is128BitVector() && !Subtarget->hasSSSE3()) ||
3733       (VT.is256BitVector() && !Subtarget->hasInt256()))
3734     return false;
3735
3736   unsigned NumElts = VT.getVectorNumElements();
3737   unsigned NumLanes = VT.is512BitVector() ? 1: VT.getSizeInBits()/128;
3738   unsigned NumLaneElts = NumElts/NumLanes;
3739
3740   // Do not handle 64-bit element shuffles with palignr.
3741   if (NumLaneElts == 2)
3742     return false;
3743
3744   for (unsigned l = 0; l != NumElts; l+=NumLaneElts) {
3745     unsigned i;
3746     for (i = 0; i != NumLaneElts; ++i) {
3747       if (Mask[i+l] >= 0)
3748         break;
3749     }
3750
3751     // Lane is all undef, go to next lane
3752     if (i == NumLaneElts)
3753       continue;
3754
3755     int Start = Mask[i+l];
3756
3757     // Make sure its in this lane in one of the sources
3758     if (!isUndefOrInRange(Start, l, l+NumLaneElts) &&
3759         !isUndefOrInRange(Start, l+NumElts, l+NumElts+NumLaneElts))
3760       return false;
3761
3762     // If not lane 0, then we must match lane 0
3763     if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Start, Mask[i]+l))
3764       return false;
3765
3766     // Correct second source to be contiguous with first source
3767     if (Start >= (int)NumElts)
3768       Start -= NumElts - NumLaneElts;
3769
3770     // Make sure we're shifting in the right direction.
3771     if (Start <= (int)(i+l))
3772       return false;
3773
3774     Start -= i;
3775
3776     // Check the rest of the elements to see if they are consecutive.
3777     for (++i; i != NumLaneElts; ++i) {
3778       int Idx = Mask[i+l];
3779
3780       // Make sure its in this lane
3781       if (!isUndefOrInRange(Idx, l, l+NumLaneElts) &&
3782           !isUndefOrInRange(Idx, l+NumElts, l+NumElts+NumLaneElts))
3783         return false;
3784
3785       // If not lane 0, then we must match lane 0
3786       if (l != 0 && Mask[i] >= 0 && !isUndefOrEqual(Idx, Mask[i]+l))
3787         return false;
3788
3789       if (Idx >= (int)NumElts)
3790         Idx -= NumElts - NumLaneElts;
3791
3792       if (!isUndefOrEqual(Idx, Start+i))
3793         return false;
3794
3795     }
3796   }
3797
3798   return true;
3799 }
3800
3801 /// CommuteVectorShuffleMask - Change values in a shuffle permute mask assuming
3802 /// the two vector operands have swapped position.
3803 static void CommuteVectorShuffleMask(SmallVectorImpl<int> &Mask,
3804                                      unsigned NumElems) {
3805   for (unsigned i = 0; i != NumElems; ++i) {
3806     int idx = Mask[i];
3807     if (idx < 0)
3808       continue;
3809     else if (idx < (int)NumElems)
3810       Mask[i] = idx + NumElems;
3811     else
3812       Mask[i] = idx - NumElems;
3813   }
3814 }
3815
3816 /// isSHUFPMask - Return true if the specified VECTOR_SHUFFLE operand
3817 /// specifies a shuffle of elements that is suitable for input to 128/256-bit
3818 /// SHUFPS and SHUFPD. If Commuted is true, then it checks for sources to be
3819 /// reverse of what x86 shuffles want.
3820 static bool isSHUFPMask(ArrayRef<int> Mask, MVT VT, bool Commuted = false) {
3821
3822   unsigned NumElems = VT.getVectorNumElements();
3823   unsigned NumLanes = VT.getSizeInBits()/128;
3824   unsigned NumLaneElems = NumElems/NumLanes;
3825
3826   if (NumLaneElems != 2 && NumLaneElems != 4)
3827     return false;
3828
3829   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
3830   bool symetricMaskRequired =
3831     (VT.getSizeInBits() >= 256) && (EltSize == 32);
3832
3833   // VSHUFPSY divides the resulting vector into 4 chunks.
3834   // The sources are also splitted into 4 chunks, and each destination
3835   // chunk must come from a different source chunk.
3836   //
3837   //  SRC1 =>   X7    X6    X5    X4    X3    X2    X1    X0
3838   //  SRC2 =>   Y7    Y6    Y5    Y4    Y3    Y2    Y1    Y9
3839   //
3840   //  DST  =>  Y7..Y4,   Y7..Y4,   X7..X4,   X7..X4,
3841   //           Y3..Y0,   Y3..Y0,   X3..X0,   X3..X0
3842   //
3843   // VSHUFPDY divides the resulting vector into 4 chunks.
3844   // The sources are also splitted into 4 chunks, and each destination
3845   // chunk must come from a different source chunk.
3846   //
3847   //  SRC1 =>      X3       X2       X1       X0
3848   //  SRC2 =>      Y3       Y2       Y1       Y0
3849   //
3850   //  DST  =>  Y3..Y2,  X3..X2,  Y1..Y0,  X1..X0
3851   //
3852   SmallVector<int, 4> MaskVal(NumLaneElems, -1);
3853   unsigned HalfLaneElems = NumLaneElems/2;
3854   for (unsigned l = 0; l != NumElems; l += NumLaneElems) {
3855     for (unsigned i = 0; i != NumLaneElems; ++i) {
3856       int Idx = Mask[i+l];
3857       unsigned RngStart = l + ((Commuted == (i<HalfLaneElems)) ? NumElems : 0);
3858       if (!isUndefOrInRange(Idx, RngStart, RngStart+NumLaneElems))
3859         return false;
3860       // For VSHUFPSY, the mask of the second half must be the same as the
3861       // first but with the appropriate offsets. This works in the same way as
3862       // VPERMILPS works with masks.
3863       if (!symetricMaskRequired || Idx < 0)
3864         continue;
3865       if (MaskVal[i] < 0) {
3866         MaskVal[i] = Idx - l;
3867         continue;
3868       }
3869       if ((signed)(Idx - l) != MaskVal[i])
3870         return false;
3871     }
3872   }
3873
3874   return true;
3875 }
3876
3877 /// isMOVHLPSMask - Return true if the specified VECTOR_SHUFFLE operand
3878 /// specifies a shuffle of elements that is suitable for input to MOVHLPS.
3879 static bool isMOVHLPSMask(ArrayRef<int> Mask, MVT VT) {
3880   if (!VT.is128BitVector())
3881     return false;
3882
3883   unsigned NumElems = VT.getVectorNumElements();
3884
3885   if (NumElems != 4)
3886     return false;
3887
3888   // Expect bit0 == 6, bit1 == 7, bit2 == 2, bit3 == 3
3889   return isUndefOrEqual(Mask[0], 6) &&
3890          isUndefOrEqual(Mask[1], 7) &&
3891          isUndefOrEqual(Mask[2], 2) &&
3892          isUndefOrEqual(Mask[3], 3);
3893 }
3894
3895 /// isMOVHLPS_v_undef_Mask - Special case of isMOVHLPSMask for canonical form
3896 /// of vector_shuffle v, v, <2, 3, 2, 3>, i.e. vector_shuffle v, undef,
3897 /// <2, 3, 2, 3>
3898 static bool isMOVHLPS_v_undef_Mask(ArrayRef<int> Mask, MVT VT) {
3899   if (!VT.is128BitVector())
3900     return false;
3901
3902   unsigned NumElems = VT.getVectorNumElements();
3903
3904   if (NumElems != 4)
3905     return false;
3906
3907   return isUndefOrEqual(Mask[0], 2) &&
3908          isUndefOrEqual(Mask[1], 3) &&
3909          isUndefOrEqual(Mask[2], 2) &&
3910          isUndefOrEqual(Mask[3], 3);
3911 }
3912
3913 /// isMOVLPMask - Return true if the specified VECTOR_SHUFFLE operand
3914 /// specifies a shuffle of elements that is suitable for input to MOVLP{S|D}.
3915 static bool isMOVLPMask(ArrayRef<int> Mask, MVT VT) {
3916   if (!VT.is128BitVector())
3917     return false;
3918
3919   unsigned NumElems = VT.getVectorNumElements();
3920
3921   if (NumElems != 2 && NumElems != 4)
3922     return false;
3923
3924   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3925     if (!isUndefOrEqual(Mask[i], i + NumElems))
3926       return false;
3927
3928   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
3929     if (!isUndefOrEqual(Mask[i], i))
3930       return false;
3931
3932   return true;
3933 }
3934
3935 /// isMOVLHPSMask - Return true if the specified VECTOR_SHUFFLE operand
3936 /// specifies a shuffle of elements that is suitable for input to MOVLHPS.
3937 static bool isMOVLHPSMask(ArrayRef<int> Mask, MVT VT) {
3938   if (!VT.is128BitVector())
3939     return false;
3940
3941   unsigned NumElems = VT.getVectorNumElements();
3942
3943   if (NumElems != 2 && NumElems != 4)
3944     return false;
3945
3946   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3947     if (!isUndefOrEqual(Mask[i], i))
3948       return false;
3949
3950   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
3951     if (!isUndefOrEqual(Mask[i + e], i + NumElems))
3952       return false;
3953
3954   return true;
3955 }
3956
3957 /// isINSERTPSMask - Return true if the specified VECTOR_SHUFFLE operand
3958 /// specifies a shuffle of elements that is suitable for input to INSERTPS.
3959 /// i. e: If all but one element come from the same vector.
3960 static bool isINSERTPSMask(ArrayRef<int> Mask, MVT VT) {
3961   // TODO: Deal with AVX's VINSERTPS
3962   if (!VT.is128BitVector() || (VT != MVT::v4f32 && VT != MVT::v4i32))
3963     return false;
3964
3965   unsigned CorrectPosV1 = 0;
3966   unsigned CorrectPosV2 = 0;
3967   for (int i = 0, e = (int)VT.getVectorNumElements(); i != e; ++i)
3968     if (Mask[i] == i)
3969       ++CorrectPosV1;
3970     else if (Mask[i] == i + 4)
3971       ++CorrectPosV2;
3972
3973   if (CorrectPosV1 == 3 || CorrectPosV2 == 3)
3974     // We have 3 elements from one vector, and one from another.
3975     return true;
3976
3977   return false;
3978 }
3979
3980 //
3981 // Some special combinations that can be optimized.
3982 //
3983 static
3984 SDValue Compact8x32ShuffleNode(ShuffleVectorSDNode *SVOp,
3985                                SelectionDAG &DAG) {
3986   MVT VT = SVOp->getSimpleValueType(0);
3987   SDLoc dl(SVOp);
3988
3989   if (VT != MVT::v8i32 && VT != MVT::v8f32)
3990     return SDValue();
3991
3992   ArrayRef<int> Mask = SVOp->getMask();
3993
3994   // These are the special masks that may be optimized.
3995   static const int MaskToOptimizeEven[] = {0, 8, 2, 10, 4, 12, 6, 14};
3996   static const int MaskToOptimizeOdd[]  = {1, 9, 3, 11, 5, 13, 7, 15};
3997   bool MatchEvenMask = true;
3998   bool MatchOddMask  = true;
3999   for (int i=0; i<8; ++i) {
4000     if (!isUndefOrEqual(Mask[i], MaskToOptimizeEven[i]))
4001       MatchEvenMask = false;
4002     if (!isUndefOrEqual(Mask[i], MaskToOptimizeOdd[i]))
4003       MatchOddMask = false;
4004   }
4005
4006   if (!MatchEvenMask && !MatchOddMask)
4007     return SDValue();
4008
4009   SDValue UndefNode = DAG.getNode(ISD::UNDEF, dl, VT);
4010
4011   SDValue Op0 = SVOp->getOperand(0);
4012   SDValue Op1 = SVOp->getOperand(1);
4013
4014   if (MatchEvenMask) {
4015     // Shift the second operand right to 32 bits.
4016     static const int ShiftRightMask[] = {-1, 0, -1, 2, -1, 4, -1, 6 };
4017     Op1 = DAG.getVectorShuffle(VT, dl, Op1, UndefNode, ShiftRightMask);
4018   } else {
4019     // Shift the first operand left to 32 bits.
4020     static const int ShiftLeftMask[] = {1, -1, 3, -1, 5, -1, 7, -1 };
4021     Op0 = DAG.getVectorShuffle(VT, dl, Op0, UndefNode, ShiftLeftMask);
4022   }
4023   static const int BlendMask[] = {0, 9, 2, 11, 4, 13, 6, 15};
4024   return DAG.getVectorShuffle(VT, dl, Op0, Op1, BlendMask);
4025 }
4026
4027 /// isUNPCKLMask - Return true if the specified VECTOR_SHUFFLE operand
4028 /// specifies a shuffle of elements that is suitable for input to UNPCKL.
4029 static bool isUNPCKLMask(ArrayRef<int> Mask, MVT VT,
4030                          bool HasInt256, bool V2IsSplat = false) {
4031
4032   assert(VT.getSizeInBits() >= 128 &&
4033          "Unsupported vector type for unpckl");
4034
4035   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4036   unsigned NumLanes;
4037   unsigned NumOf256BitLanes;
4038   unsigned NumElts = VT.getVectorNumElements();
4039   if (VT.is256BitVector()) {
4040     if (NumElts != 4 && NumElts != 8 &&
4041         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4042     return false;
4043     NumLanes = 2;
4044     NumOf256BitLanes = 1;
4045   } else if (VT.is512BitVector()) {
4046     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4047            "Unsupported vector type for unpckh");
4048     NumLanes = 2;
4049     NumOf256BitLanes = 2;
4050   } else {
4051     NumLanes = 1;
4052     NumOf256BitLanes = 1;
4053   }
4054
4055   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4056   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4057
4058   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4059     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4060       for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4061         int BitI  = Mask[l256*NumEltsInStride+l+i];
4062         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4063         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4064           return false;
4065         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4066           return false;
4067         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4068           return false;
4069       }
4070     }
4071   }
4072   return true;
4073 }
4074
4075 /// isUNPCKHMask - Return true if the specified VECTOR_SHUFFLE operand
4076 /// specifies a shuffle of elements that is suitable for input to UNPCKH.
4077 static bool isUNPCKHMask(ArrayRef<int> Mask, MVT VT,
4078                          bool HasInt256, bool V2IsSplat = false) {
4079   assert(VT.getSizeInBits() >= 128 &&
4080          "Unsupported vector type for unpckh");
4081
4082   // AVX defines UNPCK* to operate independently on 128-bit lanes.
4083   unsigned NumLanes;
4084   unsigned NumOf256BitLanes;
4085   unsigned NumElts = VT.getVectorNumElements();
4086   if (VT.is256BitVector()) {
4087     if (NumElts != 4 && NumElts != 8 &&
4088         (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4089     return false;
4090     NumLanes = 2;
4091     NumOf256BitLanes = 1;
4092   } else if (VT.is512BitVector()) {
4093     assert(VT.getScalarType().getSizeInBits() >= 32 &&
4094            "Unsupported vector type for unpckh");
4095     NumLanes = 2;
4096     NumOf256BitLanes = 2;
4097   } else {
4098     NumLanes = 1;
4099     NumOf256BitLanes = 1;
4100   }
4101
4102   unsigned NumEltsInStride = NumElts/NumOf256BitLanes;
4103   unsigned NumLaneElts = NumEltsInStride/NumLanes;
4104
4105   for (unsigned l256 = 0; l256 < NumOf256BitLanes; l256 += 1) {
4106     for (unsigned l = 0; l != NumEltsInStride; l += NumLaneElts) {
4107       for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4108         int BitI  = Mask[l256*NumEltsInStride+l+i];
4109         int BitI1 = Mask[l256*NumEltsInStride+l+i+1];
4110         if (!isUndefOrEqual(BitI, j+l256*NumElts))
4111           return false;
4112         if (V2IsSplat && !isUndefOrEqual(BitI1, NumElts))
4113           return false;
4114         if (!isUndefOrEqual(BitI1, j+l256*NumElts+NumEltsInStride))
4115           return false;
4116       }
4117     }
4118   }
4119   return true;
4120 }
4121
4122 /// isUNPCKL_v_undef_Mask - Special case of isUNPCKLMask for canonical form
4123 /// of vector_shuffle v, v, <0, 4, 1, 5>, i.e. vector_shuffle v, undef,
4124 /// <0, 0, 1, 1>
4125 static bool isUNPCKL_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4126   unsigned NumElts = VT.getVectorNumElements();
4127   bool Is256BitVec = VT.is256BitVector();
4128
4129   if (VT.is512BitVector())
4130     return false;
4131   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4132          "Unsupported vector type for unpckh");
4133
4134   if (Is256BitVec && NumElts != 4 && NumElts != 8 &&
4135       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4136     return false;
4137
4138   // For 256-bit i64/f64, use MOVDDUPY instead, so reject the matching pattern
4139   // FIXME: Need a better way to get rid of this, there's no latency difference
4140   // between UNPCKLPD and MOVDDUP, the later should always be checked first and
4141   // the former later. We should also remove the "_undef" special mask.
4142   if (NumElts == 4 && Is256BitVec)
4143     return false;
4144
4145   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4146   // independently on 128-bit lanes.
4147   unsigned NumLanes = VT.getSizeInBits()/128;
4148   unsigned NumLaneElts = NumElts/NumLanes;
4149
4150   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4151     for (unsigned i = 0, j = l; i != NumLaneElts; i += 2, ++j) {
4152       int BitI  = Mask[l+i];
4153       int BitI1 = Mask[l+i+1];
4154
4155       if (!isUndefOrEqual(BitI, j))
4156         return false;
4157       if (!isUndefOrEqual(BitI1, j))
4158         return false;
4159     }
4160   }
4161
4162   return true;
4163 }
4164
4165 /// isUNPCKH_v_undef_Mask - Special case of isUNPCKHMask for canonical form
4166 /// of vector_shuffle v, v, <2, 6, 3, 7>, i.e. vector_shuffle v, undef,
4167 /// <2, 2, 3, 3>
4168 static bool isUNPCKH_v_undef_Mask(ArrayRef<int> Mask, MVT VT, bool HasInt256) {
4169   unsigned NumElts = VT.getVectorNumElements();
4170
4171   if (VT.is512BitVector())
4172     return false;
4173
4174   assert((VT.is128BitVector() || VT.is256BitVector()) &&
4175          "Unsupported vector type for unpckh");
4176
4177   if (VT.is256BitVector() && NumElts != 4 && NumElts != 8 &&
4178       (!HasInt256 || (NumElts != 16 && NumElts != 32)))
4179     return false;
4180
4181   // Handle 128 and 256-bit vector lengths. AVX defines UNPCK* to operate
4182   // independently on 128-bit lanes.
4183   unsigned NumLanes = VT.getSizeInBits()/128;
4184   unsigned NumLaneElts = NumElts/NumLanes;
4185
4186   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
4187     for (unsigned i = 0, j = l+NumLaneElts/2; i != NumLaneElts; i += 2, ++j) {
4188       int BitI  = Mask[l+i];
4189       int BitI1 = Mask[l+i+1];
4190       if (!isUndefOrEqual(BitI, j))
4191         return false;
4192       if (!isUndefOrEqual(BitI1, j))
4193         return false;
4194     }
4195   }
4196   return true;
4197 }
4198
4199 // Match for INSERTI64x4 INSERTF64x4 instructions (src0[0], src1[0]) or
4200 // (src1[0], src0[1]), manipulation with 256-bit sub-vectors
4201 static bool isINSERT64x4Mask(ArrayRef<int> Mask, MVT VT, unsigned int *Imm) {
4202   if (!VT.is512BitVector())
4203     return false;
4204
4205   unsigned NumElts = VT.getVectorNumElements();
4206   unsigned HalfSize = NumElts/2;
4207   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, 0)) {
4208     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, NumElts)) {
4209       *Imm = 1;
4210       return true;
4211     }
4212   }
4213   if (isSequentialOrUndefInRange(Mask, 0, HalfSize, NumElts)) {
4214     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, HalfSize)) {
4215       *Imm = 0;
4216       return true;
4217     }
4218   }
4219   return false;
4220 }
4221
4222 /// isMOVLMask - Return true if the specified VECTOR_SHUFFLE operand
4223 /// specifies a shuffle of elements that is suitable for input to MOVSS,
4224 /// MOVSD, and MOVD, i.e. setting the lowest element.
4225 static bool isMOVLMask(ArrayRef<int> Mask, EVT VT) {
4226   if (VT.getVectorElementType().getSizeInBits() < 32)
4227     return false;
4228   if (!VT.is128BitVector())
4229     return false;
4230
4231   unsigned NumElts = VT.getVectorNumElements();
4232
4233   if (!isUndefOrEqual(Mask[0], NumElts))
4234     return false;
4235
4236   for (unsigned i = 1; i != NumElts; ++i)
4237     if (!isUndefOrEqual(Mask[i], i))
4238       return false;
4239
4240   return true;
4241 }
4242
4243 /// isVPERM2X128Mask - Match 256-bit shuffles where the elements are considered
4244 /// as permutations between 128-bit chunks or halves. As an example: this
4245 /// shuffle bellow:
4246 ///   vector_shuffle <4, 5, 6, 7, 12, 13, 14, 15>
4247 /// The first half comes from the second half of V1 and the second half from the
4248 /// the second half of V2.
4249 static bool isVPERM2X128Mask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4250   if (!HasFp256 || !VT.is256BitVector())
4251     return false;
4252
4253   // The shuffle result is divided into half A and half B. In total the two
4254   // sources have 4 halves, namely: C, D, E, F. The final values of A and
4255   // B must come from C, D, E or F.
4256   unsigned HalfSize = VT.getVectorNumElements()/2;
4257   bool MatchA = false, MatchB = false;
4258
4259   // Check if A comes from one of C, D, E, F.
4260   for (unsigned Half = 0; Half != 4; ++Half) {
4261     if (isSequentialOrUndefInRange(Mask, 0, HalfSize, Half*HalfSize)) {
4262       MatchA = true;
4263       break;
4264     }
4265   }
4266
4267   // Check if B comes from one of C, D, E, F.
4268   for (unsigned Half = 0; Half != 4; ++Half) {
4269     if (isSequentialOrUndefInRange(Mask, HalfSize, HalfSize, Half*HalfSize)) {
4270       MatchB = true;
4271       break;
4272     }
4273   }
4274
4275   return MatchA && MatchB;
4276 }
4277
4278 /// getShuffleVPERM2X128Immediate - Return the appropriate immediate to shuffle
4279 /// the specified VECTOR_MASK mask with VPERM2F128/VPERM2I128 instructions.
4280 static unsigned getShuffleVPERM2X128Immediate(ShuffleVectorSDNode *SVOp) {
4281   MVT VT = SVOp->getSimpleValueType(0);
4282
4283   unsigned HalfSize = VT.getVectorNumElements()/2;
4284
4285   unsigned FstHalf = 0, SndHalf = 0;
4286   for (unsigned i = 0; i < HalfSize; ++i) {
4287     if (SVOp->getMaskElt(i) > 0) {
4288       FstHalf = SVOp->getMaskElt(i)/HalfSize;
4289       break;
4290     }
4291   }
4292   for (unsigned i = HalfSize; i < HalfSize*2; ++i) {
4293     if (SVOp->getMaskElt(i) > 0) {
4294       SndHalf = SVOp->getMaskElt(i)/HalfSize;
4295       break;
4296     }
4297   }
4298
4299   return (FstHalf | (SndHalf << 4));
4300 }
4301
4302 // Symetric in-lane mask. Each lane has 4 elements (for imm8)
4303 static bool isPermImmMask(ArrayRef<int> Mask, MVT VT, unsigned& Imm8) {
4304   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4305   if (EltSize < 32)
4306     return false;
4307
4308   unsigned NumElts = VT.getVectorNumElements();
4309   Imm8 = 0;
4310   if (VT.is128BitVector() || (VT.is256BitVector() && EltSize == 64)) {
4311     for (unsigned i = 0; i != NumElts; ++i) {
4312       if (Mask[i] < 0)
4313         continue;
4314       Imm8 |= Mask[i] << (i*2);
4315     }
4316     return true;
4317   }
4318
4319   unsigned LaneSize = 4;
4320   SmallVector<int, 4> MaskVal(LaneSize, -1);
4321
4322   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4323     for (unsigned i = 0; i != LaneSize; ++i) {
4324       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4325         return false;
4326       if (Mask[i+l] < 0)
4327         continue;
4328       if (MaskVal[i] < 0) {
4329         MaskVal[i] = Mask[i+l] - l;
4330         Imm8 |= MaskVal[i] << (i*2);
4331         continue;
4332       }
4333       if (Mask[i+l] != (signed)(MaskVal[i]+l))
4334         return false;
4335     }
4336   }
4337   return true;
4338 }
4339
4340 /// isVPERMILPMask - Return true if the specified VECTOR_SHUFFLE operand
4341 /// specifies a shuffle of elements that is suitable for input to VPERMILPD*.
4342 /// Note that VPERMIL mask matching is different depending whether theunderlying
4343 /// type is 32 or 64. In the VPERMILPS the high half of the mask should point
4344 /// to the same elements of the low, but to the higher half of the source.
4345 /// In VPERMILPD the two lanes could be shuffled independently of each other
4346 /// with the same restriction that lanes can't be crossed. Also handles PSHUFDY.
4347 static bool isVPERMILPMask(ArrayRef<int> Mask, MVT VT) {
4348   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
4349   if (VT.getSizeInBits() < 256 || EltSize < 32)
4350     return false;
4351   bool symetricMaskRequired = (EltSize == 32);
4352   unsigned NumElts = VT.getVectorNumElements();
4353
4354   unsigned NumLanes = VT.getSizeInBits()/128;
4355   unsigned LaneSize = NumElts/NumLanes;
4356   // 2 or 4 elements in one lane
4357
4358   SmallVector<int, 4> ExpectedMaskVal(LaneSize, -1);
4359   for (unsigned l = 0; l != NumElts; l += LaneSize) {
4360     for (unsigned i = 0; i != LaneSize; ++i) {
4361       if (!isUndefOrInRange(Mask[i+l], l, l+LaneSize))
4362         return false;
4363       if (symetricMaskRequired) {
4364         if (ExpectedMaskVal[i] < 0 && Mask[i+l] >= 0) {
4365           ExpectedMaskVal[i] = Mask[i+l] - l;
4366           continue;
4367         }
4368         if (!isUndefOrEqual(Mask[i+l], ExpectedMaskVal[i]+l))
4369           return false;
4370       }
4371     }
4372   }
4373   return true;
4374 }
4375
4376 /// isCommutedMOVLMask - Returns true if the shuffle mask is except the reverse
4377 /// of what x86 movss want. X86 movs requires the lowest  element to be lowest
4378 /// element of vector 2 and the other elements to come from vector 1 in order.
4379 static bool isCommutedMOVLMask(ArrayRef<int> Mask, MVT VT,
4380                                bool V2IsSplat = false, bool V2IsUndef = false) {
4381   if (!VT.is128BitVector())
4382     return false;
4383
4384   unsigned NumOps = VT.getVectorNumElements();
4385   if (NumOps != 2 && NumOps != 4 && NumOps != 8 && NumOps != 16)
4386     return false;
4387
4388   if (!isUndefOrEqual(Mask[0], 0))
4389     return false;
4390
4391   for (unsigned i = 1; i != NumOps; ++i)
4392     if (!(isUndefOrEqual(Mask[i], i+NumOps) ||
4393           (V2IsUndef && isUndefOrInRange(Mask[i], NumOps, NumOps*2)) ||
4394           (V2IsSplat && isUndefOrEqual(Mask[i], NumOps))))
4395       return false;
4396
4397   return true;
4398 }
4399
4400 /// isMOVSHDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4401 /// specifies a shuffle of elements that is suitable for input to MOVSHDUP.
4402 /// Masks to match: <1, 1, 3, 3> or <1, 1, 3, 3, 5, 5, 7, 7>
4403 static bool isMOVSHDUPMask(ArrayRef<int> Mask, MVT VT,
4404                            const X86Subtarget *Subtarget) {
4405   if (!Subtarget->hasSSE3())
4406     return false;
4407
4408   unsigned NumElems = VT.getVectorNumElements();
4409
4410   if ((VT.is128BitVector() && NumElems != 4) ||
4411       (VT.is256BitVector() && NumElems != 8) ||
4412       (VT.is512BitVector() && NumElems != 16))
4413     return false;
4414
4415   // "i+1" is the value the indexed mask element must have
4416   for (unsigned i = 0; i != NumElems; i += 2)
4417     if (!isUndefOrEqual(Mask[i], i+1) ||
4418         !isUndefOrEqual(Mask[i+1], i+1))
4419       return false;
4420
4421   return true;
4422 }
4423
4424 /// isMOVSLDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4425 /// specifies a shuffle of elements that is suitable for input to MOVSLDUP.
4426 /// Masks to match: <0, 0, 2, 2> or <0, 0, 2, 2, 4, 4, 6, 6>
4427 static bool isMOVSLDUPMask(ArrayRef<int> Mask, MVT VT,
4428                            const X86Subtarget *Subtarget) {
4429   if (!Subtarget->hasSSE3())
4430     return false;
4431
4432   unsigned NumElems = VT.getVectorNumElements();
4433
4434   if ((VT.is128BitVector() && NumElems != 4) ||
4435       (VT.is256BitVector() && NumElems != 8) ||
4436       (VT.is512BitVector() && NumElems != 16))
4437     return false;
4438
4439   // "i" is the value the indexed mask element must have
4440   for (unsigned i = 0; i != NumElems; i += 2)
4441     if (!isUndefOrEqual(Mask[i], i) ||
4442         !isUndefOrEqual(Mask[i+1], i))
4443       return false;
4444
4445   return true;
4446 }
4447
4448 /// isMOVDDUPYMask - Return true if the specified VECTOR_SHUFFLE operand
4449 /// specifies a shuffle of elements that is suitable for input to 256-bit
4450 /// version of MOVDDUP.
4451 static bool isMOVDDUPYMask(ArrayRef<int> Mask, MVT VT, bool HasFp256) {
4452   if (!HasFp256 || !VT.is256BitVector())
4453     return false;
4454
4455   unsigned NumElts = VT.getVectorNumElements();
4456   if (NumElts != 4)
4457     return false;
4458
4459   for (unsigned i = 0; i != NumElts/2; ++i)
4460     if (!isUndefOrEqual(Mask[i], 0))
4461       return false;
4462   for (unsigned i = NumElts/2; i != NumElts; ++i)
4463     if (!isUndefOrEqual(Mask[i], NumElts/2))
4464       return false;
4465   return true;
4466 }
4467
4468 /// isMOVDDUPMask - Return true if the specified VECTOR_SHUFFLE operand
4469 /// specifies a shuffle of elements that is suitable for input to 128-bit
4470 /// version of MOVDDUP.
4471 static bool isMOVDDUPMask(ArrayRef<int> Mask, MVT VT) {
4472   if (!VT.is128BitVector())
4473     return false;
4474
4475   unsigned e = VT.getVectorNumElements() / 2;
4476   for (unsigned i = 0; i != e; ++i)
4477     if (!isUndefOrEqual(Mask[i], i))
4478       return false;
4479   for (unsigned i = 0; i != e; ++i)
4480     if (!isUndefOrEqual(Mask[e+i], i))
4481       return false;
4482   return true;
4483 }
4484
4485 /// isVEXTRACTIndex - Return true if the specified
4486 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4487 /// suitable for instruction that extract 128 or 256 bit vectors
4488 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4489   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4490   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4491     return false;
4492
4493   // The index should be aligned on a vecWidth-bit boundary.
4494   uint64_t Index =
4495     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4496
4497   MVT VT = N->getSimpleValueType(0);
4498   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4499   bool Result = (Index * ElSize) % vecWidth == 0;
4500
4501   return Result;
4502 }
4503
4504 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4505 /// operand specifies a subvector insert that is suitable for input to
4506 /// insertion of 128 or 256-bit subvectors
4507 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4508   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4509   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4510     return false;
4511   // The index should be aligned on a vecWidth-bit boundary.
4512   uint64_t Index =
4513     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4514
4515   MVT VT = N->getSimpleValueType(0);
4516   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4517   bool Result = (Index * ElSize) % vecWidth == 0;
4518
4519   return Result;
4520 }
4521
4522 bool X86::isVINSERT128Index(SDNode *N) {
4523   return isVINSERTIndex(N, 128);
4524 }
4525
4526 bool X86::isVINSERT256Index(SDNode *N) {
4527   return isVINSERTIndex(N, 256);
4528 }
4529
4530 bool X86::isVEXTRACT128Index(SDNode *N) {
4531   return isVEXTRACTIndex(N, 128);
4532 }
4533
4534 bool X86::isVEXTRACT256Index(SDNode *N) {
4535   return isVEXTRACTIndex(N, 256);
4536 }
4537
4538 /// getShuffleSHUFImmediate - Return the appropriate immediate to shuffle
4539 /// the specified VECTOR_SHUFFLE mask with PSHUF* and SHUFP* instructions.
4540 /// Handles 128-bit and 256-bit.
4541 static unsigned getShuffleSHUFImmediate(ShuffleVectorSDNode *N) {
4542   MVT VT = N->getSimpleValueType(0);
4543
4544   assert((VT.getSizeInBits() >= 128) &&
4545          "Unsupported vector type for PSHUF/SHUFP");
4546
4547   // Handle 128 and 256-bit vector lengths. AVX defines PSHUF/SHUFP to operate
4548   // independently on 128-bit lanes.
4549   unsigned NumElts = VT.getVectorNumElements();
4550   unsigned NumLanes = VT.getSizeInBits()/128;
4551   unsigned NumLaneElts = NumElts/NumLanes;
4552
4553   assert((NumLaneElts == 2 || NumLaneElts == 4 || NumLaneElts == 8) &&
4554          "Only supports 2, 4 or 8 elements per lane");
4555
4556   unsigned Shift = (NumLaneElts >= 4) ? 1 : 0;
4557   unsigned Mask = 0;
4558   for (unsigned i = 0; i != NumElts; ++i) {
4559     int Elt = N->getMaskElt(i);
4560     if (Elt < 0) continue;
4561     Elt &= NumLaneElts - 1;
4562     unsigned ShAmt = (i << Shift) % 8;
4563     Mask |= Elt << ShAmt;
4564   }
4565
4566   return Mask;
4567 }
4568
4569 /// getShufflePSHUFHWImmediate - Return the appropriate immediate to shuffle
4570 /// the specified VECTOR_SHUFFLE mask with the PSHUFHW instruction.
4571 static unsigned getShufflePSHUFHWImmediate(ShuffleVectorSDNode *N) {
4572   MVT VT = N->getSimpleValueType(0);
4573
4574   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4575          "Unsupported vector type for PSHUFHW");
4576
4577   unsigned NumElts = VT.getVectorNumElements();
4578
4579   unsigned Mask = 0;
4580   for (unsigned l = 0; l != NumElts; l += 8) {
4581     // 8 nodes per lane, but we only care about the last 4.
4582     for (unsigned i = 0; i < 4; ++i) {
4583       int Elt = N->getMaskElt(l+i+4);
4584       if (Elt < 0) continue;
4585       Elt &= 0x3; // only 2-bits.
4586       Mask |= Elt << (i * 2);
4587     }
4588   }
4589
4590   return Mask;
4591 }
4592
4593 /// getShufflePSHUFLWImmediate - Return the appropriate immediate to shuffle
4594 /// the specified VECTOR_SHUFFLE mask with the PSHUFLW instruction.
4595 static unsigned getShufflePSHUFLWImmediate(ShuffleVectorSDNode *N) {
4596   MVT VT = N->getSimpleValueType(0);
4597
4598   assert((VT == MVT::v8i16 || VT == MVT::v16i16) &&
4599          "Unsupported vector type for PSHUFHW");
4600
4601   unsigned NumElts = VT.getVectorNumElements();
4602
4603   unsigned Mask = 0;
4604   for (unsigned l = 0; l != NumElts; l += 8) {
4605     // 8 nodes per lane, but we only care about the first 4.
4606     for (unsigned i = 0; i < 4; ++i) {
4607       int Elt = N->getMaskElt(l+i);
4608       if (Elt < 0) continue;
4609       Elt &= 0x3; // only 2-bits
4610       Mask |= Elt << (i * 2);
4611     }
4612   }
4613
4614   return Mask;
4615 }
4616
4617 /// getShufflePALIGNRImmediate - Return the appropriate immediate to shuffle
4618 /// the specified VECTOR_SHUFFLE mask with the PALIGNR instruction.
4619 static unsigned getShufflePALIGNRImmediate(ShuffleVectorSDNode *SVOp) {
4620   MVT VT = SVOp->getSimpleValueType(0);
4621   unsigned EltSize = VT.is512BitVector() ? 1 :
4622     VT.getVectorElementType().getSizeInBits() >> 3;
4623
4624   unsigned NumElts = VT.getVectorNumElements();
4625   unsigned NumLanes = VT.is512BitVector() ? 1 : VT.getSizeInBits()/128;
4626   unsigned NumLaneElts = NumElts/NumLanes;
4627
4628   int Val = 0;
4629   unsigned i;
4630   for (i = 0; i != NumElts; ++i) {
4631     Val = SVOp->getMaskElt(i);
4632     if (Val >= 0)
4633       break;
4634   }
4635   if (Val >= (int)NumElts)
4636     Val -= NumElts - NumLaneElts;
4637
4638   assert(Val - i > 0 && "PALIGNR imm should be positive");
4639   return (Val - i) * EltSize;
4640 }
4641
4642 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4643   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4644   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4645     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4646
4647   uint64_t Index =
4648     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4649
4650   MVT VecVT = N->getOperand(0).getSimpleValueType();
4651   MVT ElVT = VecVT.getVectorElementType();
4652
4653   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4654   return Index / NumElemsPerChunk;
4655 }
4656
4657 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4658   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4659   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4660     llvm_unreachable("Illegal insert subvector for VINSERT");
4661
4662   uint64_t Index =
4663     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4664
4665   MVT VecVT = N->getSimpleValueType(0);
4666   MVT ElVT = VecVT.getVectorElementType();
4667
4668   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4669   return Index / NumElemsPerChunk;
4670 }
4671
4672 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4673 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4674 /// and VINSERTI128 instructions.
4675 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4676   return getExtractVEXTRACTImmediate(N, 128);
4677 }
4678
4679 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4680 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4681 /// and VINSERTI64x4 instructions.
4682 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4683   return getExtractVEXTRACTImmediate(N, 256);
4684 }
4685
4686 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4687 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4688 /// and VINSERTI128 instructions.
4689 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4690   return getInsertVINSERTImmediate(N, 128);
4691 }
4692
4693 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4694 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4695 /// and VINSERTI64x4 instructions.
4696 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4697   return getInsertVINSERTImmediate(N, 256);
4698 }
4699
4700 /// isZero - Returns true if Elt is a constant integer zero
4701 static bool isZero(SDValue V) {
4702   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4703   return C && C->isNullValue();
4704 }
4705
4706 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4707 /// constant +0.0.
4708 bool X86::isZeroNode(SDValue Elt) {
4709   if (isZero(Elt))
4710     return true;
4711   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4712     return CFP->getValueAPF().isPosZero();
4713   return false;
4714 }
4715
4716 /// CommuteVectorShuffle - Swap vector_shuffle operands as well as values in
4717 /// their permute mask.
4718 static SDValue CommuteVectorShuffle(ShuffleVectorSDNode *SVOp,
4719                                     SelectionDAG &DAG) {
4720   MVT VT = SVOp->getSimpleValueType(0);
4721   unsigned NumElems = VT.getVectorNumElements();
4722   SmallVector<int, 8> MaskVec;
4723
4724   for (unsigned i = 0; i != NumElems; ++i) {
4725     int Idx = SVOp->getMaskElt(i);
4726     if (Idx >= 0) {
4727       if (Idx < (int)NumElems)
4728         Idx += NumElems;
4729       else
4730         Idx -= NumElems;
4731     }
4732     MaskVec.push_back(Idx);
4733   }
4734   return DAG.getVectorShuffle(VT, SDLoc(SVOp), SVOp->getOperand(1),
4735                               SVOp->getOperand(0), &MaskVec[0]);
4736 }
4737
4738 /// ShouldXformToMOVHLPS - Return true if the node should be transformed to
4739 /// match movhlps. The lower half elements should come from upper half of
4740 /// V1 (and in order), and the upper half elements should come from the upper
4741 /// half of V2 (and in order).
4742 static bool ShouldXformToMOVHLPS(ArrayRef<int> Mask, MVT VT) {
4743   if (!VT.is128BitVector())
4744     return false;
4745   if (VT.getVectorNumElements() != 4)
4746     return false;
4747   for (unsigned i = 0, e = 2; i != e; ++i)
4748     if (!isUndefOrEqual(Mask[i], i+2))
4749       return false;
4750   for (unsigned i = 2; i != 4; ++i)
4751     if (!isUndefOrEqual(Mask[i], i+4))
4752       return false;
4753   return true;
4754 }
4755
4756 /// isScalarLoadToVector - Returns true if the node is a scalar load that
4757 /// is promoted to a vector. It also returns the LoadSDNode by reference if
4758 /// required.
4759 static bool isScalarLoadToVector(SDNode *N, LoadSDNode **LD = nullptr) {
4760   if (N->getOpcode() != ISD::SCALAR_TO_VECTOR)
4761     return false;
4762   N = N->getOperand(0).getNode();
4763   if (!ISD::isNON_EXTLoad(N))
4764     return false;
4765   if (LD)
4766     *LD = cast<LoadSDNode>(N);
4767   return true;
4768 }
4769
4770 // Test whether the given value is a vector value which will be legalized
4771 // into a load.
4772 static bool WillBeConstantPoolLoad(SDNode *N) {
4773   if (N->getOpcode() != ISD::BUILD_VECTOR)
4774     return false;
4775
4776   // Check for any non-constant elements.
4777   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
4778     switch (N->getOperand(i).getNode()->getOpcode()) {
4779     case ISD::UNDEF:
4780     case ISD::ConstantFP:
4781     case ISD::Constant:
4782       break;
4783     default:
4784       return false;
4785     }
4786
4787   // Vectors of all-zeros and all-ones are materialized with special
4788   // instructions rather than being loaded.
4789   return !ISD::isBuildVectorAllZeros(N) &&
4790          !ISD::isBuildVectorAllOnes(N);
4791 }
4792
4793 /// ShouldXformToMOVLP{S|D} - Return true if the node should be transformed to
4794 /// match movlp{s|d}. The lower half elements should come from lower half of
4795 /// V1 (and in order), and the upper half elements should come from the upper
4796 /// half of V2 (and in order). And since V1 will become the source of the
4797 /// MOVLP, it must be either a vector load or a scalar load to vector.
4798 static bool ShouldXformToMOVLP(SDNode *V1, SDNode *V2,
4799                                ArrayRef<int> Mask, MVT VT) {
4800   if (!VT.is128BitVector())
4801     return false;
4802
4803   if (!ISD::isNON_EXTLoad(V1) && !isScalarLoadToVector(V1))
4804     return false;
4805   // Is V2 is a vector load, don't do this transformation. We will try to use
4806   // load folding shufps op.
4807   if (ISD::isNON_EXTLoad(V2) || WillBeConstantPoolLoad(V2))
4808     return false;
4809
4810   unsigned NumElems = VT.getVectorNumElements();
4811
4812   if (NumElems != 2 && NumElems != 4)
4813     return false;
4814   for (unsigned i = 0, e = NumElems/2; i != e; ++i)
4815     if (!isUndefOrEqual(Mask[i], i))
4816       return false;
4817   for (unsigned i = NumElems/2, e = NumElems; i != e; ++i)
4818     if (!isUndefOrEqual(Mask[i], i+NumElems))
4819       return false;
4820   return true;
4821 }
4822
4823 /// isSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
4824 /// all the same.
4825 static bool isSplatVector(SDNode *N) {
4826   if (N->getOpcode() != ISD::BUILD_VECTOR)
4827     return false;
4828
4829   SDValue SplatValue = N->getOperand(0);
4830   for (unsigned i = 1, e = N->getNumOperands(); i != e; ++i)
4831     if (N->getOperand(i) != SplatValue)
4832       return false;
4833   return true;
4834 }
4835
4836 /// isZeroShuffle - Returns true if N is a VECTOR_SHUFFLE that can be resolved
4837 /// to an zero vector.
4838 /// FIXME: move to dag combiner / method on ShuffleVectorSDNode
4839 static bool isZeroShuffle(ShuffleVectorSDNode *N) {
4840   SDValue V1 = N->getOperand(0);
4841   SDValue V2 = N->getOperand(1);
4842   unsigned NumElems = N->getValueType(0).getVectorNumElements();
4843   for (unsigned i = 0; i != NumElems; ++i) {
4844     int Idx = N->getMaskElt(i);
4845     if (Idx >= (int)NumElems) {
4846       unsigned Opc = V2.getOpcode();
4847       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V2.getNode()))
4848         continue;
4849       if (Opc != ISD::BUILD_VECTOR ||
4850           !X86::isZeroNode(V2.getOperand(Idx-NumElems)))
4851         return false;
4852     } else if (Idx >= 0) {
4853       unsigned Opc = V1.getOpcode();
4854       if (Opc == ISD::UNDEF || ISD::isBuildVectorAllZeros(V1.getNode()))
4855         continue;
4856       if (Opc != ISD::BUILD_VECTOR ||
4857           !X86::isZeroNode(V1.getOperand(Idx)))
4858         return false;
4859     }
4860   }
4861   return true;
4862 }
4863
4864 /// getZeroVector - Returns a vector of specified type with all zero elements.
4865 ///
4866 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4867                              SelectionDAG &DAG, SDLoc dl) {
4868   assert(VT.isVector() && "Expected a vector type");
4869
4870   // Always build SSE zero vectors as <4 x i32> bitcasted
4871   // to their dest type. This ensures they get CSE'd.
4872   SDValue Vec;
4873   if (VT.is128BitVector()) {  // SSE
4874     if (Subtarget->hasSSE2()) {  // SSE2
4875       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4876       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4877     } else { // SSE1
4878       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4879       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4880     }
4881   } else if (VT.is256BitVector()) { // AVX
4882     if (Subtarget->hasInt256()) { // AVX2
4883       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4884       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4885       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4886     } else {
4887       // 256-bit logic and arithmetic instructions in AVX are all
4888       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4889       SDValue Cst = DAG.getTargetConstantFP(+0.0, MVT::f32);
4890       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4891       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4892     }
4893   } else if (VT.is512BitVector()) { // AVX-512
4894       SDValue Cst = DAG.getTargetConstant(0, MVT::i32);
4895       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4896                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4897       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4898   } else if (VT.getScalarType() == MVT::i1) {
4899     assert(VT.getVectorNumElements() <= 16 && "Unexpected vector type");
4900     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
4901     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
4902     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4903   } else
4904     llvm_unreachable("Unexpected vector type");
4905
4906   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4907 }
4908
4909 /// getOnesVector - Returns a vector of specified type with all bits set.
4910 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4911 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4912 /// Then bitcast to their original type, ensuring they get CSE'd.
4913 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4914                              SDLoc dl) {
4915   assert(VT.isVector() && "Expected a vector type");
4916
4917   SDValue Cst = DAG.getTargetConstant(~0U, MVT::i32);
4918   SDValue Vec;
4919   if (VT.is256BitVector()) {
4920     if (HasInt256) { // AVX2
4921       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4922       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4923     } else { // AVX
4924       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4925       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4926     }
4927   } else if (VT.is128BitVector()) {
4928     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4929   } else
4930     llvm_unreachable("Unexpected vector type");
4931
4932   return DAG.getNode(ISD::BITCAST, dl, VT, Vec);
4933 }
4934
4935 /// NormalizeMask - V2 is a splat, modify the mask (if needed) so all elements
4936 /// that point to V2 points to its first element.
4937 static void NormalizeMask(SmallVectorImpl<int> &Mask, unsigned NumElems) {
4938   for (unsigned i = 0; i != NumElems; ++i) {
4939     if (Mask[i] > (int)NumElems) {
4940       Mask[i] = NumElems;
4941     }
4942   }
4943 }
4944
4945 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4946 /// operation of specified width.
4947 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4948                        SDValue V2) {
4949   unsigned NumElems = VT.getVectorNumElements();
4950   SmallVector<int, 8> Mask;
4951   Mask.push_back(NumElems);
4952   for (unsigned i = 1; i != NumElems; ++i)
4953     Mask.push_back(i);
4954   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4955 }
4956
4957 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4958 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4959                           SDValue V2) {
4960   unsigned NumElems = VT.getVectorNumElements();
4961   SmallVector<int, 8> Mask;
4962   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4963     Mask.push_back(i);
4964     Mask.push_back(i + NumElems);
4965   }
4966   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4967 }
4968
4969 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4970 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4971                           SDValue V2) {
4972   unsigned NumElems = VT.getVectorNumElements();
4973   SmallVector<int, 8> Mask;
4974   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4975     Mask.push_back(i + Half);
4976     Mask.push_back(i + NumElems + Half);
4977   }
4978   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4979 }
4980
4981 // PromoteSplati8i16 - All i16 and i8 vector types can't be used directly by
4982 // a generic shuffle instruction because the target has no such instructions.
4983 // Generate shuffles which repeat i16 and i8 several times until they can be
4984 // represented by v4f32 and then be manipulated by target suported shuffles.
4985 static SDValue PromoteSplati8i16(SDValue V, SelectionDAG &DAG, int &EltNo) {
4986   MVT VT = V.getSimpleValueType();
4987   int NumElems = VT.getVectorNumElements();
4988   SDLoc dl(V);
4989
4990   while (NumElems > 4) {
4991     if (EltNo < NumElems/2) {
4992       V = getUnpackl(DAG, dl, VT, V, V);
4993     } else {
4994       V = getUnpackh(DAG, dl, VT, V, V);
4995       EltNo -= NumElems/2;
4996     }
4997     NumElems >>= 1;
4998   }
4999   return V;
5000 }
5001
5002 /// getLegalSplat - Generate a legal splat with supported x86 shuffles
5003 static SDValue getLegalSplat(SelectionDAG &DAG, SDValue V, int EltNo) {
5004   MVT VT = V.getSimpleValueType();
5005   SDLoc dl(V);
5006
5007   if (VT.is128BitVector()) {
5008     V = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V);
5009     int SplatMask[4] = { EltNo, EltNo, EltNo, EltNo };
5010     V = DAG.getVectorShuffle(MVT::v4f32, dl, V, DAG.getUNDEF(MVT::v4f32),
5011                              &SplatMask[0]);
5012   } else if (VT.is256BitVector()) {
5013     // To use VPERMILPS to splat scalars, the second half of indicies must
5014     // refer to the higher part, which is a duplication of the lower one,
5015     // because VPERMILPS can only handle in-lane permutations.
5016     int SplatMask[8] = { EltNo, EltNo, EltNo, EltNo,
5017                          EltNo+4, EltNo+4, EltNo+4, EltNo+4 };
5018
5019     V = DAG.getNode(ISD::BITCAST, dl, MVT::v8f32, V);
5020     V = DAG.getVectorShuffle(MVT::v8f32, dl, V, DAG.getUNDEF(MVT::v8f32),
5021                              &SplatMask[0]);
5022   } else
5023     llvm_unreachable("Vector size not supported");
5024
5025   return DAG.getNode(ISD::BITCAST, dl, VT, V);
5026 }
5027
5028 /// PromoteSplat - Splat is promoted to target supported vector shuffles.
5029 static SDValue PromoteSplat(ShuffleVectorSDNode *SV, SelectionDAG &DAG) {
5030   MVT SrcVT = SV->getSimpleValueType(0);
5031   SDValue V1 = SV->getOperand(0);
5032   SDLoc dl(SV);
5033
5034   int EltNo = SV->getSplatIndex();
5035   int NumElems = SrcVT.getVectorNumElements();
5036   bool Is256BitVec = SrcVT.is256BitVector();
5037
5038   assert(((SrcVT.is128BitVector() && NumElems > 4) || Is256BitVec) &&
5039          "Unknown how to promote splat for type");
5040
5041   // Extract the 128-bit part containing the splat element and update
5042   // the splat element index when it refers to the higher register.
5043   if (Is256BitVec) {
5044     V1 = Extract128BitVector(V1, EltNo, DAG, dl);
5045     if (EltNo >= NumElems/2)
5046       EltNo -= NumElems/2;
5047   }
5048
5049   // All i16 and i8 vector types can't be used directly by a generic shuffle
5050   // instruction because the target has no such instruction. Generate shuffles
5051   // which repeat i16 and i8 several times until they fit in i32, and then can
5052   // be manipulated by target suported shuffles.
5053   MVT EltVT = SrcVT.getVectorElementType();
5054   if (EltVT == MVT::i8 || EltVT == MVT::i16)
5055     V1 = PromoteSplati8i16(V1, DAG, EltNo);
5056
5057   // Recreate the 256-bit vector and place the same 128-bit vector
5058   // into the low and high part. This is necessary because we want
5059   // to use VPERM* to shuffle the vectors
5060   if (Is256BitVec) {
5061     V1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, SrcVT, V1, V1);
5062   }
5063
5064   return getLegalSplat(DAG, V1, EltNo);
5065 }
5066
5067 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
5068 /// vector of zero or undef vector.  This produces a shuffle where the low
5069 /// element of V2 is swizzled into the zero/undef vector, landing at element
5070 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
5071 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
5072                                            bool IsZero,
5073                                            const X86Subtarget *Subtarget,
5074                                            SelectionDAG &DAG) {
5075   MVT VT = V2.getSimpleValueType();
5076   SDValue V1 = IsZero
5077     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
5078   unsigned NumElems = VT.getVectorNumElements();
5079   SmallVector<int, 16> MaskVec;
5080   for (unsigned i = 0; i != NumElems; ++i)
5081     // If this is the insertion idx, put the low elt of V2 here.
5082     MaskVec.push_back(i == Idx ? NumElems : i);
5083   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
5084 }
5085
5086 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
5087 /// target specific opcode. Returns true if the Mask could be calculated.
5088 /// Sets IsUnary to true if only uses one source.
5089 static bool getTargetShuffleMask(SDNode *N, MVT VT,
5090                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
5091   unsigned NumElems = VT.getVectorNumElements();
5092   SDValue ImmN;
5093
5094   IsUnary = false;
5095   switch(N->getOpcode()) {
5096   case X86ISD::SHUFP:
5097     ImmN = N->getOperand(N->getNumOperands()-1);
5098     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5099     break;
5100   case X86ISD::UNPCKH:
5101     DecodeUNPCKHMask(VT, Mask);
5102     break;
5103   case X86ISD::UNPCKL:
5104     DecodeUNPCKLMask(VT, Mask);
5105     break;
5106   case X86ISD::MOVHLPS:
5107     DecodeMOVHLPSMask(NumElems, Mask);
5108     break;
5109   case X86ISD::MOVLHPS:
5110     DecodeMOVLHPSMask(NumElems, Mask);
5111     break;
5112   case X86ISD::PALIGNR:
5113     ImmN = N->getOperand(N->getNumOperands()-1);
5114     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5115     break;
5116   case X86ISD::PSHUFD:
5117   case X86ISD::VPERMILP:
5118     ImmN = N->getOperand(N->getNumOperands()-1);
5119     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5120     IsUnary = true;
5121     break;
5122   case X86ISD::PSHUFHW:
5123     ImmN = N->getOperand(N->getNumOperands()-1);
5124     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5125     IsUnary = true;
5126     break;
5127   case X86ISD::PSHUFLW:
5128     ImmN = N->getOperand(N->getNumOperands()-1);
5129     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5130     IsUnary = true;
5131     break;
5132   case X86ISD::VPERMI:
5133     ImmN = N->getOperand(N->getNumOperands()-1);
5134     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5135     IsUnary = true;
5136     break;
5137   case X86ISD::MOVSS:
5138   case X86ISD::MOVSD: {
5139     // The index 0 always comes from the first element of the second source,
5140     // this is why MOVSS and MOVSD are used in the first place. The other
5141     // elements come from the other positions of the first source vector
5142     Mask.push_back(NumElems);
5143     for (unsigned i = 1; i != NumElems; ++i) {
5144       Mask.push_back(i);
5145     }
5146     break;
5147   }
5148   case X86ISD::VPERM2X128:
5149     ImmN = N->getOperand(N->getNumOperands()-1);
5150     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
5151     if (Mask.empty()) return false;
5152     break;
5153   case X86ISD::MOVDDUP:
5154   case X86ISD::MOVLHPD:
5155   case X86ISD::MOVLPD:
5156   case X86ISD::MOVLPS:
5157   case X86ISD::MOVSHDUP:
5158   case X86ISD::MOVSLDUP:
5159     // Not yet implemented
5160     return false;
5161   default: llvm_unreachable("unknown target shuffle node");
5162   }
5163
5164   return true;
5165 }
5166
5167 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
5168 /// element of the result of the vector shuffle.
5169 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
5170                                    unsigned Depth) {
5171   if (Depth == 6)
5172     return SDValue();  // Limit search depth.
5173
5174   SDValue V = SDValue(N, 0);
5175   EVT VT = V.getValueType();
5176   unsigned Opcode = V.getOpcode();
5177
5178   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
5179   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
5180     int Elt = SV->getMaskElt(Index);
5181
5182     if (Elt < 0)
5183       return DAG.getUNDEF(VT.getVectorElementType());
5184
5185     unsigned NumElems = VT.getVectorNumElements();
5186     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
5187                                          : SV->getOperand(1);
5188     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
5189   }
5190
5191   // Recurse into target specific vector shuffles to find scalars.
5192   if (isTargetShuffle(Opcode)) {
5193     MVT ShufVT = V.getSimpleValueType();
5194     unsigned NumElems = ShufVT.getVectorNumElements();
5195     SmallVector<int, 16> ShuffleMask;
5196     bool IsUnary;
5197
5198     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
5199       return SDValue();
5200
5201     int Elt = ShuffleMask[Index];
5202     if (Elt < 0)
5203       return DAG.getUNDEF(ShufVT.getVectorElementType());
5204
5205     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
5206                                          : N->getOperand(1);
5207     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
5208                                Depth+1);
5209   }
5210
5211   // Actual nodes that may contain scalar elements
5212   if (Opcode == ISD::BITCAST) {
5213     V = V.getOperand(0);
5214     EVT SrcVT = V.getValueType();
5215     unsigned NumElems = VT.getVectorNumElements();
5216
5217     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
5218       return SDValue();
5219   }
5220
5221   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
5222     return (Index == 0) ? V.getOperand(0)
5223                         : DAG.getUNDEF(VT.getVectorElementType());
5224
5225   if (V.getOpcode() == ISD::BUILD_VECTOR)
5226     return V.getOperand(Index);
5227
5228   return SDValue();
5229 }
5230
5231 /// getNumOfConsecutiveZeros - Return the number of elements of a vector
5232 /// shuffle operation which come from a consecutively from a zero. The
5233 /// search can start in two different directions, from left or right.
5234 /// We count undefs as zeros until PreferredNum is reached.
5235 static unsigned getNumOfConsecutiveZeros(ShuffleVectorSDNode *SVOp,
5236                                          unsigned NumElems, bool ZerosFromLeft,
5237                                          SelectionDAG &DAG,
5238                                          unsigned PreferredNum = -1U) {
5239   unsigned NumZeros = 0;
5240   for (unsigned i = 0; i != NumElems; ++i) {
5241     unsigned Index = ZerosFromLeft ? i : NumElems - i - 1;
5242     SDValue Elt = getShuffleScalarElt(SVOp, Index, DAG, 0);
5243     if (!Elt.getNode())
5244       break;
5245
5246     if (X86::isZeroNode(Elt))
5247       ++NumZeros;
5248     else if (Elt.getOpcode() == ISD::UNDEF) // Undef as zero up to PreferredNum.
5249       NumZeros = std::min(NumZeros + 1, PreferredNum);
5250     else
5251       break;
5252   }
5253
5254   return NumZeros;
5255 }
5256
5257 /// isShuffleMaskConsecutive - Check if the shuffle mask indicies [MaskI, MaskE)
5258 /// correspond consecutively to elements from one of the vector operands,
5259 /// starting from its index OpIdx. Also tell OpNum which source vector operand.
5260 static
5261 bool isShuffleMaskConsecutive(ShuffleVectorSDNode *SVOp,
5262                               unsigned MaskI, unsigned MaskE, unsigned OpIdx,
5263                               unsigned NumElems, unsigned &OpNum) {
5264   bool SeenV1 = false;
5265   bool SeenV2 = false;
5266
5267   for (unsigned i = MaskI; i != MaskE; ++i, ++OpIdx) {
5268     int Idx = SVOp->getMaskElt(i);
5269     // Ignore undef indicies
5270     if (Idx < 0)
5271       continue;
5272
5273     if (Idx < (int)NumElems)
5274       SeenV1 = true;
5275     else
5276       SeenV2 = true;
5277
5278     // Only accept consecutive elements from the same vector
5279     if ((Idx % NumElems != OpIdx) || (SeenV1 && SeenV2))
5280       return false;
5281   }
5282
5283   OpNum = SeenV1 ? 0 : 1;
5284   return true;
5285 }
5286
5287 /// isVectorShiftRight - Returns true if the shuffle can be implemented as a
5288 /// logical left shift of a vector.
5289 static bool isVectorShiftRight(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5290                                bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5291   unsigned NumElems =
5292     SVOp->getSimpleValueType(0).getVectorNumElements();
5293   unsigned NumZeros = getNumOfConsecutiveZeros(
5294       SVOp, NumElems, false /* check zeros from right */, DAG,
5295       SVOp->getMaskElt(0));
5296   unsigned OpSrc;
5297
5298   if (!NumZeros)
5299     return false;
5300
5301   // Considering the elements in the mask that are not consecutive zeros,
5302   // check if they consecutively come from only one of the source vectors.
5303   //
5304   //               V1 = {X, A, B, C}     0
5305   //                         \  \  \    /
5306   //   vector_shuffle V1, V2 <1, 2, 3, X>
5307   //
5308   if (!isShuffleMaskConsecutive(SVOp,
5309             0,                   // Mask Start Index
5310             NumElems-NumZeros,   // Mask End Index(exclusive)
5311             NumZeros,            // Where to start looking in the src vector
5312             NumElems,            // Number of elements in vector
5313             OpSrc))              // Which source operand ?
5314     return false;
5315
5316   isLeft = false;
5317   ShAmt = NumZeros;
5318   ShVal = SVOp->getOperand(OpSrc);
5319   return true;
5320 }
5321
5322 /// isVectorShiftLeft - Returns true if the shuffle can be implemented as a
5323 /// logical left shift of a vector.
5324 static bool isVectorShiftLeft(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5325                               bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5326   unsigned NumElems =
5327     SVOp->getSimpleValueType(0).getVectorNumElements();
5328   unsigned NumZeros = getNumOfConsecutiveZeros(
5329       SVOp, NumElems, true /* check zeros from left */, DAG,
5330       NumElems - SVOp->getMaskElt(NumElems - 1) - 1);
5331   unsigned OpSrc;
5332
5333   if (!NumZeros)
5334     return false;
5335
5336   // Considering the elements in the mask that are not consecutive zeros,
5337   // check if they consecutively come from only one of the source vectors.
5338   //
5339   //                           0    { A, B, X, X } = V2
5340   //                          / \    /  /
5341   //   vector_shuffle V1, V2 <X, X, 4, 5>
5342   //
5343   if (!isShuffleMaskConsecutive(SVOp,
5344             NumZeros,     // Mask Start Index
5345             NumElems,     // Mask End Index(exclusive)
5346             0,            // Where to start looking in the src vector
5347             NumElems,     // Number of elements in vector
5348             OpSrc))       // Which source operand ?
5349     return false;
5350
5351   isLeft = true;
5352   ShAmt = NumZeros;
5353   ShVal = SVOp->getOperand(OpSrc);
5354   return true;
5355 }
5356
5357 /// isVectorShift - Returns true if the shuffle can be implemented as a
5358 /// logical left or right shift of a vector.
5359 static bool isVectorShift(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG,
5360                           bool &isLeft, SDValue &ShVal, unsigned &ShAmt) {
5361   // Although the logic below support any bitwidth size, there are no
5362   // shift instructions which handle more than 128-bit vectors.
5363   if (!SVOp->getSimpleValueType(0).is128BitVector())
5364     return false;
5365
5366   if (isVectorShiftLeft(SVOp, DAG, isLeft, ShVal, ShAmt) ||
5367       isVectorShiftRight(SVOp, DAG, isLeft, ShVal, ShAmt))
5368     return true;
5369
5370   return false;
5371 }
5372
5373 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
5374 ///
5375 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
5376                                        unsigned NumNonZero, unsigned NumZero,
5377                                        SelectionDAG &DAG,
5378                                        const X86Subtarget* Subtarget,
5379                                        const TargetLowering &TLI) {
5380   if (NumNonZero > 8)
5381     return SDValue();
5382
5383   SDLoc dl(Op);
5384   SDValue V;
5385   bool First = true;
5386   for (unsigned i = 0; i < 16; ++i) {
5387     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
5388     if (ThisIsNonZero && First) {
5389       if (NumZero)
5390         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5391       else
5392         V = DAG.getUNDEF(MVT::v8i16);
5393       First = false;
5394     }
5395
5396     if ((i & 1) != 0) {
5397       SDValue ThisElt, LastElt;
5398       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
5399       if (LastIsNonZero) {
5400         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
5401                               MVT::i16, Op.getOperand(i-1));
5402       }
5403       if (ThisIsNonZero) {
5404         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
5405         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
5406                               ThisElt, DAG.getConstant(8, MVT::i8));
5407         if (LastIsNonZero)
5408           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
5409       } else
5410         ThisElt = LastElt;
5411
5412       if (ThisElt.getNode())
5413         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
5414                         DAG.getIntPtrConstant(i/2));
5415     }
5416   }
5417
5418   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, V);
5419 }
5420
5421 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
5422 ///
5423 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
5424                                      unsigned NumNonZero, unsigned NumZero,
5425                                      SelectionDAG &DAG,
5426                                      const X86Subtarget* Subtarget,
5427                                      const TargetLowering &TLI) {
5428   if (NumNonZero > 4)
5429     return SDValue();
5430
5431   SDLoc dl(Op);
5432   SDValue V;
5433   bool First = true;
5434   for (unsigned i = 0; i < 8; ++i) {
5435     bool isNonZero = (NonZeros & (1 << i)) != 0;
5436     if (isNonZero) {
5437       if (First) {
5438         if (NumZero)
5439           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
5440         else
5441           V = DAG.getUNDEF(MVT::v8i16);
5442         First = false;
5443       }
5444       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
5445                       MVT::v8i16, V, Op.getOperand(i),
5446                       DAG.getIntPtrConstant(i));
5447     }
5448   }
5449
5450   return V;
5451 }
5452
5453 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
5454 static SDValue LowerBuildVectorv4x32(SDValue Op, unsigned NumElems,
5455                                      unsigned NonZeros, unsigned NumNonZero,
5456                                      unsigned NumZero, SelectionDAG &DAG,
5457                                      const X86Subtarget *Subtarget,
5458                                      const TargetLowering &TLI) {
5459   // We know there's at least one non-zero element
5460   unsigned FirstNonZeroIdx = 0;
5461   SDValue FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5462   while (FirstNonZero.getOpcode() == ISD::UNDEF ||
5463          X86::isZeroNode(FirstNonZero)) {
5464     ++FirstNonZeroIdx;
5465     FirstNonZero = Op->getOperand(FirstNonZeroIdx);
5466   }
5467
5468   if (FirstNonZero.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5469       !isa<ConstantSDNode>(FirstNonZero.getOperand(1)))
5470     return SDValue();
5471
5472   SDValue V = FirstNonZero.getOperand(0);
5473   MVT VVT = V.getSimpleValueType();
5474   if (!Subtarget->hasSSE41() || (VVT != MVT::v4f32 && VVT != MVT::v4i32))
5475     return SDValue();
5476
5477   unsigned FirstNonZeroDst =
5478       cast<ConstantSDNode>(FirstNonZero.getOperand(1))->getZExtValue();
5479   unsigned CorrectIdx = FirstNonZeroDst == FirstNonZeroIdx;
5480   unsigned IncorrectIdx = CorrectIdx ? -1U : FirstNonZeroIdx;
5481   unsigned IncorrectDst = CorrectIdx ? -1U : FirstNonZeroDst;
5482
5483   for (unsigned Idx = FirstNonZeroIdx + 1; Idx < NumElems; ++Idx) {
5484     SDValue Elem = Op.getOperand(Idx);
5485     if (Elem.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elem))
5486       continue;
5487
5488     // TODO: What else can be here? Deal with it.
5489     if (Elem.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
5490       return SDValue();
5491
5492     // TODO: Some optimizations are still possible here
5493     // ex: Getting one element from a vector, and the rest from another.
5494     if (Elem.getOperand(0) != V)
5495       return SDValue();
5496
5497     unsigned Dst = cast<ConstantSDNode>(Elem.getOperand(1))->getZExtValue();
5498     if (Dst == Idx)
5499       ++CorrectIdx;
5500     else if (IncorrectIdx == -1U) {
5501       IncorrectIdx = Idx;
5502       IncorrectDst = Dst;
5503     } else
5504       // There was already one element with an incorrect index.
5505       // We can't optimize this case to an insertps.
5506       return SDValue();
5507   }
5508
5509   if (NumNonZero == CorrectIdx || NumNonZero == CorrectIdx + 1) {
5510     SDLoc dl(Op);
5511     EVT VT = Op.getSimpleValueType();
5512     unsigned ElementMoveMask = 0;
5513     if (IncorrectIdx == -1U)
5514       ElementMoveMask = FirstNonZeroIdx << 6 | FirstNonZeroIdx << 4;
5515     else
5516       ElementMoveMask = IncorrectDst << 6 | IncorrectIdx << 4;
5517
5518     SDValue InsertpsMask =
5519         DAG.getIntPtrConstant(ElementMoveMask | (~NonZeros & 0xf));
5520     return DAG.getNode(X86ISD::INSERTPS, dl, VT, V, V, InsertpsMask);
5521   }
5522
5523   return SDValue();
5524 }
5525
5526 /// getVShift - Return a vector logical shift node.
5527 ///
5528 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
5529                          unsigned NumBits, SelectionDAG &DAG,
5530                          const TargetLowering &TLI, SDLoc dl) {
5531   assert(VT.is128BitVector() && "Unknown type for VShift");
5532   EVT ShVT = MVT::v2i64;
5533   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
5534   SrcOp = DAG.getNode(ISD::BITCAST, dl, ShVT, SrcOp);
5535   return DAG.getNode(ISD::BITCAST, dl, VT,
5536                      DAG.getNode(Opc, dl, ShVT, SrcOp,
5537                              DAG.getConstant(NumBits,
5538                                   TLI.getScalarShiftAmountTy(SrcOp.getValueType()))));
5539 }
5540
5541 static SDValue
5542 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
5543
5544   // Check if the scalar load can be widened into a vector load. And if
5545   // the address is "base + cst" see if the cst can be "absorbed" into
5546   // the shuffle mask.
5547   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
5548     SDValue Ptr = LD->getBasePtr();
5549     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
5550       return SDValue();
5551     EVT PVT = LD->getValueType(0);
5552     if (PVT != MVT::i32 && PVT != MVT::f32)
5553       return SDValue();
5554
5555     int FI = -1;
5556     int64_t Offset = 0;
5557     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
5558       FI = FINode->getIndex();
5559       Offset = 0;
5560     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
5561                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
5562       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
5563       Offset = Ptr.getConstantOperandVal(1);
5564       Ptr = Ptr.getOperand(0);
5565     } else {
5566       return SDValue();
5567     }
5568
5569     // FIXME: 256-bit vector instructions don't require a strict alignment,
5570     // improve this code to support it better.
5571     unsigned RequiredAlign = VT.getSizeInBits()/8;
5572     SDValue Chain = LD->getChain();
5573     // Make sure the stack object alignment is at least 16 or 32.
5574     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
5575     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
5576       if (MFI->isFixedObjectIndex(FI)) {
5577         // Can't change the alignment. FIXME: It's possible to compute
5578         // the exact stack offset and reference FI + adjust offset instead.
5579         // If someone *really* cares about this. That's the way to implement it.
5580         return SDValue();
5581       } else {
5582         MFI->setObjectAlignment(FI, RequiredAlign);
5583       }
5584     }
5585
5586     // (Offset % 16 or 32) must be multiple of 4. Then address is then
5587     // Ptr + (Offset & ~15).
5588     if (Offset < 0)
5589       return SDValue();
5590     if ((Offset % RequiredAlign) & 3)
5591       return SDValue();
5592     int64_t StartOffset = Offset & ~(RequiredAlign-1);
5593     if (StartOffset)
5594       Ptr = DAG.getNode(ISD::ADD, SDLoc(Ptr), Ptr.getValueType(),
5595                         Ptr,DAG.getConstant(StartOffset, Ptr.getValueType()));
5596
5597     int EltNo = (Offset - StartOffset) >> 2;
5598     unsigned NumElems = VT.getVectorNumElements();
5599
5600     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
5601     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
5602                              LD->getPointerInfo().getWithOffset(StartOffset),
5603                              false, false, false, 0);
5604
5605     SmallVector<int, 8> Mask;
5606     for (unsigned i = 0; i != NumElems; ++i)
5607       Mask.push_back(EltNo);
5608
5609     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
5610   }
5611
5612   return SDValue();
5613 }
5614
5615 /// EltsFromConsecutiveLoads - Given the initializing elements 'Elts' of a
5616 /// vector of type 'VT', see if the elements can be replaced by a single large
5617 /// load which has the same value as a build_vector whose operands are 'elts'.
5618 ///
5619 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5620 ///
5621 /// FIXME: we'd also like to handle the case where the last elements are zero
5622 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5623 /// There's even a handy isZeroNode for that purpose.
5624 static SDValue EltsFromConsecutiveLoads(EVT VT, SmallVectorImpl<SDValue> &Elts,
5625                                         SDLoc &DL, SelectionDAG &DAG,
5626                                         bool isAfterLegalize) {
5627   EVT EltVT = VT.getVectorElementType();
5628   unsigned NumElems = Elts.size();
5629
5630   LoadSDNode *LDBase = nullptr;
5631   unsigned LastLoadedElt = -1U;
5632
5633   // For each element in the initializer, see if we've found a load or an undef.
5634   // If we don't find an initial load element, or later load elements are
5635   // non-consecutive, bail out.
5636   for (unsigned i = 0; i < NumElems; ++i) {
5637     SDValue Elt = Elts[i];
5638
5639     if (!Elt.getNode() ||
5640         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5641       return SDValue();
5642     if (!LDBase) {
5643       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5644         return SDValue();
5645       LDBase = cast<LoadSDNode>(Elt.getNode());
5646       LastLoadedElt = i;
5647       continue;
5648     }
5649     if (Elt.getOpcode() == ISD::UNDEF)
5650       continue;
5651
5652     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5653     if (!DAG.isConsecutiveLoad(LD, LDBase, EltVT.getSizeInBits()/8, i))
5654       return SDValue();
5655     LastLoadedElt = i;
5656   }
5657
5658   // If we have found an entire vector of loads and undefs, then return a large
5659   // load of the entire vector width starting at the base pointer.  If we found
5660   // consecutive loads for the low half, generate a vzext_load node.
5661   if (LastLoadedElt == NumElems - 1) {
5662
5663     if (isAfterLegalize &&
5664         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5665       return SDValue();
5666
5667     SDValue NewLd = SDValue();
5668
5669     if (DAG.InferPtrAlignment(LDBase->getBasePtr()) >= 16)
5670       NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5671                           LDBase->getPointerInfo(),
5672                           LDBase->isVolatile(), LDBase->isNonTemporal(),
5673                           LDBase->isInvariant(), 0);
5674     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5675                         LDBase->getPointerInfo(),
5676                         LDBase->isVolatile(), LDBase->isNonTemporal(),
5677                         LDBase->isInvariant(), LDBase->getAlignment());
5678
5679     if (LDBase->hasAnyUseOfValue(1)) {
5680       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5681                                      SDValue(LDBase, 1),
5682                                      SDValue(NewLd.getNode(), 1));
5683       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5684       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5685                              SDValue(NewLd.getNode(), 1));
5686     }
5687
5688     return NewLd;
5689   }
5690   if (NumElems == 4 && LastLoadedElt == 1 &&
5691       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5692     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5693     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5694     SDValue ResNode =
5695         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5696                                 LDBase->getPointerInfo(),
5697                                 LDBase->getAlignment(),
5698                                 false/*isVolatile*/, true/*ReadMem*/,
5699                                 false/*WriteMem*/);
5700
5701     // Make sure the newly-created LOAD is in the same position as LDBase in
5702     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5703     // update uses of LDBase's output chain to use the TokenFactor.
5704     if (LDBase->hasAnyUseOfValue(1)) {
5705       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5706                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5707       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5708       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5709                              SDValue(ResNode.getNode(), 1));
5710     }
5711
5712     return DAG.getNode(ISD::BITCAST, DL, VT, ResNode);
5713   }
5714   return SDValue();
5715 }
5716
5717 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5718 /// to generate a splat value for the following cases:
5719 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5720 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5721 /// a scalar load, or a constant.
5722 /// The VBROADCAST node is returned when a pattern is found,
5723 /// or SDValue() otherwise.
5724 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5725                                     SelectionDAG &DAG) {
5726   if (!Subtarget->hasFp256())
5727     return SDValue();
5728
5729   MVT VT = Op.getSimpleValueType();
5730   SDLoc dl(Op);
5731
5732   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5733          "Unsupported vector type for broadcast.");
5734
5735   SDValue Ld;
5736   bool ConstSplatVal;
5737
5738   switch (Op.getOpcode()) {
5739     default:
5740       // Unknown pattern found.
5741       return SDValue();
5742
5743     case ISD::BUILD_VECTOR: {
5744       // The BUILD_VECTOR node must be a splat.
5745       if (!isSplatVector(Op.getNode()))
5746         return SDValue();
5747
5748       Ld = Op.getOperand(0);
5749       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5750                      Ld.getOpcode() == ISD::ConstantFP);
5751
5752       // The suspected load node has several users. Make sure that all
5753       // of its users are from the BUILD_VECTOR node.
5754       // Constants may have multiple users.
5755       if (!ConstSplatVal && !Ld->hasNUsesOfValue(VT.getVectorNumElements(), 0))
5756         return SDValue();
5757       break;
5758     }
5759
5760     case ISD::VECTOR_SHUFFLE: {
5761       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5762
5763       // Shuffles must have a splat mask where the first element is
5764       // broadcasted.
5765       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5766         return SDValue();
5767
5768       SDValue Sc = Op.getOperand(0);
5769       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5770           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5771
5772         if (!Subtarget->hasInt256())
5773           return SDValue();
5774
5775         // Use the register form of the broadcast instruction available on AVX2.
5776         if (VT.getSizeInBits() >= 256)
5777           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5778         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5779       }
5780
5781       Ld = Sc.getOperand(0);
5782       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5783                        Ld.getOpcode() == ISD::ConstantFP);
5784
5785       // The scalar_to_vector node and the suspected
5786       // load node must have exactly one user.
5787       // Constants may have multiple users.
5788
5789       // AVX-512 has register version of the broadcast
5790       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5791         Ld.getValueType().getSizeInBits() >= 32;
5792       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5793           !hasRegVer))
5794         return SDValue();
5795       break;
5796     }
5797   }
5798
5799   bool IsGE256 = (VT.getSizeInBits() >= 256);
5800
5801   // Handle the broadcasting a single constant scalar from the constant pool
5802   // into a vector. On Sandybridge it is still better to load a constant vector
5803   // from the constant pool and not to broadcast it from a scalar.
5804   if (ConstSplatVal && Subtarget->hasInt256()) {
5805     EVT CVT = Ld.getValueType();
5806     assert(!CVT.isVector() && "Must not broadcast a vector type");
5807     unsigned ScalarSize = CVT.getSizeInBits();
5808
5809     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)) {
5810       const Constant *C = nullptr;
5811       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5812         C = CI->getConstantIntValue();
5813       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5814         C = CF->getConstantFPValue();
5815
5816       assert(C && "Invalid constant type");
5817
5818       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5819       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5820       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5821       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5822                        MachinePointerInfo::getConstantPool(),
5823                        false, false, false, Alignment);
5824
5825       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5826     }
5827   }
5828
5829   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5830   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5831
5832   // Handle AVX2 in-register broadcasts.
5833   if (!IsLoad && Subtarget->hasInt256() &&
5834       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5835     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5836
5837   // The scalar source must be a normal load.
5838   if (!IsLoad)
5839     return SDValue();
5840
5841   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64))
5842     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5843
5844   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5845   // double since there is no vbroadcastsd xmm
5846   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5847     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5848       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5849   }
5850
5851   // Unsupported broadcast.
5852   return SDValue();
5853 }
5854
5855 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5856 /// underlying vector and index.
5857 ///
5858 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5859 /// index.
5860 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5861                                          SDValue ExtIdx) {
5862   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5863   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5864     return Idx;
5865
5866   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5867   // lowered this:
5868   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5869   // to:
5870   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5871   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5872   //                           undef)
5873   //                       Constant<0>)
5874   // In this case the vector is the extract_subvector expression and the index
5875   // is 2, as specified by the shuffle.
5876   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5877   SDValue ShuffleVec = SVOp->getOperand(0);
5878   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5879   assert(ShuffleVecVT.getVectorElementType() ==
5880          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5881
5882   int ShuffleIdx = SVOp->getMaskElt(Idx);
5883   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5884     ExtractedFromVec = ShuffleVec;
5885     return ShuffleIdx;
5886   }
5887   return Idx;
5888 }
5889
5890 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5891   MVT VT = Op.getSimpleValueType();
5892
5893   // Skip if insert_vec_elt is not supported.
5894   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5895   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5896     return SDValue();
5897
5898   SDLoc DL(Op);
5899   unsigned NumElems = Op.getNumOperands();
5900
5901   SDValue VecIn1;
5902   SDValue VecIn2;
5903   SmallVector<unsigned, 4> InsertIndices;
5904   SmallVector<int, 8> Mask(NumElems, -1);
5905
5906   for (unsigned i = 0; i != NumElems; ++i) {
5907     unsigned Opc = Op.getOperand(i).getOpcode();
5908
5909     if (Opc == ISD::UNDEF)
5910       continue;
5911
5912     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5913       // Quit if more than 1 elements need inserting.
5914       if (InsertIndices.size() > 1)
5915         return SDValue();
5916
5917       InsertIndices.push_back(i);
5918       continue;
5919     }
5920
5921     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5922     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5923     // Quit if non-constant index.
5924     if (!isa<ConstantSDNode>(ExtIdx))
5925       return SDValue();
5926     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5927
5928     // Quit if extracted from vector of different type.
5929     if (ExtractedFromVec.getValueType() != VT)
5930       return SDValue();
5931
5932     if (!VecIn1.getNode())
5933       VecIn1 = ExtractedFromVec;
5934     else if (VecIn1 != ExtractedFromVec) {
5935       if (!VecIn2.getNode())
5936         VecIn2 = ExtractedFromVec;
5937       else if (VecIn2 != ExtractedFromVec)
5938         // Quit if more than 2 vectors to shuffle
5939         return SDValue();
5940     }
5941
5942     if (ExtractedFromVec == VecIn1)
5943       Mask[i] = Idx;
5944     else if (ExtractedFromVec == VecIn2)
5945       Mask[i] = Idx + NumElems;
5946   }
5947
5948   if (!VecIn1.getNode())
5949     return SDValue();
5950
5951   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5952   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5953   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5954     unsigned Idx = InsertIndices[i];
5955     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5956                      DAG.getIntPtrConstant(Idx));
5957   }
5958
5959   return NV;
5960 }
5961
5962 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5963 SDValue
5964 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5965
5966   MVT VT = Op.getSimpleValueType();
5967   assert((VT.getVectorElementType() == MVT::i1) && (VT.getSizeInBits() <= 16) &&
5968          "Unexpected type in LowerBUILD_VECTORvXi1!");
5969
5970   SDLoc dl(Op);
5971   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5972     SDValue Cst = DAG.getTargetConstant(0, MVT::i1);
5973     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5974     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5975   }
5976
5977   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5978     SDValue Cst = DAG.getTargetConstant(1, MVT::i1);
5979     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5980     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5981   }
5982
5983   bool AllContants = true;
5984   uint64_t Immediate = 0;
5985   int NonConstIdx = -1;
5986   bool IsSplat = true;
5987   unsigned NumNonConsts = 0;
5988   unsigned NumConsts = 0;
5989   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5990     SDValue In = Op.getOperand(idx);
5991     if (In.getOpcode() == ISD::UNDEF)
5992       continue;
5993     if (!isa<ConstantSDNode>(In)) {
5994       AllContants = false;
5995       NonConstIdx = idx;
5996       NumNonConsts++;
5997     }
5998     else {
5999       NumConsts++;
6000       if (cast<ConstantSDNode>(In)->getZExtValue())
6001       Immediate |= (1ULL << idx);
6002     }
6003     if (In != Op.getOperand(0))
6004       IsSplat = false;
6005   }
6006
6007   if (AllContants) {
6008     SDValue FullMask = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1,
6009       DAG.getConstant(Immediate, MVT::i16));
6010     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, FullMask,
6011                        DAG.getIntPtrConstant(0));
6012   }
6013
6014   if (NumNonConsts == 1 && NonConstIdx != 0) {
6015     SDValue DstVec;
6016     if (NumConsts) {
6017       SDValue VecAsImm = DAG.getConstant(Immediate,
6018                                          MVT::getIntegerVT(VT.getSizeInBits()));
6019       DstVec = DAG.getNode(ISD::BITCAST, dl, VT, VecAsImm);
6020     }
6021     else 
6022       DstVec = DAG.getUNDEF(VT);
6023     return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
6024                        Op.getOperand(NonConstIdx),
6025                        DAG.getIntPtrConstant(NonConstIdx));
6026   }
6027   if (!IsSplat && (NonConstIdx != 0))
6028     llvm_unreachable("Unsupported BUILD_VECTOR operation");
6029   MVT SelectVT = (VT == MVT::v16i1)? MVT::i16 : MVT::i8;
6030   SDValue Select;
6031   if (IsSplat)
6032     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6033                           DAG.getConstant(-1, SelectVT),
6034                           DAG.getConstant(0, SelectVT));
6035   else
6036     Select = DAG.getNode(ISD::SELECT, dl, SelectVT, Op.getOperand(0),
6037                          DAG.getConstant((Immediate | 1), SelectVT),
6038                          DAG.getConstant(Immediate, SelectVT));
6039   return DAG.getNode(ISD::BITCAST, dl, VT, Select);
6040 }
6041
6042 SDValue
6043 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
6044   SDLoc dl(Op);
6045
6046   MVT VT = Op.getSimpleValueType();
6047   MVT ExtVT = VT.getVectorElementType();
6048   unsigned NumElems = Op.getNumOperands();
6049
6050   // Generate vectors for predicate vectors.
6051   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
6052     return LowerBUILD_VECTORvXi1(Op, DAG);
6053
6054   // Vectors containing all zeros can be matched by pxor and xorps later
6055   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
6056     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
6057     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
6058     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
6059       return Op;
6060
6061     return getZeroVector(VT, Subtarget, DAG, dl);
6062   }
6063
6064   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
6065   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
6066   // vpcmpeqd on 256-bit vectors.
6067   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
6068     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
6069       return Op;
6070
6071     if (!VT.is512BitVector())
6072       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
6073   }
6074
6075   SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
6076   if (Broadcast.getNode())
6077     return Broadcast;
6078
6079   unsigned EVTBits = ExtVT.getSizeInBits();
6080
6081   unsigned NumZero  = 0;
6082   unsigned NumNonZero = 0;
6083   unsigned NonZeros = 0;
6084   bool IsAllConstants = true;
6085   SmallSet<SDValue, 8> Values;
6086   for (unsigned i = 0; i < NumElems; ++i) {
6087     SDValue Elt = Op.getOperand(i);
6088     if (Elt.getOpcode() == ISD::UNDEF)
6089       continue;
6090     Values.insert(Elt);
6091     if (Elt.getOpcode() != ISD::Constant &&
6092         Elt.getOpcode() != ISD::ConstantFP)
6093       IsAllConstants = false;
6094     if (X86::isZeroNode(Elt))
6095       NumZero++;
6096     else {
6097       NonZeros |= (1 << i);
6098       NumNonZero++;
6099     }
6100   }
6101
6102   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
6103   if (NumNonZero == 0)
6104     return DAG.getUNDEF(VT);
6105
6106   // Special case for single non-zero, non-undef, element.
6107   if (NumNonZero == 1) {
6108     unsigned Idx = countTrailingZeros(NonZeros);
6109     SDValue Item = Op.getOperand(Idx);
6110
6111     // If this is an insertion of an i64 value on x86-32, and if the top bits of
6112     // the value are obviously zero, truncate the value to i32 and do the
6113     // insertion that way.  Only do this if the value is non-constant or if the
6114     // value is a constant being inserted into element 0.  It is cheaper to do
6115     // a constant pool load than it is to do a movd + shuffle.
6116     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
6117         (!IsAllConstants || Idx == 0)) {
6118       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
6119         // Handle SSE only.
6120         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
6121         EVT VecVT = MVT::v4i32;
6122         unsigned VecElts = 4;
6123
6124         // Truncate the value (which may itself be a constant) to i32, and
6125         // convert it to a vector with movd (S2V+shuffle to zero extend).
6126         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
6127         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
6128         Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6129
6130         // Now we have our 32-bit value zero extended in the low element of
6131         // a vector.  If Idx != 0, swizzle it into place.
6132         if (Idx != 0) {
6133           SmallVector<int, 4> Mask;
6134           Mask.push_back(Idx);
6135           for (unsigned i = 1; i != VecElts; ++i)
6136             Mask.push_back(i);
6137           Item = DAG.getVectorShuffle(VecVT, dl, Item, DAG.getUNDEF(VecVT),
6138                                       &Mask[0]);
6139         }
6140         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6141       }
6142     }
6143
6144     // If we have a constant or non-constant insertion into the low element of
6145     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
6146     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
6147     // depending on what the source datatype is.
6148     if (Idx == 0) {
6149       if (NumZero == 0)
6150         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6151
6152       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
6153           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
6154         if (VT.is256BitVector() || VT.is512BitVector()) {
6155           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
6156           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
6157                              Item, DAG.getIntPtrConstant(0));
6158         }
6159         assert(VT.is128BitVector() && "Expected an SSE value type!");
6160         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6161         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6162         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6163       }
6164
6165       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6166         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6167         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6168         if (VT.is256BitVector()) {
6169           SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6170           Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6171         } else {
6172           assert(VT.is128BitVector() && "Expected an SSE value type!");
6173           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6174         }
6175         return DAG.getNode(ISD::BITCAST, dl, VT, Item);
6176       }
6177     }
6178
6179     // Is it a vector logical left shift?
6180     if (NumElems == 2 && Idx == 1 &&
6181         X86::isZeroNode(Op.getOperand(0)) &&
6182         !X86::isZeroNode(Op.getOperand(1))) {
6183       unsigned NumBits = VT.getSizeInBits();
6184       return getVShift(true, VT,
6185                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6186                                    VT, Op.getOperand(1)),
6187                        NumBits/2, DAG, *this, dl);
6188     }
6189
6190     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6191       return SDValue();
6192
6193     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6194     // is a non-constant being inserted into an element other than the low one,
6195     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6196     // movd/movss) to move this into the low element, then shuffle it into
6197     // place.
6198     if (EVTBits == 32) {
6199       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6200
6201       // Turn it into a shuffle of zero and zero-extended scalar to vector.
6202       Item = getShuffleVectorZeroOrUndef(Item, 0, NumZero > 0, Subtarget, DAG);
6203       SmallVector<int, 8> MaskVec;
6204       for (unsigned i = 0; i != NumElems; ++i)
6205         MaskVec.push_back(i == Idx ? 0 : 1);
6206       return DAG.getVectorShuffle(VT, dl, Item, DAG.getUNDEF(VT), &MaskVec[0]);
6207     }
6208   }
6209
6210   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6211   if (Values.size() == 1) {
6212     if (EVTBits == 32) {
6213       // Instead of a shuffle like this:
6214       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6215       // Check if it's possible to issue this instead.
6216       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6217       unsigned Idx = countTrailingZeros(NonZeros);
6218       SDValue Item = Op.getOperand(Idx);
6219       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6220         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6221     }
6222     return SDValue();
6223   }
6224
6225   // A vector full of immediates; various special cases are already
6226   // handled, so this is best done with a single constant-pool load.
6227   if (IsAllConstants)
6228     return SDValue();
6229
6230   // For AVX-length vectors, build the individual 128-bit pieces and use
6231   // shuffles to put them in place.
6232   if (VT.is256BitVector() || VT.is512BitVector()) {
6233     SmallVector<SDValue, 64> V;
6234     for (unsigned i = 0; i != NumElems; ++i)
6235       V.push_back(Op.getOperand(i));
6236
6237     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6238
6239     // Build both the lower and upper subvector.
6240     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6241                                 makeArrayRef(&V[0], NumElems/2));
6242     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6243                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6244
6245     // Recreate the wider vector with the lower and upper part.
6246     if (VT.is256BitVector())
6247       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6248     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6249   }
6250
6251   // Let legalizer expand 2-wide build_vectors.
6252   if (EVTBits == 64) {
6253     if (NumNonZero == 1) {
6254       // One half is zero or undef.
6255       unsigned Idx = countTrailingZeros(NonZeros);
6256       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6257                                  Op.getOperand(Idx));
6258       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6259     }
6260     return SDValue();
6261   }
6262
6263   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6264   if (EVTBits == 8 && NumElems == 16) {
6265     SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6266                                         Subtarget, *this);
6267     if (V.getNode()) return V;
6268   }
6269
6270   if (EVTBits == 16 && NumElems == 8) {
6271     SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6272                                       Subtarget, *this);
6273     if (V.getNode()) return V;
6274   }
6275
6276   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6277   if (EVTBits == 32 && NumElems == 4) {
6278     SDValue V = LowerBuildVectorv4x32(Op, NumElems, NonZeros, NumNonZero,
6279                                       NumZero, DAG, Subtarget, *this);
6280     if (V.getNode())
6281       return V;
6282   }
6283
6284   // If element VT is == 32 bits, turn it into a number of shuffles.
6285   SmallVector<SDValue, 8> V(NumElems);
6286   if (NumElems == 4 && NumZero > 0) {
6287     for (unsigned i = 0; i < 4; ++i) {
6288       bool isZero = !(NonZeros & (1 << i));
6289       if (isZero)
6290         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6291       else
6292         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6293     }
6294
6295     for (unsigned i = 0; i < 2; ++i) {
6296       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6297         default: break;
6298         case 0:
6299           V[i] = V[i*2];  // Must be a zero vector.
6300           break;
6301         case 1:
6302           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6303           break;
6304         case 2:
6305           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6306           break;
6307         case 3:
6308           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6309           break;
6310       }
6311     }
6312
6313     bool Reverse1 = (NonZeros & 0x3) == 2;
6314     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6315     int MaskVec[] = {
6316       Reverse1 ? 1 : 0,
6317       Reverse1 ? 0 : 1,
6318       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6319       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6320     };
6321     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6322   }
6323
6324   if (Values.size() > 1 && VT.is128BitVector()) {
6325     // Check for a build vector of consecutive loads.
6326     for (unsigned i = 0; i < NumElems; ++i)
6327       V[i] = Op.getOperand(i);
6328
6329     // Check for elements which are consecutive loads.
6330     SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false);
6331     if (LD.getNode())
6332       return LD;
6333
6334     // Check for a build vector from mostly shuffle plus few inserting.
6335     SDValue Sh = buildFromShuffleMostly(Op, DAG);
6336     if (Sh.getNode())
6337       return Sh;
6338
6339     // For SSE 4.1, use insertps to put the high elements into the low element.
6340     if (getSubtarget()->hasSSE41()) {
6341       SDValue Result;
6342       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6343         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6344       else
6345         Result = DAG.getUNDEF(VT);
6346
6347       for (unsigned i = 1; i < NumElems; ++i) {
6348         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6349         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6350                              Op.getOperand(i), DAG.getIntPtrConstant(i));
6351       }
6352       return Result;
6353     }
6354
6355     // Otherwise, expand into a number of unpckl*, start by extending each of
6356     // our (non-undef) elements to the full vector width with the element in the
6357     // bottom slot of the vector (which generates no code for SSE).
6358     for (unsigned i = 0; i < NumElems; ++i) {
6359       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6360         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6361       else
6362         V[i] = DAG.getUNDEF(VT);
6363     }
6364
6365     // Next, we iteratively mix elements, e.g. for v4f32:
6366     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6367     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6368     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6369     unsigned EltStride = NumElems >> 1;
6370     while (EltStride != 0) {
6371       for (unsigned i = 0; i < EltStride; ++i) {
6372         // If V[i+EltStride] is undef and this is the first round of mixing,
6373         // then it is safe to just drop this shuffle: V[i] is already in the
6374         // right place, the one element (since it's the first round) being
6375         // inserted as undef can be dropped.  This isn't safe for successive
6376         // rounds because they will permute elements within both vectors.
6377         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6378             EltStride == NumElems/2)
6379           continue;
6380
6381         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6382       }
6383       EltStride >>= 1;
6384     }
6385     return V[0];
6386   }
6387   return SDValue();
6388 }
6389
6390 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6391 // to create 256-bit vectors from two other 128-bit ones.
6392 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6393   SDLoc dl(Op);
6394   MVT ResVT = Op.getSimpleValueType();
6395
6396   assert((ResVT.is256BitVector() ||
6397           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6398
6399   SDValue V1 = Op.getOperand(0);
6400   SDValue V2 = Op.getOperand(1);
6401   unsigned NumElems = ResVT.getVectorNumElements();
6402   if(ResVT.is256BitVector())
6403     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6404
6405   if (Op.getNumOperands() == 4) {
6406     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6407                                 ResVT.getVectorNumElements()/2);
6408     SDValue V3 = Op.getOperand(2);
6409     SDValue V4 = Op.getOperand(3);
6410     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6411       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6412   }
6413   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6414 }
6415
6416 static SDValue LowerCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6417   MVT LLVM_ATTRIBUTE_UNUSED VT = Op.getSimpleValueType();
6418   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6419          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6420           Op.getNumOperands() == 4)));
6421
6422   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6423   // from two other 128-bit ones.
6424
6425   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6426   return LowerAVXCONCAT_VECTORS(Op, DAG);
6427 }
6428
6429 static bool isBlendMask(ArrayRef<int> MaskVals, MVT VT, bool hasSSE41,
6430                         bool hasInt256, unsigned *MaskOut = nullptr) {
6431   MVT EltVT = VT.getVectorElementType();
6432
6433   // There is no blend with immediate in AVX-512.
6434   if (VT.is512BitVector())
6435     return false;
6436
6437   if (!hasSSE41 || EltVT == MVT::i8)
6438     return false;
6439   if (!hasInt256 && VT == MVT::v16i16)
6440     return false;
6441
6442   unsigned MaskValue = 0;
6443   unsigned NumElems = VT.getVectorNumElements();
6444   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
6445   unsigned NumLanes = (NumElems - 1) / 8 + 1;
6446   unsigned NumElemsInLane = NumElems / NumLanes;
6447
6448   // Blend for v16i16 should be symetric for the both lanes.
6449   for (unsigned i = 0; i < NumElemsInLane; ++i) {
6450
6451     int SndLaneEltIdx = (NumLanes == 2) ? MaskVals[i + NumElemsInLane] : -1;
6452     int EltIdx = MaskVals[i];
6453
6454     if ((EltIdx < 0 || EltIdx == (int)i) &&
6455         (SndLaneEltIdx < 0 || SndLaneEltIdx == (int)(i + NumElemsInLane)))
6456       continue;
6457
6458     if (((unsigned)EltIdx == (i + NumElems)) &&
6459         (SndLaneEltIdx < 0 ||
6460          (unsigned)SndLaneEltIdx == i + NumElems + NumElemsInLane))
6461       MaskValue |= (1 << i);
6462     else
6463       return false;
6464   }
6465
6466   if (MaskOut)
6467     *MaskOut = MaskValue;
6468   return true;
6469 }
6470
6471 // Try to lower a shuffle node into a simple blend instruction.
6472 // This function assumes isBlendMask returns true for this
6473 // SuffleVectorSDNode
6474 static SDValue LowerVECTOR_SHUFFLEtoBlend(ShuffleVectorSDNode *SVOp,
6475                                           unsigned MaskValue,
6476                                           const X86Subtarget *Subtarget,
6477                                           SelectionDAG &DAG) {
6478   MVT VT = SVOp->getSimpleValueType(0);
6479   MVT EltVT = VT.getVectorElementType();
6480   assert(isBlendMask(SVOp->getMask(), VT, Subtarget->hasSSE41(),
6481                      Subtarget->hasInt256() && "Trying to lower a "
6482                                                "VECTOR_SHUFFLE to a Blend but "
6483                                                "with the wrong mask"));
6484   SDValue V1 = SVOp->getOperand(0);
6485   SDValue V2 = SVOp->getOperand(1);
6486   SDLoc dl(SVOp);
6487   unsigned NumElems = VT.getVectorNumElements();
6488
6489   // Convert i32 vectors to floating point if it is not AVX2.
6490   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
6491   MVT BlendVT = VT;
6492   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
6493     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
6494                                NumElems);
6495     V1 = DAG.getNode(ISD::BITCAST, dl, VT, V1);
6496     V2 = DAG.getNode(ISD::BITCAST, dl, VT, V2);
6497   }
6498
6499   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, V1, V2,
6500                             DAG.getConstant(MaskValue, MVT::i32));
6501   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
6502 }
6503
6504 /// In vector type \p VT, return true if the element at index \p InputIdx
6505 /// falls on a different 128-bit lane than \p OutputIdx.
6506 static bool ShuffleCrosses128bitLane(MVT VT, unsigned InputIdx,
6507                                      unsigned OutputIdx) {
6508   unsigned EltSize = VT.getVectorElementType().getSizeInBits();
6509   return InputIdx * EltSize / 128 != OutputIdx * EltSize / 128;
6510 }
6511
6512 /// Generate a PSHUFB if possible.  Selects elements from \p V1 according to
6513 /// \p MaskVals.  MaskVals[OutputIdx] = InputIdx specifies that we want to
6514 /// shuffle the element at InputIdx in V1 to OutputIdx in the result.  If \p
6515 /// MaskVals refers to elements outside of \p V1 or is undef (-1), insert a
6516 /// zero.
6517 static SDValue getPSHUFB(ArrayRef<int> MaskVals, SDValue V1, SDLoc &dl,
6518                          SelectionDAG &DAG) {
6519   MVT VT = V1.getSimpleValueType();
6520   assert(VT.is128BitVector() || VT.is256BitVector());
6521
6522   MVT EltVT = VT.getVectorElementType();
6523   unsigned EltSizeInBytes = EltVT.getSizeInBits() / 8;
6524   unsigned NumElts = VT.getVectorNumElements();
6525
6526   SmallVector<SDValue, 32> PshufbMask;
6527   for (unsigned OutputIdx = 0; OutputIdx < NumElts; ++OutputIdx) {
6528     int InputIdx = MaskVals[OutputIdx];
6529     unsigned InputByteIdx;
6530
6531     if (InputIdx < 0 || NumElts <= (unsigned)InputIdx)
6532       InputByteIdx = 0x80;
6533     else {
6534       // Cross lane is not allowed.
6535       if (ShuffleCrosses128bitLane(VT, InputIdx, OutputIdx))
6536         return SDValue();
6537       InputByteIdx = InputIdx * EltSizeInBytes;
6538       // Index is an byte offset within the 128-bit lane.
6539       InputByteIdx &= 0xf;
6540     }
6541
6542     for (unsigned j = 0; j < EltSizeInBytes; ++j) {
6543       PshufbMask.push_back(DAG.getConstant(InputByteIdx, MVT::i8));
6544       if (InputByteIdx != 0x80)
6545         ++InputByteIdx;
6546     }
6547   }
6548
6549   MVT ShufVT = MVT::getVectorVT(MVT::i8, PshufbMask.size());
6550   if (ShufVT != VT)
6551     V1 = DAG.getNode(ISD::BITCAST, dl, ShufVT, V1);
6552   return DAG.getNode(X86ISD::PSHUFB, dl, ShufVT, V1,
6553                      DAG.getNode(ISD::BUILD_VECTOR, dl, ShufVT, PshufbMask));
6554 }
6555
6556 // v8i16 shuffles - Prefer shuffles in the following order:
6557 // 1. [all]   pshuflw, pshufhw, optional move
6558 // 2. [ssse3] 1 x pshufb
6559 // 3. [ssse3] 2 x pshufb + 1 x por
6560 // 4. [all]   mov + pshuflw + pshufhw + N x (pextrw + pinsrw)
6561 static SDValue
6562 LowerVECTOR_SHUFFLEv8i16(SDValue Op, const X86Subtarget *Subtarget,
6563                          SelectionDAG &DAG) {
6564   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6565   SDValue V1 = SVOp->getOperand(0);
6566   SDValue V2 = SVOp->getOperand(1);
6567   SDLoc dl(SVOp);
6568   SmallVector<int, 8> MaskVals;
6569
6570   // Determine if more than 1 of the words in each of the low and high quadwords
6571   // of the result come from the same quadword of one of the two inputs.  Undef
6572   // mask values count as coming from any quadword, for better codegen.
6573   //
6574   // Lo/HiQuad[i] = j indicates how many words from the ith quad of the input
6575   // feeds this quad.  For i, 0 and 1 refer to V1, 2 and 3 refer to V2.
6576   unsigned LoQuad[] = { 0, 0, 0, 0 };
6577   unsigned HiQuad[] = { 0, 0, 0, 0 };
6578   // Indices of quads used.
6579   std::bitset<4> InputQuads;
6580   for (unsigned i = 0; i < 8; ++i) {
6581     unsigned *Quad = i < 4 ? LoQuad : HiQuad;
6582     int EltIdx = SVOp->getMaskElt(i);
6583     MaskVals.push_back(EltIdx);
6584     if (EltIdx < 0) {
6585       ++Quad[0];
6586       ++Quad[1];
6587       ++Quad[2];
6588       ++Quad[3];
6589       continue;
6590     }
6591     ++Quad[EltIdx / 4];
6592     InputQuads.set(EltIdx / 4);
6593   }
6594
6595   int BestLoQuad = -1;
6596   unsigned MaxQuad = 1;
6597   for (unsigned i = 0; i < 4; ++i) {
6598     if (LoQuad[i] > MaxQuad) {
6599       BestLoQuad = i;
6600       MaxQuad = LoQuad[i];
6601     }
6602   }
6603
6604   int BestHiQuad = -1;
6605   MaxQuad = 1;
6606   for (unsigned i = 0; i < 4; ++i) {
6607     if (HiQuad[i] > MaxQuad) {
6608       BestHiQuad = i;
6609       MaxQuad = HiQuad[i];
6610     }
6611   }
6612
6613   // For SSSE3, If all 8 words of the result come from only 1 quadword of each
6614   // of the two input vectors, shuffle them into one input vector so only a
6615   // single pshufb instruction is necessary. If there are more than 2 input
6616   // quads, disable the next transformation since it does not help SSSE3.
6617   bool V1Used = InputQuads[0] || InputQuads[1];
6618   bool V2Used = InputQuads[2] || InputQuads[3];
6619   if (Subtarget->hasSSSE3()) {
6620     if (InputQuads.count() == 2 && V1Used && V2Used) {
6621       BestLoQuad = InputQuads[0] ? 0 : 1;
6622       BestHiQuad = InputQuads[2] ? 2 : 3;
6623     }
6624     if (InputQuads.count() > 2) {
6625       BestLoQuad = -1;
6626       BestHiQuad = -1;
6627     }
6628   }
6629
6630   // If BestLoQuad or BestHiQuad are set, shuffle the quads together and update
6631   // the shuffle mask.  If a quad is scored as -1, that means that it contains
6632   // words from all 4 input quadwords.
6633   SDValue NewV;
6634   if (BestLoQuad >= 0 || BestHiQuad >= 0) {
6635     int MaskV[] = {
6636       BestLoQuad < 0 ? 0 : BestLoQuad,
6637       BestHiQuad < 0 ? 1 : BestHiQuad
6638     };
6639     NewV = DAG.getVectorShuffle(MVT::v2i64, dl,
6640                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V1),
6641                   DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, V2), &MaskV[0]);
6642     NewV = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, NewV);
6643
6644     // Rewrite the MaskVals and assign NewV to V1 if NewV now contains all the
6645     // source words for the shuffle, to aid later transformations.
6646     bool AllWordsInNewV = true;
6647     bool InOrder[2] = { true, true };
6648     for (unsigned i = 0; i != 8; ++i) {
6649       int idx = MaskVals[i];
6650       if (idx != (int)i)
6651         InOrder[i/4] = false;
6652       if (idx < 0 || (idx/4) == BestLoQuad || (idx/4) == BestHiQuad)
6653         continue;
6654       AllWordsInNewV = false;
6655       break;
6656     }
6657
6658     bool pshuflw = AllWordsInNewV, pshufhw = AllWordsInNewV;
6659     if (AllWordsInNewV) {
6660       for (int i = 0; i != 8; ++i) {
6661         int idx = MaskVals[i];
6662         if (idx < 0)
6663           continue;
6664         idx = MaskVals[i] = (idx / 4) == BestLoQuad ? (idx & 3) : (idx & 3) + 4;
6665         if ((idx != i) && idx < 4)
6666           pshufhw = false;
6667         if ((idx != i) && idx > 3)
6668           pshuflw = false;
6669       }
6670       V1 = NewV;
6671       V2Used = false;
6672       BestLoQuad = 0;
6673       BestHiQuad = 1;
6674     }
6675
6676     // If we've eliminated the use of V2, and the new mask is a pshuflw or
6677     // pshufhw, that's as cheap as it gets.  Return the new shuffle.
6678     if ((pshufhw && InOrder[0]) || (pshuflw && InOrder[1])) {
6679       unsigned Opc = pshufhw ? X86ISD::PSHUFHW : X86ISD::PSHUFLW;
6680       unsigned TargetMask = 0;
6681       NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV,
6682                                   DAG.getUNDEF(MVT::v8i16), &MaskVals[0]);
6683       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6684       TargetMask = pshufhw ? getShufflePSHUFHWImmediate(SVOp):
6685                              getShufflePSHUFLWImmediate(SVOp);
6686       V1 = NewV.getOperand(0);
6687       return getTargetShuffleNode(Opc, dl, MVT::v8i16, V1, TargetMask, DAG);
6688     }
6689   }
6690
6691   // Promote splats to a larger type which usually leads to more efficient code.
6692   // FIXME: Is this true if pshufb is available?
6693   if (SVOp->isSplat())
6694     return PromoteSplat(SVOp, DAG);
6695
6696   // If we have SSSE3, and all words of the result are from 1 input vector,
6697   // case 2 is generated, otherwise case 3 is generated.  If no SSSE3
6698   // is present, fall back to case 4.
6699   if (Subtarget->hasSSSE3()) {
6700     SmallVector<SDValue,16> pshufbMask;
6701
6702     // If we have elements from both input vectors, set the high bit of the
6703     // shuffle mask element to zero out elements that come from V2 in the V1
6704     // mask, and elements that come from V1 in the V2 mask, so that the two
6705     // results can be OR'd together.
6706     bool TwoInputs = V1Used && V2Used;
6707     V1 = getPSHUFB(MaskVals, V1, dl, DAG);
6708     if (!TwoInputs)
6709       return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6710
6711     // Calculate the shuffle mask for the second input, shuffle it, and
6712     // OR it with the first shuffled input.
6713     CommuteVectorShuffleMask(MaskVals, 8);
6714     V2 = getPSHUFB(MaskVals, V2, dl, DAG);
6715     V1 = DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6716     return DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6717   }
6718
6719   // If BestLoQuad >= 0, generate a pshuflw to put the low elements in order,
6720   // and update MaskVals with new element order.
6721   std::bitset<8> InOrder;
6722   if (BestLoQuad >= 0) {
6723     int MaskV[] = { -1, -1, -1, -1, 4, 5, 6, 7 };
6724     for (int i = 0; i != 4; ++i) {
6725       int idx = MaskVals[i];
6726       if (idx < 0) {
6727         InOrder.set(i);
6728       } else if ((idx / 4) == BestLoQuad) {
6729         MaskV[i] = idx & 3;
6730         InOrder.set(i);
6731       }
6732     }
6733     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6734                                 &MaskV[0]);
6735
6736     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6737       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6738       NewV = getTargetShuffleNode(X86ISD::PSHUFLW, dl, MVT::v8i16,
6739                                   NewV.getOperand(0),
6740                                   getShufflePSHUFLWImmediate(SVOp), DAG);
6741     }
6742   }
6743
6744   // If BestHi >= 0, generate a pshufhw to put the high elements in order,
6745   // and update MaskVals with the new element order.
6746   if (BestHiQuad >= 0) {
6747     int MaskV[] = { 0, 1, 2, 3, -1, -1, -1, -1 };
6748     for (unsigned i = 4; i != 8; ++i) {
6749       int idx = MaskVals[i];
6750       if (idx < 0) {
6751         InOrder.set(i);
6752       } else if ((idx / 4) == BestHiQuad) {
6753         MaskV[i] = (idx & 3) + 4;
6754         InOrder.set(i);
6755       }
6756     }
6757     NewV = DAG.getVectorShuffle(MVT::v8i16, dl, NewV, DAG.getUNDEF(MVT::v8i16),
6758                                 &MaskV[0]);
6759
6760     if (NewV.getOpcode() == ISD::VECTOR_SHUFFLE && Subtarget->hasSSE2()) {
6761       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(NewV.getNode());
6762       NewV = getTargetShuffleNode(X86ISD::PSHUFHW, dl, MVT::v8i16,
6763                                   NewV.getOperand(0),
6764                                   getShufflePSHUFHWImmediate(SVOp), DAG);
6765     }
6766   }
6767
6768   // In case BestHi & BestLo were both -1, which means each quadword has a word
6769   // from each of the four input quadwords, calculate the InOrder bitvector now
6770   // before falling through to the insert/extract cleanup.
6771   if (BestLoQuad == -1 && BestHiQuad == -1) {
6772     NewV = V1;
6773     for (int i = 0; i != 8; ++i)
6774       if (MaskVals[i] < 0 || MaskVals[i] == i)
6775         InOrder.set(i);
6776   }
6777
6778   // The other elements are put in the right place using pextrw and pinsrw.
6779   for (unsigned i = 0; i != 8; ++i) {
6780     if (InOrder[i])
6781       continue;
6782     int EltIdx = MaskVals[i];
6783     if (EltIdx < 0)
6784       continue;
6785     SDValue ExtOp = (EltIdx < 8) ?
6786       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V1,
6787                   DAG.getIntPtrConstant(EltIdx)) :
6788       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, V2,
6789                   DAG.getIntPtrConstant(EltIdx - 8));
6790     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, ExtOp,
6791                        DAG.getIntPtrConstant(i));
6792   }
6793   return NewV;
6794 }
6795
6796 /// \brief v16i16 shuffles
6797 ///
6798 /// FIXME: We only support generation of a single pshufb currently.  We can
6799 /// generalize the other applicable cases from LowerVECTOR_SHUFFLEv8i16 as
6800 /// well (e.g 2 x pshufb + 1 x por).
6801 static SDValue
6802 LowerVECTOR_SHUFFLEv16i16(SDValue Op, SelectionDAG &DAG) {
6803   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
6804   SDValue V1 = SVOp->getOperand(0);
6805   SDValue V2 = SVOp->getOperand(1);
6806   SDLoc dl(SVOp);
6807
6808   if (V2.getOpcode() != ISD::UNDEF)
6809     return SDValue();
6810
6811   SmallVector<int, 16> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6812   return getPSHUFB(MaskVals, V1, dl, DAG);
6813 }
6814
6815 // v16i8 shuffles - Prefer shuffles in the following order:
6816 // 1. [ssse3] 1 x pshufb
6817 // 2. [ssse3] 2 x pshufb + 1 x por
6818 // 3. [all]   v8i16 shuffle + N x pextrw + rotate + pinsrw
6819 static SDValue LowerVECTOR_SHUFFLEv16i8(ShuffleVectorSDNode *SVOp,
6820                                         const X86Subtarget* Subtarget,
6821                                         SelectionDAG &DAG) {
6822   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6823   SDValue V1 = SVOp->getOperand(0);
6824   SDValue V2 = SVOp->getOperand(1);
6825   SDLoc dl(SVOp);
6826   ArrayRef<int> MaskVals = SVOp->getMask();
6827
6828   // Promote splats to a larger type which usually leads to more efficient code.
6829   // FIXME: Is this true if pshufb is available?
6830   if (SVOp->isSplat())
6831     return PromoteSplat(SVOp, DAG);
6832
6833   // If we have SSSE3, case 1 is generated when all result bytes come from
6834   // one of  the inputs.  Otherwise, case 2 is generated.  If no SSSE3 is
6835   // present, fall back to case 3.
6836
6837   // If SSSE3, use 1 pshufb instruction per vector with elements in the result.
6838   if (Subtarget->hasSSSE3()) {
6839     SmallVector<SDValue,16> pshufbMask;
6840
6841     // If all result elements are from one input vector, then only translate
6842     // undef mask values to 0x80 (zero out result) in the pshufb mask.
6843     //
6844     // Otherwise, we have elements from both input vectors, and must zero out
6845     // elements that come from V2 in the first mask, and V1 in the second mask
6846     // so that we can OR them together.
6847     for (unsigned i = 0; i != 16; ++i) {
6848       int EltIdx = MaskVals[i];
6849       if (EltIdx < 0 || EltIdx >= 16)
6850         EltIdx = 0x80;
6851       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6852     }
6853     V1 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V1,
6854                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6855                                  MVT::v16i8, pshufbMask));
6856
6857     // As PSHUFB will zero elements with negative indices, it's safe to ignore
6858     // the 2nd operand if it's undefined or zero.
6859     if (V2.getOpcode() == ISD::UNDEF ||
6860         ISD::isBuildVectorAllZeros(V2.getNode()))
6861       return V1;
6862
6863     // Calculate the shuffle mask for the second input, shuffle it, and
6864     // OR it with the first shuffled input.
6865     pshufbMask.clear();
6866     for (unsigned i = 0; i != 16; ++i) {
6867       int EltIdx = MaskVals[i];
6868       EltIdx = (EltIdx < 16) ? 0x80 : EltIdx - 16;
6869       pshufbMask.push_back(DAG.getConstant(EltIdx, MVT::i8));
6870     }
6871     V2 = DAG.getNode(X86ISD::PSHUFB, dl, MVT::v16i8, V2,
6872                      DAG.getNode(ISD::BUILD_VECTOR, dl,
6873                                  MVT::v16i8, pshufbMask));
6874     return DAG.getNode(ISD::OR, dl, MVT::v16i8, V1, V2);
6875   }
6876
6877   // No SSSE3 - Calculate in place words and then fix all out of place words
6878   // With 0-16 extracts & inserts.  Worst case is 16 bytes out of order from
6879   // the 16 different words that comprise the two doublequadword input vectors.
6880   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V1);
6881   V2 = DAG.getNode(ISD::BITCAST, dl, MVT::v8i16, V2);
6882   SDValue NewV = V1;
6883   for (int i = 0; i != 8; ++i) {
6884     int Elt0 = MaskVals[i*2];
6885     int Elt1 = MaskVals[i*2+1];
6886
6887     // This word of the result is all undef, skip it.
6888     if (Elt0 < 0 && Elt1 < 0)
6889       continue;
6890
6891     // This word of the result is already in the correct place, skip it.
6892     if ((Elt0 == i*2) && (Elt1 == i*2+1))
6893       continue;
6894
6895     SDValue Elt0Src = Elt0 < 16 ? V1 : V2;
6896     SDValue Elt1Src = Elt1 < 16 ? V1 : V2;
6897     SDValue InsElt;
6898
6899     // If Elt0 and Elt1 are defined, are consecutive, and can be load
6900     // using a single extract together, load it and store it.
6901     if ((Elt0 >= 0) && ((Elt0 + 1) == Elt1) && ((Elt0 & 1) == 0)) {
6902       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6903                            DAG.getIntPtrConstant(Elt1 / 2));
6904       NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6905                         DAG.getIntPtrConstant(i));
6906       continue;
6907     }
6908
6909     // If Elt1 is defined, extract it from the appropriate source.  If the
6910     // source byte is not also odd, shift the extracted word left 8 bits
6911     // otherwise clear the bottom 8 bits if we need to do an or.
6912     if (Elt1 >= 0) {
6913       InsElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16, Elt1Src,
6914                            DAG.getIntPtrConstant(Elt1 / 2));
6915       if ((Elt1 & 1) == 0)
6916         InsElt = DAG.getNode(ISD::SHL, dl, MVT::i16, InsElt,
6917                              DAG.getConstant(8,
6918                                   TLI.getShiftAmountTy(InsElt.getValueType())));
6919       else if (Elt0 >= 0)
6920         InsElt = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt,
6921                              DAG.getConstant(0xFF00, MVT::i16));
6922     }
6923     // If Elt0 is defined, extract it from the appropriate source.  If the
6924     // source byte is not also even, shift the extracted word right 8 bits. If
6925     // Elt1 was also defined, OR the extracted values together before
6926     // inserting them in the result.
6927     if (Elt0 >= 0) {
6928       SDValue InsElt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i16,
6929                                     Elt0Src, DAG.getIntPtrConstant(Elt0 / 2));
6930       if ((Elt0 & 1) != 0)
6931         InsElt0 = DAG.getNode(ISD::SRL, dl, MVT::i16, InsElt0,
6932                               DAG.getConstant(8,
6933                                  TLI.getShiftAmountTy(InsElt0.getValueType())));
6934       else if (Elt1 >= 0)
6935         InsElt0 = DAG.getNode(ISD::AND, dl, MVT::i16, InsElt0,
6936                              DAG.getConstant(0x00FF, MVT::i16));
6937       InsElt = Elt1 >= 0 ? DAG.getNode(ISD::OR, dl, MVT::i16, InsElt, InsElt0)
6938                          : InsElt0;
6939     }
6940     NewV = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, NewV, InsElt,
6941                        DAG.getIntPtrConstant(i));
6942   }
6943   return DAG.getNode(ISD::BITCAST, dl, MVT::v16i8, NewV);
6944 }
6945
6946 // v32i8 shuffles - Translate to VPSHUFB if possible.
6947 static
6948 SDValue LowerVECTOR_SHUFFLEv32i8(ShuffleVectorSDNode *SVOp,
6949                                  const X86Subtarget *Subtarget,
6950                                  SelectionDAG &DAG) {
6951   MVT VT = SVOp->getSimpleValueType(0);
6952   SDValue V1 = SVOp->getOperand(0);
6953   SDValue V2 = SVOp->getOperand(1);
6954   SDLoc dl(SVOp);
6955   SmallVector<int, 32> MaskVals(SVOp->getMask().begin(), SVOp->getMask().end());
6956
6957   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
6958   bool V1IsAllZero = ISD::isBuildVectorAllZeros(V1.getNode());
6959   bool V2IsAllZero = ISD::isBuildVectorAllZeros(V2.getNode());
6960
6961   // VPSHUFB may be generated if
6962   // (1) one of input vector is undefined or zeroinitializer.
6963   // The mask value 0x80 puts 0 in the corresponding slot of the vector.
6964   // And (2) the mask indexes don't cross the 128-bit lane.
6965   if (VT != MVT::v32i8 || !Subtarget->hasInt256() ||
6966       (!V2IsUndef && !V2IsAllZero && !V1IsAllZero))
6967     return SDValue();
6968
6969   if (V1IsAllZero && !V2IsAllZero) {
6970     CommuteVectorShuffleMask(MaskVals, 32);
6971     V1 = V2;
6972   }
6973   return getPSHUFB(MaskVals, V1, dl, DAG);
6974 }
6975
6976 /// RewriteAsNarrowerShuffle - Try rewriting v8i16 and v16i8 shuffles as 4 wide
6977 /// ones, or rewriting v4i32 / v4f32 as 2 wide ones if possible. This can be
6978 /// done when every pair / quad of shuffle mask elements point to elements in
6979 /// the right sequence. e.g.
6980 /// vector_shuffle X, Y, <2, 3, | 10, 11, | 0, 1, | 14, 15>
6981 static
6982 SDValue RewriteAsNarrowerShuffle(ShuffleVectorSDNode *SVOp,
6983                                  SelectionDAG &DAG) {
6984   MVT VT = SVOp->getSimpleValueType(0);
6985   SDLoc dl(SVOp);
6986   unsigned NumElems = VT.getVectorNumElements();
6987   MVT NewVT;
6988   unsigned Scale;
6989   switch (VT.SimpleTy) {
6990   default: llvm_unreachable("Unexpected!");
6991   case MVT::v2i64:
6992   case MVT::v2f64:
6993            return SDValue(SVOp, 0);
6994   case MVT::v4f32:  NewVT = MVT::v2f64; Scale = 2; break;
6995   case MVT::v4i32:  NewVT = MVT::v2i64; Scale = 2; break;
6996   case MVT::v8i16:  NewVT = MVT::v4i32; Scale = 2; break;
6997   case MVT::v16i8:  NewVT = MVT::v4i32; Scale = 4; break;
6998   case MVT::v16i16: NewVT = MVT::v8i32; Scale = 2; break;
6999   case MVT::v32i8:  NewVT = MVT::v8i32; Scale = 4; break;
7000   }
7001
7002   SmallVector<int, 8> MaskVec;
7003   for (unsigned i = 0; i != NumElems; i += Scale) {
7004     int StartIdx = -1;
7005     for (unsigned j = 0; j != Scale; ++j) {
7006       int EltIdx = SVOp->getMaskElt(i+j);
7007       if (EltIdx < 0)
7008         continue;
7009       if (StartIdx < 0)
7010         StartIdx = (EltIdx / Scale);
7011       if (EltIdx != (int)(StartIdx*Scale + j))
7012         return SDValue();
7013     }
7014     MaskVec.push_back(StartIdx);
7015   }
7016
7017   SDValue V1 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(0));
7018   SDValue V2 = DAG.getNode(ISD::BITCAST, dl, NewVT, SVOp->getOperand(1));
7019   return DAG.getVectorShuffle(NewVT, dl, V1, V2, &MaskVec[0]);
7020 }
7021
7022 /// getVZextMovL - Return a zero-extending vector move low node.
7023 ///
7024 static SDValue getVZextMovL(MVT VT, MVT OpVT,
7025                             SDValue SrcOp, SelectionDAG &DAG,
7026                             const X86Subtarget *Subtarget, SDLoc dl) {
7027   if (VT == MVT::v2f64 || VT == MVT::v4f32) {
7028     LoadSDNode *LD = nullptr;
7029     if (!isScalarLoadToVector(SrcOp.getNode(), &LD))
7030       LD = dyn_cast<LoadSDNode>(SrcOp);
7031     if (!LD) {
7032       // movssrr and movsdrr do not clear top bits. Try to use movd, movq
7033       // instead.
7034       MVT ExtVT = (OpVT == MVT::v2f64) ? MVT::i64 : MVT::i32;
7035       if ((ExtVT != MVT::i64 || Subtarget->is64Bit()) &&
7036           SrcOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
7037           SrcOp.getOperand(0).getOpcode() == ISD::BITCAST &&
7038           SrcOp.getOperand(0).getOperand(0).getValueType() == ExtVT) {
7039         // PR2108
7040         OpVT = (OpVT == MVT::v2f64) ? MVT::v2i64 : MVT::v4i32;
7041         return DAG.getNode(ISD::BITCAST, dl, VT,
7042                            DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7043                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
7044                                                    OpVT,
7045                                                    SrcOp.getOperand(0)
7046                                                           .getOperand(0))));
7047       }
7048     }
7049   }
7050
7051   return DAG.getNode(ISD::BITCAST, dl, VT,
7052                      DAG.getNode(X86ISD::VZEXT_MOVL, dl, OpVT,
7053                                  DAG.getNode(ISD::BITCAST, dl,
7054                                              OpVT, SrcOp)));
7055 }
7056
7057 /// LowerVECTOR_SHUFFLE_256 - Handle all 256-bit wide vectors shuffles
7058 /// which could not be matched by any known target speficic shuffle
7059 static SDValue
7060 LowerVECTOR_SHUFFLE_256(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7061
7062   SDValue NewOp = Compact8x32ShuffleNode(SVOp, DAG);
7063   if (NewOp.getNode())
7064     return NewOp;
7065
7066   MVT VT = SVOp->getSimpleValueType(0);
7067
7068   unsigned NumElems = VT.getVectorNumElements();
7069   unsigned NumLaneElems = NumElems / 2;
7070
7071   SDLoc dl(SVOp);
7072   MVT EltVT = VT.getVectorElementType();
7073   MVT NVT = MVT::getVectorVT(EltVT, NumLaneElems);
7074   SDValue Output[2];
7075
7076   SmallVector<int, 16> Mask;
7077   for (unsigned l = 0; l < 2; ++l) {
7078     // Build a shuffle mask for the output, discovering on the fly which
7079     // input vectors to use as shuffle operands (recorded in InputUsed).
7080     // If building a suitable shuffle vector proves too hard, then bail
7081     // out with UseBuildVector set.
7082     bool UseBuildVector = false;
7083     int InputUsed[2] = { -1, -1 }; // Not yet discovered.
7084     unsigned LaneStart = l * NumLaneElems;
7085     for (unsigned i = 0; i != NumLaneElems; ++i) {
7086       // The mask element.  This indexes into the input.
7087       int Idx = SVOp->getMaskElt(i+LaneStart);
7088       if (Idx < 0) {
7089         // the mask element does not index into any input vector.
7090         Mask.push_back(-1);
7091         continue;
7092       }
7093
7094       // The input vector this mask element indexes into.
7095       int Input = Idx / NumLaneElems;
7096
7097       // Turn the index into an offset from the start of the input vector.
7098       Idx -= Input * NumLaneElems;
7099
7100       // Find or create a shuffle vector operand to hold this input.
7101       unsigned OpNo;
7102       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
7103         if (InputUsed[OpNo] == Input)
7104           // This input vector is already an operand.
7105           break;
7106         if (InputUsed[OpNo] < 0) {
7107           // Create a new operand for this input vector.
7108           InputUsed[OpNo] = Input;
7109           break;
7110         }
7111       }
7112
7113       if (OpNo >= array_lengthof(InputUsed)) {
7114         // More than two input vectors used!  Give up on trying to create a
7115         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
7116         UseBuildVector = true;
7117         break;
7118       }
7119
7120       // Add the mask index for the new shuffle vector.
7121       Mask.push_back(Idx + OpNo * NumLaneElems);
7122     }
7123
7124     if (UseBuildVector) {
7125       SmallVector<SDValue, 16> SVOps;
7126       for (unsigned i = 0; i != NumLaneElems; ++i) {
7127         // The mask element.  This indexes into the input.
7128         int Idx = SVOp->getMaskElt(i+LaneStart);
7129         if (Idx < 0) {
7130           SVOps.push_back(DAG.getUNDEF(EltVT));
7131           continue;
7132         }
7133
7134         // The input vector this mask element indexes into.
7135         int Input = Idx / NumElems;
7136
7137         // Turn the index into an offset from the start of the input vector.
7138         Idx -= Input * NumElems;
7139
7140         // Extract the vector element by hand.
7141         SVOps.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
7142                                     SVOp->getOperand(Input),
7143                                     DAG.getIntPtrConstant(Idx)));
7144       }
7145
7146       // Construct the output using a BUILD_VECTOR.
7147       Output[l] = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, SVOps);
7148     } else if (InputUsed[0] < 0) {
7149       // No input vectors were used! The result is undefined.
7150       Output[l] = DAG.getUNDEF(NVT);
7151     } else {
7152       SDValue Op0 = Extract128BitVector(SVOp->getOperand(InputUsed[0] / 2),
7153                                         (InputUsed[0] % 2) * NumLaneElems,
7154                                         DAG, dl);
7155       // If only one input was used, use an undefined vector for the other.
7156       SDValue Op1 = (InputUsed[1] < 0) ? DAG.getUNDEF(NVT) :
7157         Extract128BitVector(SVOp->getOperand(InputUsed[1] / 2),
7158                             (InputUsed[1] % 2) * NumLaneElems, DAG, dl);
7159       // At least one input vector was used. Create a new shuffle vector.
7160       Output[l] = DAG.getVectorShuffle(NVT, dl, Op0, Op1, &Mask[0]);
7161     }
7162
7163     Mask.clear();
7164   }
7165
7166   // Concatenate the result back
7167   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, Output[0], Output[1]);
7168 }
7169
7170 /// LowerVECTOR_SHUFFLE_128v4 - Handle all 128-bit wide vectors with
7171 /// 4 elements, and match them with several different shuffle types.
7172 static SDValue
7173 LowerVECTOR_SHUFFLE_128v4(ShuffleVectorSDNode *SVOp, SelectionDAG &DAG) {
7174   SDValue V1 = SVOp->getOperand(0);
7175   SDValue V2 = SVOp->getOperand(1);
7176   SDLoc dl(SVOp);
7177   MVT VT = SVOp->getSimpleValueType(0);
7178
7179   assert(VT.is128BitVector() && "Unsupported vector size");
7180
7181   std::pair<int, int> Locs[4];
7182   int Mask1[] = { -1, -1, -1, -1 };
7183   SmallVector<int, 8> PermMask(SVOp->getMask().begin(), SVOp->getMask().end());
7184
7185   unsigned NumHi = 0;
7186   unsigned NumLo = 0;
7187   for (unsigned i = 0; i != 4; ++i) {
7188     int Idx = PermMask[i];
7189     if (Idx < 0) {
7190       Locs[i] = std::make_pair(-1, -1);
7191     } else {
7192       assert(Idx < 8 && "Invalid VECTOR_SHUFFLE index!");
7193       if (Idx < 4) {
7194         Locs[i] = std::make_pair(0, NumLo);
7195         Mask1[NumLo] = Idx;
7196         NumLo++;
7197       } else {
7198         Locs[i] = std::make_pair(1, NumHi);
7199         if (2+NumHi < 4)
7200           Mask1[2+NumHi] = Idx;
7201         NumHi++;
7202       }
7203     }
7204   }
7205
7206   if (NumLo <= 2 && NumHi <= 2) {
7207     // If no more than two elements come from either vector. This can be
7208     // implemented with two shuffles. First shuffle gather the elements.
7209     // The second shuffle, which takes the first shuffle as both of its
7210     // vector operands, put the elements into the right order.
7211     V1 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7212
7213     int Mask2[] = { -1, -1, -1, -1 };
7214
7215     for (unsigned i = 0; i != 4; ++i)
7216       if (Locs[i].first != -1) {
7217         unsigned Idx = (i < 2) ? 0 : 4;
7218         Idx += Locs[i].first * 2 + Locs[i].second;
7219         Mask2[i] = Idx;
7220       }
7221
7222     return DAG.getVectorShuffle(VT, dl, V1, V1, &Mask2[0]);
7223   }
7224
7225   if (NumLo == 3 || NumHi == 3) {
7226     // Otherwise, we must have three elements from one vector, call it X, and
7227     // one element from the other, call it Y.  First, use a shufps to build an
7228     // intermediate vector with the one element from Y and the element from X
7229     // that will be in the same half in the final destination (the indexes don't
7230     // matter). Then, use a shufps to build the final vector, taking the half
7231     // containing the element from Y from the intermediate, and the other half
7232     // from X.
7233     if (NumHi == 3) {
7234       // Normalize it so the 3 elements come from V1.
7235       CommuteVectorShuffleMask(PermMask, 4);
7236       std::swap(V1, V2);
7237     }
7238
7239     // Find the element from V2.
7240     unsigned HiIndex;
7241     for (HiIndex = 0; HiIndex < 3; ++HiIndex) {
7242       int Val = PermMask[HiIndex];
7243       if (Val < 0)
7244         continue;
7245       if (Val >= 4)
7246         break;
7247     }
7248
7249     Mask1[0] = PermMask[HiIndex];
7250     Mask1[1] = -1;
7251     Mask1[2] = PermMask[HiIndex^1];
7252     Mask1[3] = -1;
7253     V2 = DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7254
7255     if (HiIndex >= 2) {
7256       Mask1[0] = PermMask[0];
7257       Mask1[1] = PermMask[1];
7258       Mask1[2] = HiIndex & 1 ? 6 : 4;
7259       Mask1[3] = HiIndex & 1 ? 4 : 6;
7260       return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask1[0]);
7261     }
7262
7263     Mask1[0] = HiIndex & 1 ? 2 : 0;
7264     Mask1[1] = HiIndex & 1 ? 0 : 2;
7265     Mask1[2] = PermMask[2];
7266     Mask1[3] = PermMask[3];
7267     if (Mask1[2] >= 0)
7268       Mask1[2] += 4;
7269     if (Mask1[3] >= 0)
7270       Mask1[3] += 4;
7271     return DAG.getVectorShuffle(VT, dl, V2, V1, &Mask1[0]);
7272   }
7273
7274   // Break it into (shuffle shuffle_hi, shuffle_lo).
7275   int LoMask[] = { -1, -1, -1, -1 };
7276   int HiMask[] = { -1, -1, -1, -1 };
7277
7278   int *MaskPtr = LoMask;
7279   unsigned MaskIdx = 0;
7280   unsigned LoIdx = 0;
7281   unsigned HiIdx = 2;
7282   for (unsigned i = 0; i != 4; ++i) {
7283     if (i == 2) {
7284       MaskPtr = HiMask;
7285       MaskIdx = 1;
7286       LoIdx = 0;
7287       HiIdx = 2;
7288     }
7289     int Idx = PermMask[i];
7290     if (Idx < 0) {
7291       Locs[i] = std::make_pair(-1, -1);
7292     } else if (Idx < 4) {
7293       Locs[i] = std::make_pair(MaskIdx, LoIdx);
7294       MaskPtr[LoIdx] = Idx;
7295       LoIdx++;
7296     } else {
7297       Locs[i] = std::make_pair(MaskIdx, HiIdx);
7298       MaskPtr[HiIdx] = Idx;
7299       HiIdx++;
7300     }
7301   }
7302
7303   SDValue LoShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &LoMask[0]);
7304   SDValue HiShuffle = DAG.getVectorShuffle(VT, dl, V1, V2, &HiMask[0]);
7305   int MaskOps[] = { -1, -1, -1, -1 };
7306   for (unsigned i = 0; i != 4; ++i)
7307     if (Locs[i].first != -1)
7308       MaskOps[i] = Locs[i].first * 4 + Locs[i].second;
7309   return DAG.getVectorShuffle(VT, dl, LoShuffle, HiShuffle, &MaskOps[0]);
7310 }
7311
7312 static bool MayFoldVectorLoad(SDValue V) {
7313   while (V.hasOneUse() && V.getOpcode() == ISD::BITCAST)
7314     V = V.getOperand(0);
7315
7316   if (V.hasOneUse() && V.getOpcode() == ISD::SCALAR_TO_VECTOR)
7317     V = V.getOperand(0);
7318   if (V.hasOneUse() && V.getOpcode() == ISD::BUILD_VECTOR &&
7319       V.getNumOperands() == 2 && V.getOperand(1).getOpcode() == ISD::UNDEF)
7320     // BUILD_VECTOR (load), undef
7321     V = V.getOperand(0);
7322
7323   return MayFoldLoad(V);
7324 }
7325
7326 static
7327 SDValue getMOVDDup(SDValue &Op, SDLoc &dl, SDValue V1, SelectionDAG &DAG) {
7328   MVT VT = Op.getSimpleValueType();
7329
7330   // Canonizalize to v2f64.
7331   V1 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, V1);
7332   return DAG.getNode(ISD::BITCAST, dl, VT,
7333                      getTargetShuffleNode(X86ISD::MOVDDUP, dl, MVT::v2f64,
7334                                           V1, DAG));
7335 }
7336
7337 static
7338 SDValue getMOVLowToHigh(SDValue &Op, SDLoc &dl, SelectionDAG &DAG,
7339                         bool HasSSE2) {
7340   SDValue V1 = Op.getOperand(0);
7341   SDValue V2 = Op.getOperand(1);
7342   MVT VT = Op.getSimpleValueType();
7343
7344   assert(VT != MVT::v2i64 && "unsupported shuffle type");
7345
7346   if (HasSSE2 && VT == MVT::v2f64)
7347     return getTargetShuffleNode(X86ISD::MOVLHPD, dl, VT, V1, V2, DAG);
7348
7349   // v4f32 or v4i32: canonizalized to v4f32 (which is legal for SSE1)
7350   return DAG.getNode(ISD::BITCAST, dl, VT,
7351                      getTargetShuffleNode(X86ISD::MOVLHPS, dl, MVT::v4f32,
7352                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V1),
7353                            DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, V2), DAG));
7354 }
7355
7356 static
7357 SDValue getMOVHighToLow(SDValue &Op, SDLoc &dl, SelectionDAG &DAG) {
7358   SDValue V1 = Op.getOperand(0);
7359   SDValue V2 = Op.getOperand(1);
7360   MVT VT = Op.getSimpleValueType();
7361
7362   assert((VT == MVT::v4i32 || VT == MVT::v4f32) &&
7363          "unsupported shuffle type");
7364
7365   if (V2.getOpcode() == ISD::UNDEF)
7366     V2 = V1;
7367
7368   // v4i32 or v4f32
7369   return getTargetShuffleNode(X86ISD::MOVHLPS, dl, VT, V1, V2, DAG);
7370 }
7371
7372 static
7373 SDValue getMOVLP(SDValue &Op, SDLoc &dl, SelectionDAG &DAG, bool HasSSE2) {
7374   SDValue V1 = Op.getOperand(0);
7375   SDValue V2 = Op.getOperand(1);
7376   MVT VT = Op.getSimpleValueType();
7377   unsigned NumElems = VT.getVectorNumElements();
7378
7379   // Use MOVLPS and MOVLPD in case V1 or V2 are loads. During isel, the second
7380   // operand of these instructions is only memory, so check if there's a
7381   // potencial load folding here, otherwise use SHUFPS or MOVSD to match the
7382   // same masks.
7383   bool CanFoldLoad = false;
7384
7385   // Trivial case, when V2 comes from a load.
7386   if (MayFoldVectorLoad(V2))
7387     CanFoldLoad = true;
7388
7389   // When V1 is a load, it can be folded later into a store in isel, example:
7390   //  (store (v4f32 (X86Movlps (load addr:$src1), VR128:$src2)), addr:$src1)
7391   //    turns into:
7392   //  (MOVLPSmr addr:$src1, VR128:$src2)
7393   // So, recognize this potential and also use MOVLPS or MOVLPD
7394   else if (MayFoldVectorLoad(V1) && MayFoldIntoStore(Op))
7395     CanFoldLoad = true;
7396
7397   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7398   if (CanFoldLoad) {
7399     if (HasSSE2 && NumElems == 2)
7400       return getTargetShuffleNode(X86ISD::MOVLPD, dl, VT, V1, V2, DAG);
7401
7402     if (NumElems == 4)
7403       // If we don't care about the second element, proceed to use movss.
7404       if (SVOp->getMaskElt(1) != -1)
7405         return getTargetShuffleNode(X86ISD::MOVLPS, dl, VT, V1, V2, DAG);
7406   }
7407
7408   // movl and movlp will both match v2i64, but v2i64 is never matched by
7409   // movl earlier because we make it strict to avoid messing with the movlp load
7410   // folding logic (see the code above getMOVLP call). Match it here then,
7411   // this is horrible, but will stay like this until we move all shuffle
7412   // matching to x86 specific nodes. Note that for the 1st condition all
7413   // types are matched with movsd.
7414   if (HasSSE2) {
7415     // FIXME: isMOVLMask should be checked and matched before getMOVLP,
7416     // as to remove this logic from here, as much as possible
7417     if (NumElems == 2 || !isMOVLMask(SVOp->getMask(), VT))
7418       return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7419     return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7420   }
7421
7422   assert(VT != MVT::v4i32 && "unsupported shuffle type");
7423
7424   // Invert the operand order and use SHUFPS to match it.
7425   return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V2, V1,
7426                               getShuffleSHUFImmediate(SVOp), DAG);
7427 }
7428
7429 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
7430                                          SelectionDAG &DAG) {
7431   SDLoc dl(Load);
7432   MVT VT = Load->getSimpleValueType(0);
7433   MVT EVT = VT.getVectorElementType();
7434   SDValue Addr = Load->getOperand(1);
7435   SDValue NewAddr = DAG.getNode(
7436       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
7437       DAG.getConstant(Index * EVT.getStoreSize(), Addr.getSimpleValueType()));
7438
7439   SDValue NewLoad =
7440       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
7441                   DAG.getMachineFunction().getMachineMemOperand(
7442                       Load->getMemOperand(), 0, EVT.getStoreSize()));
7443   return NewLoad;
7444 }
7445
7446 // It is only safe to call this function if isINSERTPSMask is true for
7447 // this shufflevector mask.
7448 static SDValue getINSERTPS(ShuffleVectorSDNode *SVOp, SDLoc &dl,
7449                            SelectionDAG &DAG) {
7450   // Generate an insertps instruction when inserting an f32 from memory onto a
7451   // v4f32 or when copying a member from one v4f32 to another.
7452   // We also use it for transferring i32 from one register to another,
7453   // since it simply copies the same bits.
7454   // If we're transferring an i32 from memory to a specific element in a
7455   // register, we output a generic DAG that will match the PINSRD
7456   // instruction.
7457   MVT VT = SVOp->getSimpleValueType(0);
7458   MVT EVT = VT.getVectorElementType();
7459   SDValue V1 = SVOp->getOperand(0);
7460   SDValue V2 = SVOp->getOperand(1);
7461   auto Mask = SVOp->getMask();
7462   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
7463          "unsupported vector type for insertps/pinsrd");
7464
7465   int FromV1 = std::count_if(Mask.begin(), Mask.end(),
7466                              [](const int &i) { return i < 4; });
7467
7468   SDValue From;
7469   SDValue To;
7470   unsigned DestIndex;
7471   if (FromV1 == 1) {
7472     From = V1;
7473     To = V2;
7474     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7475                              [](const int &i) { return i < 4; }) -
7476                 Mask.begin();
7477   } else {
7478     From = V2;
7479     To = V1;
7480     DestIndex = std::find_if(Mask.begin(), Mask.end(),
7481                              [](const int &i) { return i >= 4; }) -
7482                 Mask.begin();
7483   }
7484
7485   if (MayFoldLoad(From)) {
7486     // Trivial case, when From comes from a load and is only used by the
7487     // shuffle. Make it use insertps from the vector that we need from that
7488     // load.
7489     SDValue NewLoad =
7490         NarrowVectorLoadToElement(cast<LoadSDNode>(From), DestIndex, DAG);
7491     if (!NewLoad.getNode())
7492       return SDValue();
7493
7494     if (EVT == MVT::f32) {
7495       // Create this as a scalar to vector to match the instruction pattern.
7496       SDValue LoadScalarToVector =
7497           DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, NewLoad);
7498       SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4);
7499       return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, LoadScalarToVector,
7500                          InsertpsMask);
7501     } else { // EVT == MVT::i32
7502       // If we're getting an i32 from memory, use an INSERT_VECTOR_ELT
7503       // instruction, to match the PINSRD instruction, which loads an i32 to a
7504       // certain vector element.
7505       return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, To, NewLoad,
7506                          DAG.getConstant(DestIndex, MVT::i32));
7507     }
7508   }
7509
7510   // Vector-element-to-vector
7511   unsigned SrcIndex = Mask[DestIndex] % 4;
7512   SDValue InsertpsMask = DAG.getIntPtrConstant(DestIndex << 4 | SrcIndex << 6);
7513   return DAG.getNode(X86ISD::INSERTPS, dl, VT, To, From, InsertpsMask);
7514 }
7515
7516 // Reduce a vector shuffle to zext.
7517 static SDValue LowerVectorIntExtend(SDValue Op, const X86Subtarget *Subtarget,
7518                                     SelectionDAG &DAG) {
7519   // PMOVZX is only available from SSE41.
7520   if (!Subtarget->hasSSE41())
7521     return SDValue();
7522
7523   MVT VT = Op.getSimpleValueType();
7524
7525   // Only AVX2 support 256-bit vector integer extending.
7526   if (!Subtarget->hasInt256() && VT.is256BitVector())
7527     return SDValue();
7528
7529   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7530   SDLoc DL(Op);
7531   SDValue V1 = Op.getOperand(0);
7532   SDValue V2 = Op.getOperand(1);
7533   unsigned NumElems = VT.getVectorNumElements();
7534
7535   // Extending is an unary operation and the element type of the source vector
7536   // won't be equal to or larger than i64.
7537   if (V2.getOpcode() != ISD::UNDEF || !VT.isInteger() ||
7538       VT.getVectorElementType() == MVT::i64)
7539     return SDValue();
7540
7541   // Find the expansion ratio, e.g. expanding from i8 to i32 has a ratio of 4.
7542   unsigned Shift = 1; // Start from 2, i.e. 1 << 1.
7543   while ((1U << Shift) < NumElems) {
7544     if (SVOp->getMaskElt(1U << Shift) == 1)
7545       break;
7546     Shift += 1;
7547     // The maximal ratio is 8, i.e. from i8 to i64.
7548     if (Shift > 3)
7549       return SDValue();
7550   }
7551
7552   // Check the shuffle mask.
7553   unsigned Mask = (1U << Shift) - 1;
7554   for (unsigned i = 0; i != NumElems; ++i) {
7555     int EltIdx = SVOp->getMaskElt(i);
7556     if ((i & Mask) != 0 && EltIdx != -1)
7557       return SDValue();
7558     if ((i & Mask) == 0 && (unsigned)EltIdx != (i >> Shift))
7559       return SDValue();
7560   }
7561
7562   unsigned NBits = VT.getVectorElementType().getSizeInBits() << Shift;
7563   MVT NeVT = MVT::getIntegerVT(NBits);
7564   MVT NVT = MVT::getVectorVT(NeVT, NumElems >> Shift);
7565
7566   if (!DAG.getTargetLoweringInfo().isTypeLegal(NVT))
7567     return SDValue();
7568
7569   // Simplify the operand as it's prepared to be fed into shuffle.
7570   unsigned SignificantBits = NVT.getSizeInBits() >> Shift;
7571   if (V1.getOpcode() == ISD::BITCAST &&
7572       V1.getOperand(0).getOpcode() == ISD::SCALAR_TO_VECTOR &&
7573       V1.getOperand(0).getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
7574       V1.getOperand(0).getOperand(0)
7575         .getSimpleValueType().getSizeInBits() == SignificantBits) {
7576     // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
7577     SDValue V = V1.getOperand(0).getOperand(0).getOperand(0);
7578     ConstantSDNode *CIdx =
7579       dyn_cast<ConstantSDNode>(V1.getOperand(0).getOperand(0).getOperand(1));
7580     // If it's foldable, i.e. normal load with single use, we will let code
7581     // selection to fold it. Otherwise, we will short the conversion sequence.
7582     if (CIdx && CIdx->getZExtValue() == 0 &&
7583         (!ISD::isNormalLoad(V.getNode()) || !V.hasOneUse())) {
7584       MVT FullVT = V.getSimpleValueType();
7585       MVT V1VT = V1.getSimpleValueType();
7586       if (FullVT.getSizeInBits() > V1VT.getSizeInBits()) {
7587         // The "ext_vec_elt" node is wider than the result node.
7588         // In this case we should extract subvector from V.
7589         // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast (extract_subvector x)).
7590         unsigned Ratio = FullVT.getSizeInBits() / V1VT.getSizeInBits();
7591         MVT SubVecVT = MVT::getVectorVT(FullVT.getVectorElementType(),
7592                                         FullVT.getVectorNumElements()/Ratio);
7593         V = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, V,
7594                         DAG.getIntPtrConstant(0));
7595       }
7596       V1 = DAG.getNode(ISD::BITCAST, DL, V1VT, V);
7597     }
7598   }
7599
7600   return DAG.getNode(ISD::BITCAST, DL, VT,
7601                      DAG.getNode(X86ISD::VZEXT, DL, NVT, V1));
7602 }
7603
7604 static SDValue NormalizeVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
7605                                       SelectionDAG &DAG) {
7606   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7607   MVT VT = Op.getSimpleValueType();
7608   SDLoc dl(Op);
7609   SDValue V1 = Op.getOperand(0);
7610   SDValue V2 = Op.getOperand(1);
7611
7612   if (isZeroShuffle(SVOp))
7613     return getZeroVector(VT, Subtarget, DAG, dl);
7614
7615   // Handle splat operations
7616   if (SVOp->isSplat()) {
7617     // Use vbroadcast whenever the splat comes from a foldable load
7618     SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG);
7619     if (Broadcast.getNode())
7620       return Broadcast;
7621   }
7622
7623   // Check integer expanding shuffles.
7624   SDValue NewOp = LowerVectorIntExtend(Op, Subtarget, DAG);
7625   if (NewOp.getNode())
7626     return NewOp;
7627
7628   // If the shuffle can be profitably rewritten as a narrower shuffle, then
7629   // do it!
7630   if (VT == MVT::v8i16 || VT == MVT::v16i8 || VT == MVT::v16i16 ||
7631       VT == MVT::v32i8) {
7632     SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7633     if (NewOp.getNode())
7634       return DAG.getNode(ISD::BITCAST, dl, VT, NewOp);
7635   } else if (VT.is128BitVector() && Subtarget->hasSSE2()) {
7636     // FIXME: Figure out a cleaner way to do this.
7637     if (ISD::isBuildVectorAllZeros(V2.getNode())) {
7638       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7639       if (NewOp.getNode()) {
7640         MVT NewVT = NewOp.getSimpleValueType();
7641         if (isCommutedMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(),
7642                                NewVT, true, false))
7643           return getVZextMovL(VT, NewVT, NewOp.getOperand(0), DAG, Subtarget,
7644                               dl);
7645       }
7646     } else if (ISD::isBuildVectorAllZeros(V1.getNode())) {
7647       SDValue NewOp = RewriteAsNarrowerShuffle(SVOp, DAG);
7648       if (NewOp.getNode()) {
7649         MVT NewVT = NewOp.getSimpleValueType();
7650         if (isMOVLMask(cast<ShuffleVectorSDNode>(NewOp)->getMask(), NewVT))
7651           return getVZextMovL(VT, NewVT, NewOp.getOperand(1), DAG, Subtarget,
7652                               dl);
7653       }
7654     }
7655   }
7656   return SDValue();
7657 }
7658
7659 SDValue
7660 X86TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG) const {
7661   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7662   SDValue V1 = Op.getOperand(0);
7663   SDValue V2 = Op.getOperand(1);
7664   MVT VT = Op.getSimpleValueType();
7665   SDLoc dl(Op);
7666   unsigned NumElems = VT.getVectorNumElements();
7667   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
7668   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
7669   bool V1IsSplat = false;
7670   bool V2IsSplat = false;
7671   bool HasSSE2 = Subtarget->hasSSE2();
7672   bool HasFp256    = Subtarget->hasFp256();
7673   bool HasInt256   = Subtarget->hasInt256();
7674   MachineFunction &MF = DAG.getMachineFunction();
7675   bool OptForSize = MF.getFunction()->getAttributes().
7676     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
7677
7678   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
7679
7680   if (V1IsUndef && V2IsUndef)
7681     return DAG.getUNDEF(VT);
7682
7683   // When we create a shuffle node we put the UNDEF node to second operand,
7684   // but in some cases the first operand may be transformed to UNDEF.
7685   // In this case we should just commute the node.
7686   if (V1IsUndef)
7687     return CommuteVectorShuffle(SVOp, DAG);
7688
7689   // Vector shuffle lowering takes 3 steps:
7690   //
7691   // 1) Normalize the input vectors. Here splats, zeroed vectors, profitable
7692   //    narrowing and commutation of operands should be handled.
7693   // 2) Matching of shuffles with known shuffle masks to x86 target specific
7694   //    shuffle nodes.
7695   // 3) Rewriting of unmatched masks into new generic shuffle operations,
7696   //    so the shuffle can be broken into other shuffles and the legalizer can
7697   //    try the lowering again.
7698   //
7699   // The general idea is that no vector_shuffle operation should be left to
7700   // be matched during isel, all of them must be converted to a target specific
7701   // node here.
7702
7703   // Normalize the input vectors. Here splats, zeroed vectors, profitable
7704   // narrowing and commutation of operands should be handled. The actual code
7705   // doesn't include all of those, work in progress...
7706   SDValue NewOp = NormalizeVectorShuffle(Op, Subtarget, DAG);
7707   if (NewOp.getNode())
7708     return NewOp;
7709
7710   SmallVector<int, 8> M(SVOp->getMask().begin(), SVOp->getMask().end());
7711
7712   // NOTE: isPSHUFDMask can also match both masks below (unpckl_undef and
7713   // unpckh_undef). Only use pshufd if speed is more important than size.
7714   if (OptForSize && isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7715     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7716   if (OptForSize && isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7717     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7718
7719   if (isMOVDDUPMask(M, VT) && Subtarget->hasSSE3() &&
7720       V2IsUndef && MayFoldVectorLoad(V1))
7721     return getMOVDDup(Op, dl, V1, DAG);
7722
7723   if (isMOVHLPS_v_undef_Mask(M, VT))
7724     return getMOVHighToLow(Op, dl, DAG);
7725
7726   // Use to match splats
7727   if (HasSSE2 && isUNPCKHMask(M, VT, HasInt256) && V2IsUndef &&
7728       (VT == MVT::v2f64 || VT == MVT::v2i64))
7729     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7730
7731   if (isPSHUFDMask(M, VT)) {
7732     // The actual implementation will match the mask in the if above and then
7733     // during isel it can match several different instructions, not only pshufd
7734     // as its name says, sad but true, emulate the behavior for now...
7735     if (isMOVDDUPMask(M, VT) && ((VT == MVT::v4f32 || VT == MVT::v2i64)))
7736       return getTargetShuffleNode(X86ISD::MOVLHPS, dl, VT, V1, V1, DAG);
7737
7738     unsigned TargetMask = getShuffleSHUFImmediate(SVOp);
7739
7740     if (HasSSE2 && (VT == MVT::v4f32 || VT == MVT::v4i32))
7741       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1, TargetMask, DAG);
7742
7743     if (HasFp256 && (VT == MVT::v4f32 || VT == MVT::v2f64))
7744       return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1, TargetMask,
7745                                   DAG);
7746
7747     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V1,
7748                                 TargetMask, DAG);
7749   }
7750
7751   if (isPALIGNRMask(M, VT, Subtarget))
7752     return getTargetShuffleNode(X86ISD::PALIGNR, dl, VT, V1, V2,
7753                                 getShufflePALIGNRImmediate(SVOp),
7754                                 DAG);
7755
7756   // Check if this can be converted into a logical shift.
7757   bool isLeft = false;
7758   unsigned ShAmt = 0;
7759   SDValue ShVal;
7760   bool isShift = HasSSE2 && isVectorShift(SVOp, DAG, isLeft, ShVal, ShAmt);
7761   if (isShift && ShVal.hasOneUse()) {
7762     // If the shifted value has multiple uses, it may be cheaper to use
7763     // v_set0 + movlhps or movhlps, etc.
7764     MVT EltVT = VT.getVectorElementType();
7765     ShAmt *= EltVT.getSizeInBits();
7766     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7767   }
7768
7769   if (isMOVLMask(M, VT)) {
7770     if (ISD::isBuildVectorAllZeros(V1.getNode()))
7771       return getVZextMovL(VT, VT, V2, DAG, Subtarget, dl);
7772     if (!isMOVLPMask(M, VT)) {
7773       if (HasSSE2 && (VT == MVT::v2i64 || VT == MVT::v2f64))
7774         return getTargetShuffleNode(X86ISD::MOVSD, dl, VT, V1, V2, DAG);
7775
7776       if (VT == MVT::v4i32 || VT == MVT::v4f32)
7777         return getTargetShuffleNode(X86ISD::MOVSS, dl, VT, V1, V2, DAG);
7778     }
7779   }
7780
7781   // FIXME: fold these into legal mask.
7782   if (isMOVLHPSMask(M, VT) && !isUNPCKLMask(M, VT, HasInt256))
7783     return getMOVLowToHigh(Op, dl, DAG, HasSSE2);
7784
7785   if (isMOVHLPSMask(M, VT))
7786     return getMOVHighToLow(Op, dl, DAG);
7787
7788   if (V2IsUndef && isMOVSHDUPMask(M, VT, Subtarget))
7789     return getTargetShuffleNode(X86ISD::MOVSHDUP, dl, VT, V1, DAG);
7790
7791   if (V2IsUndef && isMOVSLDUPMask(M, VT, Subtarget))
7792     return getTargetShuffleNode(X86ISD::MOVSLDUP, dl, VT, V1, DAG);
7793
7794   if (isMOVLPMask(M, VT))
7795     return getMOVLP(Op, dl, DAG, HasSSE2);
7796
7797   if (ShouldXformToMOVHLPS(M, VT) ||
7798       ShouldXformToMOVLP(V1.getNode(), V2.getNode(), M, VT))
7799     return CommuteVectorShuffle(SVOp, DAG);
7800
7801   if (isShift) {
7802     // No better options. Use a vshldq / vsrldq.
7803     MVT EltVT = VT.getVectorElementType();
7804     ShAmt *= EltVT.getSizeInBits();
7805     return getVShift(isLeft, VT, ShVal, ShAmt, DAG, *this, dl);
7806   }
7807
7808   bool Commuted = false;
7809   // FIXME: This should also accept a bitcast of a splat?  Be careful, not
7810   // 1,1,1,1 -> v8i16 though.
7811   V1IsSplat = isSplatVector(V1.getNode());
7812   V2IsSplat = isSplatVector(V2.getNode());
7813
7814   // Canonicalize the splat or undef, if present, to be on the RHS.
7815   if (!V2IsUndef && V1IsSplat && !V2IsSplat) {
7816     CommuteVectorShuffleMask(M, NumElems);
7817     std::swap(V1, V2);
7818     std::swap(V1IsSplat, V2IsSplat);
7819     Commuted = true;
7820   }
7821
7822   if (isCommutedMOVLMask(M, VT, V2IsSplat, V2IsUndef)) {
7823     // Shuffling low element of v1 into undef, just return v1.
7824     if (V2IsUndef)
7825       return V1;
7826     // If V2 is a splat, the mask may be malformed such as <4,3,3,3>, which
7827     // the instruction selector will not match, so get a canonical MOVL with
7828     // swapped operands to undo the commute.
7829     return getMOVL(DAG, dl, VT, V2, V1);
7830   }
7831
7832   if (isUNPCKLMask(M, VT, HasInt256))
7833     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7834
7835   if (isUNPCKHMask(M, VT, HasInt256))
7836     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7837
7838   if (V2IsSplat) {
7839     // Normalize mask so all entries that point to V2 points to its first
7840     // element then try to match unpck{h|l} again. If match, return a
7841     // new vector_shuffle with the corrected mask.p
7842     SmallVector<int, 8> NewMask(M.begin(), M.end());
7843     NormalizeMask(NewMask, NumElems);
7844     if (isUNPCKLMask(NewMask, VT, HasInt256, true))
7845       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7846     if (isUNPCKHMask(NewMask, VT, HasInt256, true))
7847       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7848   }
7849
7850   if (Commuted) {
7851     // Commute is back and try unpck* again.
7852     // FIXME: this seems wrong.
7853     CommuteVectorShuffleMask(M, NumElems);
7854     std::swap(V1, V2);
7855     std::swap(V1IsSplat, V2IsSplat);
7856
7857     if (isUNPCKLMask(M, VT, HasInt256))
7858       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V2, DAG);
7859
7860     if (isUNPCKHMask(M, VT, HasInt256))
7861       return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V2, DAG);
7862   }
7863
7864   // Normalize the node to match x86 shuffle ops if needed
7865   if (!V2IsUndef && (isSHUFPMask(M, VT, /* Commuted */ true)))
7866     return CommuteVectorShuffle(SVOp, DAG);
7867
7868   // The checks below are all present in isShuffleMaskLegal, but they are
7869   // inlined here right now to enable us to directly emit target specific
7870   // nodes, and remove one by one until they don't return Op anymore.
7871
7872   if (ShuffleVectorSDNode::isSplatMask(&M[0], VT) &&
7873       SVOp->getSplatIndex() == 0 && V2IsUndef) {
7874     if (VT == MVT::v2f64 || VT == MVT::v2i64)
7875       return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7876   }
7877
7878   if (isPSHUFHWMask(M, VT, HasInt256))
7879     return getTargetShuffleNode(X86ISD::PSHUFHW, dl, VT, V1,
7880                                 getShufflePSHUFHWImmediate(SVOp),
7881                                 DAG);
7882
7883   if (isPSHUFLWMask(M, VT, HasInt256))
7884     return getTargetShuffleNode(X86ISD::PSHUFLW, dl, VT, V1,
7885                                 getShufflePSHUFLWImmediate(SVOp),
7886                                 DAG);
7887
7888   if (isSHUFPMask(M, VT))
7889     return getTargetShuffleNode(X86ISD::SHUFP, dl, VT, V1, V2,
7890                                 getShuffleSHUFImmediate(SVOp), DAG);
7891
7892   if (isUNPCKL_v_undef_Mask(M, VT, HasInt256))
7893     return getTargetShuffleNode(X86ISD::UNPCKL, dl, VT, V1, V1, DAG);
7894   if (isUNPCKH_v_undef_Mask(M, VT, HasInt256))
7895     return getTargetShuffleNode(X86ISD::UNPCKH, dl, VT, V1, V1, DAG);
7896
7897   //===--------------------------------------------------------------------===//
7898   // Generate target specific nodes for 128 or 256-bit shuffles only
7899   // supported in the AVX instruction set.
7900   //
7901
7902   // Handle VMOVDDUPY permutations
7903   if (V2IsUndef && isMOVDDUPYMask(M, VT, HasFp256))
7904     return getTargetShuffleNode(X86ISD::MOVDDUP, dl, VT, V1, DAG);
7905
7906   // Handle VPERMILPS/D* permutations
7907   if (isVPERMILPMask(M, VT)) {
7908     if ((HasInt256 && VT == MVT::v8i32) || VT == MVT::v16i32)
7909       return getTargetShuffleNode(X86ISD::PSHUFD, dl, VT, V1,
7910                                   getShuffleSHUFImmediate(SVOp), DAG);
7911     return getTargetShuffleNode(X86ISD::VPERMILP, dl, VT, V1,
7912                                 getShuffleSHUFImmediate(SVOp), DAG);
7913   }
7914
7915   unsigned Idx;
7916   if (VT.is512BitVector() && isINSERT64x4Mask(M, VT, &Idx))
7917     return Insert256BitVector(V1, Extract256BitVector(V2, 0, DAG, dl),
7918                               Idx*(NumElems/2), DAG, dl);
7919
7920   // Handle VPERM2F128/VPERM2I128 permutations
7921   if (isVPERM2X128Mask(M, VT, HasFp256))
7922     return getTargetShuffleNode(X86ISD::VPERM2X128, dl, VT, V1,
7923                                 V2, getShuffleVPERM2X128Immediate(SVOp), DAG);
7924
7925   unsigned MaskValue;
7926   if (isBlendMask(M, VT, Subtarget->hasSSE41(), Subtarget->hasInt256(),
7927                   &MaskValue))
7928     return LowerVECTOR_SHUFFLEtoBlend(SVOp, MaskValue, Subtarget, DAG);
7929
7930   if (Subtarget->hasSSE41() && isINSERTPSMask(M, VT))
7931     return getINSERTPS(SVOp, dl, DAG);
7932
7933   unsigned Imm8;
7934   if (V2IsUndef && HasInt256 && isPermImmMask(M, VT, Imm8))
7935     return getTargetShuffleNode(X86ISD::VPERMI, dl, VT, V1, Imm8, DAG);
7936
7937   if ((V2IsUndef && HasInt256 && VT.is256BitVector() && NumElems == 8) ||
7938       VT.is512BitVector()) {
7939     MVT MaskEltVT = MVT::getIntegerVT(VT.getVectorElementType().getSizeInBits());
7940     MVT MaskVectorVT = MVT::getVectorVT(MaskEltVT, NumElems);
7941     SmallVector<SDValue, 16> permclMask;
7942     for (unsigned i = 0; i != NumElems; ++i) {
7943       permclMask.push_back(DAG.getConstant((M[i]>=0) ? M[i] : 0, MaskEltVT));
7944     }
7945
7946     SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, MaskVectorVT, permclMask);
7947     if (V2IsUndef)
7948       // Bitcast is for VPERMPS since mask is v8i32 but node takes v8f32
7949       return DAG.getNode(X86ISD::VPERMV, dl, VT,
7950                           DAG.getNode(ISD::BITCAST, dl, VT, Mask), V1);
7951     return DAG.getNode(X86ISD::VPERMV3, dl, VT, V1,
7952                        DAG.getNode(ISD::BITCAST, dl, VT, Mask), V2);
7953   }
7954
7955   //===--------------------------------------------------------------------===//
7956   // Since no target specific shuffle was selected for this generic one,
7957   // lower it into other known shuffles. FIXME: this isn't true yet, but
7958   // this is the plan.
7959   //
7960
7961   // Handle v8i16 specifically since SSE can do byte extraction and insertion.
7962   if (VT == MVT::v8i16) {
7963     SDValue NewOp = LowerVECTOR_SHUFFLEv8i16(Op, Subtarget, DAG);
7964     if (NewOp.getNode())
7965       return NewOp;
7966   }
7967
7968   if (VT == MVT::v16i16 && Subtarget->hasInt256()) {
7969     SDValue NewOp = LowerVECTOR_SHUFFLEv16i16(Op, DAG);
7970     if (NewOp.getNode())
7971       return NewOp;
7972   }
7973
7974   if (VT == MVT::v16i8) {
7975     SDValue NewOp = LowerVECTOR_SHUFFLEv16i8(SVOp, Subtarget, DAG);
7976     if (NewOp.getNode())
7977       return NewOp;
7978   }
7979
7980   if (VT == MVT::v32i8) {
7981     SDValue NewOp = LowerVECTOR_SHUFFLEv32i8(SVOp, Subtarget, DAG);
7982     if (NewOp.getNode())
7983       return NewOp;
7984   }
7985
7986   // Handle all 128-bit wide vectors with 4 elements, and match them with
7987   // several different shuffle types.
7988   if (NumElems == 4 && VT.is128BitVector())
7989     return LowerVECTOR_SHUFFLE_128v4(SVOp, DAG);
7990
7991   // Handle general 256-bit shuffles
7992   if (VT.is256BitVector())
7993     return LowerVECTOR_SHUFFLE_256(SVOp, DAG);
7994
7995   return SDValue();
7996 }
7997
7998 // This function assumes its argument is a BUILD_VECTOR of constants or
7999 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
8000 // true.
8001 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
8002                                     unsigned &MaskValue) {
8003   MaskValue = 0;
8004   unsigned NumElems = BuildVector->getNumOperands();
8005   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
8006   unsigned NumLanes = (NumElems - 1) / 8 + 1;
8007   unsigned NumElemsInLane = NumElems / NumLanes;
8008
8009   // Blend for v16i16 should be symetric for the both lanes.
8010   for (unsigned i = 0; i < NumElemsInLane; ++i) {
8011     SDValue EltCond = BuildVector->getOperand(i);
8012     SDValue SndLaneEltCond =
8013         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
8014
8015     int Lane1Cond = -1, Lane2Cond = -1;
8016     if (isa<ConstantSDNode>(EltCond))
8017       Lane1Cond = !isZero(EltCond);
8018     if (isa<ConstantSDNode>(SndLaneEltCond))
8019       Lane2Cond = !isZero(SndLaneEltCond);
8020
8021     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
8022       // Lane1Cond != 0, means we want the first argument.
8023       // Lane1Cond == 0, means we want the second argument.
8024       // The encoding of this argument is 0 for the first argument, 1
8025       // for the second. Therefore, invert the condition.
8026       MaskValue |= !Lane1Cond << i;
8027     else if (Lane1Cond < 0)
8028       MaskValue |= !Lane2Cond << i;
8029     else
8030       return false;
8031   }
8032   return true;
8033 }
8034
8035 // Try to lower a vselect node into a simple blend instruction.
8036 static SDValue LowerVSELECTtoBlend(SDValue Op, const X86Subtarget *Subtarget,
8037                                    SelectionDAG &DAG) {
8038   SDValue Cond = Op.getOperand(0);
8039   SDValue LHS = Op.getOperand(1);
8040   SDValue RHS = Op.getOperand(2);
8041   SDLoc dl(Op);
8042   MVT VT = Op.getSimpleValueType();
8043   MVT EltVT = VT.getVectorElementType();
8044   unsigned NumElems = VT.getVectorNumElements();
8045
8046   // There is no blend with immediate in AVX-512.
8047   if (VT.is512BitVector())
8048     return SDValue();
8049
8050   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
8051     return SDValue();
8052   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
8053     return SDValue();
8054
8055   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
8056     return SDValue();
8057
8058   // Check the mask for BLEND and build the value.
8059   unsigned MaskValue = 0;
8060   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
8061     return SDValue();
8062
8063   // Convert i32 vectors to floating point if it is not AVX2.
8064   // AVX2 introduced VPBLENDD instruction for 128 and 256-bit vectors.
8065   MVT BlendVT = VT;
8066   if (EltVT == MVT::i64 || (EltVT == MVT::i32 && !Subtarget->hasInt256())) {
8067     BlendVT = MVT::getVectorVT(MVT::getFloatingPointVT(EltVT.getSizeInBits()),
8068                                NumElems);
8069     LHS = DAG.getNode(ISD::BITCAST, dl, VT, LHS);
8070     RHS = DAG.getNode(ISD::BITCAST, dl, VT, RHS);
8071   }
8072
8073   SDValue Ret = DAG.getNode(X86ISD::BLENDI, dl, BlendVT, LHS, RHS,
8074                             DAG.getConstant(MaskValue, MVT::i32));
8075   return DAG.getNode(ISD::BITCAST, dl, VT, Ret);
8076 }
8077
8078 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
8079   SDValue BlendOp = LowerVSELECTtoBlend(Op, Subtarget, DAG);
8080   if (BlendOp.getNode())
8081     return BlendOp;
8082
8083   // Some types for vselect were previously set to Expand, not Legal or
8084   // Custom. Return an empty SDValue so we fall-through to Expand, after
8085   // the Custom lowering phase.
8086   MVT VT = Op.getSimpleValueType();
8087   switch (VT.SimpleTy) {
8088   default:
8089     break;
8090   case MVT::v8i16:
8091   case MVT::v16i16:
8092     return SDValue();
8093   }
8094
8095   // We couldn't create a "Blend with immediate" node.
8096   // This node should still be legal, but we'll have to emit a blendv*
8097   // instruction.
8098   return Op;
8099 }
8100
8101 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8102   MVT VT = Op.getSimpleValueType();
8103   SDLoc dl(Op);
8104
8105   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
8106     return SDValue();
8107
8108   if (VT.getSizeInBits() == 8) {
8109     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
8110                                   Op.getOperand(0), Op.getOperand(1));
8111     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8112                                   DAG.getValueType(VT));
8113     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8114   }
8115
8116   if (VT.getSizeInBits() == 16) {
8117     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8118     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
8119     if (Idx == 0)
8120       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8121                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8122                                      DAG.getNode(ISD::BITCAST, dl,
8123                                                  MVT::v4i32,
8124                                                  Op.getOperand(0)),
8125                                      Op.getOperand(1)));
8126     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
8127                                   Op.getOperand(0), Op.getOperand(1));
8128     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
8129                                   DAG.getValueType(VT));
8130     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8131   }
8132
8133   if (VT == MVT::f32) {
8134     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
8135     // the result back to FR32 register. It's only worth matching if the
8136     // result has a single use which is a store or a bitcast to i32.  And in
8137     // the case of a store, it's not worth it if the index is a constant 0,
8138     // because a MOVSSmr can be used instead, which is smaller and faster.
8139     if (!Op.hasOneUse())
8140       return SDValue();
8141     SDNode *User = *Op.getNode()->use_begin();
8142     if ((User->getOpcode() != ISD::STORE ||
8143          (isa<ConstantSDNode>(Op.getOperand(1)) &&
8144           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
8145         (User->getOpcode() != ISD::BITCAST ||
8146          User->getValueType(0) != MVT::i32))
8147       return SDValue();
8148     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8149                                   DAG.getNode(ISD::BITCAST, dl, MVT::v4i32,
8150                                               Op.getOperand(0)),
8151                                               Op.getOperand(1));
8152     return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Extract);
8153   }
8154
8155   if (VT == MVT::i32 || VT == MVT::i64) {
8156     // ExtractPS/pextrq works with constant index.
8157     if (isa<ConstantSDNode>(Op.getOperand(1)))
8158       return Op;
8159   }
8160   return SDValue();
8161 }
8162
8163 /// Extract one bit from mask vector, like v16i1 or v8i1.
8164 /// AVX-512 feature.
8165 SDValue
8166 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
8167   SDValue Vec = Op.getOperand(0);
8168   SDLoc dl(Vec);
8169   MVT VecVT = Vec.getSimpleValueType();
8170   SDValue Idx = Op.getOperand(1);
8171   MVT EltVT = Op.getSimpleValueType();
8172
8173   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
8174
8175   // variable index can't be handled in mask registers,
8176   // extend vector to VR512
8177   if (!isa<ConstantSDNode>(Idx)) {
8178     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8179     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
8180     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
8181                               ExtVT.getVectorElementType(), Ext, Idx);
8182     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
8183   }
8184
8185   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8186   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8187   unsigned MaxSift = rc->getSize()*8 - 1;
8188   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
8189                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8190   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
8191                     DAG.getConstant(MaxSift, MVT::i8));
8192   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
8193                        DAG.getIntPtrConstant(0));
8194 }
8195
8196 SDValue
8197 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
8198                                            SelectionDAG &DAG) const {
8199   SDLoc dl(Op);
8200   SDValue Vec = Op.getOperand(0);
8201   MVT VecVT = Vec.getSimpleValueType();
8202   SDValue Idx = Op.getOperand(1);
8203
8204   if (Op.getSimpleValueType() == MVT::i1)
8205     return ExtractBitFromMaskVector(Op, DAG);
8206
8207   if (!isa<ConstantSDNode>(Idx)) {
8208     if (VecVT.is512BitVector() ||
8209         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
8210          VecVT.getVectorElementType().getSizeInBits() == 32)) {
8211
8212       MVT MaskEltVT =
8213         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
8214       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
8215                                     MaskEltVT.getSizeInBits());
8216
8217       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
8218       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
8219                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
8220                                 Idx, DAG.getConstant(0, getPointerTy()));
8221       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
8222       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
8223                         Perm, DAG.getConstant(0, getPointerTy()));
8224     }
8225     return SDValue();
8226   }
8227
8228   // If this is a 256-bit vector result, first extract the 128-bit vector and
8229   // then extract the element from the 128-bit vector.
8230   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
8231
8232     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8233     // Get the 128-bit vector.
8234     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
8235     MVT EltVT = VecVT.getVectorElementType();
8236
8237     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
8238
8239     //if (IdxVal >= NumElems/2)
8240     //  IdxVal -= NumElems/2;
8241     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
8242     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
8243                        DAG.getConstant(IdxVal, MVT::i32));
8244   }
8245
8246   assert(VecVT.is128BitVector() && "Unexpected vector length");
8247
8248   if (Subtarget->hasSSE41()) {
8249     SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG);
8250     if (Res.getNode())
8251       return Res;
8252   }
8253
8254   MVT VT = Op.getSimpleValueType();
8255   // TODO: handle v16i8.
8256   if (VT.getSizeInBits() == 16) {
8257     SDValue Vec = Op.getOperand(0);
8258     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8259     if (Idx == 0)
8260       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
8261                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
8262                                      DAG.getNode(ISD::BITCAST, dl,
8263                                                  MVT::v4i32, Vec),
8264                                      Op.getOperand(1)));
8265     // Transform it so it match pextrw which produces a 32-bit result.
8266     MVT EltVT = MVT::i32;
8267     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
8268                                   Op.getOperand(0), Op.getOperand(1));
8269     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
8270                                   DAG.getValueType(VT));
8271     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
8272   }
8273
8274   if (VT.getSizeInBits() == 32) {
8275     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8276     if (Idx == 0)
8277       return Op;
8278
8279     // SHUFPS the element to the lowest double word, then movss.
8280     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
8281     MVT VVT = Op.getOperand(0).getSimpleValueType();
8282     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8283                                        DAG.getUNDEF(VVT), Mask);
8284     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8285                        DAG.getIntPtrConstant(0));
8286   }
8287
8288   if (VT.getSizeInBits() == 64) {
8289     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
8290     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
8291     //        to match extract_elt for f64.
8292     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
8293     if (Idx == 0)
8294       return Op;
8295
8296     // UNPCKHPD the element to the lowest double word, then movsd.
8297     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
8298     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
8299     int Mask[2] = { 1, -1 };
8300     MVT VVT = Op.getOperand(0).getSimpleValueType();
8301     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
8302                                        DAG.getUNDEF(VVT), Mask);
8303     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
8304                        DAG.getIntPtrConstant(0));
8305   }
8306
8307   return SDValue();
8308 }
8309
8310 static SDValue LowerINSERT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
8311   MVT VT = Op.getSimpleValueType();
8312   MVT EltVT = VT.getVectorElementType();
8313   SDLoc dl(Op);
8314
8315   SDValue N0 = Op.getOperand(0);
8316   SDValue N1 = Op.getOperand(1);
8317   SDValue N2 = Op.getOperand(2);
8318
8319   if (!VT.is128BitVector())
8320     return SDValue();
8321
8322   if ((EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) &&
8323       isa<ConstantSDNode>(N2)) {
8324     unsigned Opc;
8325     if (VT == MVT::v8i16)
8326       Opc = X86ISD::PINSRW;
8327     else if (VT == MVT::v16i8)
8328       Opc = X86ISD::PINSRB;
8329     else
8330       Opc = X86ISD::PINSRB;
8331
8332     // Transform it so it match pinsr{b,w} which expects a GR32 as its second
8333     // argument.
8334     if (N1.getValueType() != MVT::i32)
8335       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8336     if (N2.getValueType() != MVT::i32)
8337       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8338     return DAG.getNode(Opc, dl, VT, N0, N1, N2);
8339   }
8340
8341   if (EltVT == MVT::f32 && isa<ConstantSDNode>(N2)) {
8342     // Bits [7:6] of the constant are the source select.  This will always be
8343     //  zero here.  The DAG Combiner may combine an extract_elt index into these
8344     //  bits.  For example (insert (extract, 3), 2) could be matched by putting
8345     //  the '3' into bits [7:6] of X86ISD::INSERTPS.
8346     // Bits [5:4] of the constant are the destination select.  This is the
8347     //  value of the incoming immediate.
8348     // Bits [3:0] of the constant are the zero mask.  The DAG Combiner may
8349     //   combine either bitwise AND or insert of float 0.0 to set these bits.
8350     N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue() << 4);
8351     // Create this as a scalar to vector..
8352     N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
8353     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
8354   }
8355
8356   if ((EltVT == MVT::i32 || EltVT == MVT::i64) && isa<ConstantSDNode>(N2)) {
8357     // PINSR* works with constant index.
8358     return Op;
8359   }
8360   return SDValue();
8361 }
8362
8363 /// Insert one bit to mask vector, like v16i1 or v8i1.
8364 /// AVX-512 feature.
8365 SDValue 
8366 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
8367   SDLoc dl(Op);
8368   SDValue Vec = Op.getOperand(0);
8369   SDValue Elt = Op.getOperand(1);
8370   SDValue Idx = Op.getOperand(2);
8371   MVT VecVT = Vec.getSimpleValueType();
8372
8373   if (!isa<ConstantSDNode>(Idx)) {
8374     // Non constant index. Extend source and destination,
8375     // insert element and then truncate the result.
8376     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
8377     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
8378     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT, 
8379       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
8380       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
8381     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
8382   }
8383
8384   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8385   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
8386   if (Vec.getOpcode() == ISD::UNDEF)
8387     return DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8388                        DAG.getConstant(IdxVal, MVT::i8));
8389   const TargetRegisterClass* rc = getRegClassFor(VecVT);
8390   unsigned MaxSift = rc->getSize()*8 - 1;
8391   EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
8392                     DAG.getConstant(MaxSift, MVT::i8));
8393   EltInVec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, EltInVec,
8394                     DAG.getConstant(MaxSift - IdxVal, MVT::i8));
8395   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
8396 }
8397 SDValue
8398 X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op, SelectionDAG &DAG) const {
8399   MVT VT = Op.getSimpleValueType();
8400   MVT EltVT = VT.getVectorElementType();
8401   
8402   if (EltVT == MVT::i1)
8403     return InsertBitToMaskVector(Op, DAG);
8404
8405   SDLoc dl(Op);
8406   SDValue N0 = Op.getOperand(0);
8407   SDValue N1 = Op.getOperand(1);
8408   SDValue N2 = Op.getOperand(2);
8409
8410   // If this is a 256-bit vector result, first extract the 128-bit vector,
8411   // insert the element into the extracted half and then place it back.
8412   if (VT.is256BitVector() || VT.is512BitVector()) {
8413     if (!isa<ConstantSDNode>(N2))
8414       return SDValue();
8415
8416     // Get the desired 128-bit vector half.
8417     unsigned IdxVal = cast<ConstantSDNode>(N2)->getZExtValue();
8418     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
8419
8420     // Insert the element into the desired half.
8421     unsigned NumEltsIn128 = 128/EltVT.getSizeInBits();
8422     unsigned IdxIn128 = IdxVal - (IdxVal/NumEltsIn128) * NumEltsIn128;
8423
8424     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
8425                     DAG.getConstant(IdxIn128, MVT::i32));
8426
8427     // Insert the changed part back to the 256-bit vector
8428     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
8429   }
8430
8431   if (Subtarget->hasSSE41())
8432     return LowerINSERT_VECTOR_ELT_SSE4(Op, DAG);
8433
8434   if (EltVT == MVT::i8)
8435     return SDValue();
8436
8437   if (EltVT.getSizeInBits() == 16 && isa<ConstantSDNode>(N2)) {
8438     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
8439     // as its second argument.
8440     if (N1.getValueType() != MVT::i32)
8441       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
8442     if (N2.getValueType() != MVT::i32)
8443       N2 = DAG.getIntPtrConstant(cast<ConstantSDNode>(N2)->getZExtValue());
8444     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
8445   }
8446   return SDValue();
8447 }
8448
8449 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
8450   SDLoc dl(Op);
8451   MVT OpVT = Op.getSimpleValueType();
8452
8453   // If this is a 256-bit vector result, first insert into a 128-bit
8454   // vector and then insert into the 256-bit vector.
8455   if (!OpVT.is128BitVector()) {
8456     // Insert into a 128-bit vector.
8457     unsigned SizeFactor = OpVT.getSizeInBits()/128;
8458     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
8459                                  OpVT.getVectorNumElements() / SizeFactor);
8460
8461     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
8462
8463     // Insert the 128-bit vector.
8464     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
8465   }
8466
8467   if (OpVT == MVT::v1i64 &&
8468       Op.getOperand(0).getValueType() == MVT::i64)
8469     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
8470
8471   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
8472   assert(OpVT.is128BitVector() && "Expected an SSE type!");
8473   return DAG.getNode(ISD::BITCAST, dl, OpVT,
8474                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,AnyExt));
8475 }
8476
8477 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
8478 // a simple subregister reference or explicit instructions to grab
8479 // upper bits of a vector.
8480 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8481                                       SelectionDAG &DAG) {
8482   SDLoc dl(Op);
8483   SDValue In =  Op.getOperand(0);
8484   SDValue Idx = Op.getOperand(1);
8485   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8486   MVT ResVT   = Op.getSimpleValueType();
8487   MVT InVT    = In.getSimpleValueType();
8488
8489   if (Subtarget->hasFp256()) {
8490     if (ResVT.is128BitVector() &&
8491         (InVT.is256BitVector() || InVT.is512BitVector()) &&
8492         isa<ConstantSDNode>(Idx)) {
8493       return Extract128BitVector(In, IdxVal, DAG, dl);
8494     }
8495     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
8496         isa<ConstantSDNode>(Idx)) {
8497       return Extract256BitVector(In, IdxVal, DAG, dl);
8498     }
8499   }
8500   return SDValue();
8501 }
8502
8503 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
8504 // simple superregister reference or explicit instructions to insert
8505 // the upper bits of a vector.
8506 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
8507                                      SelectionDAG &DAG) {
8508   if (Subtarget->hasFp256()) {
8509     SDLoc dl(Op.getNode());
8510     SDValue Vec = Op.getNode()->getOperand(0);
8511     SDValue SubVec = Op.getNode()->getOperand(1);
8512     SDValue Idx = Op.getNode()->getOperand(2);
8513
8514     if ((Op.getNode()->getSimpleValueType(0).is256BitVector() ||
8515          Op.getNode()->getSimpleValueType(0).is512BitVector()) &&
8516         SubVec.getNode()->getSimpleValueType(0).is128BitVector() &&
8517         isa<ConstantSDNode>(Idx)) {
8518       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8519       return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
8520     }
8521
8522     if (Op.getNode()->getSimpleValueType(0).is512BitVector() &&
8523         SubVec.getNode()->getSimpleValueType(0).is256BitVector() &&
8524         isa<ConstantSDNode>(Idx)) {
8525       unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
8526       return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
8527     }
8528   }
8529   return SDValue();
8530 }
8531
8532 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
8533 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
8534 // one of the above mentioned nodes. It has to be wrapped because otherwise
8535 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
8536 // be used to form addressing mode. These wrapped nodes will be selected
8537 // into MOV32ri.
8538 SDValue
8539 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
8540   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
8541
8542   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8543   // global base reg.
8544   unsigned char OpFlag = 0;
8545   unsigned WrapperKind = X86ISD::Wrapper;
8546   CodeModel::Model M = getTargetMachine().getCodeModel();
8547
8548   if (Subtarget->isPICStyleRIPRel() &&
8549       (M == CodeModel::Small || M == CodeModel::Kernel))
8550     WrapperKind = X86ISD::WrapperRIP;
8551   else if (Subtarget->isPICStyleGOT())
8552     OpFlag = X86II::MO_GOTOFF;
8553   else if (Subtarget->isPICStyleStubPIC())
8554     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8555
8556   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
8557                                              CP->getAlignment(),
8558                                              CP->getOffset(), OpFlag);
8559   SDLoc DL(CP);
8560   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8561   // With PIC, the address is actually $g + Offset.
8562   if (OpFlag) {
8563     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8564                          DAG.getNode(X86ISD::GlobalBaseReg,
8565                                      SDLoc(), getPointerTy()),
8566                          Result);
8567   }
8568
8569   return Result;
8570 }
8571
8572 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
8573   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
8574
8575   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8576   // global base reg.
8577   unsigned char OpFlag = 0;
8578   unsigned WrapperKind = X86ISD::Wrapper;
8579   CodeModel::Model M = getTargetMachine().getCodeModel();
8580
8581   if (Subtarget->isPICStyleRIPRel() &&
8582       (M == CodeModel::Small || M == CodeModel::Kernel))
8583     WrapperKind = X86ISD::WrapperRIP;
8584   else if (Subtarget->isPICStyleGOT())
8585     OpFlag = X86II::MO_GOTOFF;
8586   else if (Subtarget->isPICStyleStubPIC())
8587     OpFlag = X86II::MO_PIC_BASE_OFFSET;
8588
8589   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
8590                                           OpFlag);
8591   SDLoc DL(JT);
8592   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8593
8594   // With PIC, the address is actually $g + Offset.
8595   if (OpFlag)
8596     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8597                          DAG.getNode(X86ISD::GlobalBaseReg,
8598                                      SDLoc(), getPointerTy()),
8599                          Result);
8600
8601   return Result;
8602 }
8603
8604 SDValue
8605 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
8606   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
8607
8608   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8609   // global base reg.
8610   unsigned char OpFlag = 0;
8611   unsigned WrapperKind = X86ISD::Wrapper;
8612   CodeModel::Model M = getTargetMachine().getCodeModel();
8613
8614   if (Subtarget->isPICStyleRIPRel() &&
8615       (M == CodeModel::Small || M == CodeModel::Kernel)) {
8616     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
8617       OpFlag = X86II::MO_GOTPCREL;
8618     WrapperKind = X86ISD::WrapperRIP;
8619   } else if (Subtarget->isPICStyleGOT()) {
8620     OpFlag = X86II::MO_GOT;
8621   } else if (Subtarget->isPICStyleStubPIC()) {
8622     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
8623   } else if (Subtarget->isPICStyleStubNoDynamic()) {
8624     OpFlag = X86II::MO_DARWIN_NONLAZY;
8625   }
8626
8627   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
8628
8629   SDLoc DL(Op);
8630   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8631
8632   // With PIC, the address is actually $g + Offset.
8633   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
8634       !Subtarget->is64Bit()) {
8635     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8636                          DAG.getNode(X86ISD::GlobalBaseReg,
8637                                      SDLoc(), getPointerTy()),
8638                          Result);
8639   }
8640
8641   // For symbols that require a load from a stub to get the address, emit the
8642   // load.
8643   if (isGlobalStubReference(OpFlag))
8644     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
8645                          MachinePointerInfo::getGOT(), false, false, false, 0);
8646
8647   return Result;
8648 }
8649
8650 SDValue
8651 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
8652   // Create the TargetBlockAddressAddress node.
8653   unsigned char OpFlags =
8654     Subtarget->ClassifyBlockAddressReference();
8655   CodeModel::Model M = getTargetMachine().getCodeModel();
8656   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
8657   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
8658   SDLoc dl(Op);
8659   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
8660                                              OpFlags);
8661
8662   if (Subtarget->isPICStyleRIPRel() &&
8663       (M == CodeModel::Small || M == CodeModel::Kernel))
8664     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8665   else
8666     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8667
8668   // With PIC, the address is actually $g + Offset.
8669   if (isGlobalRelativeToPICBase(OpFlags)) {
8670     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8671                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8672                          Result);
8673   }
8674
8675   return Result;
8676 }
8677
8678 SDValue
8679 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
8680                                       int64_t Offset, SelectionDAG &DAG) const {
8681   // Create the TargetGlobalAddress node, folding in the constant
8682   // offset if it is legal.
8683   unsigned char OpFlags =
8684     Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
8685   CodeModel::Model M = getTargetMachine().getCodeModel();
8686   SDValue Result;
8687   if (OpFlags == X86II::MO_NO_FLAG &&
8688       X86::isOffsetSuitableForCodeModel(Offset, M)) {
8689     // A direct static reference to a global.
8690     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
8691     Offset = 0;
8692   } else {
8693     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
8694   }
8695
8696   if (Subtarget->isPICStyleRIPRel() &&
8697       (M == CodeModel::Small || M == CodeModel::Kernel))
8698     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
8699   else
8700     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
8701
8702   // With PIC, the address is actually $g + Offset.
8703   if (isGlobalRelativeToPICBase(OpFlags)) {
8704     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
8705                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
8706                          Result);
8707   }
8708
8709   // For globals that require a load from a stub to get the address, emit the
8710   // load.
8711   if (isGlobalStubReference(OpFlags))
8712     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
8713                          MachinePointerInfo::getGOT(), false, false, false, 0);
8714
8715   // If there was a non-zero offset that we didn't fold, create an explicit
8716   // addition for it.
8717   if (Offset != 0)
8718     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
8719                          DAG.getConstant(Offset, getPointerTy()));
8720
8721   return Result;
8722 }
8723
8724 SDValue
8725 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
8726   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
8727   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
8728   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
8729 }
8730
8731 static SDValue
8732 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
8733            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
8734            unsigned char OperandFlags, bool LocalDynamic = false) {
8735   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8736   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8737   SDLoc dl(GA);
8738   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8739                                            GA->getValueType(0),
8740                                            GA->getOffset(),
8741                                            OperandFlags);
8742
8743   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
8744                                            : X86ISD::TLSADDR;
8745
8746   if (InFlag) {
8747     SDValue Ops[] = { Chain,  TGA, *InFlag };
8748     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8749   } else {
8750     SDValue Ops[]  = { Chain, TGA };
8751     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
8752   }
8753
8754   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
8755   MFI->setAdjustsStack(true);
8756
8757   SDValue Flag = Chain.getValue(1);
8758   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
8759 }
8760
8761 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
8762 static SDValue
8763 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8764                                 const EVT PtrVT) {
8765   SDValue InFlag;
8766   SDLoc dl(GA);  // ? function entry point might be better
8767   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8768                                    DAG.getNode(X86ISD::GlobalBaseReg,
8769                                                SDLoc(), PtrVT), InFlag);
8770   InFlag = Chain.getValue(1);
8771
8772   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
8773 }
8774
8775 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
8776 static SDValue
8777 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8778                                 const EVT PtrVT) {
8779   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
8780                     X86::RAX, X86II::MO_TLSGD);
8781 }
8782
8783 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
8784                                            SelectionDAG &DAG,
8785                                            const EVT PtrVT,
8786                                            bool is64Bit) {
8787   SDLoc dl(GA);
8788
8789   // Get the start address of the TLS block for this module.
8790   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
8791       .getInfo<X86MachineFunctionInfo>();
8792   MFI->incNumLocalDynamicTLSAccesses();
8793
8794   SDValue Base;
8795   if (is64Bit) {
8796     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
8797                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
8798   } else {
8799     SDValue InFlag;
8800     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
8801         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
8802     InFlag = Chain.getValue(1);
8803     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
8804                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
8805   }
8806
8807   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
8808   // of Base.
8809
8810   // Build x@dtpoff.
8811   unsigned char OperandFlags = X86II::MO_DTPOFF;
8812   unsigned WrapperKind = X86ISD::Wrapper;
8813   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
8814                                            GA->getValueType(0),
8815                                            GA->getOffset(), OperandFlags);
8816   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8817
8818   // Add x@dtpoff with the base.
8819   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
8820 }
8821
8822 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
8823 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
8824                                    const EVT PtrVT, TLSModel::Model model,
8825                                    bool is64Bit, bool isPIC) {
8826   SDLoc dl(GA);
8827
8828   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
8829   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
8830                                                          is64Bit ? 257 : 256));
8831
8832   SDValue ThreadPointer =
8833       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0),
8834                   MachinePointerInfo(Ptr), false, false, false, 0);
8835
8836   unsigned char OperandFlags = 0;
8837   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
8838   // initialexec.
8839   unsigned WrapperKind = X86ISD::Wrapper;
8840   if (model == TLSModel::LocalExec) {
8841     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
8842   } else if (model == TLSModel::InitialExec) {
8843     if (is64Bit) {
8844       OperandFlags = X86II::MO_GOTTPOFF;
8845       WrapperKind = X86ISD::WrapperRIP;
8846     } else {
8847       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
8848     }
8849   } else {
8850     llvm_unreachable("Unexpected model");
8851   }
8852
8853   // emit "addl x@ntpoff,%eax" (local exec)
8854   // or "addl x@indntpoff,%eax" (initial exec)
8855   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
8856   SDValue TGA =
8857       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
8858                                  GA->getOffset(), OperandFlags);
8859   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
8860
8861   if (model == TLSModel::InitialExec) {
8862     if (isPIC && !is64Bit) {
8863       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
8864                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
8865                            Offset);
8866     }
8867
8868     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
8869                          MachinePointerInfo::getGOT(), false, false, false, 0);
8870   }
8871
8872   // The address of the thread local variable is the add of the thread
8873   // pointer with the offset of the variable.
8874   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
8875 }
8876
8877 SDValue
8878 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
8879
8880   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
8881   const GlobalValue *GV = GA->getGlobal();
8882
8883   if (Subtarget->isTargetELF()) {
8884     TLSModel::Model model = getTargetMachine().getTLSModel(GV);
8885
8886     switch (model) {
8887       case TLSModel::GeneralDynamic:
8888         if (Subtarget->is64Bit())
8889           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
8890         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
8891       case TLSModel::LocalDynamic:
8892         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
8893                                            Subtarget->is64Bit());
8894       case TLSModel::InitialExec:
8895       case TLSModel::LocalExec:
8896         return LowerToTLSExecModel(GA, DAG, getPointerTy(), model,
8897                                    Subtarget->is64Bit(),
8898                         getTargetMachine().getRelocationModel() == Reloc::PIC_);
8899     }
8900     llvm_unreachable("Unknown TLS model.");
8901   }
8902
8903   if (Subtarget->isTargetDarwin()) {
8904     // Darwin only has one model of TLS.  Lower to that.
8905     unsigned char OpFlag = 0;
8906     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
8907                            X86ISD::WrapperRIP : X86ISD::Wrapper;
8908
8909     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
8910     // global base reg.
8911     bool PIC32 = (getTargetMachine().getRelocationModel() == Reloc::PIC_) &&
8912                   !Subtarget->is64Bit();
8913     if (PIC32)
8914       OpFlag = X86II::MO_TLVP_PIC_BASE;
8915     else
8916       OpFlag = X86II::MO_TLVP;
8917     SDLoc DL(Op);
8918     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
8919                                                 GA->getValueType(0),
8920                                                 GA->getOffset(), OpFlag);
8921     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
8922
8923     // With PIC32, the address is actually $g + Offset.
8924     if (PIC32)
8925       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
8926                            DAG.getNode(X86ISD::GlobalBaseReg,
8927                                        SDLoc(), getPointerTy()),
8928                            Offset);
8929
8930     // Lowering the machine isd will make sure everything is in the right
8931     // location.
8932     SDValue Chain = DAG.getEntryNode();
8933     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
8934     SDValue Args[] = { Chain, Offset };
8935     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
8936
8937     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
8938     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
8939     MFI->setAdjustsStack(true);
8940
8941     // And our return value (tls address) is in the standard call return value
8942     // location.
8943     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
8944     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
8945                               Chain.getValue(1));
8946   }
8947
8948   if (Subtarget->isTargetKnownWindowsMSVC() ||
8949       Subtarget->isTargetWindowsGNU()) {
8950     // Just use the implicit TLS architecture
8951     // Need to generate someting similar to:
8952     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
8953     //                                  ; from TEB
8954     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
8955     //   mov     rcx, qword [rdx+rcx*8]
8956     //   mov     eax, .tls$:tlsvar
8957     //   [rax+rcx] contains the address
8958     // Windows 64bit: gs:0x58
8959     // Windows 32bit: fs:__tls_array
8960
8961     SDLoc dl(GA);
8962     SDValue Chain = DAG.getEntryNode();
8963
8964     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
8965     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
8966     // use its literal value of 0x2C.
8967     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
8968                                         ? Type::getInt8PtrTy(*DAG.getContext(),
8969                                                              256)
8970                                         : Type::getInt32PtrTy(*DAG.getContext(),
8971                                                               257));
8972
8973     SDValue TlsArray =
8974         Subtarget->is64Bit()
8975             ? DAG.getIntPtrConstant(0x58)
8976             : (Subtarget->isTargetWindowsGNU()
8977                    ? DAG.getIntPtrConstant(0x2C)
8978                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
8979
8980     SDValue ThreadPointer =
8981         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
8982                     MachinePointerInfo(Ptr), false, false, false, 0);
8983
8984     // Load the _tls_index variable
8985     SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
8986     if (Subtarget->is64Bit())
8987       IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain,
8988                            IDX, MachinePointerInfo(), MVT::i32,
8989                            false, false, 0);
8990     else
8991       IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
8992                         false, false, false, 0);
8993
8994     SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()),
8995                                     getPointerTy());
8996     IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
8997
8998     SDValue res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
8999     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
9000                       false, false, false, 0);
9001
9002     // Get the offset of start of .tls section
9003     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
9004                                              GA->getValueType(0),
9005                                              GA->getOffset(), X86II::MO_SECREL);
9006     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
9007
9008     // The address of the thread local variable is the add of the thread
9009     // pointer with the offset of the variable.
9010     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
9011   }
9012
9013   llvm_unreachable("TLS not implemented for this target.");
9014 }
9015
9016 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
9017 /// and take a 2 x i32 value to shift plus a shift amount.
9018 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
9019   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
9020   MVT VT = Op.getSimpleValueType();
9021   unsigned VTBits = VT.getSizeInBits();
9022   SDLoc dl(Op);
9023   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
9024   SDValue ShOpLo = Op.getOperand(0);
9025   SDValue ShOpHi = Op.getOperand(1);
9026   SDValue ShAmt  = Op.getOperand(2);
9027   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
9028   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
9029   // during isel.
9030   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9031                                   DAG.getConstant(VTBits - 1, MVT::i8));
9032   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
9033                                      DAG.getConstant(VTBits - 1, MVT::i8))
9034                        : DAG.getConstant(0, VT);
9035
9036   SDValue Tmp2, Tmp3;
9037   if (Op.getOpcode() == ISD::SHL_PARTS) {
9038     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
9039     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
9040   } else {
9041     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
9042     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
9043   }
9044
9045   // If the shift amount is larger or equal than the width of a part we can't
9046   // rely on the results of shld/shrd. Insert a test and select the appropriate
9047   // values for large shift amounts.
9048   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
9049                                 DAG.getConstant(VTBits, MVT::i8));
9050   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
9051                              AndNode, DAG.getConstant(0, MVT::i8));
9052
9053   SDValue Hi, Lo;
9054   SDValue CC = DAG.getConstant(X86::COND_NE, MVT::i8);
9055   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
9056   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
9057
9058   if (Op.getOpcode() == ISD::SHL_PARTS) {
9059     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9060     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9061   } else {
9062     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
9063     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
9064   }
9065
9066   SDValue Ops[2] = { Lo, Hi };
9067   return DAG.getMergeValues(Ops, dl);
9068 }
9069
9070 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
9071                                            SelectionDAG &DAG) const {
9072   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
9073
9074   if (SrcVT.isVector())
9075     return SDValue();
9076
9077   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
9078          "Unknown SINT_TO_FP to lower!");
9079
9080   // These are really Legal; return the operand so the caller accepts it as
9081   // Legal.
9082   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
9083     return Op;
9084   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
9085       Subtarget->is64Bit()) {
9086     return Op;
9087   }
9088
9089   SDLoc dl(Op);
9090   unsigned Size = SrcVT.getSizeInBits()/8;
9091   MachineFunction &MF = DAG.getMachineFunction();
9092   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
9093   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9094   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9095                                StackSlot,
9096                                MachinePointerInfo::getFixedStack(SSFI),
9097                                false, false, 0);
9098   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
9099 }
9100
9101 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
9102                                      SDValue StackSlot,
9103                                      SelectionDAG &DAG) const {
9104   // Build the FILD
9105   SDLoc DL(Op);
9106   SDVTList Tys;
9107   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
9108   if (useSSE)
9109     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
9110   else
9111     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
9112
9113   unsigned ByteSize = SrcVT.getSizeInBits()/8;
9114
9115   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
9116   MachineMemOperand *MMO;
9117   if (FI) {
9118     int SSFI = FI->getIndex();
9119     MMO =
9120       DAG.getMachineFunction()
9121       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9122                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
9123   } else {
9124     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
9125     StackSlot = StackSlot.getOperand(1);
9126   }
9127   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
9128   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
9129                                            X86ISD::FILD, DL,
9130                                            Tys, Ops, SrcVT, MMO);
9131
9132   if (useSSE) {
9133     Chain = Result.getValue(1);
9134     SDValue InFlag = Result.getValue(2);
9135
9136     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
9137     // shouldn't be necessary except that RFP cannot be live across
9138     // multiple blocks. When stackifier is fixed, they can be uncoupled.
9139     MachineFunction &MF = DAG.getMachineFunction();
9140     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
9141     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
9142     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9143     Tys = DAG.getVTList(MVT::Other);
9144     SDValue Ops[] = {
9145       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
9146     };
9147     MachineMemOperand *MMO =
9148       DAG.getMachineFunction()
9149       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9150                             MachineMemOperand::MOStore, SSFISize, SSFISize);
9151
9152     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
9153                                     Ops, Op.getValueType(), MMO);
9154     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
9155                          MachinePointerInfo::getFixedStack(SSFI),
9156                          false, false, false, 0);
9157   }
9158
9159   return Result;
9160 }
9161
9162 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
9163 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
9164                                                SelectionDAG &DAG) const {
9165   // This algorithm is not obvious. Here it is what we're trying to output:
9166   /*
9167      movq       %rax,  %xmm0
9168      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
9169      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
9170      #ifdef __SSE3__
9171        haddpd   %xmm0, %xmm0
9172      #else
9173        pshufd   $0x4e, %xmm0, %xmm1
9174        addpd    %xmm1, %xmm0
9175      #endif
9176   */
9177
9178   SDLoc dl(Op);
9179   LLVMContext *Context = DAG.getContext();
9180
9181   // Build some magic constants.
9182   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
9183   Constant *C0 = ConstantDataVector::get(*Context, CV0);
9184   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
9185
9186   SmallVector<Constant*,2> CV1;
9187   CV1.push_back(
9188     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9189                                       APInt(64, 0x4330000000000000ULL))));
9190   CV1.push_back(
9191     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9192                                       APInt(64, 0x4530000000000000ULL))));
9193   Constant *C1 = ConstantVector::get(CV1);
9194   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
9195
9196   // Load the 64-bit value into an XMM register.
9197   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
9198                             Op.getOperand(0));
9199   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
9200                               MachinePointerInfo::getConstantPool(),
9201                               false, false, false, 16);
9202   SDValue Unpck1 = getUnpackl(DAG, dl, MVT::v4i32,
9203                               DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, XR1),
9204                               CLod0);
9205
9206   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
9207                               MachinePointerInfo::getConstantPool(),
9208                               false, false, false, 16);
9209   SDValue XR2F = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Unpck1);
9210   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
9211   SDValue Result;
9212
9213   if (Subtarget->hasSSE3()) {
9214     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
9215     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
9216   } else {
9217     SDValue S2F = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Sub);
9218     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
9219                                            S2F, 0x4E, DAG);
9220     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
9221                          DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Shuffle),
9222                          Sub);
9223   }
9224
9225   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
9226                      DAG.getIntPtrConstant(0));
9227 }
9228
9229 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
9230 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
9231                                                SelectionDAG &DAG) const {
9232   SDLoc dl(Op);
9233   // FP constant to bias correct the final result.
9234   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
9235                                    MVT::f64);
9236
9237   // Load the 32-bit value into an XMM register.
9238   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
9239                              Op.getOperand(0));
9240
9241   // Zero out the upper parts of the register.
9242   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
9243
9244   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9245                      DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Load),
9246                      DAG.getIntPtrConstant(0));
9247
9248   // Or the load with the bias.
9249   SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64,
9250                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9251                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9252                                                    MVT::v2f64, Load)),
9253                            DAG.getNode(ISD::BITCAST, dl, MVT::v2i64,
9254                                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
9255                                                    MVT::v2f64, Bias)));
9256   Or = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
9257                    DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or),
9258                    DAG.getIntPtrConstant(0));
9259
9260   // Subtract the bias.
9261   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
9262
9263   // Handle final rounding.
9264   EVT DestVT = Op.getValueType();
9265
9266   if (DestVT.bitsLT(MVT::f64))
9267     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
9268                        DAG.getIntPtrConstant(0));
9269   if (DestVT.bitsGT(MVT::f64))
9270     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
9271
9272   // Handle final rounding.
9273   return Sub;
9274 }
9275
9276 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
9277                                                SelectionDAG &DAG) const {
9278   SDValue N0 = Op.getOperand(0);
9279   MVT SVT = N0.getSimpleValueType();
9280   SDLoc dl(Op);
9281
9282   assert((SVT == MVT::v4i8 || SVT == MVT::v4i16 ||
9283           SVT == MVT::v8i8 || SVT == MVT::v8i16) &&
9284          "Custom UINT_TO_FP is not supported!");
9285
9286   MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
9287   return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
9288                      DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
9289 }
9290
9291 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
9292                                            SelectionDAG &DAG) const {
9293   SDValue N0 = Op.getOperand(0);
9294   SDLoc dl(Op);
9295
9296   if (Op.getValueType().isVector())
9297     return lowerUINT_TO_FP_vec(Op, DAG);
9298
9299   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
9300   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
9301   // the optimization here.
9302   if (DAG.SignBitIsZero(N0))
9303     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
9304
9305   MVT SrcVT = N0.getSimpleValueType();
9306   MVT DstVT = Op.getSimpleValueType();
9307   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
9308     return LowerUINT_TO_FP_i64(Op, DAG);
9309   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
9310     return LowerUINT_TO_FP_i32(Op, DAG);
9311   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
9312     return SDValue();
9313
9314   // Make a 64-bit buffer, and use it to build an FILD.
9315   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
9316   if (SrcVT == MVT::i32) {
9317     SDValue WordOff = DAG.getConstant(4, getPointerTy());
9318     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
9319                                      getPointerTy(), StackSlot, WordOff);
9320     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9321                                   StackSlot, MachinePointerInfo(),
9322                                   false, false, 0);
9323     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, MVT::i32),
9324                                   OffsetSlot, MachinePointerInfo(),
9325                                   false, false, 0);
9326     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
9327     return Fild;
9328   }
9329
9330   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
9331   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
9332                                StackSlot, MachinePointerInfo(),
9333                                false, false, 0);
9334   // For i64 source, we need to add the appropriate power of 2 if the input
9335   // was negative.  This is the same as the optimization in
9336   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
9337   // we must be careful to do the computation in x87 extended precision, not
9338   // in SSE. (The generic code can't know it's OK to do this, or how to.)
9339   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
9340   MachineMemOperand *MMO =
9341     DAG.getMachineFunction()
9342     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9343                           MachineMemOperand::MOLoad, 8, 8);
9344
9345   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
9346   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
9347   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
9348                                          MVT::i64, MMO);
9349
9350   APInt FF(32, 0x5F800000ULL);
9351
9352   // Check whether the sign bit is set.
9353   SDValue SignSet = DAG.getSetCC(dl,
9354                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
9355                                  Op.getOperand(0), DAG.getConstant(0, MVT::i64),
9356                                  ISD::SETLT);
9357
9358   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
9359   SDValue FudgePtr = DAG.getConstantPool(
9360                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
9361                                          getPointerTy());
9362
9363   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
9364   SDValue Zero = DAG.getIntPtrConstant(0);
9365   SDValue Four = DAG.getIntPtrConstant(4);
9366   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
9367                                Zero, Four);
9368   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
9369
9370   // Load the value out, extending it from f32 to f80.
9371   // FIXME: Avoid the extend by constructing the right constant pool?
9372   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
9373                                  FudgePtr, MachinePointerInfo::getConstantPool(),
9374                                  MVT::f32, false, false, 4);
9375   // Extend everything to 80 bits to force it to be done on x87.
9376   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
9377   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add, DAG.getIntPtrConstant(0));
9378 }
9379
9380 std::pair<SDValue,SDValue>
9381 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
9382                                     bool IsSigned, bool IsReplace) const {
9383   SDLoc DL(Op);
9384
9385   EVT DstTy = Op.getValueType();
9386
9387   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
9388     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
9389     DstTy = MVT::i64;
9390   }
9391
9392   assert(DstTy.getSimpleVT() <= MVT::i64 &&
9393          DstTy.getSimpleVT() >= MVT::i16 &&
9394          "Unknown FP_TO_INT to lower!");
9395
9396   // These are really Legal.
9397   if (DstTy == MVT::i32 &&
9398       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9399     return std::make_pair(SDValue(), SDValue());
9400   if (Subtarget->is64Bit() &&
9401       DstTy == MVT::i64 &&
9402       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
9403     return std::make_pair(SDValue(), SDValue());
9404
9405   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
9406   // stack slot, or into the FTOL runtime function.
9407   MachineFunction &MF = DAG.getMachineFunction();
9408   unsigned MemSize = DstTy.getSizeInBits()/8;
9409   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9410   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9411
9412   unsigned Opc;
9413   if (!IsSigned && isIntegerTypeFTOL(DstTy))
9414     Opc = X86ISD::WIN_FTOL;
9415   else
9416     switch (DstTy.getSimpleVT().SimpleTy) {
9417     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
9418     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
9419     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
9420     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
9421     }
9422
9423   SDValue Chain = DAG.getEntryNode();
9424   SDValue Value = Op.getOperand(0);
9425   EVT TheVT = Op.getOperand(0).getValueType();
9426   // FIXME This causes a redundant load/store if the SSE-class value is already
9427   // in memory, such as if it is on the callstack.
9428   if (isScalarFPTypeInSSEReg(TheVT)) {
9429     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
9430     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
9431                          MachinePointerInfo::getFixedStack(SSFI),
9432                          false, false, 0);
9433     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
9434     SDValue Ops[] = {
9435       Chain, StackSlot, DAG.getValueType(TheVT)
9436     };
9437
9438     MachineMemOperand *MMO =
9439       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9440                               MachineMemOperand::MOLoad, MemSize, MemSize);
9441     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
9442     Chain = Value.getValue(1);
9443     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
9444     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
9445   }
9446
9447   MachineMemOperand *MMO =
9448     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
9449                             MachineMemOperand::MOStore, MemSize, MemSize);
9450
9451   if (Opc != X86ISD::WIN_FTOL) {
9452     // Build the FP_TO_INT*_IN_MEM
9453     SDValue Ops[] = { Chain, Value, StackSlot };
9454     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
9455                                            Ops, DstTy, MMO);
9456     return std::make_pair(FIST, StackSlot);
9457   } else {
9458     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
9459       DAG.getVTList(MVT::Other, MVT::Glue),
9460       Chain, Value);
9461     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
9462       MVT::i32, ftol.getValue(1));
9463     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
9464       MVT::i32, eax.getValue(2));
9465     SDValue Ops[] = { eax, edx };
9466     SDValue pair = IsReplace
9467       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
9468       : DAG.getMergeValues(Ops, DL);
9469     return std::make_pair(pair, SDValue());
9470   }
9471 }
9472
9473 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
9474                               const X86Subtarget *Subtarget) {
9475   MVT VT = Op->getSimpleValueType(0);
9476   SDValue In = Op->getOperand(0);
9477   MVT InVT = In.getSimpleValueType();
9478   SDLoc dl(Op);
9479
9480   // Optimize vectors in AVX mode:
9481   //
9482   //   v8i16 -> v8i32
9483   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
9484   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
9485   //   Concat upper and lower parts.
9486   //
9487   //   v4i32 -> v4i64
9488   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
9489   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
9490   //   Concat upper and lower parts.
9491   //
9492
9493   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
9494       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
9495       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
9496     return SDValue();
9497
9498   if (Subtarget->hasInt256())
9499     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
9500
9501   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
9502   SDValue Undef = DAG.getUNDEF(InVT);
9503   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
9504   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9505   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
9506
9507   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
9508                              VT.getVectorNumElements()/2);
9509
9510   OpLo = DAG.getNode(ISD::BITCAST, dl, HVT, OpLo);
9511   OpHi = DAG.getNode(ISD::BITCAST, dl, HVT, OpHi);
9512
9513   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
9514 }
9515
9516 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
9517                                         SelectionDAG &DAG) {
9518   MVT VT = Op->getSimpleValueType(0);
9519   SDValue In = Op->getOperand(0);
9520   MVT InVT = In.getSimpleValueType();
9521   SDLoc DL(Op);
9522   unsigned int NumElts = VT.getVectorNumElements();
9523   if (NumElts != 8 && NumElts != 16)
9524     return SDValue();
9525
9526   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
9527     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
9528
9529   EVT ExtVT = (NumElts == 8)? MVT::v8i64 : MVT::v16i32;
9530   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9531   // Now we have only mask extension
9532   assert(InVT.getVectorElementType() == MVT::i1);
9533   SDValue Cst = DAG.getTargetConstant(1, ExtVT.getScalarType());
9534   const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9535   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
9536   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9537   SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9538                            MachinePointerInfo::getConstantPool(),
9539                            false, false, false, Alignment);
9540
9541   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, DL, ExtVT, In, Ld);
9542   if (VT.is512BitVector())
9543     return Brcst;
9544   return DAG.getNode(X86ISD::VTRUNC, DL, VT, Brcst);
9545 }
9546
9547 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9548                                SelectionDAG &DAG) {
9549   if (Subtarget->hasFp256()) {
9550     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9551     if (Res.getNode())
9552       return Res;
9553   }
9554
9555   return SDValue();
9556 }
9557
9558 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
9559                                 SelectionDAG &DAG) {
9560   SDLoc DL(Op);
9561   MVT VT = Op.getSimpleValueType();
9562   SDValue In = Op.getOperand(0);
9563   MVT SVT = In.getSimpleValueType();
9564
9565   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
9566     return LowerZERO_EXTEND_AVX512(Op, DAG);
9567
9568   if (Subtarget->hasFp256()) {
9569     SDValue Res = LowerAVXExtend(Op, DAG, Subtarget);
9570     if (Res.getNode())
9571       return Res;
9572   }
9573
9574   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
9575          VT.getVectorNumElements() != SVT.getVectorNumElements());
9576   return SDValue();
9577 }
9578
9579 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
9580   SDLoc DL(Op);
9581   MVT VT = Op.getSimpleValueType();
9582   SDValue In = Op.getOperand(0);
9583   MVT InVT = In.getSimpleValueType();
9584
9585   if (VT == MVT::i1) {
9586     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
9587            "Invalid scalar TRUNCATE operation");
9588     if (InVT == MVT::i32)
9589       return SDValue();
9590     if (InVT.getSizeInBits() == 64)
9591       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::i32, In);
9592     else if (InVT.getSizeInBits() < 32)
9593       In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
9594     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
9595   }
9596   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
9597          "Invalid TRUNCATE operation");
9598
9599   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
9600     if (VT.getVectorElementType().getSizeInBits() >=8)
9601       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
9602
9603     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
9604     unsigned NumElts = InVT.getVectorNumElements();
9605     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
9606     if (InVT.getSizeInBits() < 512) {
9607       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
9608       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
9609       InVT = ExtVT;
9610     }
9611     
9612     SDValue Cst = DAG.getTargetConstant(1, InVT.getVectorElementType());
9613     const Constant *C = (dyn_cast<ConstantSDNode>(Cst))->getConstantIntValue();
9614     SDValue CP = DAG.getConstantPool(C, getPointerTy());
9615     unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
9616     SDValue Ld = DAG.getLoad(Cst.getValueType(), DL, DAG.getEntryNode(), CP,
9617                            MachinePointerInfo::getConstantPool(),
9618                            false, false, false, Alignment);
9619     SDValue OneV = DAG.getNode(X86ISD::VBROADCAST, DL, InVT, Ld);
9620     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
9621     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
9622   }
9623
9624   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
9625     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
9626     if (Subtarget->hasInt256()) {
9627       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
9628       In = DAG.getNode(ISD::BITCAST, DL, MVT::v8i32, In);
9629       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
9630                                 ShufMask);
9631       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
9632                          DAG.getIntPtrConstant(0));
9633     }
9634
9635     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9636                                DAG.getIntPtrConstant(0));
9637     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9638                                DAG.getIntPtrConstant(2));
9639     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9640     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9641     static const int ShufMask[] = {0, 2, 4, 6};
9642     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
9643   }
9644
9645   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
9646     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
9647     if (Subtarget->hasInt256()) {
9648       In = DAG.getNode(ISD::BITCAST, DL, MVT::v32i8, In);
9649
9650       SmallVector<SDValue,32> pshufbMask;
9651       for (unsigned i = 0; i < 2; ++i) {
9652         pshufbMask.push_back(DAG.getConstant(0x0, MVT::i8));
9653         pshufbMask.push_back(DAG.getConstant(0x1, MVT::i8));
9654         pshufbMask.push_back(DAG.getConstant(0x4, MVT::i8));
9655         pshufbMask.push_back(DAG.getConstant(0x5, MVT::i8));
9656         pshufbMask.push_back(DAG.getConstant(0x8, MVT::i8));
9657         pshufbMask.push_back(DAG.getConstant(0x9, MVT::i8));
9658         pshufbMask.push_back(DAG.getConstant(0xc, MVT::i8));
9659         pshufbMask.push_back(DAG.getConstant(0xd, MVT::i8));
9660         for (unsigned j = 0; j < 8; ++j)
9661           pshufbMask.push_back(DAG.getConstant(0x80, MVT::i8));
9662       }
9663       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
9664       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
9665       In = DAG.getNode(ISD::BITCAST, DL, MVT::v4i64, In);
9666
9667       static const int ShufMask[] = {0,  2,  -1,  -1};
9668       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
9669                                 &ShufMask[0]);
9670       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
9671                        DAG.getIntPtrConstant(0));
9672       return DAG.getNode(ISD::BITCAST, DL, VT, In);
9673     }
9674
9675     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9676                                DAG.getIntPtrConstant(0));
9677
9678     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
9679                                DAG.getIntPtrConstant(4));
9680
9681     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpLo);
9682     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, OpHi);
9683
9684     // The PSHUFB mask:
9685     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
9686                                    -1, -1, -1, -1, -1, -1, -1, -1};
9687
9688     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
9689     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
9690     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
9691
9692     OpLo = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpLo);
9693     OpHi = DAG.getNode(ISD::BITCAST, DL, MVT::v4i32, OpHi);
9694
9695     // The MOVLHPS Mask:
9696     static const int ShufMask2[] = {0, 1, 4, 5};
9697     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
9698     return DAG.getNode(ISD::BITCAST, DL, MVT::v8i16, res);
9699   }
9700
9701   // Handle truncation of V256 to V128 using shuffles.
9702   if (!VT.is128BitVector() || !InVT.is256BitVector())
9703     return SDValue();
9704
9705   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
9706
9707   unsigned NumElems = VT.getVectorNumElements();
9708   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
9709
9710   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
9711   // Prepare truncation shuffle mask
9712   for (unsigned i = 0; i != NumElems; ++i)
9713     MaskVec[i] = i * 2;
9714   SDValue V = DAG.getVectorShuffle(NVT, DL,
9715                                    DAG.getNode(ISD::BITCAST, DL, NVT, In),
9716                                    DAG.getUNDEF(NVT), &MaskVec[0]);
9717   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
9718                      DAG.getIntPtrConstant(0));
9719 }
9720
9721 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
9722                                            SelectionDAG &DAG) const {
9723   assert(!Op.getSimpleValueType().isVector());
9724
9725   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9726     /*IsSigned=*/ true, /*IsReplace=*/ false);
9727   SDValue FIST = Vals.first, StackSlot = Vals.second;
9728   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
9729   if (!FIST.getNode()) return Op;
9730
9731   if (StackSlot.getNode())
9732     // Load the result.
9733     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9734                        FIST, StackSlot, MachinePointerInfo(),
9735                        false, false, false, 0);
9736
9737   // The node is the result.
9738   return FIST;
9739 }
9740
9741 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
9742                                            SelectionDAG &DAG) const {
9743   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
9744     /*IsSigned=*/ false, /*IsReplace=*/ false);
9745   SDValue FIST = Vals.first, StackSlot = Vals.second;
9746   assert(FIST.getNode() && "Unexpected failure");
9747
9748   if (StackSlot.getNode())
9749     // Load the result.
9750     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
9751                        FIST, StackSlot, MachinePointerInfo(),
9752                        false, false, false, 0);
9753
9754   // The node is the result.
9755   return FIST;
9756 }
9757
9758 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
9759   SDLoc DL(Op);
9760   MVT VT = Op.getSimpleValueType();
9761   SDValue In = Op.getOperand(0);
9762   MVT SVT = In.getSimpleValueType();
9763
9764   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
9765
9766   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
9767                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
9768                                  In, DAG.getUNDEF(SVT)));
9769 }
9770
9771 static SDValue LowerFABS(SDValue Op, SelectionDAG &DAG) {
9772   LLVMContext *Context = DAG.getContext();
9773   SDLoc dl(Op);
9774   MVT VT = Op.getSimpleValueType();
9775   MVT EltVT = VT;
9776   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9777   if (VT.isVector()) {
9778     EltVT = VT.getVectorElementType();
9779     NumElts = VT.getVectorNumElements();
9780   }
9781   Constant *C;
9782   if (EltVT == MVT::f64)
9783     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9784                                           APInt(64, ~(1ULL << 63))));
9785   else
9786     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9787                                           APInt(32, ~(1U << 31))));
9788   C = ConstantVector::getSplat(NumElts, C);
9789   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9790   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9791   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9792   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9793                              MachinePointerInfo::getConstantPool(),
9794                              false, false, false, Alignment);
9795   if (VT.isVector()) {
9796     MVT ANDVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
9797     return DAG.getNode(ISD::BITCAST, dl, VT,
9798                        DAG.getNode(ISD::AND, dl, ANDVT,
9799                                    DAG.getNode(ISD::BITCAST, dl, ANDVT,
9800                                                Op.getOperand(0)),
9801                                    DAG.getNode(ISD::BITCAST, dl, ANDVT, Mask)));
9802   }
9803   return DAG.getNode(X86ISD::FAND, dl, VT, Op.getOperand(0), Mask);
9804 }
9805
9806 static SDValue LowerFNEG(SDValue Op, SelectionDAG &DAG) {
9807   LLVMContext *Context = DAG.getContext();
9808   SDLoc dl(Op);
9809   MVT VT = Op.getSimpleValueType();
9810   MVT EltVT = VT;
9811   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
9812   if (VT.isVector()) {
9813     EltVT = VT.getVectorElementType();
9814     NumElts = VT.getVectorNumElements();
9815   }
9816   Constant *C;
9817   if (EltVT == MVT::f64)
9818     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
9819                                           APInt(64, 1ULL << 63)));
9820   else
9821     C = ConstantFP::get(*Context, APFloat(APFloat::IEEEsingle,
9822                                           APInt(32, 1U << 31)));
9823   C = ConstantVector::getSplat(NumElts, C);
9824   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9825   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
9826   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9827   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9828                              MachinePointerInfo::getConstantPool(),
9829                              false, false, false, Alignment);
9830   if (VT.isVector()) {
9831     MVT XORVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits()/64);
9832     return DAG.getNode(ISD::BITCAST, dl, VT,
9833                        DAG.getNode(ISD::XOR, dl, XORVT,
9834                                    DAG.getNode(ISD::BITCAST, dl, XORVT,
9835                                                Op.getOperand(0)),
9836                                    DAG.getNode(ISD::BITCAST, dl, XORVT, Mask)));
9837   }
9838
9839   return DAG.getNode(X86ISD::FXOR, dl, VT, Op.getOperand(0), Mask);
9840 }
9841
9842 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
9843   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9844   LLVMContext *Context = DAG.getContext();
9845   SDValue Op0 = Op.getOperand(0);
9846   SDValue Op1 = Op.getOperand(1);
9847   SDLoc dl(Op);
9848   MVT VT = Op.getSimpleValueType();
9849   MVT SrcVT = Op1.getSimpleValueType();
9850
9851   // If second operand is smaller, extend it first.
9852   if (SrcVT.bitsLT(VT)) {
9853     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
9854     SrcVT = VT;
9855   }
9856   // And if it is bigger, shrink it first.
9857   if (SrcVT.bitsGT(VT)) {
9858     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1));
9859     SrcVT = VT;
9860   }
9861
9862   // At this point the operands and the result should have the same
9863   // type, and that won't be f80 since that is not custom lowered.
9864
9865   // First get the sign bit of second operand.
9866   SmallVector<Constant*,4> CV;
9867   if (SrcVT == MVT::f64) {
9868     const fltSemantics &Sem = APFloat::IEEEdouble;
9869     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 1ULL << 63))));
9870     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9871   } else {
9872     const fltSemantics &Sem = APFloat::IEEEsingle;
9873     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 1U << 31))));
9874     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9875     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9876     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9877   }
9878   Constant *C = ConstantVector::get(CV);
9879   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9880   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
9881                               MachinePointerInfo::getConstantPool(),
9882                               false, false, false, 16);
9883   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
9884
9885   // Shift sign bit right or left if the two operands have different types.
9886   if (SrcVT.bitsGT(VT)) {
9887     // Op0 is MVT::f32, Op1 is MVT::f64.
9888     SignBit = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, SignBit);
9889     SignBit = DAG.getNode(X86ISD::FSRL, dl, MVT::v2f64, SignBit,
9890                           DAG.getConstant(32, MVT::i32));
9891     SignBit = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, SignBit);
9892     SignBit = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f32, SignBit,
9893                           DAG.getIntPtrConstant(0));
9894   }
9895
9896   // Clear first operand sign bit.
9897   CV.clear();
9898   if (VT == MVT::f64) {
9899     const fltSemantics &Sem = APFloat::IEEEdouble;
9900     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9901                                                    APInt(64, ~(1ULL << 63)))));
9902     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(64, 0))));
9903   } else {
9904     const fltSemantics &Sem = APFloat::IEEEsingle;
9905     CV.push_back(ConstantFP::get(*Context, APFloat(Sem,
9906                                                    APInt(32, ~(1U << 31)))));
9907     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9908     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9909     CV.push_back(ConstantFP::get(*Context, APFloat(Sem, APInt(32, 0))));
9910   }
9911   C = ConstantVector::get(CV);
9912   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
9913   SDValue Mask2 = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
9914                               MachinePointerInfo::getConstantPool(),
9915                               false, false, false, 16);
9916   SDValue Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Mask2);
9917
9918   // Or the value with the sign bit.
9919   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
9920 }
9921
9922 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
9923   SDValue N0 = Op.getOperand(0);
9924   SDLoc dl(Op);
9925   MVT VT = Op.getSimpleValueType();
9926
9927   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
9928   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
9929                                   DAG.getConstant(1, VT));
9930   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, VT));
9931 }
9932
9933 // LowerVectorAllZeroTest - Check whether an OR'd tree is PTEST-able.
9934 //
9935 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
9936                                       SelectionDAG &DAG) {
9937   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
9938
9939   if (!Subtarget->hasSSE41())
9940     return SDValue();
9941
9942   if (!Op->hasOneUse())
9943     return SDValue();
9944
9945   SDNode *N = Op.getNode();
9946   SDLoc DL(N);
9947
9948   SmallVector<SDValue, 8> Opnds;
9949   DenseMap<SDValue, unsigned> VecInMap;
9950   SmallVector<SDValue, 8> VecIns;
9951   EVT VT = MVT::Other;
9952
9953   // Recognize a special case where a vector is casted into wide integer to
9954   // test all 0s.
9955   Opnds.push_back(N->getOperand(0));
9956   Opnds.push_back(N->getOperand(1));
9957
9958   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
9959     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
9960     // BFS traverse all OR'd operands.
9961     if (I->getOpcode() == ISD::OR) {
9962       Opnds.push_back(I->getOperand(0));
9963       Opnds.push_back(I->getOperand(1));
9964       // Re-evaluate the number of nodes to be traversed.
9965       e += 2; // 2 more nodes (LHS and RHS) are pushed.
9966       continue;
9967     }
9968
9969     // Quit if a non-EXTRACT_VECTOR_ELT
9970     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9971       return SDValue();
9972
9973     // Quit if without a constant index.
9974     SDValue Idx = I->getOperand(1);
9975     if (!isa<ConstantSDNode>(Idx))
9976       return SDValue();
9977
9978     SDValue ExtractedFromVec = I->getOperand(0);
9979     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
9980     if (M == VecInMap.end()) {
9981       VT = ExtractedFromVec.getValueType();
9982       // Quit if not 128/256-bit vector.
9983       if (!VT.is128BitVector() && !VT.is256BitVector())
9984         return SDValue();
9985       // Quit if not the same type.
9986       if (VecInMap.begin() != VecInMap.end() &&
9987           VT != VecInMap.begin()->first.getValueType())
9988         return SDValue();
9989       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
9990       VecIns.push_back(ExtractedFromVec);
9991     }
9992     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
9993   }
9994
9995   assert((VT.is128BitVector() || VT.is256BitVector()) &&
9996          "Not extracted from 128-/256-bit vector.");
9997
9998   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
9999
10000   for (DenseMap<SDValue, unsigned>::const_iterator
10001         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
10002     // Quit if not all elements are used.
10003     if (I->second != FullMask)
10004       return SDValue();
10005   }
10006
10007   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
10008
10009   // Cast all vectors into TestVT for PTEST.
10010   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
10011     VecIns[i] = DAG.getNode(ISD::BITCAST, DL, TestVT, VecIns[i]);
10012
10013   // If more than one full vectors are evaluated, OR them first before PTEST.
10014   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
10015     // Each iteration will OR 2 nodes and append the result until there is only
10016     // 1 node left, i.e. the final OR'd value of all vectors.
10017     SDValue LHS = VecIns[Slot];
10018     SDValue RHS = VecIns[Slot + 1];
10019     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
10020   }
10021
10022   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
10023                      VecIns.back(), VecIns.back());
10024 }
10025
10026 /// \brief return true if \c Op has a use that doesn't just read flags.
10027 static bool hasNonFlagsUse(SDValue Op) {
10028   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
10029        ++UI) {
10030     SDNode *User = *UI;
10031     unsigned UOpNo = UI.getOperandNo();
10032     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
10033       // Look pass truncate.
10034       UOpNo = User->use_begin().getOperandNo();
10035       User = *User->use_begin();
10036     }
10037
10038     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
10039         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
10040       return true;
10041   }
10042   return false;
10043 }
10044
10045 /// Emit nodes that will be selected as "test Op0,Op0", or something
10046 /// equivalent.
10047 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
10048                                     SelectionDAG &DAG) const {
10049   if (Op.getValueType() == MVT::i1)
10050     // KORTEST instruction should be selected
10051     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10052                        DAG.getConstant(0, Op.getValueType()));
10053
10054   // CF and OF aren't always set the way we want. Determine which
10055   // of these we need.
10056   bool NeedCF = false;
10057   bool NeedOF = false;
10058   switch (X86CC) {
10059   default: break;
10060   case X86::COND_A: case X86::COND_AE:
10061   case X86::COND_B: case X86::COND_BE:
10062     NeedCF = true;
10063     break;
10064   case X86::COND_G: case X86::COND_GE:
10065   case X86::COND_L: case X86::COND_LE:
10066   case X86::COND_O: case X86::COND_NO:
10067     NeedOF = true;
10068     break;
10069   }
10070   // See if we can use the EFLAGS value from the operand instead of
10071   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
10072   // we prove that the arithmetic won't overflow, we can't use OF or CF.
10073   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
10074     // Emit a CMP with 0, which is the TEST pattern.
10075     //if (Op.getValueType() == MVT::i1)
10076     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
10077     //                     DAG.getConstant(0, MVT::i1));
10078     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10079                        DAG.getConstant(0, Op.getValueType()));
10080   }
10081   unsigned Opcode = 0;
10082   unsigned NumOperands = 0;
10083
10084   // Truncate operations may prevent the merge of the SETCC instruction
10085   // and the arithmetic instruction before it. Attempt to truncate the operands
10086   // of the arithmetic instruction and use a reduced bit-width instruction.
10087   bool NeedTruncation = false;
10088   SDValue ArithOp = Op;
10089   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
10090     SDValue Arith = Op->getOperand(0);
10091     // Both the trunc and the arithmetic op need to have one user each.
10092     if (Arith->hasOneUse())
10093       switch (Arith.getOpcode()) {
10094         default: break;
10095         case ISD::ADD:
10096         case ISD::SUB:
10097         case ISD::AND:
10098         case ISD::OR:
10099         case ISD::XOR: {
10100           NeedTruncation = true;
10101           ArithOp = Arith;
10102         }
10103       }
10104   }
10105
10106   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
10107   // which may be the result of a CAST.  We use the variable 'Op', which is the
10108   // non-casted variable when we check for possible users.
10109   switch (ArithOp.getOpcode()) {
10110   case ISD::ADD:
10111     // Due to an isel shortcoming, be conservative if this add is likely to be
10112     // selected as part of a load-modify-store instruction. When the root node
10113     // in a match is a store, isel doesn't know how to remap non-chain non-flag
10114     // uses of other nodes in the match, such as the ADD in this case. This
10115     // leads to the ADD being left around and reselected, with the result being
10116     // two adds in the output.  Alas, even if none our users are stores, that
10117     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
10118     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
10119     // climbing the DAG back to the root, and it doesn't seem to be worth the
10120     // effort.
10121     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10122          UE = Op.getNode()->use_end(); UI != UE; ++UI)
10123       if (UI->getOpcode() != ISD::CopyToReg &&
10124           UI->getOpcode() != ISD::SETCC &&
10125           UI->getOpcode() != ISD::STORE)
10126         goto default_case;
10127
10128     if (ConstantSDNode *C =
10129         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
10130       // An add of one will be selected as an INC.
10131       if (C->getAPIntValue() == 1) {
10132         Opcode = X86ISD::INC;
10133         NumOperands = 1;
10134         break;
10135       }
10136
10137       // An add of negative one (subtract of one) will be selected as a DEC.
10138       if (C->getAPIntValue().isAllOnesValue()) {
10139         Opcode = X86ISD::DEC;
10140         NumOperands = 1;
10141         break;
10142       }
10143     }
10144
10145     // Otherwise use a regular EFLAGS-setting add.
10146     Opcode = X86ISD::ADD;
10147     NumOperands = 2;
10148     break;
10149   case ISD::SHL:
10150   case ISD::SRL:
10151     // If we have a constant logical shift that's only used in a comparison
10152     // against zero turn it into an equivalent AND. This allows turning it into
10153     // a TEST instruction later.
10154     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) &&
10155         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
10156       EVT VT = Op.getValueType();
10157       unsigned BitWidth = VT.getSizeInBits();
10158       unsigned ShAmt = Op->getConstantOperandVal(1);
10159       if (ShAmt >= BitWidth) // Avoid undefined shifts.
10160         break;
10161       APInt Mask = ArithOp.getOpcode() == ISD::SRL
10162                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
10163                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
10164       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
10165         break;
10166       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
10167                                 DAG.getConstant(Mask, VT));
10168       DAG.ReplaceAllUsesWith(Op, New);
10169       Op = New;
10170     }
10171     break;
10172
10173   case ISD::AND:
10174     // If the primary and result isn't used, don't bother using X86ISD::AND,
10175     // because a TEST instruction will be better.
10176     if (!hasNonFlagsUse(Op))
10177       break;
10178     // FALL THROUGH
10179   case ISD::SUB:
10180   case ISD::OR:
10181   case ISD::XOR:
10182     // Due to the ISEL shortcoming noted above, be conservative if this op is
10183     // likely to be selected as part of a load-modify-store instruction.
10184     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
10185            UE = Op.getNode()->use_end(); UI != UE; ++UI)
10186       if (UI->getOpcode() == ISD::STORE)
10187         goto default_case;
10188
10189     // Otherwise use a regular EFLAGS-setting instruction.
10190     switch (ArithOp.getOpcode()) {
10191     default: llvm_unreachable("unexpected operator!");
10192     case ISD::SUB: Opcode = X86ISD::SUB; break;
10193     case ISD::XOR: Opcode = X86ISD::XOR; break;
10194     case ISD::AND: Opcode = X86ISD::AND; break;
10195     case ISD::OR: {
10196       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
10197         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
10198         if (EFLAGS.getNode())
10199           return EFLAGS;
10200       }
10201       Opcode = X86ISD::OR;
10202       break;
10203     }
10204     }
10205
10206     NumOperands = 2;
10207     break;
10208   case X86ISD::ADD:
10209   case X86ISD::SUB:
10210   case X86ISD::INC:
10211   case X86ISD::DEC:
10212   case X86ISD::OR:
10213   case X86ISD::XOR:
10214   case X86ISD::AND:
10215     return SDValue(Op.getNode(), 1);
10216   default:
10217   default_case:
10218     break;
10219   }
10220
10221   // If we found that truncation is beneficial, perform the truncation and
10222   // update 'Op'.
10223   if (NeedTruncation) {
10224     EVT VT = Op.getValueType();
10225     SDValue WideVal = Op->getOperand(0);
10226     EVT WideVT = WideVal.getValueType();
10227     unsigned ConvertedOp = 0;
10228     // Use a target machine opcode to prevent further DAGCombine
10229     // optimizations that may separate the arithmetic operations
10230     // from the setcc node.
10231     switch (WideVal.getOpcode()) {
10232       default: break;
10233       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
10234       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
10235       case ISD::AND: ConvertedOp = X86ISD::AND; break;
10236       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
10237       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
10238     }
10239
10240     if (ConvertedOp) {
10241       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10242       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
10243         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
10244         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
10245         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
10246       }
10247     }
10248   }
10249
10250   if (Opcode == 0)
10251     // Emit a CMP with 0, which is the TEST pattern.
10252     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
10253                        DAG.getConstant(0, Op.getValueType()));
10254
10255   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
10256   SmallVector<SDValue, 4> Ops;
10257   for (unsigned i = 0; i != NumOperands; ++i)
10258     Ops.push_back(Op.getOperand(i));
10259
10260   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
10261   DAG.ReplaceAllUsesWith(Op, New);
10262   return SDValue(New.getNode(), 1);
10263 }
10264
10265 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
10266 /// equivalent.
10267 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
10268                                    SDLoc dl, SelectionDAG &DAG) const {
10269   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
10270     if (C->getAPIntValue() == 0)
10271       return EmitTest(Op0, X86CC, dl, DAG);
10272
10273      if (Op0.getValueType() == MVT::i1)
10274        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
10275   }
10276  
10277   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
10278        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
10279     // Do the comparison at i32 if it's smaller, besides the Atom case. 
10280     // This avoids subregister aliasing issues. Keep the smaller reference 
10281     // if we're optimizing for size, however, as that'll allow better folding 
10282     // of memory operations.
10283     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
10284         !DAG.getMachineFunction().getFunction()->getAttributes().hasAttribute(
10285              AttributeSet::FunctionIndex, Attribute::MinSize) &&
10286         !Subtarget->isAtom()) {
10287       unsigned ExtendOp =
10288           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
10289       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
10290       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
10291     }
10292     // Use SUB instead of CMP to enable CSE between SUB and CMP.
10293     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
10294     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
10295                               Op0, Op1);
10296     return SDValue(Sub.getNode(), 1);
10297   }
10298   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
10299 }
10300
10301 /// Convert a comparison if required by the subtarget.
10302 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
10303                                                  SelectionDAG &DAG) const {
10304   // If the subtarget does not support the FUCOMI instruction, floating-point
10305   // comparisons have to be converted.
10306   if (Subtarget->hasCMov() ||
10307       Cmp.getOpcode() != X86ISD::CMP ||
10308       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
10309       !Cmp.getOperand(1).getValueType().isFloatingPoint())
10310     return Cmp;
10311
10312   // The instruction selector will select an FUCOM instruction instead of
10313   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
10314   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
10315   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
10316   SDLoc dl(Cmp);
10317   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
10318   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
10319   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
10320                             DAG.getConstant(8, MVT::i8));
10321   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
10322   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
10323 }
10324
10325 static bool isAllOnes(SDValue V) {
10326   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
10327   return C && C->isAllOnesValue();
10328 }
10329
10330 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
10331 /// if it's possible.
10332 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
10333                                      SDLoc dl, SelectionDAG &DAG) const {
10334   SDValue Op0 = And.getOperand(0);
10335   SDValue Op1 = And.getOperand(1);
10336   if (Op0.getOpcode() == ISD::TRUNCATE)
10337     Op0 = Op0.getOperand(0);
10338   if (Op1.getOpcode() == ISD::TRUNCATE)
10339     Op1 = Op1.getOperand(0);
10340
10341   SDValue LHS, RHS;
10342   if (Op1.getOpcode() == ISD::SHL)
10343     std::swap(Op0, Op1);
10344   if (Op0.getOpcode() == ISD::SHL) {
10345     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
10346       if (And00C->getZExtValue() == 1) {
10347         // If we looked past a truncate, check that it's only truncating away
10348         // known zeros.
10349         unsigned BitWidth = Op0.getValueSizeInBits();
10350         unsigned AndBitWidth = And.getValueSizeInBits();
10351         if (BitWidth > AndBitWidth) {
10352           APInt Zeros, Ones;
10353           DAG.computeKnownBits(Op0, Zeros, Ones);
10354           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
10355             return SDValue();
10356         }
10357         LHS = Op1;
10358         RHS = Op0.getOperand(1);
10359       }
10360   } else if (Op1.getOpcode() == ISD::Constant) {
10361     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
10362     uint64_t AndRHSVal = AndRHS->getZExtValue();
10363     SDValue AndLHS = Op0;
10364
10365     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
10366       LHS = AndLHS.getOperand(0);
10367       RHS = AndLHS.getOperand(1);
10368     }
10369
10370     // Use BT if the immediate can't be encoded in a TEST instruction.
10371     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
10372       LHS = AndLHS;
10373       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), LHS.getValueType());
10374     }
10375   }
10376
10377   if (LHS.getNode()) {
10378     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
10379     // instruction.  Since the shift amount is in-range-or-undefined, we know
10380     // that doing a bittest on the i32 value is ok.  We extend to i32 because
10381     // the encoding for the i16 version is larger than the i32 version.
10382     // Also promote i16 to i32 for performance / code size reason.
10383     if (LHS.getValueType() == MVT::i8 ||
10384         LHS.getValueType() == MVT::i16)
10385       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
10386
10387     // If the operand types disagree, extend the shift amount to match.  Since
10388     // BT ignores high bits (like shifts) we can use anyextend.
10389     if (LHS.getValueType() != RHS.getValueType())
10390       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
10391
10392     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
10393     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
10394     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10395                        DAG.getConstant(Cond, MVT::i8), BT);
10396   }
10397
10398   return SDValue();
10399 }
10400
10401 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
10402 /// mask CMPs.
10403 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
10404                               SDValue &Op1) {
10405   unsigned SSECC;
10406   bool Swap = false;
10407
10408   // SSE Condition code mapping:
10409   //  0 - EQ
10410   //  1 - LT
10411   //  2 - LE
10412   //  3 - UNORD
10413   //  4 - NEQ
10414   //  5 - NLT
10415   //  6 - NLE
10416   //  7 - ORD
10417   switch (SetCCOpcode) {
10418   default: llvm_unreachable("Unexpected SETCC condition");
10419   case ISD::SETOEQ:
10420   case ISD::SETEQ:  SSECC = 0; break;
10421   case ISD::SETOGT:
10422   case ISD::SETGT:  Swap = true; // Fallthrough
10423   case ISD::SETLT:
10424   case ISD::SETOLT: SSECC = 1; break;
10425   case ISD::SETOGE:
10426   case ISD::SETGE:  Swap = true; // Fallthrough
10427   case ISD::SETLE:
10428   case ISD::SETOLE: SSECC = 2; break;
10429   case ISD::SETUO:  SSECC = 3; break;
10430   case ISD::SETUNE:
10431   case ISD::SETNE:  SSECC = 4; break;
10432   case ISD::SETULE: Swap = true; // Fallthrough
10433   case ISD::SETUGE: SSECC = 5; break;
10434   case ISD::SETULT: Swap = true; // Fallthrough
10435   case ISD::SETUGT: SSECC = 6; break;
10436   case ISD::SETO:   SSECC = 7; break;
10437   case ISD::SETUEQ:
10438   case ISD::SETONE: SSECC = 8; break;
10439   }
10440   if (Swap)
10441     std::swap(Op0, Op1);
10442
10443   return SSECC;
10444 }
10445
10446 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
10447 // ones, and then concatenate the result back.
10448 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
10449   MVT VT = Op.getSimpleValueType();
10450
10451   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
10452          "Unsupported value type for operation");
10453
10454   unsigned NumElems = VT.getVectorNumElements();
10455   SDLoc dl(Op);
10456   SDValue CC = Op.getOperand(2);
10457
10458   // Extract the LHS vectors
10459   SDValue LHS = Op.getOperand(0);
10460   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
10461   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
10462
10463   // Extract the RHS vectors
10464   SDValue RHS = Op.getOperand(1);
10465   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
10466   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
10467
10468   // Issue the operation on the smaller types and concatenate the result back
10469   MVT EltVT = VT.getVectorElementType();
10470   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
10471   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10472                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
10473                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
10474 }
10475
10476 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
10477                                      const X86Subtarget *Subtarget) {
10478   SDValue Op0 = Op.getOperand(0);
10479   SDValue Op1 = Op.getOperand(1);
10480   SDValue CC = Op.getOperand(2);
10481   MVT VT = Op.getSimpleValueType();
10482   SDLoc dl(Op);
10483
10484   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 32 &&
10485          Op.getValueType().getScalarType() == MVT::i1 &&
10486          "Cannot set masked compare for this operation");
10487
10488   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10489   unsigned  Opc = 0;
10490   bool Unsigned = false;
10491   bool Swap = false;
10492   unsigned SSECC;
10493   switch (SetCCOpcode) {
10494   default: llvm_unreachable("Unexpected SETCC condition");
10495   case ISD::SETNE:  SSECC = 4; break;
10496   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
10497   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
10498   case ISD::SETLT:  Swap = true; //fall-through
10499   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
10500   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
10501   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
10502   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
10503   case ISD::SETULE: Unsigned = true; //fall-through
10504   case ISD::SETLE:  SSECC = 2; break;
10505   }
10506
10507   if (Swap)
10508     std::swap(Op0, Op1);
10509   if (Opc)
10510     return DAG.getNode(Opc, dl, VT, Op0, Op1);
10511   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
10512   return DAG.getNode(Opc, dl, VT, Op0, Op1,
10513                      DAG.getConstant(SSECC, MVT::i8));
10514 }
10515
10516 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
10517 /// operand \p Op1.  If non-trivial (for example because it's not constant)
10518 /// return an empty value.
10519 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
10520 {
10521   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
10522   if (!BV)
10523     return SDValue();
10524
10525   MVT VT = Op1.getSimpleValueType();
10526   MVT EVT = VT.getVectorElementType();
10527   unsigned n = VT.getVectorNumElements();
10528   SmallVector<SDValue, 8> ULTOp1;
10529
10530   for (unsigned i = 0; i < n; ++i) {
10531     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
10532     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
10533       return SDValue();
10534
10535     // Avoid underflow.
10536     APInt Val = Elt->getAPIntValue();
10537     if (Val == 0)
10538       return SDValue();
10539
10540     ULTOp1.push_back(DAG.getConstant(Val - 1, EVT));
10541   }
10542
10543   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
10544 }
10545
10546 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
10547                            SelectionDAG &DAG) {
10548   SDValue Op0 = Op.getOperand(0);
10549   SDValue Op1 = Op.getOperand(1);
10550   SDValue CC = Op.getOperand(2);
10551   MVT VT = Op.getSimpleValueType();
10552   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
10553   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
10554   SDLoc dl(Op);
10555
10556   if (isFP) {
10557 #ifndef NDEBUG
10558     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
10559     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
10560 #endif
10561
10562     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
10563     unsigned Opc = X86ISD::CMPP;
10564     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
10565       assert(VT.getVectorNumElements() <= 16);
10566       Opc = X86ISD::CMPM;
10567     }
10568     // In the two special cases we can't handle, emit two comparisons.
10569     if (SSECC == 8) {
10570       unsigned CC0, CC1;
10571       unsigned CombineOpc;
10572       if (SetCCOpcode == ISD::SETUEQ) {
10573         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
10574       } else {
10575         assert(SetCCOpcode == ISD::SETONE);
10576         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
10577       }
10578
10579       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10580                                  DAG.getConstant(CC0, MVT::i8));
10581       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
10582                                  DAG.getConstant(CC1, MVT::i8));
10583       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
10584     }
10585     // Handle all other FP comparisons here.
10586     return DAG.getNode(Opc, dl, VT, Op0, Op1,
10587                        DAG.getConstant(SSECC, MVT::i8));
10588   }
10589
10590   // Break 256-bit integer vector compare into smaller ones.
10591   if (VT.is256BitVector() && !Subtarget->hasInt256())
10592     return Lower256IntVSETCC(Op, DAG);
10593
10594   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
10595   EVT OpVT = Op1.getValueType();
10596   if (Subtarget->hasAVX512()) {
10597     if (Op1.getValueType().is512BitVector() ||
10598         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
10599       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
10600
10601     // In AVX-512 architecture setcc returns mask with i1 elements,
10602     // But there is no compare instruction for i8 and i16 elements.
10603     // We are not talking about 512-bit operands in this case, these
10604     // types are illegal.
10605     if (MaskResult &&
10606         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
10607          OpVT.getVectorElementType().getSizeInBits() >= 8))
10608       return DAG.getNode(ISD::TRUNCATE, dl, VT,
10609                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
10610   }
10611
10612   // We are handling one of the integer comparisons here.  Since SSE only has
10613   // GT and EQ comparisons for integer, swapping operands and multiple
10614   // operations may be required for some comparisons.
10615   unsigned Opc;
10616   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
10617   bool Subus = false;
10618
10619   switch (SetCCOpcode) {
10620   default: llvm_unreachable("Unexpected SETCC condition");
10621   case ISD::SETNE:  Invert = true;
10622   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
10623   case ISD::SETLT:  Swap = true;
10624   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
10625   case ISD::SETGE:  Swap = true;
10626   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
10627                     Invert = true; break;
10628   case ISD::SETULT: Swap = true;
10629   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
10630                     FlipSigns = true; break;
10631   case ISD::SETUGE: Swap = true;
10632   case ISD::SETULE: Opc = X86ISD::PCMPGT;
10633                     FlipSigns = true; Invert = true; break;
10634   }
10635
10636   // Special case: Use min/max operations for SETULE/SETUGE
10637   MVT VET = VT.getVectorElementType();
10638   bool hasMinMax =
10639        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
10640     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
10641
10642   if (hasMinMax) {
10643     switch (SetCCOpcode) {
10644     default: break;
10645     case ISD::SETULE: Opc = X86ISD::UMIN; MinMax = true; break;
10646     case ISD::SETUGE: Opc = X86ISD::UMAX; MinMax = true; break;
10647     }
10648
10649     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
10650   }
10651
10652   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
10653   if (!MinMax && hasSubus) {
10654     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
10655     // Op0 u<= Op1:
10656     //   t = psubus Op0, Op1
10657     //   pcmpeq t, <0..0>
10658     switch (SetCCOpcode) {
10659     default: break;
10660     case ISD::SETULT: {
10661       // If the comparison is against a constant we can turn this into a
10662       // setule.  With psubus, setule does not require a swap.  This is
10663       // beneficial because the constant in the register is no longer
10664       // destructed as the destination so it can be hoisted out of a loop.
10665       // Only do this pre-AVX since vpcmp* is no longer destructive.
10666       if (Subtarget->hasAVX())
10667         break;
10668       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
10669       if (ULEOp1.getNode()) {
10670         Op1 = ULEOp1;
10671         Subus = true; Invert = false; Swap = false;
10672       }
10673       break;
10674     }
10675     // Psubus is better than flip-sign because it requires no inversion.
10676     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
10677     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
10678     }
10679
10680     if (Subus) {
10681       Opc = X86ISD::SUBUS;
10682       FlipSigns = false;
10683     }
10684   }
10685
10686   if (Swap)
10687     std::swap(Op0, Op1);
10688
10689   // Check that the operation in question is available (most are plain SSE2,
10690   // but PCMPGTQ and PCMPEQQ have different requirements).
10691   if (VT == MVT::v2i64) {
10692     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
10693       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
10694
10695       // First cast everything to the right type.
10696       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10697       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10698
10699       // Since SSE has no unsigned integer comparisons, we need to flip the sign
10700       // bits of the inputs before performing those operations. The lower
10701       // compare is always unsigned.
10702       SDValue SB;
10703       if (FlipSigns) {
10704         SB = DAG.getConstant(0x80000000U, MVT::v4i32);
10705       } else {
10706         SDValue Sign = DAG.getConstant(0x80000000U, MVT::i32);
10707         SDValue Zero = DAG.getConstant(0x00000000U, MVT::i32);
10708         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
10709                          Sign, Zero, Sign, Zero);
10710       }
10711       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
10712       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
10713
10714       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
10715       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
10716       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
10717
10718       // Create masks for only the low parts/high parts of the 64 bit integers.
10719       static const int MaskHi[] = { 1, 1, 3, 3 };
10720       static const int MaskLo[] = { 0, 0, 2, 2 };
10721       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
10722       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
10723       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
10724
10725       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
10726       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
10727
10728       if (Invert)
10729         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10730
10731       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10732     }
10733
10734     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
10735       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
10736       // pcmpeqd + pshufd + pand.
10737       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
10738
10739       // First cast everything to the right type.
10740       Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op0);
10741       Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::v4i32, Op1);
10742
10743       // Do the compare.
10744       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
10745
10746       // Make sure the lower and upper halves are both all-ones.
10747       static const int Mask[] = { 1, 0, 3, 2 };
10748       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
10749       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
10750
10751       if (Invert)
10752         Result = DAG.getNOT(dl, Result, MVT::v4i32);
10753
10754       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
10755     }
10756   }
10757
10758   // Since SSE has no unsigned integer comparisons, we need to flip the sign
10759   // bits of the inputs before performing those operations.
10760   if (FlipSigns) {
10761     EVT EltVT = VT.getVectorElementType();
10762     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), VT);
10763     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
10764     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
10765   }
10766
10767   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
10768
10769   // If the logical-not of the result is required, perform that now.
10770   if (Invert)
10771     Result = DAG.getNOT(dl, Result, VT);
10772
10773   if (MinMax)
10774     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
10775
10776   if (Subus)
10777     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
10778                          getZeroVector(VT, Subtarget, DAG, dl));
10779
10780   return Result;
10781 }
10782
10783 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
10784
10785   MVT VT = Op.getSimpleValueType();
10786
10787   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
10788
10789   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
10790          && "SetCC type must be 8-bit or 1-bit integer");
10791   SDValue Op0 = Op.getOperand(0);
10792   SDValue Op1 = Op.getOperand(1);
10793   SDLoc dl(Op);
10794   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
10795
10796   // Optimize to BT if possible.
10797   // Lower (X & (1 << N)) == 0 to BT(X, N).
10798   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
10799   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
10800   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
10801       Op1.getOpcode() == ISD::Constant &&
10802       cast<ConstantSDNode>(Op1)->isNullValue() &&
10803       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10804     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
10805     if (NewSetCC.getNode())
10806       return NewSetCC;
10807   }
10808
10809   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
10810   // these.
10811   if (Op1.getOpcode() == ISD::Constant &&
10812       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
10813        cast<ConstantSDNode>(Op1)->isNullValue()) &&
10814       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10815
10816     // If the input is a setcc, then reuse the input setcc or use a new one with
10817     // the inverted condition.
10818     if (Op0.getOpcode() == X86ISD::SETCC) {
10819       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
10820       bool Invert = (CC == ISD::SETNE) ^
10821         cast<ConstantSDNode>(Op1)->isNullValue();
10822       if (!Invert)
10823         return Op0;
10824
10825       CCode = X86::GetOppositeBranchCondition(CCode);
10826       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10827                                   DAG.getConstant(CCode, MVT::i8),
10828                                   Op0.getOperand(1));
10829       if (VT == MVT::i1)
10830         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10831       return SetCC;
10832     }
10833   }
10834   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
10835       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
10836       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
10837
10838     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
10839     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, MVT::i1), NewCC);
10840   }
10841
10842   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
10843   unsigned X86CC = TranslateX86CC(CC, isFP, Op0, Op1, DAG);
10844   if (X86CC == X86::COND_INVALID)
10845     return SDValue();
10846
10847   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
10848   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
10849   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
10850                               DAG.getConstant(X86CC, MVT::i8), EFLAGS);
10851   if (VT == MVT::i1)
10852     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
10853   return SetCC;
10854 }
10855
10856 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
10857 static bool isX86LogicalCmp(SDValue Op) {
10858   unsigned Opc = Op.getNode()->getOpcode();
10859   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
10860       Opc == X86ISD::SAHF)
10861     return true;
10862   if (Op.getResNo() == 1 &&
10863       (Opc == X86ISD::ADD ||
10864        Opc == X86ISD::SUB ||
10865        Opc == X86ISD::ADC ||
10866        Opc == X86ISD::SBB ||
10867        Opc == X86ISD::SMUL ||
10868        Opc == X86ISD::UMUL ||
10869        Opc == X86ISD::INC ||
10870        Opc == X86ISD::DEC ||
10871        Opc == X86ISD::OR ||
10872        Opc == X86ISD::XOR ||
10873        Opc == X86ISD::AND))
10874     return true;
10875
10876   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
10877     return true;
10878
10879   return false;
10880 }
10881
10882 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
10883   if (V.getOpcode() != ISD::TRUNCATE)
10884     return false;
10885
10886   SDValue VOp0 = V.getOperand(0);
10887   unsigned InBits = VOp0.getValueSizeInBits();
10888   unsigned Bits = V.getValueSizeInBits();
10889   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
10890 }
10891
10892 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
10893   bool addTest = true;
10894   SDValue Cond  = Op.getOperand(0);
10895   SDValue Op1 = Op.getOperand(1);
10896   SDValue Op2 = Op.getOperand(2);
10897   SDLoc DL(Op);
10898   EVT VT = Op1.getValueType();
10899   SDValue CC;
10900
10901   // Lower fp selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
10902   // are available. Otherwise fp cmovs get lowered into a less efficient branch
10903   // sequence later on.
10904   if (Cond.getOpcode() == ISD::SETCC &&
10905       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
10906        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
10907       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
10908     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
10909     int SSECC = translateX86FSETCC(
10910         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
10911
10912     if (SSECC != 8) {
10913       if (Subtarget->hasAVX512()) {
10914         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
10915                                   DAG.getConstant(SSECC, MVT::i8));
10916         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
10917       }
10918       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
10919                                 DAG.getConstant(SSECC, MVT::i8));
10920       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
10921       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
10922       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
10923     }
10924   }
10925
10926   if (Cond.getOpcode() == ISD::SETCC) {
10927     SDValue NewCond = LowerSETCC(Cond, DAG);
10928     if (NewCond.getNode())
10929       Cond = NewCond;
10930   }
10931
10932   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
10933   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
10934   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
10935   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
10936   if (Cond.getOpcode() == X86ISD::SETCC &&
10937       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
10938       isZero(Cond.getOperand(1).getOperand(1))) {
10939     SDValue Cmp = Cond.getOperand(1);
10940
10941     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
10942
10943     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
10944         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
10945       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
10946
10947       SDValue CmpOp0 = Cmp.getOperand(0);
10948       // Apply further optimizations for special cases
10949       // (select (x != 0), -1, 0) -> neg & sbb
10950       // (select (x == 0), 0, -1) -> neg & sbb
10951       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
10952         if (YC->isNullValue() &&
10953             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
10954           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
10955           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
10956                                     DAG.getConstant(0, CmpOp0.getValueType()),
10957                                     CmpOp0);
10958           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10959                                     DAG.getConstant(X86::COND_B, MVT::i8),
10960                                     SDValue(Neg.getNode(), 1));
10961           return Res;
10962         }
10963
10964       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
10965                         CmpOp0, DAG.getConstant(1, CmpOp0.getValueType()));
10966       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
10967
10968       SDValue Res =   // Res = 0 or -1.
10969         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
10970                     DAG.getConstant(X86::COND_B, MVT::i8), Cmp);
10971
10972       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
10973         Res = DAG.getNOT(DL, Res, Res.getValueType());
10974
10975       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
10976       if (!N2C || !N2C->isNullValue())
10977         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
10978       return Res;
10979     }
10980   }
10981
10982   // Look past (and (setcc_carry (cmp ...)), 1).
10983   if (Cond.getOpcode() == ISD::AND &&
10984       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
10985     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
10986     if (C && C->getAPIntValue() == 1)
10987       Cond = Cond.getOperand(0);
10988   }
10989
10990   // If condition flag is set by a X86ISD::CMP, then use it as the condition
10991   // setting operand in place of the X86ISD::SETCC.
10992   unsigned CondOpcode = Cond.getOpcode();
10993   if (CondOpcode == X86ISD::SETCC ||
10994       CondOpcode == X86ISD::SETCC_CARRY) {
10995     CC = Cond.getOperand(0);
10996
10997     SDValue Cmp = Cond.getOperand(1);
10998     unsigned Opc = Cmp.getOpcode();
10999     MVT VT = Op.getSimpleValueType();
11000
11001     bool IllegalFPCMov = false;
11002     if (VT.isFloatingPoint() && !VT.isVector() &&
11003         !isScalarFPTypeInSSEReg(VT))  // FPStack?
11004       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
11005
11006     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
11007         Opc == X86ISD::BT) { // FIXME
11008       Cond = Cmp;
11009       addTest = false;
11010     }
11011   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11012              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11013              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11014               Cond.getOperand(0).getValueType() != MVT::i8)) {
11015     SDValue LHS = Cond.getOperand(0);
11016     SDValue RHS = Cond.getOperand(1);
11017     unsigned X86Opcode;
11018     unsigned X86Cond;
11019     SDVTList VTs;
11020     switch (CondOpcode) {
11021     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11022     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11023     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11024     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11025     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11026     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11027     default: llvm_unreachable("unexpected overflowing operator");
11028     }
11029     if (CondOpcode == ISD::UMULO)
11030       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11031                           MVT::i32);
11032     else
11033       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11034
11035     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
11036
11037     if (CondOpcode == ISD::UMULO)
11038       Cond = X86Op.getValue(2);
11039     else
11040       Cond = X86Op.getValue(1);
11041
11042     CC = DAG.getConstant(X86Cond, MVT::i8);
11043     addTest = false;
11044   }
11045
11046   if (addTest) {
11047     // Look pass the truncate if the high bits are known zero.
11048     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11049         Cond = Cond.getOperand(0);
11050
11051     // We know the result of AND is compared against zero. Try to match
11052     // it to BT.
11053     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11054       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
11055       if (NewSetCC.getNode()) {
11056         CC = NewSetCC.getOperand(0);
11057         Cond = NewSetCC.getOperand(1);
11058         addTest = false;
11059       }
11060     }
11061   }
11062
11063   if (addTest) {
11064     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11065     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
11066   }
11067
11068   // a <  b ? -1 :  0 -> RES = ~setcc_carry
11069   // a <  b ?  0 : -1 -> RES = setcc_carry
11070   // a >= b ? -1 :  0 -> RES = setcc_carry
11071   // a >= b ?  0 : -1 -> RES = ~setcc_carry
11072   if (Cond.getOpcode() == X86ISD::SUB) {
11073     Cond = ConvertCmpIfNecessary(Cond, DAG);
11074     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
11075
11076     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
11077         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
11078       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
11079                                 DAG.getConstant(X86::COND_B, MVT::i8), Cond);
11080       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
11081         return DAG.getNOT(DL, Res, Res.getValueType());
11082       return Res;
11083     }
11084   }
11085
11086   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
11087   // widen the cmov and push the truncate through. This avoids introducing a new
11088   // branch during isel and doesn't add any extensions.
11089   if (Op.getValueType() == MVT::i8 &&
11090       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
11091     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
11092     if (T1.getValueType() == T2.getValueType() &&
11093         // Blacklist CopyFromReg to avoid partial register stalls.
11094         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
11095       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
11096       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
11097       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
11098     }
11099   }
11100
11101   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
11102   // condition is true.
11103   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
11104   SDValue Ops[] = { Op2, Op1, CC, Cond };
11105   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
11106 }
11107
11108 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op, SelectionDAG &DAG) {
11109   MVT VT = Op->getSimpleValueType(0);
11110   SDValue In = Op->getOperand(0);
11111   MVT InVT = In.getSimpleValueType();
11112   SDLoc dl(Op);
11113
11114   unsigned int NumElts = VT.getVectorNumElements();
11115   if (NumElts != 8 && NumElts != 16)
11116     return SDValue();
11117
11118   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
11119     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11120
11121   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11122   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
11123
11124   MVT ExtVT = (NumElts == 8) ? MVT::v8i64 : MVT::v16i32;
11125   Constant *C = ConstantInt::get(*DAG.getContext(),
11126     APInt::getAllOnesValue(ExtVT.getScalarType().getSizeInBits()));
11127
11128   SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
11129   unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
11130   SDValue Ld = DAG.getLoad(ExtVT.getScalarType(), dl, DAG.getEntryNode(), CP,
11131                           MachinePointerInfo::getConstantPool(),
11132                           false, false, false, Alignment);
11133   SDValue Brcst = DAG.getNode(X86ISD::VBROADCASTM, dl, ExtVT, In, Ld);
11134   if (VT.is512BitVector())
11135     return Brcst;
11136   return DAG.getNode(X86ISD::VTRUNC, dl, VT, Brcst);
11137 }
11138
11139 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
11140                                 SelectionDAG &DAG) {
11141   MVT VT = Op->getSimpleValueType(0);
11142   SDValue In = Op->getOperand(0);
11143   MVT InVT = In.getSimpleValueType();
11144   SDLoc dl(Op);
11145
11146   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
11147     return LowerSIGN_EXTEND_AVX512(Op, DAG);
11148
11149   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
11150       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
11151       (VT != MVT::v16i16 || InVT != MVT::v16i8))
11152     return SDValue();
11153
11154   if (Subtarget->hasInt256())
11155     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
11156
11157   // Optimize vectors in AVX mode
11158   // Sign extend  v8i16 to v8i32 and
11159   //              v4i32 to v4i64
11160   //
11161   // Divide input vector into two parts
11162   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
11163   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
11164   // concat the vectors to original VT
11165
11166   unsigned NumElems = InVT.getVectorNumElements();
11167   SDValue Undef = DAG.getUNDEF(InVT);
11168
11169   SmallVector<int,8> ShufMask1(NumElems, -1);
11170   for (unsigned i = 0; i != NumElems/2; ++i)
11171     ShufMask1[i] = i;
11172
11173   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
11174
11175   SmallVector<int,8> ShufMask2(NumElems, -1);
11176   for (unsigned i = 0; i != NumElems/2; ++i)
11177     ShufMask2[i] = i + NumElems/2;
11178
11179   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
11180
11181   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
11182                                 VT.getVectorNumElements()/2);
11183
11184   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
11185   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
11186
11187   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
11188 }
11189
11190 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
11191 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
11192 // from the AND / OR.
11193 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
11194   Opc = Op.getOpcode();
11195   if (Opc != ISD::OR && Opc != ISD::AND)
11196     return false;
11197   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11198           Op.getOperand(0).hasOneUse() &&
11199           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
11200           Op.getOperand(1).hasOneUse());
11201 }
11202
11203 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
11204 // 1 and that the SETCC node has a single use.
11205 static bool isXor1OfSetCC(SDValue Op) {
11206   if (Op.getOpcode() != ISD::XOR)
11207     return false;
11208   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11209   if (N1C && N1C->getAPIntValue() == 1) {
11210     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
11211       Op.getOperand(0).hasOneUse();
11212   }
11213   return false;
11214 }
11215
11216 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
11217   bool addTest = true;
11218   SDValue Chain = Op.getOperand(0);
11219   SDValue Cond  = Op.getOperand(1);
11220   SDValue Dest  = Op.getOperand(2);
11221   SDLoc dl(Op);
11222   SDValue CC;
11223   bool Inverted = false;
11224
11225   if (Cond.getOpcode() == ISD::SETCC) {
11226     // Check for setcc([su]{add,sub,mul}o == 0).
11227     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
11228         isa<ConstantSDNode>(Cond.getOperand(1)) &&
11229         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
11230         Cond.getOperand(0).getResNo() == 1 &&
11231         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
11232          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
11233          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
11234          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
11235          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
11236          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
11237       Inverted = true;
11238       Cond = Cond.getOperand(0);
11239     } else {
11240       SDValue NewCond = LowerSETCC(Cond, DAG);
11241       if (NewCond.getNode())
11242         Cond = NewCond;
11243     }
11244   }
11245 #if 0
11246   // FIXME: LowerXALUO doesn't handle these!!
11247   else if (Cond.getOpcode() == X86ISD::ADD  ||
11248            Cond.getOpcode() == X86ISD::SUB  ||
11249            Cond.getOpcode() == X86ISD::SMUL ||
11250            Cond.getOpcode() == X86ISD::UMUL)
11251     Cond = LowerXALUO(Cond, DAG);
11252 #endif
11253
11254   // Look pass (and (setcc_carry (cmp ...)), 1).
11255   if (Cond.getOpcode() == ISD::AND &&
11256       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
11257     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
11258     if (C && C->getAPIntValue() == 1)
11259       Cond = Cond.getOperand(0);
11260   }
11261
11262   // If condition flag is set by a X86ISD::CMP, then use it as the condition
11263   // setting operand in place of the X86ISD::SETCC.
11264   unsigned CondOpcode = Cond.getOpcode();
11265   if (CondOpcode == X86ISD::SETCC ||
11266       CondOpcode == X86ISD::SETCC_CARRY) {
11267     CC = Cond.getOperand(0);
11268
11269     SDValue Cmp = Cond.getOperand(1);
11270     unsigned Opc = Cmp.getOpcode();
11271     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
11272     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
11273       Cond = Cmp;
11274       addTest = false;
11275     } else {
11276       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
11277       default: break;
11278       case X86::COND_O:
11279       case X86::COND_B:
11280         // These can only come from an arithmetic instruction with overflow,
11281         // e.g. SADDO, UADDO.
11282         Cond = Cond.getNode()->getOperand(1);
11283         addTest = false;
11284         break;
11285       }
11286     }
11287   }
11288   CondOpcode = Cond.getOpcode();
11289   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
11290       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
11291       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
11292        Cond.getOperand(0).getValueType() != MVT::i8)) {
11293     SDValue LHS = Cond.getOperand(0);
11294     SDValue RHS = Cond.getOperand(1);
11295     unsigned X86Opcode;
11296     unsigned X86Cond;
11297     SDVTList VTs;
11298     // Keep this in sync with LowerXALUO, otherwise we might create redundant
11299     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
11300     // X86ISD::INC).
11301     switch (CondOpcode) {
11302     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
11303     case ISD::SADDO:
11304       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11305         if (C->isOne()) {
11306           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
11307           break;
11308         }
11309       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
11310     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
11311     case ISD::SSUBO:
11312       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
11313         if (C->isOne()) {
11314           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
11315           break;
11316         }
11317       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
11318     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
11319     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
11320     default: llvm_unreachable("unexpected overflowing operator");
11321     }
11322     if (Inverted)
11323       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
11324     if (CondOpcode == ISD::UMULO)
11325       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
11326                           MVT::i32);
11327     else
11328       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
11329
11330     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
11331
11332     if (CondOpcode == ISD::UMULO)
11333       Cond = X86Op.getValue(2);
11334     else
11335       Cond = X86Op.getValue(1);
11336
11337     CC = DAG.getConstant(X86Cond, MVT::i8);
11338     addTest = false;
11339   } else {
11340     unsigned CondOpc;
11341     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
11342       SDValue Cmp = Cond.getOperand(0).getOperand(1);
11343       if (CondOpc == ISD::OR) {
11344         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
11345         // two branches instead of an explicit OR instruction with a
11346         // separate test.
11347         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11348             isX86LogicalCmp(Cmp)) {
11349           CC = Cond.getOperand(0).getOperand(0);
11350           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11351                               Chain, Dest, CC, Cmp);
11352           CC = Cond.getOperand(1).getOperand(0);
11353           Cond = Cmp;
11354           addTest = false;
11355         }
11356       } else { // ISD::AND
11357         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
11358         // two branches instead of an explicit AND instruction with a
11359         // separate test. However, we only do this if this block doesn't
11360         // have a fall-through edge, because this requires an explicit
11361         // jmp when the condition is false.
11362         if (Cmp == Cond.getOperand(1).getOperand(1) &&
11363             isX86LogicalCmp(Cmp) &&
11364             Op.getNode()->hasOneUse()) {
11365           X86::CondCode CCode =
11366             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11367           CCode = X86::GetOppositeBranchCondition(CCode);
11368           CC = DAG.getConstant(CCode, MVT::i8);
11369           SDNode *User = *Op.getNode()->use_begin();
11370           // Look for an unconditional branch following this conditional branch.
11371           // We need this because we need to reverse the successors in order
11372           // to implement FCMP_OEQ.
11373           if (User->getOpcode() == ISD::BR) {
11374             SDValue FalseBB = User->getOperand(1);
11375             SDNode *NewBR =
11376               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11377             assert(NewBR == User);
11378             (void)NewBR;
11379             Dest = FalseBB;
11380
11381             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11382                                 Chain, Dest, CC, Cmp);
11383             X86::CondCode CCode =
11384               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
11385             CCode = X86::GetOppositeBranchCondition(CCode);
11386             CC = DAG.getConstant(CCode, MVT::i8);
11387             Cond = Cmp;
11388             addTest = false;
11389           }
11390         }
11391       }
11392     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
11393       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
11394       // It should be transformed during dag combiner except when the condition
11395       // is set by a arithmetics with overflow node.
11396       X86::CondCode CCode =
11397         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
11398       CCode = X86::GetOppositeBranchCondition(CCode);
11399       CC = DAG.getConstant(CCode, MVT::i8);
11400       Cond = Cond.getOperand(0).getOperand(1);
11401       addTest = false;
11402     } else if (Cond.getOpcode() == ISD::SETCC &&
11403                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
11404       // For FCMP_OEQ, we can emit
11405       // two branches instead of an explicit AND instruction with a
11406       // separate test. However, we only do this if this block doesn't
11407       // have a fall-through edge, because this requires an explicit
11408       // jmp when the condition is false.
11409       if (Op.getNode()->hasOneUse()) {
11410         SDNode *User = *Op.getNode()->use_begin();
11411         // Look for an unconditional branch following this conditional branch.
11412         // We need this because we need to reverse the successors in order
11413         // to implement FCMP_OEQ.
11414         if (User->getOpcode() == ISD::BR) {
11415           SDValue FalseBB = User->getOperand(1);
11416           SDNode *NewBR =
11417             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11418           assert(NewBR == User);
11419           (void)NewBR;
11420           Dest = FalseBB;
11421
11422           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11423                                     Cond.getOperand(0), Cond.getOperand(1));
11424           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11425           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11426           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11427                               Chain, Dest, CC, Cmp);
11428           CC = DAG.getConstant(X86::COND_P, MVT::i8);
11429           Cond = Cmp;
11430           addTest = false;
11431         }
11432       }
11433     } else if (Cond.getOpcode() == ISD::SETCC &&
11434                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
11435       // For FCMP_UNE, we can emit
11436       // two branches instead of an explicit AND instruction with a
11437       // separate test. However, we only do this if this block doesn't
11438       // have a fall-through edge, because this requires an explicit
11439       // jmp when the condition is false.
11440       if (Op.getNode()->hasOneUse()) {
11441         SDNode *User = *Op.getNode()->use_begin();
11442         // Look for an unconditional branch following this conditional branch.
11443         // We need this because we need to reverse the successors in order
11444         // to implement FCMP_UNE.
11445         if (User->getOpcode() == ISD::BR) {
11446           SDValue FalseBB = User->getOperand(1);
11447           SDNode *NewBR =
11448             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
11449           assert(NewBR == User);
11450           (void)NewBR;
11451
11452           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11453                                     Cond.getOperand(0), Cond.getOperand(1));
11454           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
11455           CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11456           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11457                               Chain, Dest, CC, Cmp);
11458           CC = DAG.getConstant(X86::COND_NP, MVT::i8);
11459           Cond = Cmp;
11460           addTest = false;
11461           Dest = FalseBB;
11462         }
11463       }
11464     }
11465   }
11466
11467   if (addTest) {
11468     // Look pass the truncate if the high bits are known zero.
11469     if (isTruncWithZeroHighBitsInput(Cond, DAG))
11470         Cond = Cond.getOperand(0);
11471
11472     // We know the result of AND is compared against zero. Try to match
11473     // it to BT.
11474     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
11475       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
11476       if (NewSetCC.getNode()) {
11477         CC = NewSetCC.getOperand(0);
11478         Cond = NewSetCC.getOperand(1);
11479         addTest = false;
11480       }
11481     }
11482   }
11483
11484   if (addTest) {
11485     CC = DAG.getConstant(X86::COND_NE, MVT::i8);
11486     Cond = EmitTest(Cond, X86::COND_NE, dl, DAG);
11487   }
11488   Cond = ConvertCmpIfNecessary(Cond, DAG);
11489   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
11490                      Chain, Dest, CC, Cond);
11491 }
11492
11493 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
11494 // Calls to _alloca is needed to probe the stack when allocating more than 4k
11495 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
11496 // that the guard pages used by the OS virtual memory manager are allocated in
11497 // correct sequence.
11498 SDValue
11499 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
11500                                            SelectionDAG &DAG) const {
11501   MachineFunction &MF = DAG.getMachineFunction();
11502   bool SplitStack = MF.shouldSplitStack();
11503   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMacho()) ||
11504                SplitStack;
11505   SDLoc dl(Op);
11506
11507   if (!Lower) {
11508     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11509     SDNode* Node = Op.getNode();
11510
11511     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
11512     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
11513         " not tell us which reg is the stack pointer!");
11514     EVT VT = Node->getValueType(0);
11515     SDValue Tmp1 = SDValue(Node, 0);
11516     SDValue Tmp2 = SDValue(Node, 1);
11517     SDValue Tmp3 = Node->getOperand(2);
11518     SDValue Chain = Tmp1.getOperand(0);
11519
11520     // Chain the dynamic stack allocation so that it doesn't modify the stack
11521     // pointer when other instructions are using the stack.
11522     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true),
11523         SDLoc(Node));
11524
11525     SDValue Size = Tmp2.getOperand(1);
11526     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
11527     Chain = SP.getValue(1);
11528     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
11529     const TargetFrameLowering &TFI = *getTargetMachine().getFrameLowering();
11530     unsigned StackAlign = TFI.getStackAlignment();
11531     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
11532     if (Align > StackAlign)
11533       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
11534           DAG.getConstant(-(uint64_t)Align, VT));
11535     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
11536
11537     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, true),
11538         DAG.getIntPtrConstant(0, true), SDValue(),
11539         SDLoc(Node));
11540
11541     SDValue Ops[2] = { Tmp1, Tmp2 };
11542     return DAG.getMergeValues(Ops, dl);
11543   }
11544
11545   // Get the inputs.
11546   SDValue Chain = Op.getOperand(0);
11547   SDValue Size  = Op.getOperand(1);
11548   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
11549   EVT VT = Op.getNode()->getValueType(0);
11550
11551   bool Is64Bit = Subtarget->is64Bit();
11552   EVT SPTy = Is64Bit ? MVT::i64 : MVT::i32;
11553
11554   if (SplitStack) {
11555     MachineRegisterInfo &MRI = MF.getRegInfo();
11556
11557     if (Is64Bit) {
11558       // The 64 bit implementation of segmented stacks needs to clobber both r10
11559       // r11. This makes it impossible to use it along with nested parameters.
11560       const Function *F = MF.getFunction();
11561
11562       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
11563            I != E; ++I)
11564         if (I->hasNestAttr())
11565           report_fatal_error("Cannot use segmented stacks with functions that "
11566                              "have nested arguments.");
11567     }
11568
11569     const TargetRegisterClass *AddrRegClass =
11570       getRegClassFor(Subtarget->is64Bit() ? MVT::i64:MVT::i32);
11571     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
11572     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
11573     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
11574                                 DAG.getRegister(Vreg, SPTy));
11575     SDValue Ops1[2] = { Value, Chain };
11576     return DAG.getMergeValues(Ops1, dl);
11577   } else {
11578     SDValue Flag;
11579     unsigned Reg = (Subtarget->is64Bit() ? X86::RAX : X86::EAX);
11580
11581     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
11582     Flag = Chain.getValue(1);
11583     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11584
11585     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
11586
11587     const X86RegisterInfo *RegInfo =
11588       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
11589     unsigned SPReg = RegInfo->getStackRegister();
11590     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
11591     Chain = SP.getValue(1);
11592
11593     if (Align) {
11594       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
11595                        DAG.getConstant(-(uint64_t)Align, VT));
11596       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
11597     }
11598
11599     SDValue Ops1[2] = { SP, Chain };
11600     return DAG.getMergeValues(Ops1, dl);
11601   }
11602 }
11603
11604 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
11605   MachineFunction &MF = DAG.getMachineFunction();
11606   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
11607
11608   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11609   SDLoc DL(Op);
11610
11611   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
11612     // vastart just stores the address of the VarArgsFrameIndex slot into the
11613     // memory location argument.
11614     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11615                                    getPointerTy());
11616     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
11617                         MachinePointerInfo(SV), false, false, 0);
11618   }
11619
11620   // __va_list_tag:
11621   //   gp_offset         (0 - 6 * 8)
11622   //   fp_offset         (48 - 48 + 8 * 16)
11623   //   overflow_arg_area (point to parameters coming in memory).
11624   //   reg_save_area
11625   SmallVector<SDValue, 8> MemOps;
11626   SDValue FIN = Op.getOperand(1);
11627   // Store gp_offset
11628   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
11629                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
11630                                                MVT::i32),
11631                                FIN, MachinePointerInfo(SV), false, false, 0);
11632   MemOps.push_back(Store);
11633
11634   // Store fp_offset
11635   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11636                     FIN, DAG.getIntPtrConstant(4));
11637   Store = DAG.getStore(Op.getOperand(0), DL,
11638                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(),
11639                                        MVT::i32),
11640                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
11641   MemOps.push_back(Store);
11642
11643   // Store ptr to overflow_arg_area
11644   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11645                     FIN, DAG.getIntPtrConstant(4));
11646   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
11647                                     getPointerTy());
11648   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
11649                        MachinePointerInfo(SV, 8),
11650                        false, false, 0);
11651   MemOps.push_back(Store);
11652
11653   // Store ptr to reg_save_area.
11654   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11655                     FIN, DAG.getIntPtrConstant(8));
11656   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
11657                                     getPointerTy());
11658   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
11659                        MachinePointerInfo(SV, 16), false, false, 0);
11660   MemOps.push_back(Store);
11661   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
11662 }
11663
11664 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
11665   assert(Subtarget->is64Bit() &&
11666          "LowerVAARG only handles 64-bit va_arg!");
11667   assert((Subtarget->isTargetLinux() ||
11668           Subtarget->isTargetDarwin()) &&
11669           "Unhandled target in LowerVAARG");
11670   assert(Op.getNode()->getNumOperands() == 4);
11671   SDValue Chain = Op.getOperand(0);
11672   SDValue SrcPtr = Op.getOperand(1);
11673   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
11674   unsigned Align = Op.getConstantOperandVal(3);
11675   SDLoc dl(Op);
11676
11677   EVT ArgVT = Op.getNode()->getValueType(0);
11678   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
11679   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
11680   uint8_t ArgMode;
11681
11682   // Decide which area this value should be read from.
11683   // TODO: Implement the AMD64 ABI in its entirety. This simple
11684   // selection mechanism works only for the basic types.
11685   if (ArgVT == MVT::f80) {
11686     llvm_unreachable("va_arg for f80 not yet implemented");
11687   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
11688     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
11689   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
11690     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
11691   } else {
11692     llvm_unreachable("Unhandled argument type in LowerVAARG");
11693   }
11694
11695   if (ArgMode == 2) {
11696     // Sanity Check: Make sure using fp_offset makes sense.
11697     assert(!getTargetMachine().Options.UseSoftFloat &&
11698            !(DAG.getMachineFunction()
11699                 .getFunction()->getAttributes()
11700                 .hasAttribute(AttributeSet::FunctionIndex,
11701                               Attribute::NoImplicitFloat)) &&
11702            Subtarget->hasSSE1());
11703   }
11704
11705   // Insert VAARG_64 node into the DAG
11706   // VAARG_64 returns two values: Variable Argument Address, Chain
11707   SmallVector<SDValue, 11> InstOps;
11708   InstOps.push_back(Chain);
11709   InstOps.push_back(SrcPtr);
11710   InstOps.push_back(DAG.getConstant(ArgSize, MVT::i32));
11711   InstOps.push_back(DAG.getConstant(ArgMode, MVT::i8));
11712   InstOps.push_back(DAG.getConstant(Align, MVT::i32));
11713   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
11714   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
11715                                           VTs, InstOps, MVT::i64,
11716                                           MachinePointerInfo(SV),
11717                                           /*Align=*/0,
11718                                           /*Volatile=*/false,
11719                                           /*ReadMem=*/true,
11720                                           /*WriteMem=*/true);
11721   Chain = VAARG.getValue(1);
11722
11723   // Load the next argument and return it
11724   return DAG.getLoad(ArgVT, dl,
11725                      Chain,
11726                      VAARG,
11727                      MachinePointerInfo(),
11728                      false, false, false, 0);
11729 }
11730
11731 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
11732                            SelectionDAG &DAG) {
11733   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
11734   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
11735   SDValue Chain = Op.getOperand(0);
11736   SDValue DstPtr = Op.getOperand(1);
11737   SDValue SrcPtr = Op.getOperand(2);
11738   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
11739   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
11740   SDLoc DL(Op);
11741
11742   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
11743                        DAG.getIntPtrConstant(24), 8, /*isVolatile*/false,
11744                        false,
11745                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
11746 }
11747
11748 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
11749 // amount is a constant. Takes immediate version of shift as input.
11750 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
11751                                           SDValue SrcOp, uint64_t ShiftAmt,
11752                                           SelectionDAG &DAG) {
11753   MVT ElementType = VT.getVectorElementType();
11754
11755   // Fold this packed shift into its first operand if ShiftAmt is 0.
11756   if (ShiftAmt == 0)
11757     return SrcOp;
11758
11759   // Check for ShiftAmt >= element width
11760   if (ShiftAmt >= ElementType.getSizeInBits()) {
11761     if (Opc == X86ISD::VSRAI)
11762       ShiftAmt = ElementType.getSizeInBits() - 1;
11763     else
11764       return DAG.getConstant(0, VT);
11765   }
11766
11767   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
11768          && "Unknown target vector shift-by-constant node");
11769
11770   // Fold this packed vector shift into a build vector if SrcOp is a
11771   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
11772   if (VT == SrcOp.getSimpleValueType() &&
11773       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
11774     SmallVector<SDValue, 8> Elts;
11775     unsigned NumElts = SrcOp->getNumOperands();
11776     ConstantSDNode *ND;
11777
11778     switch(Opc) {
11779     default: llvm_unreachable(nullptr);
11780     case X86ISD::VSHLI:
11781       for (unsigned i=0; i!=NumElts; ++i) {
11782         SDValue CurrentOp = SrcOp->getOperand(i);
11783         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11784           Elts.push_back(CurrentOp);
11785           continue;
11786         }
11787         ND = cast<ConstantSDNode>(CurrentOp);
11788         const APInt &C = ND->getAPIntValue();
11789         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), ElementType));
11790       }
11791       break;
11792     case X86ISD::VSRLI:
11793       for (unsigned i=0; i!=NumElts; ++i) {
11794         SDValue CurrentOp = SrcOp->getOperand(i);
11795         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11796           Elts.push_back(CurrentOp);
11797           continue;
11798         }
11799         ND = cast<ConstantSDNode>(CurrentOp);
11800         const APInt &C = ND->getAPIntValue();
11801         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), ElementType));
11802       }
11803       break;
11804     case X86ISD::VSRAI:
11805       for (unsigned i=0; i!=NumElts; ++i) {
11806         SDValue CurrentOp = SrcOp->getOperand(i);
11807         if (CurrentOp->getOpcode() == ISD::UNDEF) {
11808           Elts.push_back(CurrentOp);
11809           continue;
11810         }
11811         ND = cast<ConstantSDNode>(CurrentOp);
11812         const APInt &C = ND->getAPIntValue();
11813         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), ElementType));
11814       }
11815       break;
11816     }
11817
11818     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
11819   }
11820
11821   return DAG.getNode(Opc, dl, VT, SrcOp, DAG.getConstant(ShiftAmt, MVT::i8));
11822 }
11823
11824 // getTargetVShiftNode - Handle vector element shifts where the shift amount
11825 // may or may not be a constant. Takes immediate version of shift as input.
11826 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
11827                                    SDValue SrcOp, SDValue ShAmt,
11828                                    SelectionDAG &DAG) {
11829   assert(ShAmt.getValueType() == MVT::i32 && "ShAmt is not i32");
11830
11831   // Catch shift-by-constant.
11832   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
11833     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
11834                                       CShAmt->getZExtValue(), DAG);
11835
11836   // Change opcode to non-immediate version
11837   switch (Opc) {
11838     default: llvm_unreachable("Unknown target vector shift node");
11839     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
11840     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
11841     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
11842   }
11843
11844   // Need to build a vector containing shift amount
11845   // Shift amount is 32-bits, but SSE instructions read 64-bit, so fill with 0
11846   SDValue ShOps[4];
11847   ShOps[0] = ShAmt;
11848   ShOps[1] = DAG.getConstant(0, MVT::i32);
11849   ShOps[2] = ShOps[3] = DAG.getUNDEF(MVT::i32);
11850   ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, ShOps);
11851
11852   // The return type has to be a 128-bit type with the same element
11853   // type as the input type.
11854   MVT EltVT = VT.getVectorElementType();
11855   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
11856
11857   ShAmt = DAG.getNode(ISD::BITCAST, dl, ShVT, ShAmt);
11858   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
11859 }
11860
11861 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, SelectionDAG &DAG) {
11862   SDLoc dl(Op);
11863   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
11864   switch (IntNo) {
11865   default: return SDValue();    // Don't custom lower most intrinsics.
11866   // Comparison intrinsics.
11867   case Intrinsic::x86_sse_comieq_ss:
11868   case Intrinsic::x86_sse_comilt_ss:
11869   case Intrinsic::x86_sse_comile_ss:
11870   case Intrinsic::x86_sse_comigt_ss:
11871   case Intrinsic::x86_sse_comige_ss:
11872   case Intrinsic::x86_sse_comineq_ss:
11873   case Intrinsic::x86_sse_ucomieq_ss:
11874   case Intrinsic::x86_sse_ucomilt_ss:
11875   case Intrinsic::x86_sse_ucomile_ss:
11876   case Intrinsic::x86_sse_ucomigt_ss:
11877   case Intrinsic::x86_sse_ucomige_ss:
11878   case Intrinsic::x86_sse_ucomineq_ss:
11879   case Intrinsic::x86_sse2_comieq_sd:
11880   case Intrinsic::x86_sse2_comilt_sd:
11881   case Intrinsic::x86_sse2_comile_sd:
11882   case Intrinsic::x86_sse2_comigt_sd:
11883   case Intrinsic::x86_sse2_comige_sd:
11884   case Intrinsic::x86_sse2_comineq_sd:
11885   case Intrinsic::x86_sse2_ucomieq_sd:
11886   case Intrinsic::x86_sse2_ucomilt_sd:
11887   case Intrinsic::x86_sse2_ucomile_sd:
11888   case Intrinsic::x86_sse2_ucomigt_sd:
11889   case Intrinsic::x86_sse2_ucomige_sd:
11890   case Intrinsic::x86_sse2_ucomineq_sd: {
11891     unsigned Opc;
11892     ISD::CondCode CC;
11893     switch (IntNo) {
11894     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
11895     case Intrinsic::x86_sse_comieq_ss:
11896     case Intrinsic::x86_sse2_comieq_sd:
11897       Opc = X86ISD::COMI;
11898       CC = ISD::SETEQ;
11899       break;
11900     case Intrinsic::x86_sse_comilt_ss:
11901     case Intrinsic::x86_sse2_comilt_sd:
11902       Opc = X86ISD::COMI;
11903       CC = ISD::SETLT;
11904       break;
11905     case Intrinsic::x86_sse_comile_ss:
11906     case Intrinsic::x86_sse2_comile_sd:
11907       Opc = X86ISD::COMI;
11908       CC = ISD::SETLE;
11909       break;
11910     case Intrinsic::x86_sse_comigt_ss:
11911     case Intrinsic::x86_sse2_comigt_sd:
11912       Opc = X86ISD::COMI;
11913       CC = ISD::SETGT;
11914       break;
11915     case Intrinsic::x86_sse_comige_ss:
11916     case Intrinsic::x86_sse2_comige_sd:
11917       Opc = X86ISD::COMI;
11918       CC = ISD::SETGE;
11919       break;
11920     case Intrinsic::x86_sse_comineq_ss:
11921     case Intrinsic::x86_sse2_comineq_sd:
11922       Opc = X86ISD::COMI;
11923       CC = ISD::SETNE;
11924       break;
11925     case Intrinsic::x86_sse_ucomieq_ss:
11926     case Intrinsic::x86_sse2_ucomieq_sd:
11927       Opc = X86ISD::UCOMI;
11928       CC = ISD::SETEQ;
11929       break;
11930     case Intrinsic::x86_sse_ucomilt_ss:
11931     case Intrinsic::x86_sse2_ucomilt_sd:
11932       Opc = X86ISD::UCOMI;
11933       CC = ISD::SETLT;
11934       break;
11935     case Intrinsic::x86_sse_ucomile_ss:
11936     case Intrinsic::x86_sse2_ucomile_sd:
11937       Opc = X86ISD::UCOMI;
11938       CC = ISD::SETLE;
11939       break;
11940     case Intrinsic::x86_sse_ucomigt_ss:
11941     case Intrinsic::x86_sse2_ucomigt_sd:
11942       Opc = X86ISD::UCOMI;
11943       CC = ISD::SETGT;
11944       break;
11945     case Intrinsic::x86_sse_ucomige_ss:
11946     case Intrinsic::x86_sse2_ucomige_sd:
11947       Opc = X86ISD::UCOMI;
11948       CC = ISD::SETGE;
11949       break;
11950     case Intrinsic::x86_sse_ucomineq_ss:
11951     case Intrinsic::x86_sse2_ucomineq_sd:
11952       Opc = X86ISD::UCOMI;
11953       CC = ISD::SETNE;
11954       break;
11955     }
11956
11957     SDValue LHS = Op.getOperand(1);
11958     SDValue RHS = Op.getOperand(2);
11959     unsigned X86CC = TranslateX86CC(CC, true, LHS, RHS, DAG);
11960     assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
11961     SDValue Cond = DAG.getNode(Opc, dl, MVT::i32, LHS, RHS);
11962     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
11963                                 DAG.getConstant(X86CC, MVT::i8), Cond);
11964     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
11965   }
11966
11967   // Arithmetic intrinsics.
11968   case Intrinsic::x86_sse2_pmulu_dq:
11969   case Intrinsic::x86_avx2_pmulu_dq:
11970     return DAG.getNode(X86ISD::PMULUDQ, dl, Op.getValueType(),
11971                        Op.getOperand(1), Op.getOperand(2));
11972
11973   case Intrinsic::x86_sse41_pmuldq:
11974   case Intrinsic::x86_avx2_pmul_dq:
11975     return DAG.getNode(X86ISD::PMULDQ, dl, Op.getValueType(),
11976                        Op.getOperand(1), Op.getOperand(2));
11977
11978   case Intrinsic::x86_sse2_pmulhu_w:
11979   case Intrinsic::x86_avx2_pmulhu_w:
11980     return DAG.getNode(ISD::MULHU, dl, Op.getValueType(),
11981                        Op.getOperand(1), Op.getOperand(2));
11982
11983   case Intrinsic::x86_sse2_pmulh_w:
11984   case Intrinsic::x86_avx2_pmulh_w:
11985     return DAG.getNode(ISD::MULHS, dl, Op.getValueType(),
11986                        Op.getOperand(1), Op.getOperand(2));
11987
11988   // SSE2/AVX2 sub with unsigned saturation intrinsics
11989   case Intrinsic::x86_sse2_psubus_b:
11990   case Intrinsic::x86_sse2_psubus_w:
11991   case Intrinsic::x86_avx2_psubus_b:
11992   case Intrinsic::x86_avx2_psubus_w:
11993     return DAG.getNode(X86ISD::SUBUS, dl, Op.getValueType(),
11994                        Op.getOperand(1), Op.getOperand(2));
11995
11996   // SSE3/AVX horizontal add/sub intrinsics
11997   case Intrinsic::x86_sse3_hadd_ps:
11998   case Intrinsic::x86_sse3_hadd_pd:
11999   case Intrinsic::x86_avx_hadd_ps_256:
12000   case Intrinsic::x86_avx_hadd_pd_256:
12001   case Intrinsic::x86_sse3_hsub_ps:
12002   case Intrinsic::x86_sse3_hsub_pd:
12003   case Intrinsic::x86_avx_hsub_ps_256:
12004   case Intrinsic::x86_avx_hsub_pd_256:
12005   case Intrinsic::x86_ssse3_phadd_w_128:
12006   case Intrinsic::x86_ssse3_phadd_d_128:
12007   case Intrinsic::x86_avx2_phadd_w:
12008   case Intrinsic::x86_avx2_phadd_d:
12009   case Intrinsic::x86_ssse3_phsub_w_128:
12010   case Intrinsic::x86_ssse3_phsub_d_128:
12011   case Intrinsic::x86_avx2_phsub_w:
12012   case Intrinsic::x86_avx2_phsub_d: {
12013     unsigned Opcode;
12014     switch (IntNo) {
12015     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12016     case Intrinsic::x86_sse3_hadd_ps:
12017     case Intrinsic::x86_sse3_hadd_pd:
12018     case Intrinsic::x86_avx_hadd_ps_256:
12019     case Intrinsic::x86_avx_hadd_pd_256:
12020       Opcode = X86ISD::FHADD;
12021       break;
12022     case Intrinsic::x86_sse3_hsub_ps:
12023     case Intrinsic::x86_sse3_hsub_pd:
12024     case Intrinsic::x86_avx_hsub_ps_256:
12025     case Intrinsic::x86_avx_hsub_pd_256:
12026       Opcode = X86ISD::FHSUB;
12027       break;
12028     case Intrinsic::x86_ssse3_phadd_w_128:
12029     case Intrinsic::x86_ssse3_phadd_d_128:
12030     case Intrinsic::x86_avx2_phadd_w:
12031     case Intrinsic::x86_avx2_phadd_d:
12032       Opcode = X86ISD::HADD;
12033       break;
12034     case Intrinsic::x86_ssse3_phsub_w_128:
12035     case Intrinsic::x86_ssse3_phsub_d_128:
12036     case Intrinsic::x86_avx2_phsub_w:
12037     case Intrinsic::x86_avx2_phsub_d:
12038       Opcode = X86ISD::HSUB;
12039       break;
12040     }
12041     return DAG.getNode(Opcode, dl, Op.getValueType(),
12042                        Op.getOperand(1), Op.getOperand(2));
12043   }
12044
12045   // SSE2/SSE41/AVX2 integer max/min intrinsics.
12046   case Intrinsic::x86_sse2_pmaxu_b:
12047   case Intrinsic::x86_sse41_pmaxuw:
12048   case Intrinsic::x86_sse41_pmaxud:
12049   case Intrinsic::x86_avx2_pmaxu_b:
12050   case Intrinsic::x86_avx2_pmaxu_w:
12051   case Intrinsic::x86_avx2_pmaxu_d:
12052   case Intrinsic::x86_sse2_pminu_b:
12053   case Intrinsic::x86_sse41_pminuw:
12054   case Intrinsic::x86_sse41_pminud:
12055   case Intrinsic::x86_avx2_pminu_b:
12056   case Intrinsic::x86_avx2_pminu_w:
12057   case Intrinsic::x86_avx2_pminu_d:
12058   case Intrinsic::x86_sse41_pmaxsb:
12059   case Intrinsic::x86_sse2_pmaxs_w:
12060   case Intrinsic::x86_sse41_pmaxsd:
12061   case Intrinsic::x86_avx2_pmaxs_b:
12062   case Intrinsic::x86_avx2_pmaxs_w:
12063   case Intrinsic::x86_avx2_pmaxs_d:
12064   case Intrinsic::x86_sse41_pminsb:
12065   case Intrinsic::x86_sse2_pmins_w:
12066   case Intrinsic::x86_sse41_pminsd:
12067   case Intrinsic::x86_avx2_pmins_b:
12068   case Intrinsic::x86_avx2_pmins_w:
12069   case Intrinsic::x86_avx2_pmins_d: {
12070     unsigned Opcode;
12071     switch (IntNo) {
12072     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12073     case Intrinsic::x86_sse2_pmaxu_b:
12074     case Intrinsic::x86_sse41_pmaxuw:
12075     case Intrinsic::x86_sse41_pmaxud:
12076     case Intrinsic::x86_avx2_pmaxu_b:
12077     case Intrinsic::x86_avx2_pmaxu_w:
12078     case Intrinsic::x86_avx2_pmaxu_d:
12079       Opcode = X86ISD::UMAX;
12080       break;
12081     case Intrinsic::x86_sse2_pminu_b:
12082     case Intrinsic::x86_sse41_pminuw:
12083     case Intrinsic::x86_sse41_pminud:
12084     case Intrinsic::x86_avx2_pminu_b:
12085     case Intrinsic::x86_avx2_pminu_w:
12086     case Intrinsic::x86_avx2_pminu_d:
12087       Opcode = X86ISD::UMIN;
12088       break;
12089     case Intrinsic::x86_sse41_pmaxsb:
12090     case Intrinsic::x86_sse2_pmaxs_w:
12091     case Intrinsic::x86_sse41_pmaxsd:
12092     case Intrinsic::x86_avx2_pmaxs_b:
12093     case Intrinsic::x86_avx2_pmaxs_w:
12094     case Intrinsic::x86_avx2_pmaxs_d:
12095       Opcode = X86ISD::SMAX;
12096       break;
12097     case Intrinsic::x86_sse41_pminsb:
12098     case Intrinsic::x86_sse2_pmins_w:
12099     case Intrinsic::x86_sse41_pminsd:
12100     case Intrinsic::x86_avx2_pmins_b:
12101     case Intrinsic::x86_avx2_pmins_w:
12102     case Intrinsic::x86_avx2_pmins_d:
12103       Opcode = X86ISD::SMIN;
12104       break;
12105     }
12106     return DAG.getNode(Opcode, dl, Op.getValueType(),
12107                        Op.getOperand(1), Op.getOperand(2));
12108   }
12109
12110   // SSE/SSE2/AVX floating point max/min intrinsics.
12111   case Intrinsic::x86_sse_max_ps:
12112   case Intrinsic::x86_sse2_max_pd:
12113   case Intrinsic::x86_avx_max_ps_256:
12114   case Intrinsic::x86_avx_max_pd_256:
12115   case Intrinsic::x86_sse_min_ps:
12116   case Intrinsic::x86_sse2_min_pd:
12117   case Intrinsic::x86_avx_min_ps_256:
12118   case Intrinsic::x86_avx_min_pd_256: {
12119     unsigned Opcode;
12120     switch (IntNo) {
12121     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12122     case Intrinsic::x86_sse_max_ps:
12123     case Intrinsic::x86_sse2_max_pd:
12124     case Intrinsic::x86_avx_max_ps_256:
12125     case Intrinsic::x86_avx_max_pd_256:
12126       Opcode = X86ISD::FMAX;
12127       break;
12128     case Intrinsic::x86_sse_min_ps:
12129     case Intrinsic::x86_sse2_min_pd:
12130     case Intrinsic::x86_avx_min_ps_256:
12131     case Intrinsic::x86_avx_min_pd_256:
12132       Opcode = X86ISD::FMIN;
12133       break;
12134     }
12135     return DAG.getNode(Opcode, dl, Op.getValueType(),
12136                        Op.getOperand(1), Op.getOperand(2));
12137   }
12138
12139   // AVX2 variable shift intrinsics
12140   case Intrinsic::x86_avx2_psllv_d:
12141   case Intrinsic::x86_avx2_psllv_q:
12142   case Intrinsic::x86_avx2_psllv_d_256:
12143   case Intrinsic::x86_avx2_psllv_q_256:
12144   case Intrinsic::x86_avx2_psrlv_d:
12145   case Intrinsic::x86_avx2_psrlv_q:
12146   case Intrinsic::x86_avx2_psrlv_d_256:
12147   case Intrinsic::x86_avx2_psrlv_q_256:
12148   case Intrinsic::x86_avx2_psrav_d:
12149   case Intrinsic::x86_avx2_psrav_d_256: {
12150     unsigned Opcode;
12151     switch (IntNo) {
12152     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12153     case Intrinsic::x86_avx2_psllv_d:
12154     case Intrinsic::x86_avx2_psllv_q:
12155     case Intrinsic::x86_avx2_psllv_d_256:
12156     case Intrinsic::x86_avx2_psllv_q_256:
12157       Opcode = ISD::SHL;
12158       break;
12159     case Intrinsic::x86_avx2_psrlv_d:
12160     case Intrinsic::x86_avx2_psrlv_q:
12161     case Intrinsic::x86_avx2_psrlv_d_256:
12162     case Intrinsic::x86_avx2_psrlv_q_256:
12163       Opcode = ISD::SRL;
12164       break;
12165     case Intrinsic::x86_avx2_psrav_d:
12166     case Intrinsic::x86_avx2_psrav_d_256:
12167       Opcode = ISD::SRA;
12168       break;
12169     }
12170     return DAG.getNode(Opcode, dl, Op.getValueType(),
12171                        Op.getOperand(1), Op.getOperand(2));
12172   }
12173
12174   case Intrinsic::x86_ssse3_pshuf_b_128:
12175   case Intrinsic::x86_avx2_pshuf_b:
12176     return DAG.getNode(X86ISD::PSHUFB, dl, Op.getValueType(),
12177                        Op.getOperand(1), Op.getOperand(2));
12178
12179   case Intrinsic::x86_ssse3_psign_b_128:
12180   case Intrinsic::x86_ssse3_psign_w_128:
12181   case Intrinsic::x86_ssse3_psign_d_128:
12182   case Intrinsic::x86_avx2_psign_b:
12183   case Intrinsic::x86_avx2_psign_w:
12184   case Intrinsic::x86_avx2_psign_d:
12185     return DAG.getNode(X86ISD::PSIGN, dl, Op.getValueType(),
12186                        Op.getOperand(1), Op.getOperand(2));
12187
12188   case Intrinsic::x86_sse41_insertps:
12189     return DAG.getNode(X86ISD::INSERTPS, dl, Op.getValueType(),
12190                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12191
12192   case Intrinsic::x86_avx_vperm2f128_ps_256:
12193   case Intrinsic::x86_avx_vperm2f128_pd_256:
12194   case Intrinsic::x86_avx_vperm2f128_si_256:
12195   case Intrinsic::x86_avx2_vperm2i128:
12196     return DAG.getNode(X86ISD::VPERM2X128, dl, Op.getValueType(),
12197                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
12198
12199   case Intrinsic::x86_avx2_permd:
12200   case Intrinsic::x86_avx2_permps:
12201     // Operands intentionally swapped. Mask is last operand to intrinsic,
12202     // but second operand for node/instruction.
12203     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
12204                        Op.getOperand(2), Op.getOperand(1));
12205
12206   case Intrinsic::x86_sse_sqrt_ps:
12207   case Intrinsic::x86_sse2_sqrt_pd:
12208   case Intrinsic::x86_avx_sqrt_ps_256:
12209   case Intrinsic::x86_avx_sqrt_pd_256:
12210     return DAG.getNode(ISD::FSQRT, dl, Op.getValueType(), Op.getOperand(1));
12211
12212   // ptest and testp intrinsics. The intrinsic these come from are designed to
12213   // return an integer value, not just an instruction so lower it to the ptest
12214   // or testp pattern and a setcc for the result.
12215   case Intrinsic::x86_sse41_ptestz:
12216   case Intrinsic::x86_sse41_ptestc:
12217   case Intrinsic::x86_sse41_ptestnzc:
12218   case Intrinsic::x86_avx_ptestz_256:
12219   case Intrinsic::x86_avx_ptestc_256:
12220   case Intrinsic::x86_avx_ptestnzc_256:
12221   case Intrinsic::x86_avx_vtestz_ps:
12222   case Intrinsic::x86_avx_vtestc_ps:
12223   case Intrinsic::x86_avx_vtestnzc_ps:
12224   case Intrinsic::x86_avx_vtestz_pd:
12225   case Intrinsic::x86_avx_vtestc_pd:
12226   case Intrinsic::x86_avx_vtestnzc_pd:
12227   case Intrinsic::x86_avx_vtestz_ps_256:
12228   case Intrinsic::x86_avx_vtestc_ps_256:
12229   case Intrinsic::x86_avx_vtestnzc_ps_256:
12230   case Intrinsic::x86_avx_vtestz_pd_256:
12231   case Intrinsic::x86_avx_vtestc_pd_256:
12232   case Intrinsic::x86_avx_vtestnzc_pd_256: {
12233     bool IsTestPacked = false;
12234     unsigned X86CC;
12235     switch (IntNo) {
12236     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
12237     case Intrinsic::x86_avx_vtestz_ps:
12238     case Intrinsic::x86_avx_vtestz_pd:
12239     case Intrinsic::x86_avx_vtestz_ps_256:
12240     case Intrinsic::x86_avx_vtestz_pd_256:
12241       IsTestPacked = true; // Fallthrough
12242     case Intrinsic::x86_sse41_ptestz:
12243     case Intrinsic::x86_avx_ptestz_256:
12244       // ZF = 1
12245       X86CC = X86::COND_E;
12246       break;
12247     case Intrinsic::x86_avx_vtestc_ps:
12248     case Intrinsic::x86_avx_vtestc_pd:
12249     case Intrinsic::x86_avx_vtestc_ps_256:
12250     case Intrinsic::x86_avx_vtestc_pd_256:
12251       IsTestPacked = true; // Fallthrough
12252     case Intrinsic::x86_sse41_ptestc:
12253     case Intrinsic::x86_avx_ptestc_256:
12254       // CF = 1
12255       X86CC = X86::COND_B;
12256       break;
12257     case Intrinsic::x86_avx_vtestnzc_ps:
12258     case Intrinsic::x86_avx_vtestnzc_pd:
12259     case Intrinsic::x86_avx_vtestnzc_ps_256:
12260     case Intrinsic::x86_avx_vtestnzc_pd_256:
12261       IsTestPacked = true; // Fallthrough
12262     case Intrinsic::x86_sse41_ptestnzc:
12263     case Intrinsic::x86_avx_ptestnzc_256:
12264       // ZF and CF = 0
12265       X86CC = X86::COND_A;
12266       break;
12267     }
12268
12269     SDValue LHS = Op.getOperand(1);
12270     SDValue RHS = Op.getOperand(2);
12271     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
12272     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
12273     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12274     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
12275     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12276   }
12277   case Intrinsic::x86_avx512_kortestz_w:
12278   case Intrinsic::x86_avx512_kortestc_w: {
12279     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
12280     SDValue LHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(1));
12281     SDValue RHS = DAG.getNode(ISD::BITCAST, dl, MVT::v16i1, Op.getOperand(2));
12282     SDValue CC = DAG.getConstant(X86CC, MVT::i8);
12283     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
12284     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
12285     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12286   }
12287
12288   // SSE/AVX shift intrinsics
12289   case Intrinsic::x86_sse2_psll_w:
12290   case Intrinsic::x86_sse2_psll_d:
12291   case Intrinsic::x86_sse2_psll_q:
12292   case Intrinsic::x86_avx2_psll_w:
12293   case Intrinsic::x86_avx2_psll_d:
12294   case Intrinsic::x86_avx2_psll_q:
12295   case Intrinsic::x86_sse2_psrl_w:
12296   case Intrinsic::x86_sse2_psrl_d:
12297   case Intrinsic::x86_sse2_psrl_q:
12298   case Intrinsic::x86_avx2_psrl_w:
12299   case Intrinsic::x86_avx2_psrl_d:
12300   case Intrinsic::x86_avx2_psrl_q:
12301   case Intrinsic::x86_sse2_psra_w:
12302   case Intrinsic::x86_sse2_psra_d:
12303   case Intrinsic::x86_avx2_psra_w:
12304   case Intrinsic::x86_avx2_psra_d: {
12305     unsigned Opcode;
12306     switch (IntNo) {
12307     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12308     case Intrinsic::x86_sse2_psll_w:
12309     case Intrinsic::x86_sse2_psll_d:
12310     case Intrinsic::x86_sse2_psll_q:
12311     case Intrinsic::x86_avx2_psll_w:
12312     case Intrinsic::x86_avx2_psll_d:
12313     case Intrinsic::x86_avx2_psll_q:
12314       Opcode = X86ISD::VSHL;
12315       break;
12316     case Intrinsic::x86_sse2_psrl_w:
12317     case Intrinsic::x86_sse2_psrl_d:
12318     case Intrinsic::x86_sse2_psrl_q:
12319     case Intrinsic::x86_avx2_psrl_w:
12320     case Intrinsic::x86_avx2_psrl_d:
12321     case Intrinsic::x86_avx2_psrl_q:
12322       Opcode = X86ISD::VSRL;
12323       break;
12324     case Intrinsic::x86_sse2_psra_w:
12325     case Intrinsic::x86_sse2_psra_d:
12326     case Intrinsic::x86_avx2_psra_w:
12327     case Intrinsic::x86_avx2_psra_d:
12328       Opcode = X86ISD::VSRA;
12329       break;
12330     }
12331     return DAG.getNode(Opcode, dl, Op.getValueType(),
12332                        Op.getOperand(1), Op.getOperand(2));
12333   }
12334
12335   // SSE/AVX immediate shift intrinsics
12336   case Intrinsic::x86_sse2_pslli_w:
12337   case Intrinsic::x86_sse2_pslli_d:
12338   case Intrinsic::x86_sse2_pslli_q:
12339   case Intrinsic::x86_avx2_pslli_w:
12340   case Intrinsic::x86_avx2_pslli_d:
12341   case Intrinsic::x86_avx2_pslli_q:
12342   case Intrinsic::x86_sse2_psrli_w:
12343   case Intrinsic::x86_sse2_psrli_d:
12344   case Intrinsic::x86_sse2_psrli_q:
12345   case Intrinsic::x86_avx2_psrli_w:
12346   case Intrinsic::x86_avx2_psrli_d:
12347   case Intrinsic::x86_avx2_psrli_q:
12348   case Intrinsic::x86_sse2_psrai_w:
12349   case Intrinsic::x86_sse2_psrai_d:
12350   case Intrinsic::x86_avx2_psrai_w:
12351   case Intrinsic::x86_avx2_psrai_d: {
12352     unsigned Opcode;
12353     switch (IntNo) {
12354     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12355     case Intrinsic::x86_sse2_pslli_w:
12356     case Intrinsic::x86_sse2_pslli_d:
12357     case Intrinsic::x86_sse2_pslli_q:
12358     case Intrinsic::x86_avx2_pslli_w:
12359     case Intrinsic::x86_avx2_pslli_d:
12360     case Intrinsic::x86_avx2_pslli_q:
12361       Opcode = X86ISD::VSHLI;
12362       break;
12363     case Intrinsic::x86_sse2_psrli_w:
12364     case Intrinsic::x86_sse2_psrli_d:
12365     case Intrinsic::x86_sse2_psrli_q:
12366     case Intrinsic::x86_avx2_psrli_w:
12367     case Intrinsic::x86_avx2_psrli_d:
12368     case Intrinsic::x86_avx2_psrli_q:
12369       Opcode = X86ISD::VSRLI;
12370       break;
12371     case Intrinsic::x86_sse2_psrai_w:
12372     case Intrinsic::x86_sse2_psrai_d:
12373     case Intrinsic::x86_avx2_psrai_w:
12374     case Intrinsic::x86_avx2_psrai_d:
12375       Opcode = X86ISD::VSRAI;
12376       break;
12377     }
12378     return getTargetVShiftNode(Opcode, dl, Op.getSimpleValueType(),
12379                                Op.getOperand(1), Op.getOperand(2), DAG);
12380   }
12381
12382   case Intrinsic::x86_sse42_pcmpistria128:
12383   case Intrinsic::x86_sse42_pcmpestria128:
12384   case Intrinsic::x86_sse42_pcmpistric128:
12385   case Intrinsic::x86_sse42_pcmpestric128:
12386   case Intrinsic::x86_sse42_pcmpistrio128:
12387   case Intrinsic::x86_sse42_pcmpestrio128:
12388   case Intrinsic::x86_sse42_pcmpistris128:
12389   case Intrinsic::x86_sse42_pcmpestris128:
12390   case Intrinsic::x86_sse42_pcmpistriz128:
12391   case Intrinsic::x86_sse42_pcmpestriz128: {
12392     unsigned Opcode;
12393     unsigned X86CC;
12394     switch (IntNo) {
12395     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12396     case Intrinsic::x86_sse42_pcmpistria128:
12397       Opcode = X86ISD::PCMPISTRI;
12398       X86CC = X86::COND_A;
12399       break;
12400     case Intrinsic::x86_sse42_pcmpestria128:
12401       Opcode = X86ISD::PCMPESTRI;
12402       X86CC = X86::COND_A;
12403       break;
12404     case Intrinsic::x86_sse42_pcmpistric128:
12405       Opcode = X86ISD::PCMPISTRI;
12406       X86CC = X86::COND_B;
12407       break;
12408     case Intrinsic::x86_sse42_pcmpestric128:
12409       Opcode = X86ISD::PCMPESTRI;
12410       X86CC = X86::COND_B;
12411       break;
12412     case Intrinsic::x86_sse42_pcmpistrio128:
12413       Opcode = X86ISD::PCMPISTRI;
12414       X86CC = X86::COND_O;
12415       break;
12416     case Intrinsic::x86_sse42_pcmpestrio128:
12417       Opcode = X86ISD::PCMPESTRI;
12418       X86CC = X86::COND_O;
12419       break;
12420     case Intrinsic::x86_sse42_pcmpistris128:
12421       Opcode = X86ISD::PCMPISTRI;
12422       X86CC = X86::COND_S;
12423       break;
12424     case Intrinsic::x86_sse42_pcmpestris128:
12425       Opcode = X86ISD::PCMPESTRI;
12426       X86CC = X86::COND_S;
12427       break;
12428     case Intrinsic::x86_sse42_pcmpistriz128:
12429       Opcode = X86ISD::PCMPISTRI;
12430       X86CC = X86::COND_E;
12431       break;
12432     case Intrinsic::x86_sse42_pcmpestriz128:
12433       Opcode = X86ISD::PCMPESTRI;
12434       X86CC = X86::COND_E;
12435       break;
12436     }
12437     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12438     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12439     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
12440     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12441                                 DAG.getConstant(X86CC, MVT::i8),
12442                                 SDValue(PCMP.getNode(), 1));
12443     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
12444   }
12445
12446   case Intrinsic::x86_sse42_pcmpistri128:
12447   case Intrinsic::x86_sse42_pcmpestri128: {
12448     unsigned Opcode;
12449     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
12450       Opcode = X86ISD::PCMPISTRI;
12451     else
12452       Opcode = X86ISD::PCMPESTRI;
12453
12454     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
12455     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12456     return DAG.getNode(Opcode, dl, VTs, NewOps);
12457   }
12458   case Intrinsic::x86_fma_vfmadd_ps:
12459   case Intrinsic::x86_fma_vfmadd_pd:
12460   case Intrinsic::x86_fma_vfmsub_ps:
12461   case Intrinsic::x86_fma_vfmsub_pd:
12462   case Intrinsic::x86_fma_vfnmadd_ps:
12463   case Intrinsic::x86_fma_vfnmadd_pd:
12464   case Intrinsic::x86_fma_vfnmsub_ps:
12465   case Intrinsic::x86_fma_vfnmsub_pd:
12466   case Intrinsic::x86_fma_vfmaddsub_ps:
12467   case Intrinsic::x86_fma_vfmaddsub_pd:
12468   case Intrinsic::x86_fma_vfmsubadd_ps:
12469   case Intrinsic::x86_fma_vfmsubadd_pd:
12470   case Intrinsic::x86_fma_vfmadd_ps_256:
12471   case Intrinsic::x86_fma_vfmadd_pd_256:
12472   case Intrinsic::x86_fma_vfmsub_ps_256:
12473   case Intrinsic::x86_fma_vfmsub_pd_256:
12474   case Intrinsic::x86_fma_vfnmadd_ps_256:
12475   case Intrinsic::x86_fma_vfnmadd_pd_256:
12476   case Intrinsic::x86_fma_vfnmsub_ps_256:
12477   case Intrinsic::x86_fma_vfnmsub_pd_256:
12478   case Intrinsic::x86_fma_vfmaddsub_ps_256:
12479   case Intrinsic::x86_fma_vfmaddsub_pd_256:
12480   case Intrinsic::x86_fma_vfmsubadd_ps_256:
12481   case Intrinsic::x86_fma_vfmsubadd_pd_256:
12482   case Intrinsic::x86_fma_vfmadd_ps_512:
12483   case Intrinsic::x86_fma_vfmadd_pd_512:
12484   case Intrinsic::x86_fma_vfmsub_ps_512:
12485   case Intrinsic::x86_fma_vfmsub_pd_512:
12486   case Intrinsic::x86_fma_vfnmadd_ps_512:
12487   case Intrinsic::x86_fma_vfnmadd_pd_512:
12488   case Intrinsic::x86_fma_vfnmsub_ps_512:
12489   case Intrinsic::x86_fma_vfnmsub_pd_512:
12490   case Intrinsic::x86_fma_vfmaddsub_ps_512:
12491   case Intrinsic::x86_fma_vfmaddsub_pd_512:
12492   case Intrinsic::x86_fma_vfmsubadd_ps_512:
12493   case Intrinsic::x86_fma_vfmsubadd_pd_512: {
12494     unsigned Opc;
12495     switch (IntNo) {
12496     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
12497     case Intrinsic::x86_fma_vfmadd_ps:
12498     case Intrinsic::x86_fma_vfmadd_pd:
12499     case Intrinsic::x86_fma_vfmadd_ps_256:
12500     case Intrinsic::x86_fma_vfmadd_pd_256:
12501     case Intrinsic::x86_fma_vfmadd_ps_512:
12502     case Intrinsic::x86_fma_vfmadd_pd_512:
12503       Opc = X86ISD::FMADD;
12504       break;
12505     case Intrinsic::x86_fma_vfmsub_ps:
12506     case Intrinsic::x86_fma_vfmsub_pd:
12507     case Intrinsic::x86_fma_vfmsub_ps_256:
12508     case Intrinsic::x86_fma_vfmsub_pd_256:
12509     case Intrinsic::x86_fma_vfmsub_ps_512:
12510     case Intrinsic::x86_fma_vfmsub_pd_512:
12511       Opc = X86ISD::FMSUB;
12512       break;
12513     case Intrinsic::x86_fma_vfnmadd_ps:
12514     case Intrinsic::x86_fma_vfnmadd_pd:
12515     case Intrinsic::x86_fma_vfnmadd_ps_256:
12516     case Intrinsic::x86_fma_vfnmadd_pd_256:
12517     case Intrinsic::x86_fma_vfnmadd_ps_512:
12518     case Intrinsic::x86_fma_vfnmadd_pd_512:
12519       Opc = X86ISD::FNMADD;
12520       break;
12521     case Intrinsic::x86_fma_vfnmsub_ps:
12522     case Intrinsic::x86_fma_vfnmsub_pd:
12523     case Intrinsic::x86_fma_vfnmsub_ps_256:
12524     case Intrinsic::x86_fma_vfnmsub_pd_256:
12525     case Intrinsic::x86_fma_vfnmsub_ps_512:
12526     case Intrinsic::x86_fma_vfnmsub_pd_512:
12527       Opc = X86ISD::FNMSUB;
12528       break;
12529     case Intrinsic::x86_fma_vfmaddsub_ps:
12530     case Intrinsic::x86_fma_vfmaddsub_pd:
12531     case Intrinsic::x86_fma_vfmaddsub_ps_256:
12532     case Intrinsic::x86_fma_vfmaddsub_pd_256:
12533     case Intrinsic::x86_fma_vfmaddsub_ps_512:
12534     case Intrinsic::x86_fma_vfmaddsub_pd_512:
12535       Opc = X86ISD::FMADDSUB;
12536       break;
12537     case Intrinsic::x86_fma_vfmsubadd_ps:
12538     case Intrinsic::x86_fma_vfmsubadd_pd:
12539     case Intrinsic::x86_fma_vfmsubadd_ps_256:
12540     case Intrinsic::x86_fma_vfmsubadd_pd_256:
12541     case Intrinsic::x86_fma_vfmsubadd_ps_512:
12542     case Intrinsic::x86_fma_vfmsubadd_pd_512:
12543       Opc = X86ISD::FMSUBADD;
12544       break;
12545     }
12546
12547     return DAG.getNode(Opc, dl, Op.getValueType(), Op.getOperand(1),
12548                        Op.getOperand(2), Op.getOperand(3));
12549   }
12550   }
12551 }
12552
12553 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12554                               SDValue Src, SDValue Mask, SDValue Base,
12555                               SDValue Index, SDValue ScaleOp, SDValue Chain,
12556                               const X86Subtarget * Subtarget) {
12557   SDLoc dl(Op);
12558   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12559   assert(C && "Invalid scale type");
12560   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12561   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12562                              Index.getSimpleValueType().getVectorNumElements());
12563   SDValue MaskInReg;
12564   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12565   if (MaskC)
12566     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12567   else
12568     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12569   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
12570   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12571   SDValue Segment = DAG.getRegister(0, MVT::i32);
12572   if (Src.getOpcode() == ISD::UNDEF)
12573     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
12574   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12575   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12576   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
12577   return DAG.getMergeValues(RetOps, dl);
12578 }
12579
12580 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12581                                SDValue Src, SDValue Mask, SDValue Base,
12582                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
12583   SDLoc dl(Op);
12584   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12585   assert(C && "Invalid scale type");
12586   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12587   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12588   SDValue Segment = DAG.getRegister(0, MVT::i32);
12589   EVT MaskVT = MVT::getVectorVT(MVT::i1,
12590                              Index.getSimpleValueType().getVectorNumElements());
12591   SDValue MaskInReg;
12592   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12593   if (MaskC)
12594     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12595   else
12596     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12597   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
12598   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
12599   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
12600   return SDValue(Res, 1);
12601 }
12602
12603 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
12604                                SDValue Mask, SDValue Base, SDValue Index,
12605                                SDValue ScaleOp, SDValue Chain) {
12606   SDLoc dl(Op);
12607   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
12608   assert(C && "Invalid scale type");
12609   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), MVT::i8);
12610   SDValue Disp = DAG.getTargetConstant(0, MVT::i32);
12611   SDValue Segment = DAG.getRegister(0, MVT::i32);
12612   EVT MaskVT =
12613     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
12614   SDValue MaskInReg;
12615   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
12616   if (MaskC)
12617     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), MaskVT);
12618   else
12619     MaskInReg = DAG.getNode(ISD::BITCAST, dl, MaskVT, Mask);
12620   //SDVTList VTs = DAG.getVTList(MVT::Other);
12621   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
12622   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
12623   return SDValue(Res, 0);
12624 }
12625
12626 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
12627 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
12628 // also used to custom lower READCYCLECOUNTER nodes.
12629 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
12630                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
12631                               SmallVectorImpl<SDValue> &Results) {
12632   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
12633   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
12634   SDValue LO, HI;
12635
12636   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
12637   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
12638   // and the EAX register is loaded with the low-order 32 bits.
12639   if (Subtarget->is64Bit()) {
12640     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
12641     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
12642                             LO.getValue(2));
12643   } else {
12644     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
12645     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
12646                             LO.getValue(2));
12647   }
12648   SDValue Chain = HI.getValue(1);
12649
12650   if (Opcode == X86ISD::RDTSCP_DAG) {
12651     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
12652
12653     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
12654     // the ECX register. Add 'ecx' explicitly to the chain.
12655     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
12656                                      HI.getValue(2));
12657     // Explicitly store the content of ECX at the location passed in input
12658     // to the 'rdtscp' intrinsic.
12659     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
12660                          MachinePointerInfo(), false, false, 0);
12661   }
12662
12663   if (Subtarget->is64Bit()) {
12664     // The EDX register is loaded with the high-order 32 bits of the MSR, and
12665     // the EAX register is loaded with the low-order 32 bits.
12666     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
12667                               DAG.getConstant(32, MVT::i8));
12668     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
12669     Results.push_back(Chain);
12670     return;
12671   }
12672
12673   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
12674   SDValue Ops[] = { LO, HI };
12675   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
12676   Results.push_back(Pair);
12677   Results.push_back(Chain);
12678 }
12679
12680 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
12681                                      SelectionDAG &DAG) {
12682   SmallVector<SDValue, 2> Results;
12683   SDLoc DL(Op);
12684   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
12685                           Results);
12686   return DAG.getMergeValues(Results, DL);
12687 }
12688
12689 enum IntrinsicType {
12690   GATHER, SCATTER, PREFETCH, RDSEED, RDRAND, RDTSC, XTEST
12691 };
12692
12693 struct IntrinsicData {
12694   IntrinsicData(IntrinsicType IType, unsigned IOpc0, unsigned IOpc1)
12695     :Type(IType), Opc0(IOpc0), Opc1(IOpc1) {}
12696   IntrinsicType Type;
12697   unsigned      Opc0;
12698   unsigned      Opc1;
12699 };
12700
12701 std::map < unsigned, IntrinsicData> IntrMap;
12702 static void InitIntinsicsMap() {
12703   static bool Initialized = false;
12704   if (Initialized) 
12705     return;
12706   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12707                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12708   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qps_512,
12709                                 IntrinsicData(GATHER, X86::VGATHERQPSZrm, 0)));
12710   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpd_512,
12711                                 IntrinsicData(GATHER, X86::VGATHERQPDZrm, 0)));
12712   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpd_512,
12713                                 IntrinsicData(GATHER, X86::VGATHERDPDZrm, 0)));
12714   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dps_512,
12715                                 IntrinsicData(GATHER, X86::VGATHERDPSZrm, 0)));
12716   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpi_512, 
12717                                 IntrinsicData(GATHER, X86::VPGATHERQDZrm, 0)));
12718   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_qpq_512, 
12719                                 IntrinsicData(GATHER, X86::VPGATHERQQZrm, 0)));
12720   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpi_512, 
12721                                 IntrinsicData(GATHER, X86::VPGATHERDDZrm, 0)));
12722   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gather_dpq_512, 
12723                                 IntrinsicData(GATHER, X86::VPGATHERDQZrm, 0)));
12724
12725   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qps_512,
12726                                 IntrinsicData(SCATTER, X86::VSCATTERQPSZmr, 0)));
12727   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpd_512, 
12728                                 IntrinsicData(SCATTER, X86::VSCATTERQPDZmr, 0)));
12729   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpd_512, 
12730                                 IntrinsicData(SCATTER, X86::VSCATTERDPDZmr, 0)));
12731   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dps_512, 
12732                                 IntrinsicData(SCATTER, X86::VSCATTERDPSZmr, 0)));
12733   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpi_512, 
12734                                 IntrinsicData(SCATTER, X86::VPSCATTERQDZmr, 0)));
12735   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_qpq_512, 
12736                                 IntrinsicData(SCATTER, X86::VPSCATTERQQZmr, 0)));
12737   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpi_512, 
12738                                 IntrinsicData(SCATTER, X86::VPSCATTERDDZmr, 0)));
12739   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatter_dpq_512, 
12740                                 IntrinsicData(SCATTER, X86::VPSCATTERDQZmr, 0)));
12741    
12742   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qps_512, 
12743                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPSm,
12744                                                         X86::VGATHERPF1QPSm)));
12745   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_qpd_512, 
12746                                 IntrinsicData(PREFETCH, X86::VGATHERPF0QPDm,
12747                                                         X86::VGATHERPF1QPDm)));
12748   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dpd_512, 
12749                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPDm,
12750                                                         X86::VGATHERPF1DPDm)));
12751   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_gatherpf_dps_512, 
12752                                 IntrinsicData(PREFETCH, X86::VGATHERPF0DPSm,
12753                                                         X86::VGATHERPF1DPSm)));
12754   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qps_512, 
12755                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPSm,
12756                                                         X86::VSCATTERPF1QPSm)));
12757   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_qpd_512, 
12758                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0QPDm,
12759                                                         X86::VSCATTERPF1QPDm)));
12760   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dpd_512, 
12761                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPDm,
12762                                                         X86::VSCATTERPF1DPDm)));
12763   IntrMap.insert(std::make_pair(Intrinsic::x86_avx512_scatterpf_dps_512, 
12764                                 IntrinsicData(PREFETCH, X86::VSCATTERPF0DPSm,
12765                                                         X86::VSCATTERPF1DPSm)));
12766   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_16,
12767                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12768   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_32,
12769                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12770   IntrMap.insert(std::make_pair(Intrinsic::x86_rdrand_64,
12771                                 IntrinsicData(RDRAND, X86ISD::RDRAND, 0)));
12772   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_16,
12773                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12774   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_32,
12775                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12776   IntrMap.insert(std::make_pair(Intrinsic::x86_rdseed_64,
12777                                 IntrinsicData(RDSEED, X86ISD::RDSEED, 0)));
12778   IntrMap.insert(std::make_pair(Intrinsic::x86_xtest,
12779                                 IntrinsicData(XTEST,  X86ISD::XTEST,  0)));
12780   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtsc,
12781                                 IntrinsicData(RDTSC,  X86ISD::RDTSC_DAG, 0)));
12782   IntrMap.insert(std::make_pair(Intrinsic::x86_rdtscp,
12783                                 IntrinsicData(RDTSC,  X86ISD::RDTSCP_DAG, 0)));
12784   Initialized = true;
12785 }
12786
12787 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
12788                                       SelectionDAG &DAG) {
12789   InitIntinsicsMap();
12790   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
12791   std::map < unsigned, IntrinsicData>::const_iterator itr = IntrMap.find(IntNo);
12792   if (itr == IntrMap.end())
12793     return SDValue();
12794
12795   SDLoc dl(Op);
12796   IntrinsicData Intr = itr->second;
12797   switch(Intr.Type) {
12798   case RDSEED:
12799   case RDRAND: {
12800     // Emit the node with the right value type.
12801     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
12802     SDValue Result = DAG.getNode(Intr.Opc0, dl, VTs, Op.getOperand(0));
12803
12804     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
12805     // Otherwise return the value from Rand, which is always 0, casted to i32.
12806     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
12807                       DAG.getConstant(1, Op->getValueType(1)),
12808                       DAG.getConstant(X86::COND_B, MVT::i32),
12809                       SDValue(Result.getNode(), 1) };
12810     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
12811                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
12812                                   Ops);
12813
12814     // Return { result, isValid, chain }.
12815     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
12816                        SDValue(Result.getNode(), 2));
12817   }
12818   case GATHER: {
12819   //gather(v1, mask, index, base, scale);
12820     SDValue Chain = Op.getOperand(0);
12821     SDValue Src   = Op.getOperand(2);
12822     SDValue Base  = Op.getOperand(3);
12823     SDValue Index = Op.getOperand(4);
12824     SDValue Mask  = Op.getOperand(5);
12825     SDValue Scale = Op.getOperand(6);
12826     return getGatherNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain,
12827                           Subtarget);
12828   }
12829   case SCATTER: {
12830   //scatter(base, mask, index, v1, scale);
12831     SDValue Chain = Op.getOperand(0);
12832     SDValue Base  = Op.getOperand(2);
12833     SDValue Mask  = Op.getOperand(3);
12834     SDValue Index = Op.getOperand(4);
12835     SDValue Src   = Op.getOperand(5);
12836     SDValue Scale = Op.getOperand(6);
12837     return getScatterNode(Intr.Opc0, Op, DAG, Src, Mask, Base, Index, Scale, Chain);
12838   }
12839   case PREFETCH: {
12840     SDValue Hint = Op.getOperand(6);
12841     unsigned HintVal;
12842     if (dyn_cast<ConstantSDNode> (Hint) == 0 ||
12843         (HintVal = dyn_cast<ConstantSDNode> (Hint)->getZExtValue()) > 1)
12844       llvm_unreachable("Wrong prefetch hint in intrinsic: should be 0 or 1");
12845     unsigned Opcode = (HintVal ? Intr.Opc1 : Intr.Opc0);
12846     SDValue Chain = Op.getOperand(0);
12847     SDValue Mask  = Op.getOperand(2);
12848     SDValue Index = Op.getOperand(3);
12849     SDValue Base  = Op.getOperand(4);
12850     SDValue Scale = Op.getOperand(5);
12851     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
12852   }
12853   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
12854   case RDTSC: {
12855     SmallVector<SDValue, 2> Results;
12856     getReadTimeStampCounter(Op.getNode(), dl, Intr.Opc0, DAG, Subtarget, Results);
12857     return DAG.getMergeValues(Results, dl);
12858   }
12859   // XTEST intrinsics.
12860   case XTEST: {
12861     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
12862     SDValue InTrans = DAG.getNode(X86ISD::XTEST, dl, VTs, Op.getOperand(0));
12863     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
12864                                 DAG.getConstant(X86::COND_NE, MVT::i8),
12865                                 InTrans);
12866     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
12867     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
12868                        Ret, SDValue(InTrans.getNode(), 1));
12869   }
12870   }
12871   llvm_unreachable("Unknown Intrinsic Type");
12872 }
12873
12874 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
12875                                            SelectionDAG &DAG) const {
12876   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12877   MFI->setReturnAddressIsTaken(true);
12878
12879   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
12880     return SDValue();
12881
12882   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12883   SDLoc dl(Op);
12884   EVT PtrVT = getPointerTy();
12885
12886   if (Depth > 0) {
12887     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
12888     const X86RegisterInfo *RegInfo =
12889       static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12890     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), PtrVT);
12891     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12892                        DAG.getNode(ISD::ADD, dl, PtrVT,
12893                                    FrameAddr, Offset),
12894                        MachinePointerInfo(), false, false, false, 0);
12895   }
12896
12897   // Just load the return address.
12898   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
12899   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
12900                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
12901 }
12902
12903 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
12904   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12905   MFI->setFrameAddressIsTaken(true);
12906
12907   EVT VT = Op.getValueType();
12908   SDLoc dl(Op);  // FIXME probably not meaningful
12909   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
12910   const X86RegisterInfo *RegInfo =
12911     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12912   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12913   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
12914           (FrameReg == X86::EBP && VT == MVT::i32)) &&
12915          "Invalid Frame Register!");
12916   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
12917   while (Depth--)
12918     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
12919                             MachinePointerInfo(),
12920                             false, false, false, 0);
12921   return FrameAddr;
12922 }
12923
12924 // FIXME? Maybe this could be a TableGen attribute on some registers and
12925 // this table could be generated automatically from RegInfo.
12926 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
12927                                               EVT VT) const {
12928   unsigned Reg = StringSwitch<unsigned>(RegName)
12929                        .Case("esp", X86::ESP)
12930                        .Case("rsp", X86::RSP)
12931                        .Default(0);
12932   if (Reg)
12933     return Reg;
12934   report_fatal_error("Invalid register name global variable");
12935 }
12936
12937 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
12938                                                      SelectionDAG &DAG) const {
12939   const X86RegisterInfo *RegInfo =
12940     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12941   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize());
12942 }
12943
12944 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
12945   SDValue Chain     = Op.getOperand(0);
12946   SDValue Offset    = Op.getOperand(1);
12947   SDValue Handler   = Op.getOperand(2);
12948   SDLoc dl      (Op);
12949
12950   EVT PtrVT = getPointerTy();
12951   const X86RegisterInfo *RegInfo =
12952     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
12953   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
12954   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
12955           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
12956          "Invalid Frame Register!");
12957   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
12958   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
12959
12960   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
12961                                  DAG.getIntPtrConstant(RegInfo->getSlotSize()));
12962   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
12963   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
12964                        false, false, 0);
12965   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
12966
12967   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
12968                      DAG.getRegister(StoreAddrReg, PtrVT));
12969 }
12970
12971 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
12972                                                SelectionDAG &DAG) const {
12973   SDLoc DL(Op);
12974   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
12975                      DAG.getVTList(MVT::i32, MVT::Other),
12976                      Op.getOperand(0), Op.getOperand(1));
12977 }
12978
12979 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
12980                                                 SelectionDAG &DAG) const {
12981   SDLoc DL(Op);
12982   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
12983                      Op.getOperand(0), Op.getOperand(1));
12984 }
12985
12986 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
12987   return Op.getOperand(0);
12988 }
12989
12990 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
12991                                                 SelectionDAG &DAG) const {
12992   SDValue Root = Op.getOperand(0);
12993   SDValue Trmp = Op.getOperand(1); // trampoline
12994   SDValue FPtr = Op.getOperand(2); // nested function
12995   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
12996   SDLoc dl (Op);
12997
12998   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
12999   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
13000
13001   if (Subtarget->is64Bit()) {
13002     SDValue OutChains[6];
13003
13004     // Large code-model.
13005     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
13006     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
13007
13008     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
13009     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
13010
13011     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
13012
13013     // Load the pointer to the nested function into R11.
13014     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
13015     SDValue Addr = Trmp;
13016     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13017                                 Addr, MachinePointerInfo(TrmpAddr),
13018                                 false, false, 0);
13019
13020     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13021                        DAG.getConstant(2, MVT::i64));
13022     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
13023                                 MachinePointerInfo(TrmpAddr, 2),
13024                                 false, false, 2);
13025
13026     // Load the 'nest' parameter value into R10.
13027     // R10 is specified in X86CallingConv.td
13028     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
13029     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13030                        DAG.getConstant(10, MVT::i64));
13031     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13032                                 Addr, MachinePointerInfo(TrmpAddr, 10),
13033                                 false, false, 0);
13034
13035     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13036                        DAG.getConstant(12, MVT::i64));
13037     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
13038                                 MachinePointerInfo(TrmpAddr, 12),
13039                                 false, false, 2);
13040
13041     // Jump to the nested function.
13042     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
13043     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13044                        DAG.getConstant(20, MVT::i64));
13045     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, MVT::i16),
13046                                 Addr, MachinePointerInfo(TrmpAddr, 20),
13047                                 false, false, 0);
13048
13049     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
13050     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
13051                        DAG.getConstant(22, MVT::i64));
13052     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, MVT::i8), Addr,
13053                                 MachinePointerInfo(TrmpAddr, 22),
13054                                 false, false, 0);
13055
13056     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13057   } else {
13058     const Function *Func =
13059       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
13060     CallingConv::ID CC = Func->getCallingConv();
13061     unsigned NestReg;
13062
13063     switch (CC) {
13064     default:
13065       llvm_unreachable("Unsupported calling convention");
13066     case CallingConv::C:
13067     case CallingConv::X86_StdCall: {
13068       // Pass 'nest' parameter in ECX.
13069       // Must be kept in sync with X86CallingConv.td
13070       NestReg = X86::ECX;
13071
13072       // Check that ECX wasn't needed by an 'inreg' parameter.
13073       FunctionType *FTy = Func->getFunctionType();
13074       const AttributeSet &Attrs = Func->getAttributes();
13075
13076       if (!Attrs.isEmpty() && !Func->isVarArg()) {
13077         unsigned InRegCount = 0;
13078         unsigned Idx = 1;
13079
13080         for (FunctionType::param_iterator I = FTy->param_begin(),
13081              E = FTy->param_end(); I != E; ++I, ++Idx)
13082           if (Attrs.hasAttribute(Idx, Attribute::InReg))
13083             // FIXME: should only count parameters that are lowered to integers.
13084             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
13085
13086         if (InRegCount > 2) {
13087           report_fatal_error("Nest register in use - reduce number of inreg"
13088                              " parameters!");
13089         }
13090       }
13091       break;
13092     }
13093     case CallingConv::X86_FastCall:
13094     case CallingConv::X86_ThisCall:
13095     case CallingConv::Fast:
13096       // Pass 'nest' parameter in EAX.
13097       // Must be kept in sync with X86CallingConv.td
13098       NestReg = X86::EAX;
13099       break;
13100     }
13101
13102     SDValue OutChains[4];
13103     SDValue Addr, Disp;
13104
13105     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13106                        DAG.getConstant(10, MVT::i32));
13107     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
13108
13109     // This is storing the opcode for MOV32ri.
13110     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
13111     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
13112     OutChains[0] = DAG.getStore(Root, dl,
13113                                 DAG.getConstant(MOV32ri|N86Reg, MVT::i8),
13114                                 Trmp, MachinePointerInfo(TrmpAddr),
13115                                 false, false, 0);
13116
13117     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13118                        DAG.getConstant(1, MVT::i32));
13119     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
13120                                 MachinePointerInfo(TrmpAddr, 1),
13121                                 false, false, 1);
13122
13123     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
13124     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13125                        DAG.getConstant(5, MVT::i32));
13126     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, MVT::i8), Addr,
13127                                 MachinePointerInfo(TrmpAddr, 5),
13128                                 false, false, 1);
13129
13130     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
13131                        DAG.getConstant(6, MVT::i32));
13132     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
13133                                 MachinePointerInfo(TrmpAddr, 6),
13134                                 false, false, 1);
13135
13136     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
13137   }
13138 }
13139
13140 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
13141                                             SelectionDAG &DAG) const {
13142   /*
13143    The rounding mode is in bits 11:10 of FPSR, and has the following
13144    settings:
13145      00 Round to nearest
13146      01 Round to -inf
13147      10 Round to +inf
13148      11 Round to 0
13149
13150   FLT_ROUNDS, on the other hand, expects the following:
13151     -1 Undefined
13152      0 Round to 0
13153      1 Round to nearest
13154      2 Round to +inf
13155      3 Round to -inf
13156
13157   To perform the conversion, we do:
13158     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
13159   */
13160
13161   MachineFunction &MF = DAG.getMachineFunction();
13162   const TargetMachine &TM = MF.getTarget();
13163   const TargetFrameLowering &TFI = *TM.getFrameLowering();
13164   unsigned StackAlignment = TFI.getStackAlignment();
13165   MVT VT = Op.getSimpleValueType();
13166   SDLoc DL(Op);
13167
13168   // Save FP Control Word to stack slot
13169   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
13170   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
13171
13172   MachineMemOperand *MMO =
13173    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
13174                            MachineMemOperand::MOStore, 2, 2);
13175
13176   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
13177   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
13178                                           DAG.getVTList(MVT::Other),
13179                                           Ops, MVT::i16, MMO);
13180
13181   // Load FP Control Word from stack slot
13182   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
13183                             MachinePointerInfo(), false, false, false, 0);
13184
13185   // Transform as necessary
13186   SDValue CWD1 =
13187     DAG.getNode(ISD::SRL, DL, MVT::i16,
13188                 DAG.getNode(ISD::AND, DL, MVT::i16,
13189                             CWD, DAG.getConstant(0x800, MVT::i16)),
13190                 DAG.getConstant(11, MVT::i8));
13191   SDValue CWD2 =
13192     DAG.getNode(ISD::SRL, DL, MVT::i16,
13193                 DAG.getNode(ISD::AND, DL, MVT::i16,
13194                             CWD, DAG.getConstant(0x400, MVT::i16)),
13195                 DAG.getConstant(9, MVT::i8));
13196
13197   SDValue RetVal =
13198     DAG.getNode(ISD::AND, DL, MVT::i16,
13199                 DAG.getNode(ISD::ADD, DL, MVT::i16,
13200                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
13201                             DAG.getConstant(1, MVT::i16)),
13202                 DAG.getConstant(3, MVT::i16));
13203
13204   return DAG.getNode((VT.getSizeInBits() < 16 ?
13205                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
13206 }
13207
13208 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
13209   MVT VT = Op.getSimpleValueType();
13210   EVT OpVT = VT;
13211   unsigned NumBits = VT.getSizeInBits();
13212   SDLoc dl(Op);
13213
13214   Op = Op.getOperand(0);
13215   if (VT == MVT::i8) {
13216     // Zero extend to i32 since there is not an i8 bsr.
13217     OpVT = MVT::i32;
13218     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13219   }
13220
13221   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
13222   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13223   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13224
13225   // If src is zero (i.e. bsr sets ZF), returns NumBits.
13226   SDValue Ops[] = {
13227     Op,
13228     DAG.getConstant(NumBits+NumBits-1, OpVT),
13229     DAG.getConstant(X86::COND_E, MVT::i8),
13230     Op.getValue(1)
13231   };
13232   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
13233
13234   // Finally xor with NumBits-1.
13235   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13236
13237   if (VT == MVT::i8)
13238     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13239   return Op;
13240 }
13241
13242 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
13243   MVT VT = Op.getSimpleValueType();
13244   EVT OpVT = VT;
13245   unsigned NumBits = VT.getSizeInBits();
13246   SDLoc dl(Op);
13247
13248   Op = Op.getOperand(0);
13249   if (VT == MVT::i8) {
13250     // Zero extend to i32 since there is not an i8 bsr.
13251     OpVT = MVT::i32;
13252     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
13253   }
13254
13255   // Issue a bsr (scan bits in reverse).
13256   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
13257   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
13258
13259   // And xor with NumBits-1.
13260   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op, DAG.getConstant(NumBits-1, OpVT));
13261
13262   if (VT == MVT::i8)
13263     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
13264   return Op;
13265 }
13266
13267 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
13268   MVT VT = Op.getSimpleValueType();
13269   unsigned NumBits = VT.getSizeInBits();
13270   SDLoc dl(Op);
13271   Op = Op.getOperand(0);
13272
13273   // Issue a bsf (scan bits forward) which also sets EFLAGS.
13274   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
13275   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
13276
13277   // If src is zero (i.e. bsf sets ZF), returns NumBits.
13278   SDValue Ops[] = {
13279     Op,
13280     DAG.getConstant(NumBits, VT),
13281     DAG.getConstant(X86::COND_E, MVT::i8),
13282     Op.getValue(1)
13283   };
13284   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
13285 }
13286
13287 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
13288 // ones, and then concatenate the result back.
13289 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
13290   MVT VT = Op.getSimpleValueType();
13291
13292   assert(VT.is256BitVector() && VT.isInteger() &&
13293          "Unsupported value type for operation");
13294
13295   unsigned NumElems = VT.getVectorNumElements();
13296   SDLoc dl(Op);
13297
13298   // Extract the LHS vectors
13299   SDValue LHS = Op.getOperand(0);
13300   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13301   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13302
13303   // Extract the RHS vectors
13304   SDValue RHS = Op.getOperand(1);
13305   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13306   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13307
13308   MVT EltVT = VT.getVectorElementType();
13309   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13310
13311   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13312                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
13313                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
13314 }
13315
13316 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
13317   assert(Op.getSimpleValueType().is256BitVector() &&
13318          Op.getSimpleValueType().isInteger() &&
13319          "Only handle AVX 256-bit vector integer operation");
13320   return Lower256IntArith(Op, DAG);
13321 }
13322
13323 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
13324   assert(Op.getSimpleValueType().is256BitVector() &&
13325          Op.getSimpleValueType().isInteger() &&
13326          "Only handle AVX 256-bit vector integer operation");
13327   return Lower256IntArith(Op, DAG);
13328 }
13329
13330 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
13331                         SelectionDAG &DAG) {
13332   SDLoc dl(Op);
13333   MVT VT = Op.getSimpleValueType();
13334
13335   // Decompose 256-bit ops into smaller 128-bit ops.
13336   if (VT.is256BitVector() && !Subtarget->hasInt256())
13337     return Lower256IntArith(Op, DAG);
13338
13339   SDValue A = Op.getOperand(0);
13340   SDValue B = Op.getOperand(1);
13341
13342   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
13343   if (VT == MVT::v4i32) {
13344     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
13345            "Should not custom lower when pmuldq is available!");
13346
13347     // Extract the odd parts.
13348     static const int UnpackMask[] = { 1, -1, 3, -1 };
13349     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
13350     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
13351
13352     // Multiply the even parts.
13353     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
13354     // Now multiply odd parts.
13355     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
13356
13357     Evens = DAG.getNode(ISD::BITCAST, dl, VT, Evens);
13358     Odds = DAG.getNode(ISD::BITCAST, dl, VT, Odds);
13359
13360     // Merge the two vectors back together with a shuffle. This expands into 2
13361     // shuffles.
13362     static const int ShufMask[] = { 0, 4, 2, 6 };
13363     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
13364   }
13365
13366   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
13367          "Only know how to lower V2I64/V4I64/V8I64 multiply");
13368
13369   //  Ahi = psrlqi(a, 32);
13370   //  Bhi = psrlqi(b, 32);
13371   //
13372   //  AloBlo = pmuludq(a, b);
13373   //  AloBhi = pmuludq(a, Bhi);
13374   //  AhiBlo = pmuludq(Ahi, b);
13375
13376   //  AloBhi = psllqi(AloBhi, 32);
13377   //  AhiBlo = psllqi(AhiBlo, 32);
13378   //  return AloBlo + AloBhi + AhiBlo;
13379
13380   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
13381   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
13382
13383   // Bit cast to 32-bit vectors for MULUDQ
13384   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
13385                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
13386   A = DAG.getNode(ISD::BITCAST, dl, MulVT, A);
13387   B = DAG.getNode(ISD::BITCAST, dl, MulVT, B);
13388   Ahi = DAG.getNode(ISD::BITCAST, dl, MulVT, Ahi);
13389   Bhi = DAG.getNode(ISD::BITCAST, dl, MulVT, Bhi);
13390
13391   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
13392   SDValue AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
13393   SDValue AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
13394
13395   AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
13396   AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
13397
13398   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
13399   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
13400 }
13401
13402 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
13403   assert(Subtarget->isTargetWin64() && "Unexpected target");
13404   EVT VT = Op.getValueType();
13405   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
13406          "Unexpected return type for lowering");
13407
13408   RTLIB::Libcall LC;
13409   bool isSigned;
13410   switch (Op->getOpcode()) {
13411   default: llvm_unreachable("Unexpected request for libcall!");
13412   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
13413   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
13414   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
13415   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
13416   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
13417   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
13418   }
13419
13420   SDLoc dl(Op);
13421   SDValue InChain = DAG.getEntryNode();
13422
13423   TargetLowering::ArgListTy Args;
13424   TargetLowering::ArgListEntry Entry;
13425   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
13426     EVT ArgVT = Op->getOperand(i).getValueType();
13427     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
13428            "Unexpected argument type for lowering");
13429     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
13430     Entry.Node = StackPtr;
13431     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
13432                            false, false, 16);
13433     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
13434     Entry.Ty = PointerType::get(ArgTy,0);
13435     Entry.isSExt = false;
13436     Entry.isZExt = false;
13437     Args.push_back(Entry);
13438   }
13439
13440   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
13441                                          getPointerTy());
13442
13443   TargetLowering::CallLoweringInfo CLI(DAG);
13444   CLI.setDebugLoc(dl).setChain(InChain)
13445     .setCallee(getLibcallCallingConv(LC),
13446                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
13447                Callee, &Args, 0)
13448     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
13449
13450   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
13451   return DAG.getNode(ISD::BITCAST, dl, VT, CallInfo.first);
13452 }
13453
13454 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
13455                              SelectionDAG &DAG) {
13456   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
13457   EVT VT = Op0.getValueType();
13458   SDLoc dl(Op);
13459
13460   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
13461          (VT == MVT::v8i32 && Subtarget->hasInt256()));
13462
13463   // Get the high parts.
13464   const int Mask[] = {1, 2, 3, 4, 5, 6, 7, 8};
13465   SDValue Hi0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
13466   SDValue Hi1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
13467
13468   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
13469   // ints.
13470   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
13471   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
13472   unsigned Opcode =
13473       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
13474   SDValue Mul1 = DAG.getNode(ISD::BITCAST, dl, VT,
13475                              DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
13476   SDValue Mul2 = DAG.getNode(ISD::BITCAST, dl, VT,
13477                              DAG.getNode(Opcode, dl, MulVT, Hi0, Hi1));
13478
13479   // Shuffle it back into the right order.
13480   const int HighMask[] = {1, 5, 3, 7, 9, 13, 11, 15};
13481   SDValue Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
13482   const int LowMask[] = {0, 4, 2, 6, 8, 12, 10, 14};
13483   SDValue Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
13484
13485   // If we have a signed multiply but no PMULDQ fix up the high parts of a
13486   // unsigned multiply.
13487   if (IsSigned && !Subtarget->hasSSE41()) {
13488     SDValue ShAmt =
13489         DAG.getConstant(31, DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
13490     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
13491                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
13492     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
13493                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
13494
13495     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
13496     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
13497   }
13498
13499   return DAG.getNode(ISD::MERGE_VALUES, dl, Op.getValueType(), Highs, Lows);
13500 }
13501
13502 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
13503                                          const X86Subtarget *Subtarget) {
13504   MVT VT = Op.getSimpleValueType();
13505   SDLoc dl(Op);
13506   SDValue R = Op.getOperand(0);
13507   SDValue Amt = Op.getOperand(1);
13508
13509   // Optimize shl/srl/sra with constant shift amount.
13510   if (isSplatVector(Amt.getNode())) {
13511     SDValue SclrAmt = Amt->getOperand(0);
13512     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
13513       uint64_t ShiftAmt = C->getZExtValue();
13514
13515       if (VT == MVT::v2i64 || VT == MVT::v4i32 || VT == MVT::v8i16 ||
13516           (Subtarget->hasInt256() &&
13517            (VT == MVT::v4i64 || VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13518           (Subtarget->hasAVX512() &&
13519            (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13520         if (Op.getOpcode() == ISD::SHL)
13521           return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13522                                             DAG);
13523         if (Op.getOpcode() == ISD::SRL)
13524           return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13525                                             DAG);
13526         if (Op.getOpcode() == ISD::SRA && VT != MVT::v2i64 && VT != MVT::v4i64)
13527           return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13528                                             DAG);
13529       }
13530
13531       if (VT == MVT::v16i8) {
13532         if (Op.getOpcode() == ISD::SHL) {
13533           // Make a large shift.
13534           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13535                                                    MVT::v8i16, R, ShiftAmt,
13536                                                    DAG);
13537           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13538           // Zero out the rightmost bits.
13539           SmallVector<SDValue, 16> V(16,
13540                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13541                                                      MVT::i8));
13542           return DAG.getNode(ISD::AND, dl, VT, SHL,
13543                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13544         }
13545         if (Op.getOpcode() == ISD::SRL) {
13546           // Make a large shift.
13547           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13548                                                    MVT::v8i16, R, ShiftAmt,
13549                                                    DAG);
13550           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13551           // Zero out the leftmost bits.
13552           SmallVector<SDValue, 16> V(16,
13553                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13554                                                      MVT::i8));
13555           return DAG.getNode(ISD::AND, dl, VT, SRL,
13556                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13557         }
13558         if (Op.getOpcode() == ISD::SRA) {
13559           if (ShiftAmt == 7) {
13560             // R s>> 7  ===  R s< 0
13561             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13562             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13563           }
13564
13565           // R s>> a === ((R u>> a) ^ m) - m
13566           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13567           SmallVector<SDValue, 16> V(16, DAG.getConstant(128 >> ShiftAmt,
13568                                                          MVT::i8));
13569           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13570           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13571           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13572           return Res;
13573         }
13574         llvm_unreachable("Unknown shift opcode.");
13575       }
13576
13577       if (Subtarget->hasInt256() && VT == MVT::v32i8) {
13578         if (Op.getOpcode() == ISD::SHL) {
13579           // Make a large shift.
13580           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl,
13581                                                    MVT::v16i16, R, ShiftAmt,
13582                                                    DAG);
13583           SHL = DAG.getNode(ISD::BITCAST, dl, VT, SHL);
13584           // Zero out the rightmost bits.
13585           SmallVector<SDValue, 32> V(32,
13586                                      DAG.getConstant(uint8_t(-1U << ShiftAmt),
13587                                                      MVT::i8));
13588           return DAG.getNode(ISD::AND, dl, VT, SHL,
13589                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13590         }
13591         if (Op.getOpcode() == ISD::SRL) {
13592           // Make a large shift.
13593           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl,
13594                                                    MVT::v16i16, R, ShiftAmt,
13595                                                    DAG);
13596           SRL = DAG.getNode(ISD::BITCAST, dl, VT, SRL);
13597           // Zero out the leftmost bits.
13598           SmallVector<SDValue, 32> V(32,
13599                                      DAG.getConstant(uint8_t(-1U) >> ShiftAmt,
13600                                                      MVT::i8));
13601           return DAG.getNode(ISD::AND, dl, VT, SRL,
13602                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
13603         }
13604         if (Op.getOpcode() == ISD::SRA) {
13605           if (ShiftAmt == 7) {
13606             // R s>> 7  ===  R s< 0
13607             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
13608             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
13609           }
13610
13611           // R s>> a === ((R u>> a) ^ m) - m
13612           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
13613           SmallVector<SDValue, 32> V(32, DAG.getConstant(128 >> ShiftAmt,
13614                                                          MVT::i8));
13615           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
13616           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
13617           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
13618           return Res;
13619         }
13620         llvm_unreachable("Unknown shift opcode.");
13621       }
13622     }
13623   }
13624
13625   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13626   if (!Subtarget->is64Bit() &&
13627       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
13628       Amt.getOpcode() == ISD::BITCAST &&
13629       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13630     Amt = Amt.getOperand(0);
13631     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13632                      VT.getVectorNumElements();
13633     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
13634     uint64_t ShiftAmt = 0;
13635     for (unsigned i = 0; i != Ratio; ++i) {
13636       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
13637       if (!C)
13638         return SDValue();
13639       // 6 == Log2(64)
13640       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
13641     }
13642     // Check remaining shift amounts.
13643     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13644       uint64_t ShAmt = 0;
13645       for (unsigned j = 0; j != Ratio; ++j) {
13646         ConstantSDNode *C =
13647           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
13648         if (!C)
13649           return SDValue();
13650         // 6 == Log2(64)
13651         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
13652       }
13653       if (ShAmt != ShiftAmt)
13654         return SDValue();
13655     }
13656     switch (Op.getOpcode()) {
13657     default:
13658       llvm_unreachable("Unknown shift opcode!");
13659     case ISD::SHL:
13660       return getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, R, ShiftAmt,
13661                                         DAG);
13662     case ISD::SRL:
13663       return getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt,
13664                                         DAG);
13665     case ISD::SRA:
13666       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, R, ShiftAmt,
13667                                         DAG);
13668     }
13669   }
13670
13671   return SDValue();
13672 }
13673
13674 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
13675                                         const X86Subtarget* Subtarget) {
13676   MVT VT = Op.getSimpleValueType();
13677   SDLoc dl(Op);
13678   SDValue R = Op.getOperand(0);
13679   SDValue Amt = Op.getOperand(1);
13680
13681   if ((VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) ||
13682       VT == MVT::v4i32 || VT == MVT::v8i16 ||
13683       (Subtarget->hasInt256() &&
13684        ((VT == MVT::v4i64 && Op.getOpcode() != ISD::SRA) ||
13685         VT == MVT::v8i32 || VT == MVT::v16i16)) ||
13686        (Subtarget->hasAVX512() && (VT == MVT::v8i64 || VT == MVT::v16i32))) {
13687     SDValue BaseShAmt;
13688     EVT EltVT = VT.getVectorElementType();
13689
13690     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
13691       unsigned NumElts = VT.getVectorNumElements();
13692       unsigned i, j;
13693       for (i = 0; i != NumElts; ++i) {
13694         if (Amt.getOperand(i).getOpcode() == ISD::UNDEF)
13695           continue;
13696         break;
13697       }
13698       for (j = i; j != NumElts; ++j) {
13699         SDValue Arg = Amt.getOperand(j);
13700         if (Arg.getOpcode() == ISD::UNDEF) continue;
13701         if (Arg != Amt.getOperand(i))
13702           break;
13703       }
13704       if (i != NumElts && j == NumElts)
13705         BaseShAmt = Amt.getOperand(i);
13706     } else {
13707       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
13708         Amt = Amt.getOperand(0);
13709       if (Amt.getOpcode() == ISD::VECTOR_SHUFFLE &&
13710                cast<ShuffleVectorSDNode>(Amt)->isSplat()) {
13711         SDValue InVec = Amt.getOperand(0);
13712         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
13713           unsigned NumElts = InVec.getValueType().getVectorNumElements();
13714           unsigned i = 0;
13715           for (; i != NumElts; ++i) {
13716             SDValue Arg = InVec.getOperand(i);
13717             if (Arg.getOpcode() == ISD::UNDEF) continue;
13718             BaseShAmt = Arg;
13719             break;
13720           }
13721         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
13722            if (ConstantSDNode *C =
13723                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
13724              unsigned SplatIdx =
13725                cast<ShuffleVectorSDNode>(Amt)->getSplatIndex();
13726              if (C->getZExtValue() == SplatIdx)
13727                BaseShAmt = InVec.getOperand(1);
13728            }
13729         }
13730         if (!BaseShAmt.getNode())
13731           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Amt,
13732                                   DAG.getIntPtrConstant(0));
13733       }
13734     }
13735
13736     if (BaseShAmt.getNode()) {
13737       if (EltVT.bitsGT(MVT::i32))
13738         BaseShAmt = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BaseShAmt);
13739       else if (EltVT.bitsLT(MVT::i32))
13740         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
13741
13742       switch (Op.getOpcode()) {
13743       default:
13744         llvm_unreachable("Unknown shift opcode!");
13745       case ISD::SHL:
13746         switch (VT.SimpleTy) {
13747         default: return SDValue();
13748         case MVT::v2i64:
13749         case MVT::v4i32:
13750         case MVT::v8i16:
13751         case MVT::v4i64:
13752         case MVT::v8i32:
13753         case MVT::v16i16:
13754         case MVT::v16i32:
13755         case MVT::v8i64:
13756           return getTargetVShiftNode(X86ISD::VSHLI, dl, VT, R, BaseShAmt, DAG);
13757         }
13758       case ISD::SRA:
13759         switch (VT.SimpleTy) {
13760         default: return SDValue();
13761         case MVT::v4i32:
13762         case MVT::v8i16:
13763         case MVT::v8i32:
13764         case MVT::v16i16:
13765         case MVT::v16i32:
13766         case MVT::v8i64:
13767           return getTargetVShiftNode(X86ISD::VSRAI, dl, VT, R, BaseShAmt, DAG);
13768         }
13769       case ISD::SRL:
13770         switch (VT.SimpleTy) {
13771         default: return SDValue();
13772         case MVT::v2i64:
13773         case MVT::v4i32:
13774         case MVT::v8i16:
13775         case MVT::v4i64:
13776         case MVT::v8i32:
13777         case MVT::v16i16:
13778         case MVT::v16i32:
13779         case MVT::v8i64:
13780           return getTargetVShiftNode(X86ISD::VSRLI, dl, VT, R, BaseShAmt, DAG);
13781         }
13782       }
13783     }
13784   }
13785
13786   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
13787   if (!Subtarget->is64Bit() &&
13788       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64) ||
13789       (Subtarget->hasAVX512() && VT == MVT::v8i64)) &&
13790       Amt.getOpcode() == ISD::BITCAST &&
13791       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
13792     Amt = Amt.getOperand(0);
13793     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
13794                      VT.getVectorNumElements();
13795     std::vector<SDValue> Vals(Ratio);
13796     for (unsigned i = 0; i != Ratio; ++i)
13797       Vals[i] = Amt.getOperand(i);
13798     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
13799       for (unsigned j = 0; j != Ratio; ++j)
13800         if (Vals[j] != Amt.getOperand(i + j))
13801           return SDValue();
13802     }
13803     switch (Op.getOpcode()) {
13804     default:
13805       llvm_unreachable("Unknown shift opcode!");
13806     case ISD::SHL:
13807       return DAG.getNode(X86ISD::VSHL, dl, VT, R, Op.getOperand(1));
13808     case ISD::SRL:
13809       return DAG.getNode(X86ISD::VSRL, dl, VT, R, Op.getOperand(1));
13810     case ISD::SRA:
13811       return DAG.getNode(X86ISD::VSRA, dl, VT, R, Op.getOperand(1));
13812     }
13813   }
13814
13815   return SDValue();
13816 }
13817
13818 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
13819                           SelectionDAG &DAG) {
13820
13821   MVT VT = Op.getSimpleValueType();
13822   SDLoc dl(Op);
13823   SDValue R = Op.getOperand(0);
13824   SDValue Amt = Op.getOperand(1);
13825   SDValue V;
13826
13827   if (!Subtarget->hasSSE2())
13828     return SDValue();
13829
13830   V = LowerScalarImmediateShift(Op, DAG, Subtarget);
13831   if (V.getNode())
13832     return V;
13833
13834   V = LowerScalarVariableShift(Op, DAG, Subtarget);
13835   if (V.getNode())
13836       return V;
13837
13838   if (Subtarget->hasAVX512() && (VT == MVT::v16i32 || VT == MVT::v8i64))
13839     return Op;
13840   // AVX2 has VPSLLV/VPSRAV/VPSRLV.
13841   if (Subtarget->hasInt256()) {
13842     if (Op.getOpcode() == ISD::SRL &&
13843         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13844          VT == MVT::v4i64 || VT == MVT::v8i32))
13845       return Op;
13846     if (Op.getOpcode() == ISD::SHL &&
13847         (VT == MVT::v2i64 || VT == MVT::v4i32 ||
13848          VT == MVT::v4i64 || VT == MVT::v8i32))
13849       return Op;
13850     if (Op.getOpcode() == ISD::SRA && (VT == MVT::v4i32 || VT == MVT::v8i32))
13851       return Op;
13852   }
13853
13854   // If possible, lower this packed shift into a vector multiply instead of
13855   // expanding it into a sequence of scalar shifts.
13856   // Do this only if the vector shift count is a constant build_vector.
13857   if (Op.getOpcode() == ISD::SHL && 
13858       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
13859        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
13860       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13861     SmallVector<SDValue, 8> Elts;
13862     EVT SVT = VT.getScalarType();
13863     unsigned SVTBits = SVT.getSizeInBits();
13864     const APInt &One = APInt(SVTBits, 1);
13865     unsigned NumElems = VT.getVectorNumElements();
13866
13867     for (unsigned i=0; i !=NumElems; ++i) {
13868       SDValue Op = Amt->getOperand(i);
13869       if (Op->getOpcode() == ISD::UNDEF) {
13870         Elts.push_back(Op);
13871         continue;
13872       }
13873
13874       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
13875       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
13876       uint64_t ShAmt = C.getZExtValue();
13877       if (ShAmt >= SVTBits) {
13878         Elts.push_back(DAG.getUNDEF(SVT));
13879         continue;
13880       }
13881       Elts.push_back(DAG.getConstant(One.shl(ShAmt), SVT));
13882     }
13883     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
13884     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
13885   }
13886
13887   // Lower SHL with variable shift amount.
13888   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
13889     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, VT));
13890
13891     Op = DAG.getNode(ISD::ADD, dl, VT, Op, DAG.getConstant(0x3f800000U, VT));
13892     Op = DAG.getNode(ISD::BITCAST, dl, MVT::v4f32, Op);
13893     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
13894     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
13895   }
13896
13897   // If possible, lower this shift as a sequence of two shifts by
13898   // constant plus a MOVSS/MOVSD instead of scalarizing it.
13899   // Example:
13900   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
13901   //
13902   // Could be rewritten as:
13903   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
13904   //
13905   // The advantage is that the two shifts from the example would be
13906   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
13907   // the vector shift into four scalar shifts plus four pairs of vector
13908   // insert/extract.
13909   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
13910       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
13911     unsigned TargetOpcode = X86ISD::MOVSS;
13912     bool CanBeSimplified;
13913     // The splat value for the first packed shift (the 'X' from the example).
13914     SDValue Amt1 = Amt->getOperand(0);
13915     // The splat value for the second packed shift (the 'Y' from the example).
13916     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
13917                                         Amt->getOperand(2);
13918
13919     // See if it is possible to replace this node with a sequence of
13920     // two shifts followed by a MOVSS/MOVSD
13921     if (VT == MVT::v4i32) {
13922       // Check if it is legal to use a MOVSS.
13923       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
13924                         Amt2 == Amt->getOperand(3);
13925       if (!CanBeSimplified) {
13926         // Otherwise, check if we can still simplify this node using a MOVSD.
13927         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
13928                           Amt->getOperand(2) == Amt->getOperand(3);
13929         TargetOpcode = X86ISD::MOVSD;
13930         Amt2 = Amt->getOperand(2);
13931       }
13932     } else {
13933       // Do similar checks for the case where the machine value type
13934       // is MVT::v8i16.
13935       CanBeSimplified = Amt1 == Amt->getOperand(1);
13936       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
13937         CanBeSimplified = Amt2 == Amt->getOperand(i);
13938
13939       if (!CanBeSimplified) {
13940         TargetOpcode = X86ISD::MOVSD;
13941         CanBeSimplified = true;
13942         Amt2 = Amt->getOperand(4);
13943         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
13944           CanBeSimplified = Amt1 == Amt->getOperand(i);
13945         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
13946           CanBeSimplified = Amt2 == Amt->getOperand(j);
13947       }
13948     }
13949     
13950     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
13951         isa<ConstantSDNode>(Amt2)) {
13952       // Replace this node with two shifts followed by a MOVSS/MOVSD.
13953       EVT CastVT = MVT::v4i32;
13954       SDValue Splat1 = 
13955         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), VT);
13956       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
13957       SDValue Splat2 = 
13958         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), VT);
13959       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
13960       if (TargetOpcode == X86ISD::MOVSD)
13961         CastVT = MVT::v2i64;
13962       SDValue BitCast1 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift1);
13963       SDValue BitCast2 = DAG.getNode(ISD::BITCAST, dl, CastVT, Shift2);
13964       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
13965                                             BitCast1, DAG);
13966       return DAG.getNode(ISD::BITCAST, dl, VT, Result);
13967     }
13968   }
13969
13970   if (VT == MVT::v16i8 && Op->getOpcode() == ISD::SHL) {
13971     assert(Subtarget->hasSSE2() && "Need SSE2 for pslli/pcmpeq.");
13972
13973     // a = a << 5;
13974     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(5, VT));
13975     Op = DAG.getNode(ISD::BITCAST, dl, VT, Op);
13976
13977     // Turn 'a' into a mask suitable for VSELECT
13978     SDValue VSelM = DAG.getConstant(0x80, VT);
13979     SDValue OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13980     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13981
13982     SDValue CM1 = DAG.getConstant(0x0f, VT);
13983     SDValue CM2 = DAG.getConstant(0x3f, VT);
13984
13985     // r = VSELECT(r, psllw(r & (char16)15, 4), a);
13986     SDValue M = DAG.getNode(ISD::AND, dl, VT, R, CM1);
13987     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 4, DAG);
13988     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
13989     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
13990
13991     // a += a
13992     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
13993     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
13994     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
13995
13996     // r = VSELECT(r, psllw(r & (char16)63, 2), a);
13997     M = DAG.getNode(ISD::AND, dl, VT, R, CM2);
13998     M = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, MVT::v8i16, M, 2, DAG);
13999     M = DAG.getNode(ISD::BITCAST, dl, VT, M);
14000     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel, M, R);
14001
14002     // a += a
14003     Op = DAG.getNode(ISD::ADD, dl, VT, Op, Op);
14004     OpVSel = DAG.getNode(ISD::AND, dl, VT, VSelM, Op);
14005     OpVSel = DAG.getNode(X86ISD::PCMPEQ, dl, VT, OpVSel, VSelM);
14006
14007     // return VSELECT(r, r+r, a);
14008     R = DAG.getNode(ISD::VSELECT, dl, VT, OpVSel,
14009                     DAG.getNode(ISD::ADD, dl, VT, R, R), R);
14010     return R;
14011   }
14012
14013   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
14014   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
14015   // solution better.
14016   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
14017     MVT NewVT = VT == MVT::v8i16 ? MVT::v8i32 : MVT::v16i16;
14018     unsigned ExtOpc =
14019         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
14020     R = DAG.getNode(ExtOpc, dl, NewVT, R);
14021     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, NewVT, Amt);
14022     return DAG.getNode(ISD::TRUNCATE, dl, VT,
14023                        DAG.getNode(Op.getOpcode(), dl, NewVT, R, Amt));
14024     }
14025
14026   // Decompose 256-bit shifts into smaller 128-bit shifts.
14027   if (VT.is256BitVector()) {
14028     unsigned NumElems = VT.getVectorNumElements();
14029     MVT EltVT = VT.getVectorElementType();
14030     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14031
14032     // Extract the two vectors
14033     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
14034     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
14035
14036     // Recreate the shift amount vectors
14037     SDValue Amt1, Amt2;
14038     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
14039       // Constant shift amount
14040       SmallVector<SDValue, 4> Amt1Csts;
14041       SmallVector<SDValue, 4> Amt2Csts;
14042       for (unsigned i = 0; i != NumElems/2; ++i)
14043         Amt1Csts.push_back(Amt->getOperand(i));
14044       for (unsigned i = NumElems/2; i != NumElems; ++i)
14045         Amt2Csts.push_back(Amt->getOperand(i));
14046
14047       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
14048       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
14049     } else {
14050       // Variable shift amount
14051       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
14052       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
14053     }
14054
14055     // Issue new vector shifts for the smaller types
14056     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
14057     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
14058
14059     // Concatenate the result back
14060     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
14061   }
14062
14063   return SDValue();
14064 }
14065
14066 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
14067   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
14068   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
14069   // looks for this combo and may remove the "setcc" instruction if the "setcc"
14070   // has only one use.
14071   SDNode *N = Op.getNode();
14072   SDValue LHS = N->getOperand(0);
14073   SDValue RHS = N->getOperand(1);
14074   unsigned BaseOp = 0;
14075   unsigned Cond = 0;
14076   SDLoc DL(Op);
14077   switch (Op.getOpcode()) {
14078   default: llvm_unreachable("Unknown ovf instruction!");
14079   case ISD::SADDO:
14080     // A subtract of one will be selected as a INC. Note that INC doesn't
14081     // set CF, so we can't do this for UADDO.
14082     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14083       if (C->isOne()) {
14084         BaseOp = X86ISD::INC;
14085         Cond = X86::COND_O;
14086         break;
14087       }
14088     BaseOp = X86ISD::ADD;
14089     Cond = X86::COND_O;
14090     break;
14091   case ISD::UADDO:
14092     BaseOp = X86ISD::ADD;
14093     Cond = X86::COND_B;
14094     break;
14095   case ISD::SSUBO:
14096     // A subtract of one will be selected as a DEC. Note that DEC doesn't
14097     // set CF, so we can't do this for USUBO.
14098     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14099       if (C->isOne()) {
14100         BaseOp = X86ISD::DEC;
14101         Cond = X86::COND_O;
14102         break;
14103       }
14104     BaseOp = X86ISD::SUB;
14105     Cond = X86::COND_O;
14106     break;
14107   case ISD::USUBO:
14108     BaseOp = X86ISD::SUB;
14109     Cond = X86::COND_B;
14110     break;
14111   case ISD::SMULO:
14112     BaseOp = X86ISD::SMUL;
14113     Cond = X86::COND_O;
14114     break;
14115   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
14116     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
14117                                  MVT::i32);
14118     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
14119
14120     SDValue SetCC =
14121       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
14122                   DAG.getConstant(X86::COND_O, MVT::i32),
14123                   SDValue(Sum.getNode(), 2));
14124
14125     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14126   }
14127   }
14128
14129   // Also sets EFLAGS.
14130   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
14131   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
14132
14133   SDValue SetCC =
14134     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
14135                 DAG.getConstant(Cond, MVT::i32),
14136                 SDValue(Sum.getNode(), 1));
14137
14138   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
14139 }
14140
14141 SDValue X86TargetLowering::LowerSIGN_EXTEND_INREG(SDValue Op,
14142                                                   SelectionDAG &DAG) const {
14143   SDLoc dl(Op);
14144   EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
14145   MVT VT = Op.getSimpleValueType();
14146
14147   if (!Subtarget->hasSSE2() || !VT.isVector())
14148     return SDValue();
14149
14150   unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
14151                       ExtraVT.getScalarType().getSizeInBits();
14152
14153   switch (VT.SimpleTy) {
14154     default: return SDValue();
14155     case MVT::v8i32:
14156     case MVT::v16i16:
14157       if (!Subtarget->hasFp256())
14158         return SDValue();
14159       if (!Subtarget->hasInt256()) {
14160         // needs to be split
14161         unsigned NumElems = VT.getVectorNumElements();
14162
14163         // Extract the LHS vectors
14164         SDValue LHS = Op.getOperand(0);
14165         SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
14166         SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
14167
14168         MVT EltVT = VT.getVectorElementType();
14169         EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
14170
14171         EVT ExtraEltVT = ExtraVT.getVectorElementType();
14172         unsigned ExtraNumElems = ExtraVT.getVectorNumElements();
14173         ExtraVT = EVT::getVectorVT(*DAG.getContext(), ExtraEltVT,
14174                                    ExtraNumElems/2);
14175         SDValue Extra = DAG.getValueType(ExtraVT);
14176
14177         LHS1 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, Extra);
14178         LHS2 = DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, Extra);
14179
14180         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, LHS1, LHS2);
14181       }
14182       // fall through
14183     case MVT::v4i32:
14184     case MVT::v8i16: {
14185       SDValue Op0 = Op.getOperand(0);
14186       SDValue Op00 = Op0.getOperand(0);
14187       SDValue Tmp1;
14188       // Hopefully, this VECTOR_SHUFFLE is just a VZEXT.
14189       if (Op0.getOpcode() == ISD::BITCAST &&
14190           Op00.getOpcode() == ISD::VECTOR_SHUFFLE) {
14191         // (sext (vzext x)) -> (vsext x)
14192         Tmp1 = LowerVectorIntExtend(Op00, Subtarget, DAG);
14193         if (Tmp1.getNode()) {
14194           EVT ExtraEltVT = ExtraVT.getVectorElementType();
14195           // This folding is only valid when the in-reg type is a vector of i8,
14196           // i16, or i32.
14197           if (ExtraEltVT == MVT::i8 || ExtraEltVT == MVT::i16 ||
14198               ExtraEltVT == MVT::i32) {
14199             SDValue Tmp1Op0 = Tmp1.getOperand(0);
14200             assert(Tmp1Op0.getOpcode() == X86ISD::VZEXT &&
14201                    "This optimization is invalid without a VZEXT.");
14202             return DAG.getNode(X86ISD::VSEXT, dl, VT, Tmp1Op0.getOperand(0));
14203           }
14204           Op0 = Tmp1;
14205         }
14206       }
14207
14208       // If the above didn't work, then just use Shift-Left + Shift-Right.
14209       Tmp1 = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, Op0, BitsDiff,
14210                                         DAG);
14211       return getTargetVShiftByConstNode(X86ISD::VSRAI, dl, VT, Tmp1, BitsDiff,
14212                                         DAG);
14213     }
14214   }
14215 }
14216
14217 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
14218                                  SelectionDAG &DAG) {
14219   SDLoc dl(Op);
14220   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
14221     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
14222   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
14223     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
14224
14225   // The only fence that needs an instruction is a sequentially-consistent
14226   // cross-thread fence.
14227   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
14228     // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
14229     // no-sse2). There isn't any reason to disable it if the target processor
14230     // supports it.
14231     if (Subtarget->hasSSE2() || Subtarget->is64Bit())
14232       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
14233
14234     SDValue Chain = Op.getOperand(0);
14235     SDValue Zero = DAG.getConstant(0, MVT::i32);
14236     SDValue Ops[] = {
14237       DAG.getRegister(X86::ESP, MVT::i32), // Base
14238       DAG.getTargetConstant(1, MVT::i8),   // Scale
14239       DAG.getRegister(0, MVT::i32),        // Index
14240       DAG.getTargetConstant(0, MVT::i32),  // Disp
14241       DAG.getRegister(0, MVT::i32),        // Segment.
14242       Zero,
14243       Chain
14244     };
14245     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
14246     return SDValue(Res, 0);
14247   }
14248
14249   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
14250   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
14251 }
14252
14253 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
14254                              SelectionDAG &DAG) {
14255   MVT T = Op.getSimpleValueType();
14256   SDLoc DL(Op);
14257   unsigned Reg = 0;
14258   unsigned size = 0;
14259   switch(T.SimpleTy) {
14260   default: llvm_unreachable("Invalid value type!");
14261   case MVT::i8:  Reg = X86::AL;  size = 1; break;
14262   case MVT::i16: Reg = X86::AX;  size = 2; break;
14263   case MVT::i32: Reg = X86::EAX; size = 4; break;
14264   case MVT::i64:
14265     assert(Subtarget->is64Bit() && "Node not type legal!");
14266     Reg = X86::RAX; size = 8;
14267     break;
14268   }
14269   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
14270                                     Op.getOperand(2), SDValue());
14271   SDValue Ops[] = { cpIn.getValue(0),
14272                     Op.getOperand(1),
14273                     Op.getOperand(3),
14274                     DAG.getTargetConstant(size, MVT::i8),
14275                     cpIn.getValue(1) };
14276   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14277   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
14278   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
14279                                            Ops, T, MMO);
14280   SDValue cpOut =
14281     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
14282   return cpOut;
14283 }
14284
14285 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
14286                             SelectionDAG &DAG) {
14287   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
14288   MVT DstVT = Op.getSimpleValueType();
14289
14290   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
14291     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14292     if (DstVT != MVT::f64)
14293       // This conversion needs to be expanded.
14294       return SDValue();
14295
14296     SDValue InVec = Op->getOperand(0);
14297     SDLoc dl(Op);
14298     unsigned NumElts = SrcVT.getVectorNumElements();
14299     EVT SVT = SrcVT.getVectorElementType();
14300
14301     // Widen the vector in input in the case of MVT::v2i32.
14302     // Example: from MVT::v2i32 to MVT::v4i32.
14303     SmallVector<SDValue, 16> Elts;
14304     for (unsigned i = 0, e = NumElts; i != e; ++i)
14305       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
14306                                  DAG.getIntPtrConstant(i)));
14307
14308     // Explicitly mark the extra elements as Undef.
14309     SDValue Undef = DAG.getUNDEF(SVT);
14310     for (unsigned i = NumElts, e = NumElts * 2; i != e; ++i)
14311       Elts.push_back(Undef);
14312
14313     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14314     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
14315     SDValue ToV2F64 = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, BV);
14316     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
14317                        DAG.getIntPtrConstant(0));
14318   }
14319
14320   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
14321          Subtarget->hasMMX() && "Unexpected custom BITCAST");
14322   assert((DstVT == MVT::i64 ||
14323           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
14324          "Unexpected custom BITCAST");
14325   // i64 <=> MMX conversions are Legal.
14326   if (SrcVT==MVT::i64 && DstVT.isVector())
14327     return Op;
14328   if (DstVT==MVT::i64 && SrcVT.isVector())
14329     return Op;
14330   // MMX <=> MMX conversions are Legal.
14331   if (SrcVT.isVector() && DstVT.isVector())
14332     return Op;
14333   // All other conversions need to be expanded.
14334   return SDValue();
14335 }
14336
14337 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
14338   SDNode *Node = Op.getNode();
14339   SDLoc dl(Node);
14340   EVT T = Node->getValueType(0);
14341   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
14342                               DAG.getConstant(0, T), Node->getOperand(2));
14343   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
14344                        cast<AtomicSDNode>(Node)->getMemoryVT(),
14345                        Node->getOperand(0),
14346                        Node->getOperand(1), negOp,
14347                        cast<AtomicSDNode>(Node)->getMemOperand(),
14348                        cast<AtomicSDNode>(Node)->getOrdering(),
14349                        cast<AtomicSDNode>(Node)->getSynchScope());
14350 }
14351
14352 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
14353   SDNode *Node = Op.getNode();
14354   SDLoc dl(Node);
14355   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14356
14357   // Convert seq_cst store -> xchg
14358   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
14359   // FIXME: On 32-bit, store -> fist or movq would be more efficient
14360   //        (The only way to get a 16-byte store is cmpxchg16b)
14361   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
14362   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
14363       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
14364     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
14365                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
14366                                  Node->getOperand(0),
14367                                  Node->getOperand(1), Node->getOperand(2),
14368                                  cast<AtomicSDNode>(Node)->getMemOperand(),
14369                                  cast<AtomicSDNode>(Node)->getOrdering(),
14370                                  cast<AtomicSDNode>(Node)->getSynchScope());
14371     return Swap.getValue(1);
14372   }
14373   // Other atomic stores have a simple pattern.
14374   return Op;
14375 }
14376
14377 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
14378   EVT VT = Op.getNode()->getSimpleValueType(0);
14379
14380   // Let legalize expand this if it isn't a legal type yet.
14381   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
14382     return SDValue();
14383
14384   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
14385
14386   unsigned Opc;
14387   bool ExtraOp = false;
14388   switch (Op.getOpcode()) {
14389   default: llvm_unreachable("Invalid code");
14390   case ISD::ADDC: Opc = X86ISD::ADD; break;
14391   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
14392   case ISD::SUBC: Opc = X86ISD::SUB; break;
14393   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
14394   }
14395
14396   if (!ExtraOp)
14397     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14398                        Op.getOperand(1));
14399   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
14400                      Op.getOperand(1), Op.getOperand(2));
14401 }
14402
14403 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
14404                             SelectionDAG &DAG) {
14405   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
14406
14407   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
14408   // which returns the values as { float, float } (in XMM0) or
14409   // { double, double } (which is returned in XMM0, XMM1).
14410   SDLoc dl(Op);
14411   SDValue Arg = Op.getOperand(0);
14412   EVT ArgVT = Arg.getValueType();
14413   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14414
14415   TargetLowering::ArgListTy Args;
14416   TargetLowering::ArgListEntry Entry;
14417
14418   Entry.Node = Arg;
14419   Entry.Ty = ArgTy;
14420   Entry.isSExt = false;
14421   Entry.isZExt = false;
14422   Args.push_back(Entry);
14423
14424   bool isF64 = ArgVT == MVT::f64;
14425   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
14426   // the small struct {f32, f32} is returned in (eax, edx). For f64,
14427   // the results are returned via SRet in memory.
14428   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
14429   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14430   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
14431
14432   Type *RetTy = isF64
14433     ? (Type*)StructType::get(ArgTy, ArgTy, NULL)
14434     : (Type*)VectorType::get(ArgTy, 4);
14435
14436   TargetLowering::CallLoweringInfo CLI(DAG);
14437   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
14438     .setCallee(CallingConv::C, RetTy, Callee, &Args, 0);
14439
14440   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
14441
14442   if (isF64)
14443     // Returned in xmm0 and xmm1.
14444     return CallResult.first;
14445
14446   // Returned in bits 0:31 and 32:64 xmm0.
14447   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14448                                CallResult.first, DAG.getIntPtrConstant(0));
14449   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
14450                                CallResult.first, DAG.getIntPtrConstant(1));
14451   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
14452   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
14453 }
14454
14455 /// LowerOperation - Provide custom lowering hooks for some operations.
14456 ///
14457 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
14458   switch (Op.getOpcode()) {
14459   default: llvm_unreachable("Should not custom lower this!");
14460   case ISD::SIGN_EXTEND_INREG:  return LowerSIGN_EXTEND_INREG(Op,DAG);
14461   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
14462   case ISD::ATOMIC_CMP_SWAP:    return LowerCMP_SWAP(Op, Subtarget, DAG);
14463   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
14464   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
14465   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
14466   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, DAG);
14467   case ISD::VECTOR_SHUFFLE:     return LowerVECTOR_SHUFFLE(Op, DAG);
14468   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
14469   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
14470   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
14471   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
14472   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
14473   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
14474   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
14475   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
14476   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
14477   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
14478   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
14479   case ISD::SHL_PARTS:
14480   case ISD::SRA_PARTS:
14481   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
14482   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
14483   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
14484   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
14485   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
14486   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
14487   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
14488   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
14489   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
14490   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
14491   case ISD::FABS:               return LowerFABS(Op, DAG);
14492   case ISD::FNEG:               return LowerFNEG(Op, DAG);
14493   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
14494   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
14495   case ISD::SETCC:              return LowerSETCC(Op, DAG);
14496   case ISD::SELECT:             return LowerSELECT(Op, DAG);
14497   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
14498   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
14499   case ISD::VASTART:            return LowerVASTART(Op, DAG);
14500   case ISD::VAARG:              return LowerVAARG(Op, DAG);
14501   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
14502   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
14503   case ISD::INTRINSIC_VOID:
14504   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
14505   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
14506   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
14507   case ISD::FRAME_TO_ARGS_OFFSET:
14508                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
14509   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
14510   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
14511   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
14512   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
14513   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
14514   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
14515   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
14516   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
14517   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
14518   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
14519   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
14520   case ISD::UMUL_LOHI:
14521   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
14522   case ISD::SRA:
14523   case ISD::SRL:
14524   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
14525   case ISD::SADDO:
14526   case ISD::UADDO:
14527   case ISD::SSUBO:
14528   case ISD::USUBO:
14529   case ISD::SMULO:
14530   case ISD::UMULO:              return LowerXALUO(Op, DAG);
14531   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
14532   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
14533   case ISD::ADDC:
14534   case ISD::ADDE:
14535   case ISD::SUBC:
14536   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
14537   case ISD::ADD:                return LowerADD(Op, DAG);
14538   case ISD::SUB:                return LowerSUB(Op, DAG);
14539   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
14540   }
14541 }
14542
14543 static void ReplaceATOMIC_LOAD(SDNode *Node,
14544                                   SmallVectorImpl<SDValue> &Results,
14545                                   SelectionDAG &DAG) {
14546   SDLoc dl(Node);
14547   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
14548
14549   // Convert wide load -> cmpxchg8b/cmpxchg16b
14550   // FIXME: On 32-bit, load -> fild or movq would be more efficient
14551   //        (The only way to get a 16-byte load is cmpxchg16b)
14552   // FIXME: 16-byte ATOMIC_CMP_SWAP isn't actually hooked up at the moment.
14553   SDValue Zero = DAG.getConstant(0, VT);
14554   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
14555                                Node->getOperand(0),
14556                                Node->getOperand(1), Zero, Zero,
14557                                cast<AtomicSDNode>(Node)->getMemOperand(),
14558                                cast<AtomicSDNode>(Node)->getOrdering(),
14559                                cast<AtomicSDNode>(Node)->getOrdering(),
14560                                cast<AtomicSDNode>(Node)->getSynchScope());
14561   Results.push_back(Swap.getValue(0));
14562   Results.push_back(Swap.getValue(1));
14563 }
14564
14565 static void
14566 ReplaceATOMIC_BINARY_64(SDNode *Node, SmallVectorImpl<SDValue>&Results,
14567                         SelectionDAG &DAG, unsigned NewOp) {
14568   SDLoc dl(Node);
14569   assert (Node->getValueType(0) == MVT::i64 &&
14570           "Only know how to expand i64 atomics");
14571
14572   SDValue Chain = Node->getOperand(0);
14573   SDValue In1 = Node->getOperand(1);
14574   SDValue In2L = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14575                              Node->getOperand(2), DAG.getIntPtrConstant(0));
14576   SDValue In2H = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32,
14577                              Node->getOperand(2), DAG.getIntPtrConstant(1));
14578   SDValue Ops[] = { Chain, In1, In2L, In2H };
14579   SDVTList Tys = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
14580   SDValue Result =
14581     DAG.getMemIntrinsicNode(NewOp, dl, Tys, Ops, MVT::i64,
14582                             cast<MemSDNode>(Node)->getMemOperand());
14583   SDValue OpsF[] = { Result.getValue(0), Result.getValue(1)};
14584   Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, OpsF));
14585   Results.push_back(Result.getValue(2));
14586 }
14587
14588 /// ReplaceNodeResults - Replace a node with an illegal result type
14589 /// with a new node built out of custom code.
14590 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
14591                                            SmallVectorImpl<SDValue>&Results,
14592                                            SelectionDAG &DAG) const {
14593   SDLoc dl(N);
14594   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14595   switch (N->getOpcode()) {
14596   default:
14597     llvm_unreachable("Do not know how to custom type legalize this operation!");
14598   case ISD::SIGN_EXTEND_INREG:
14599   case ISD::ADDC:
14600   case ISD::ADDE:
14601   case ISD::SUBC:
14602   case ISD::SUBE:
14603     // We don't want to expand or promote these.
14604     return;
14605   case ISD::SDIV:
14606   case ISD::UDIV:
14607   case ISD::SREM:
14608   case ISD::UREM:
14609   case ISD::SDIVREM:
14610   case ISD::UDIVREM: {
14611     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
14612     Results.push_back(V);
14613     return;
14614   }
14615   case ISD::FP_TO_SINT:
14616   case ISD::FP_TO_UINT: {
14617     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
14618
14619     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
14620       return;
14621
14622     std::pair<SDValue,SDValue> Vals =
14623         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
14624     SDValue FIST = Vals.first, StackSlot = Vals.second;
14625     if (FIST.getNode()) {
14626       EVT VT = N->getValueType(0);
14627       // Return a load from the stack slot.
14628       if (StackSlot.getNode())
14629         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
14630                                       MachinePointerInfo(),
14631                                       false, false, false, 0));
14632       else
14633         Results.push_back(FIST);
14634     }
14635     return;
14636   }
14637   case ISD::UINT_TO_FP: {
14638     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14639     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
14640         N->getValueType(0) != MVT::v2f32)
14641       return;
14642     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
14643                                  N->getOperand(0));
14644     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL),
14645                                      MVT::f64);
14646     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
14647     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
14648                              DAG.getNode(ISD::BITCAST, dl, MVT::v2i64, VBias));
14649     Or = DAG.getNode(ISD::BITCAST, dl, MVT::v2f64, Or);
14650     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
14651     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
14652     return;
14653   }
14654   case ISD::FP_ROUND: {
14655     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
14656         return;
14657     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
14658     Results.push_back(V);
14659     return;
14660   }
14661   case ISD::INTRINSIC_W_CHAIN: {
14662     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
14663     switch (IntNo) {
14664     default : llvm_unreachable("Do not know how to custom type "
14665                                "legalize this intrinsic operation!");
14666     case Intrinsic::x86_rdtsc:
14667       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14668                                      Results);
14669     case Intrinsic::x86_rdtscp:
14670       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
14671                                      Results);
14672     }
14673   }
14674   case ISD::READCYCLECOUNTER: {
14675     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
14676                                    Results);
14677   }
14678   case ISD::ATOMIC_CMP_SWAP: {
14679     EVT T = N->getValueType(0);
14680     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
14681     bool Regs64bit = T == MVT::i128;
14682     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
14683     SDValue cpInL, cpInH;
14684     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14685                         DAG.getConstant(0, HalfT));
14686     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
14687                         DAG.getConstant(1, HalfT));
14688     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
14689                              Regs64bit ? X86::RAX : X86::EAX,
14690                              cpInL, SDValue());
14691     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
14692                              Regs64bit ? X86::RDX : X86::EDX,
14693                              cpInH, cpInL.getValue(1));
14694     SDValue swapInL, swapInH;
14695     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14696                           DAG.getConstant(0, HalfT));
14697     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
14698                           DAG.getConstant(1, HalfT));
14699     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
14700                                Regs64bit ? X86::RBX : X86::EBX,
14701                                swapInL, cpInH.getValue(1));
14702     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
14703                                Regs64bit ? X86::RCX : X86::ECX,
14704                                swapInH, swapInL.getValue(1));
14705     SDValue Ops[] = { swapInH.getValue(0),
14706                       N->getOperand(1),
14707                       swapInH.getValue(1) };
14708     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
14709     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
14710     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
14711                                   X86ISD::LCMPXCHG8_DAG;
14712     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
14713     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
14714                                         Regs64bit ? X86::RAX : X86::EAX,
14715                                         HalfT, Result.getValue(1));
14716     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
14717                                         Regs64bit ? X86::RDX : X86::EDX,
14718                                         HalfT, cpOutL.getValue(2));
14719     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
14720     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
14721     Results.push_back(cpOutH.getValue(1));
14722     return;
14723   }
14724   case ISD::ATOMIC_LOAD_ADD:
14725   case ISD::ATOMIC_LOAD_AND:
14726   case ISD::ATOMIC_LOAD_NAND:
14727   case ISD::ATOMIC_LOAD_OR:
14728   case ISD::ATOMIC_LOAD_SUB:
14729   case ISD::ATOMIC_LOAD_XOR:
14730   case ISD::ATOMIC_LOAD_MAX:
14731   case ISD::ATOMIC_LOAD_MIN:
14732   case ISD::ATOMIC_LOAD_UMAX:
14733   case ISD::ATOMIC_LOAD_UMIN:
14734   case ISD::ATOMIC_SWAP: {
14735     unsigned Opc;
14736     switch (N->getOpcode()) {
14737     default: llvm_unreachable("Unexpected opcode");
14738     case ISD::ATOMIC_LOAD_ADD:
14739       Opc = X86ISD::ATOMADD64_DAG;
14740       break;
14741     case ISD::ATOMIC_LOAD_AND:
14742       Opc = X86ISD::ATOMAND64_DAG;
14743       break;
14744     case ISD::ATOMIC_LOAD_NAND:
14745       Opc = X86ISD::ATOMNAND64_DAG;
14746       break;
14747     case ISD::ATOMIC_LOAD_OR:
14748       Opc = X86ISD::ATOMOR64_DAG;
14749       break;
14750     case ISD::ATOMIC_LOAD_SUB:
14751       Opc = X86ISD::ATOMSUB64_DAG;
14752       break;
14753     case ISD::ATOMIC_LOAD_XOR:
14754       Opc = X86ISD::ATOMXOR64_DAG;
14755       break;
14756     case ISD::ATOMIC_LOAD_MAX:
14757       Opc = X86ISD::ATOMMAX64_DAG;
14758       break;
14759     case ISD::ATOMIC_LOAD_MIN:
14760       Opc = X86ISD::ATOMMIN64_DAG;
14761       break;
14762     case ISD::ATOMIC_LOAD_UMAX:
14763       Opc = X86ISD::ATOMUMAX64_DAG;
14764       break;
14765     case ISD::ATOMIC_LOAD_UMIN:
14766       Opc = X86ISD::ATOMUMIN64_DAG;
14767       break;
14768     case ISD::ATOMIC_SWAP:
14769       Opc = X86ISD::ATOMSWAP64_DAG;
14770       break;
14771     }
14772     ReplaceATOMIC_BINARY_64(N, Results, DAG, Opc);
14773     return;
14774   }
14775   case ISD::ATOMIC_LOAD: {
14776     ReplaceATOMIC_LOAD(N, Results, DAG);
14777     return;
14778   }
14779   case ISD::BITCAST: {
14780     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
14781     EVT DstVT = N->getValueType(0);
14782     EVT SrcVT = N->getOperand(0)->getValueType(0);
14783
14784     if (SrcVT != MVT::f64 ||
14785         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
14786       return;
14787
14788     unsigned NumElts = DstVT.getVectorNumElements();
14789     EVT SVT = DstVT.getVectorElementType();
14790     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
14791     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
14792                                    MVT::v2f64, N->getOperand(0));
14793     SDValue ToVecInt = DAG.getNode(ISD::BITCAST, dl, WiderVT, Expanded);
14794
14795     SmallVector<SDValue, 8> Elts;
14796     for (unsigned i = 0, e = NumElts; i != e; ++i)
14797       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
14798                                    ToVecInt, DAG.getIntPtrConstant(i)));
14799
14800     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
14801   }
14802   }
14803 }
14804
14805 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
14806   switch (Opcode) {
14807   default: return nullptr;
14808   case X86ISD::BSF:                return "X86ISD::BSF";
14809   case X86ISD::BSR:                return "X86ISD::BSR";
14810   case X86ISD::SHLD:               return "X86ISD::SHLD";
14811   case X86ISD::SHRD:               return "X86ISD::SHRD";
14812   case X86ISD::FAND:               return "X86ISD::FAND";
14813   case X86ISD::FANDN:              return "X86ISD::FANDN";
14814   case X86ISD::FOR:                return "X86ISD::FOR";
14815   case X86ISD::FXOR:               return "X86ISD::FXOR";
14816   case X86ISD::FSRL:               return "X86ISD::FSRL";
14817   case X86ISD::FILD:               return "X86ISD::FILD";
14818   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
14819   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
14820   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
14821   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
14822   case X86ISD::FLD:                return "X86ISD::FLD";
14823   case X86ISD::FST:                return "X86ISD::FST";
14824   case X86ISD::CALL:               return "X86ISD::CALL";
14825   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
14826   case X86ISD::BT:                 return "X86ISD::BT";
14827   case X86ISD::CMP:                return "X86ISD::CMP";
14828   case X86ISD::COMI:               return "X86ISD::COMI";
14829   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
14830   case X86ISD::CMPM:               return "X86ISD::CMPM";
14831   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
14832   case X86ISD::SETCC:              return "X86ISD::SETCC";
14833   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
14834   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
14835   case X86ISD::CMOV:               return "X86ISD::CMOV";
14836   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
14837   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
14838   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
14839   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
14840   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
14841   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
14842   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
14843   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
14844   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
14845   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
14846   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
14847   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
14848   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
14849   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
14850   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
14851   case X86ISD::BLENDV:             return "X86ISD::BLENDV";
14852   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
14853   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
14854   case X86ISD::HADD:               return "X86ISD::HADD";
14855   case X86ISD::HSUB:               return "X86ISD::HSUB";
14856   case X86ISD::FHADD:              return "X86ISD::FHADD";
14857   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
14858   case X86ISD::UMAX:               return "X86ISD::UMAX";
14859   case X86ISD::UMIN:               return "X86ISD::UMIN";
14860   case X86ISD::SMAX:               return "X86ISD::SMAX";
14861   case X86ISD::SMIN:               return "X86ISD::SMIN";
14862   case X86ISD::FMAX:               return "X86ISD::FMAX";
14863   case X86ISD::FMIN:               return "X86ISD::FMIN";
14864   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
14865   case X86ISD::FMINC:              return "X86ISD::FMINC";
14866   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
14867   case X86ISD::FRCP:               return "X86ISD::FRCP";
14868   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
14869   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
14870   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
14871   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
14872   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
14873   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
14874   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
14875   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
14876   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
14877   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
14878   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
14879   case X86ISD::ATOMADD64_DAG:      return "X86ISD::ATOMADD64_DAG";
14880   case X86ISD::ATOMSUB64_DAG:      return "X86ISD::ATOMSUB64_DAG";
14881   case X86ISD::ATOMOR64_DAG:       return "X86ISD::ATOMOR64_DAG";
14882   case X86ISD::ATOMXOR64_DAG:      return "X86ISD::ATOMXOR64_DAG";
14883   case X86ISD::ATOMAND64_DAG:      return "X86ISD::ATOMAND64_DAG";
14884   case X86ISD::ATOMNAND64_DAG:     return "X86ISD::ATOMNAND64_DAG";
14885   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
14886   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
14887   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
14888   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
14889   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
14890   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
14891   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
14892   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
14893   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
14894   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
14895   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
14896   case X86ISD::VSHL:               return "X86ISD::VSHL";
14897   case X86ISD::VSRL:               return "X86ISD::VSRL";
14898   case X86ISD::VSRA:               return "X86ISD::VSRA";
14899   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
14900   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
14901   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
14902   case X86ISD::CMPP:               return "X86ISD::CMPP";
14903   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
14904   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
14905   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
14906   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
14907   case X86ISD::ADD:                return "X86ISD::ADD";
14908   case X86ISD::SUB:                return "X86ISD::SUB";
14909   case X86ISD::ADC:                return "X86ISD::ADC";
14910   case X86ISD::SBB:                return "X86ISD::SBB";
14911   case X86ISD::SMUL:               return "X86ISD::SMUL";
14912   case X86ISD::UMUL:               return "X86ISD::UMUL";
14913   case X86ISD::INC:                return "X86ISD::INC";
14914   case X86ISD::DEC:                return "X86ISD::DEC";
14915   case X86ISD::OR:                 return "X86ISD::OR";
14916   case X86ISD::XOR:                return "X86ISD::XOR";
14917   case X86ISD::AND:                return "X86ISD::AND";
14918   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
14919   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
14920   case X86ISD::PTEST:              return "X86ISD::PTEST";
14921   case X86ISD::TESTP:              return "X86ISD::TESTP";
14922   case X86ISD::TESTM:              return "X86ISD::TESTM";
14923   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
14924   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
14925   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
14926   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
14927   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
14928   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
14929   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
14930   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
14931   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
14932   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
14933   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
14934   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
14935   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
14936   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
14937   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
14938   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
14939   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
14940   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
14941   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
14942   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
14943   case X86ISD::VBROADCASTM:        return "X86ISD::VBROADCASTM";
14944   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
14945   case X86ISD::VPERMILP:           return "X86ISD::VPERMILP";
14946   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
14947   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
14948   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
14949   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
14950   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
14951   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
14952   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
14953   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
14954   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
14955   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
14956   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
14957   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
14958   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
14959   case X86ISD::SAHF:               return "X86ISD::SAHF";
14960   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
14961   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
14962   case X86ISD::FMADD:              return "X86ISD::FMADD";
14963   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
14964   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
14965   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
14966   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
14967   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
14968   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
14969   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
14970   case X86ISD::XTEST:              return "X86ISD::XTEST";
14971   }
14972 }
14973
14974 // isLegalAddressingMode - Return true if the addressing mode represented
14975 // by AM is legal for this target, for a load/store of the specified type.
14976 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
14977                                               Type *Ty) const {
14978   // X86 supports extremely general addressing modes.
14979   CodeModel::Model M = getTargetMachine().getCodeModel();
14980   Reloc::Model R = getTargetMachine().getRelocationModel();
14981
14982   // X86 allows a sign-extended 32-bit immediate field as a displacement.
14983   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
14984     return false;
14985
14986   if (AM.BaseGV) {
14987     unsigned GVFlags =
14988       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
14989
14990     // If a reference to this global requires an extra load, we can't fold it.
14991     if (isGlobalStubReference(GVFlags))
14992       return false;
14993
14994     // If BaseGV requires a register for the PIC base, we cannot also have a
14995     // BaseReg specified.
14996     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
14997       return false;
14998
14999     // If lower 4G is not available, then we must use rip-relative addressing.
15000     if ((M != CodeModel::Small || R != Reloc::Static) &&
15001         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
15002       return false;
15003   }
15004
15005   switch (AM.Scale) {
15006   case 0:
15007   case 1:
15008   case 2:
15009   case 4:
15010   case 8:
15011     // These scales always work.
15012     break;
15013   case 3:
15014   case 5:
15015   case 9:
15016     // These scales are formed with basereg+scalereg.  Only accept if there is
15017     // no basereg yet.
15018     if (AM.HasBaseReg)
15019       return false;
15020     break;
15021   default:  // Other stuff never works.
15022     return false;
15023   }
15024
15025   return true;
15026 }
15027
15028 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
15029   unsigned Bits = Ty->getScalarSizeInBits();
15030
15031   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
15032   // particularly cheaper than those without.
15033   if (Bits == 8)
15034     return false;
15035
15036   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
15037   // variable shifts just as cheap as scalar ones.
15038   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
15039     return false;
15040
15041   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
15042   // fully general vector.
15043   return true;
15044 }
15045
15046 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
15047   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15048     return false;
15049   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
15050   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
15051   return NumBits1 > NumBits2;
15052 }
15053
15054 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
15055   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
15056     return false;
15057
15058   if (!isTypeLegal(EVT::getEVT(Ty1)))
15059     return false;
15060
15061   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
15062
15063   // Assuming the caller doesn't have a zeroext or signext return parameter,
15064   // truncation all the way down to i1 is valid.
15065   return true;
15066 }
15067
15068 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
15069   return isInt<32>(Imm);
15070 }
15071
15072 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
15073   // Can also use sub to handle negated immediates.
15074   return isInt<32>(Imm);
15075 }
15076
15077 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
15078   if (!VT1.isInteger() || !VT2.isInteger())
15079     return false;
15080   unsigned NumBits1 = VT1.getSizeInBits();
15081   unsigned NumBits2 = VT2.getSizeInBits();
15082   return NumBits1 > NumBits2;
15083 }
15084
15085 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
15086   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15087   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
15088 }
15089
15090 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
15091   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
15092   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
15093 }
15094
15095 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
15096   EVT VT1 = Val.getValueType();
15097   if (isZExtFree(VT1, VT2))
15098     return true;
15099
15100   if (Val.getOpcode() != ISD::LOAD)
15101     return false;
15102
15103   if (!VT1.isSimple() || !VT1.isInteger() ||
15104       !VT2.isSimple() || !VT2.isInteger())
15105     return false;
15106
15107   switch (VT1.getSimpleVT().SimpleTy) {
15108   default: break;
15109   case MVT::i8:
15110   case MVT::i16:
15111   case MVT::i32:
15112     // X86 has 8, 16, and 32-bit zero-extending loads.
15113     return true;
15114   }
15115
15116   return false;
15117 }
15118
15119 bool
15120 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
15121   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4()))
15122     return false;
15123
15124   VT = VT.getScalarType();
15125
15126   if (!VT.isSimple())
15127     return false;
15128
15129   switch (VT.getSimpleVT().SimpleTy) {
15130   case MVT::f32:
15131   case MVT::f64:
15132     return true;
15133   default:
15134     break;
15135   }
15136
15137   return false;
15138 }
15139
15140 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
15141   // i16 instructions are longer (0x66 prefix) and potentially slower.
15142   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
15143 }
15144
15145 /// isShuffleMaskLegal - Targets can use this to indicate that they only
15146 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
15147 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
15148 /// are assumed to be legal.
15149 bool
15150 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
15151                                       EVT VT) const {
15152   if (!VT.isSimple())
15153     return false;
15154
15155   MVT SVT = VT.getSimpleVT();
15156
15157   // Very little shuffling can be done for 64-bit vectors right now.
15158   if (VT.getSizeInBits() == 64)
15159     return false;
15160
15161   // If this is a single-input shuffle with no 128 bit lane crossings we can
15162   // lower it into pshufb.
15163   if ((SVT.is128BitVector() && Subtarget->hasSSSE3()) ||
15164       (SVT.is256BitVector() && Subtarget->hasInt256())) {
15165     bool isLegal = true;
15166     for (unsigned I = 0, E = M.size(); I != E; ++I) {
15167       if (M[I] >= (int)SVT.getVectorNumElements() ||
15168           ShuffleCrosses128bitLane(SVT, I, M[I])) {
15169         isLegal = false;
15170         break;
15171       }
15172     }
15173     if (isLegal)
15174       return true;
15175   }
15176
15177   // FIXME: blends, shifts.
15178   return (SVT.getVectorNumElements() == 2 ||
15179           ShuffleVectorSDNode::isSplatMask(&M[0], VT) ||
15180           isMOVLMask(M, SVT) ||
15181           isSHUFPMask(M, SVT) ||
15182           isPSHUFDMask(M, SVT) ||
15183           isPSHUFHWMask(M, SVT, Subtarget->hasInt256()) ||
15184           isPSHUFLWMask(M, SVT, Subtarget->hasInt256()) ||
15185           isPALIGNRMask(M, SVT, Subtarget) ||
15186           isUNPCKLMask(M, SVT, Subtarget->hasInt256()) ||
15187           isUNPCKHMask(M, SVT, Subtarget->hasInt256()) ||
15188           isUNPCKL_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15189           isUNPCKH_v_undef_Mask(M, SVT, Subtarget->hasInt256()) ||
15190           isBlendMask(M, SVT, Subtarget->hasSSE41(), Subtarget->hasInt256()));
15191 }
15192
15193 bool
15194 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
15195                                           EVT VT) const {
15196   if (!VT.isSimple())
15197     return false;
15198
15199   MVT SVT = VT.getSimpleVT();
15200   unsigned NumElts = SVT.getVectorNumElements();
15201   // FIXME: This collection of masks seems suspect.
15202   if (NumElts == 2)
15203     return true;
15204   if (NumElts == 4 && SVT.is128BitVector()) {
15205     return (isMOVLMask(Mask, SVT)  ||
15206             isCommutedMOVLMask(Mask, SVT, true) ||
15207             isSHUFPMask(Mask, SVT) ||
15208             isSHUFPMask(Mask, SVT, /* Commuted */ true));
15209   }
15210   return false;
15211 }
15212
15213 //===----------------------------------------------------------------------===//
15214 //                           X86 Scheduler Hooks
15215 //===----------------------------------------------------------------------===//
15216
15217 /// Utility function to emit xbegin specifying the start of an RTM region.
15218 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
15219                                      const TargetInstrInfo *TII) {
15220   DebugLoc DL = MI->getDebugLoc();
15221
15222   const BasicBlock *BB = MBB->getBasicBlock();
15223   MachineFunction::iterator I = MBB;
15224   ++I;
15225
15226   // For the v = xbegin(), we generate
15227   //
15228   // thisMBB:
15229   //  xbegin sinkMBB
15230   //
15231   // mainMBB:
15232   //  eax = -1
15233   //
15234   // sinkMBB:
15235   //  v = eax
15236
15237   MachineBasicBlock *thisMBB = MBB;
15238   MachineFunction *MF = MBB->getParent();
15239   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15240   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15241   MF->insert(I, mainMBB);
15242   MF->insert(I, sinkMBB);
15243
15244   // Transfer the remainder of BB and its successor edges to sinkMBB.
15245   sinkMBB->splice(sinkMBB->begin(), MBB,
15246                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15247   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15248
15249   // thisMBB:
15250   //  xbegin sinkMBB
15251   //  # fallthrough to mainMBB
15252   //  # abortion to sinkMBB
15253   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
15254   thisMBB->addSuccessor(mainMBB);
15255   thisMBB->addSuccessor(sinkMBB);
15256
15257   // mainMBB:
15258   //  EAX = -1
15259   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
15260   mainMBB->addSuccessor(sinkMBB);
15261
15262   // sinkMBB:
15263   // EAX is live into the sinkMBB
15264   sinkMBB->addLiveIn(X86::EAX);
15265   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15266           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15267     .addReg(X86::EAX);
15268
15269   MI->eraseFromParent();
15270   return sinkMBB;
15271 }
15272
15273 // Get CMPXCHG opcode for the specified data type.
15274 static unsigned getCmpXChgOpcode(EVT VT) {
15275   switch (VT.getSimpleVT().SimpleTy) {
15276   case MVT::i8:  return X86::LCMPXCHG8;
15277   case MVT::i16: return X86::LCMPXCHG16;
15278   case MVT::i32: return X86::LCMPXCHG32;
15279   case MVT::i64: return X86::LCMPXCHG64;
15280   default:
15281     break;
15282   }
15283   llvm_unreachable("Invalid operand size!");
15284 }
15285
15286 // Get LOAD opcode for the specified data type.
15287 static unsigned getLoadOpcode(EVT VT) {
15288   switch (VT.getSimpleVT().SimpleTy) {
15289   case MVT::i8:  return X86::MOV8rm;
15290   case MVT::i16: return X86::MOV16rm;
15291   case MVT::i32: return X86::MOV32rm;
15292   case MVT::i64: return X86::MOV64rm;
15293   default:
15294     break;
15295   }
15296   llvm_unreachable("Invalid operand size!");
15297 }
15298
15299 // Get opcode of the non-atomic one from the specified atomic instruction.
15300 static unsigned getNonAtomicOpcode(unsigned Opc) {
15301   switch (Opc) {
15302   case X86::ATOMAND8:  return X86::AND8rr;
15303   case X86::ATOMAND16: return X86::AND16rr;
15304   case X86::ATOMAND32: return X86::AND32rr;
15305   case X86::ATOMAND64: return X86::AND64rr;
15306   case X86::ATOMOR8:   return X86::OR8rr;
15307   case X86::ATOMOR16:  return X86::OR16rr;
15308   case X86::ATOMOR32:  return X86::OR32rr;
15309   case X86::ATOMOR64:  return X86::OR64rr;
15310   case X86::ATOMXOR8:  return X86::XOR8rr;
15311   case X86::ATOMXOR16: return X86::XOR16rr;
15312   case X86::ATOMXOR32: return X86::XOR32rr;
15313   case X86::ATOMXOR64: return X86::XOR64rr;
15314   }
15315   llvm_unreachable("Unhandled atomic-load-op opcode!");
15316 }
15317
15318 // Get opcode of the non-atomic one from the specified atomic instruction with
15319 // extra opcode.
15320 static unsigned getNonAtomicOpcodeWithExtraOpc(unsigned Opc,
15321                                                unsigned &ExtraOpc) {
15322   switch (Opc) {
15323   case X86::ATOMNAND8:  ExtraOpc = X86::NOT8r;   return X86::AND8rr;
15324   case X86::ATOMNAND16: ExtraOpc = X86::NOT16r;  return X86::AND16rr;
15325   case X86::ATOMNAND32: ExtraOpc = X86::NOT32r;  return X86::AND32rr;
15326   case X86::ATOMNAND64: ExtraOpc = X86::NOT64r;  return X86::AND64rr;
15327   case X86::ATOMMAX8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVL32rr;
15328   case X86::ATOMMAX16:  ExtraOpc = X86::CMP16rr; return X86::CMOVL16rr;
15329   case X86::ATOMMAX32:  ExtraOpc = X86::CMP32rr; return X86::CMOVL32rr;
15330   case X86::ATOMMAX64:  ExtraOpc = X86::CMP64rr; return X86::CMOVL64rr;
15331   case X86::ATOMMIN8:   ExtraOpc = X86::CMP8rr;  return X86::CMOVG32rr;
15332   case X86::ATOMMIN16:  ExtraOpc = X86::CMP16rr; return X86::CMOVG16rr;
15333   case X86::ATOMMIN32:  ExtraOpc = X86::CMP32rr; return X86::CMOVG32rr;
15334   case X86::ATOMMIN64:  ExtraOpc = X86::CMP64rr; return X86::CMOVG64rr;
15335   case X86::ATOMUMAX8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVB32rr;
15336   case X86::ATOMUMAX16: ExtraOpc = X86::CMP16rr; return X86::CMOVB16rr;
15337   case X86::ATOMUMAX32: ExtraOpc = X86::CMP32rr; return X86::CMOVB32rr;
15338   case X86::ATOMUMAX64: ExtraOpc = X86::CMP64rr; return X86::CMOVB64rr;
15339   case X86::ATOMUMIN8:  ExtraOpc = X86::CMP8rr;  return X86::CMOVA32rr;
15340   case X86::ATOMUMIN16: ExtraOpc = X86::CMP16rr; return X86::CMOVA16rr;
15341   case X86::ATOMUMIN32: ExtraOpc = X86::CMP32rr; return X86::CMOVA32rr;
15342   case X86::ATOMUMIN64: ExtraOpc = X86::CMP64rr; return X86::CMOVA64rr;
15343   }
15344   llvm_unreachable("Unhandled atomic-load-op opcode!");
15345 }
15346
15347 // Get opcode of the non-atomic one from the specified atomic instruction for
15348 // 64-bit data type on 32-bit target.
15349 static unsigned getNonAtomic6432Opcode(unsigned Opc, unsigned &HiOpc) {
15350   switch (Opc) {
15351   case X86::ATOMAND6432:  HiOpc = X86::AND32rr; return X86::AND32rr;
15352   case X86::ATOMOR6432:   HiOpc = X86::OR32rr;  return X86::OR32rr;
15353   case X86::ATOMXOR6432:  HiOpc = X86::XOR32rr; return X86::XOR32rr;
15354   case X86::ATOMADD6432:  HiOpc = X86::ADC32rr; return X86::ADD32rr;
15355   case X86::ATOMSUB6432:  HiOpc = X86::SBB32rr; return X86::SUB32rr;
15356   case X86::ATOMSWAP6432: HiOpc = X86::MOV32rr; return X86::MOV32rr;
15357   case X86::ATOMMAX6432:  HiOpc = X86::SETLr;   return X86::SETLr;
15358   case X86::ATOMMIN6432:  HiOpc = X86::SETGr;   return X86::SETGr;
15359   case X86::ATOMUMAX6432: HiOpc = X86::SETBr;   return X86::SETBr;
15360   case X86::ATOMUMIN6432: HiOpc = X86::SETAr;   return X86::SETAr;
15361   }
15362   llvm_unreachable("Unhandled atomic-load-op opcode!");
15363 }
15364
15365 // Get opcode of the non-atomic one from the specified atomic instruction for
15366 // 64-bit data type on 32-bit target with extra opcode.
15367 static unsigned getNonAtomic6432OpcodeWithExtraOpc(unsigned Opc,
15368                                                    unsigned &HiOpc,
15369                                                    unsigned &ExtraOpc) {
15370   switch (Opc) {
15371   case X86::ATOMNAND6432:
15372     ExtraOpc = X86::NOT32r;
15373     HiOpc = X86::AND32rr;
15374     return X86::AND32rr;
15375   }
15376   llvm_unreachable("Unhandled atomic-load-op opcode!");
15377 }
15378
15379 // Get pseudo CMOV opcode from the specified data type.
15380 static unsigned getPseudoCMOVOpc(EVT VT) {
15381   switch (VT.getSimpleVT().SimpleTy) {
15382   case MVT::i8:  return X86::CMOV_GR8;
15383   case MVT::i16: return X86::CMOV_GR16;
15384   case MVT::i32: return X86::CMOV_GR32;
15385   default:
15386     break;
15387   }
15388   llvm_unreachable("Unknown CMOV opcode!");
15389 }
15390
15391 // EmitAtomicLoadArith - emit the code sequence for pseudo atomic instructions.
15392 // They will be translated into a spin-loop or compare-exchange loop from
15393 //
15394 //    ...
15395 //    dst = atomic-fetch-op MI.addr, MI.val
15396 //    ...
15397 //
15398 // to
15399 //
15400 //    ...
15401 //    t1 = LOAD MI.addr
15402 // loop:
15403 //    t4 = phi(t1, t3 / loop)
15404 //    t2 = OP MI.val, t4
15405 //    EAX = t4
15406 //    LCMPXCHG [MI.addr], t2, [EAX is implicitly used & defined]
15407 //    t3 = EAX
15408 //    JNE loop
15409 // sink:
15410 //    dst = t3
15411 //    ...
15412 MachineBasicBlock *
15413 X86TargetLowering::EmitAtomicLoadArith(MachineInstr *MI,
15414                                        MachineBasicBlock *MBB) const {
15415   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15416   DebugLoc DL = MI->getDebugLoc();
15417
15418   MachineFunction *MF = MBB->getParent();
15419   MachineRegisterInfo &MRI = MF->getRegInfo();
15420
15421   const BasicBlock *BB = MBB->getBasicBlock();
15422   MachineFunction::iterator I = MBB;
15423   ++I;
15424
15425   assert(MI->getNumOperands() <= X86::AddrNumOperands + 4 &&
15426          "Unexpected number of operands");
15427
15428   assert(MI->hasOneMemOperand() &&
15429          "Expected atomic-load-op to have one memoperand");
15430
15431   // Memory Reference
15432   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15433   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15434
15435   unsigned DstReg, SrcReg;
15436   unsigned MemOpndSlot;
15437
15438   unsigned CurOp = 0;
15439
15440   DstReg = MI->getOperand(CurOp++).getReg();
15441   MemOpndSlot = CurOp;
15442   CurOp += X86::AddrNumOperands;
15443   SrcReg = MI->getOperand(CurOp++).getReg();
15444
15445   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
15446   MVT::SimpleValueType VT = *RC->vt_begin();
15447   unsigned t1 = MRI.createVirtualRegister(RC);
15448   unsigned t2 = MRI.createVirtualRegister(RC);
15449   unsigned t3 = MRI.createVirtualRegister(RC);
15450   unsigned t4 = MRI.createVirtualRegister(RC);
15451   unsigned PhyReg = getX86SubSuperRegister(X86::EAX, VT);
15452
15453   unsigned LCMPXCHGOpc = getCmpXChgOpcode(VT);
15454   unsigned LOADOpc = getLoadOpcode(VT);
15455
15456   // For the atomic load-arith operator, we generate
15457   //
15458   //  thisMBB:
15459   //    t1 = LOAD [MI.addr]
15460   //  mainMBB:
15461   //    t4 = phi(t1 / thisMBB, t3 / mainMBB)
15462   //    t1 = OP MI.val, EAX
15463   //    EAX = t4
15464   //    LCMPXCHG [MI.addr], t1, [EAX is implicitly used & defined]
15465   //    t3 = EAX
15466   //    JNE mainMBB
15467   //  sinkMBB:
15468   //    dst = t3
15469
15470   MachineBasicBlock *thisMBB = MBB;
15471   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15472   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15473   MF->insert(I, mainMBB);
15474   MF->insert(I, sinkMBB);
15475
15476   MachineInstrBuilder MIB;
15477
15478   // Transfer the remainder of BB and its successor edges to sinkMBB.
15479   sinkMBB->splice(sinkMBB->begin(), MBB,
15480                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15481   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15482
15483   // thisMBB:
15484   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1);
15485   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15486     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15487     if (NewMO.isReg())
15488       NewMO.setIsKill(false);
15489     MIB.addOperand(NewMO);
15490   }
15491   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15492     unsigned flags = (*MMOI)->getFlags();
15493     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15494     MachineMemOperand *MMO =
15495       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15496                                (*MMOI)->getSize(),
15497                                (*MMOI)->getBaseAlignment(),
15498                                (*MMOI)->getTBAAInfo(),
15499                                (*MMOI)->getRanges());
15500     MIB.addMemOperand(MMO);
15501   }
15502
15503   thisMBB->addSuccessor(mainMBB);
15504
15505   // mainMBB:
15506   MachineBasicBlock *origMainMBB = mainMBB;
15507
15508   // Add a PHI.
15509   MachineInstr *Phi = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4)
15510                         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15511
15512   unsigned Opc = MI->getOpcode();
15513   switch (Opc) {
15514   default:
15515     llvm_unreachable("Unhandled atomic-load-op opcode!");
15516   case X86::ATOMAND8:
15517   case X86::ATOMAND16:
15518   case X86::ATOMAND32:
15519   case X86::ATOMAND64:
15520   case X86::ATOMOR8:
15521   case X86::ATOMOR16:
15522   case X86::ATOMOR32:
15523   case X86::ATOMOR64:
15524   case X86::ATOMXOR8:
15525   case X86::ATOMXOR16:
15526   case X86::ATOMXOR32:
15527   case X86::ATOMXOR64: {
15528     unsigned ARITHOpc = getNonAtomicOpcode(Opc);
15529     BuildMI(mainMBB, DL, TII->get(ARITHOpc), t2).addReg(SrcReg)
15530       .addReg(t4);
15531     break;
15532   }
15533   case X86::ATOMNAND8:
15534   case X86::ATOMNAND16:
15535   case X86::ATOMNAND32:
15536   case X86::ATOMNAND64: {
15537     unsigned Tmp = MRI.createVirtualRegister(RC);
15538     unsigned NOTOpc;
15539     unsigned ANDOpc = getNonAtomicOpcodeWithExtraOpc(Opc, NOTOpc);
15540     BuildMI(mainMBB, DL, TII->get(ANDOpc), Tmp).addReg(SrcReg)
15541       .addReg(t4);
15542     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2).addReg(Tmp);
15543     break;
15544   }
15545   case X86::ATOMMAX8:
15546   case X86::ATOMMAX16:
15547   case X86::ATOMMAX32:
15548   case X86::ATOMMAX64:
15549   case X86::ATOMMIN8:
15550   case X86::ATOMMIN16:
15551   case X86::ATOMMIN32:
15552   case X86::ATOMMIN64:
15553   case X86::ATOMUMAX8:
15554   case X86::ATOMUMAX16:
15555   case X86::ATOMUMAX32:
15556   case X86::ATOMUMAX64:
15557   case X86::ATOMUMIN8:
15558   case X86::ATOMUMIN16:
15559   case X86::ATOMUMIN32:
15560   case X86::ATOMUMIN64: {
15561     unsigned CMPOpc;
15562     unsigned CMOVOpc = getNonAtomicOpcodeWithExtraOpc(Opc, CMPOpc);
15563
15564     BuildMI(mainMBB, DL, TII->get(CMPOpc))
15565       .addReg(SrcReg)
15566       .addReg(t4);
15567
15568     if (Subtarget->hasCMov()) {
15569       if (VT != MVT::i8) {
15570         // Native support
15571         BuildMI(mainMBB, DL, TII->get(CMOVOpc), t2)
15572           .addReg(SrcReg)
15573           .addReg(t4);
15574       } else {
15575         // Promote i8 to i32 to use CMOV32
15576         const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
15577         const TargetRegisterClass *RC32 =
15578           TRI->getSubClassWithSubReg(getRegClassFor(MVT::i32), X86::sub_8bit);
15579         unsigned SrcReg32 = MRI.createVirtualRegister(RC32);
15580         unsigned AccReg32 = MRI.createVirtualRegister(RC32);
15581         unsigned Tmp = MRI.createVirtualRegister(RC32);
15582
15583         unsigned Undef = MRI.createVirtualRegister(RC32);
15584         BuildMI(mainMBB, DL, TII->get(TargetOpcode::IMPLICIT_DEF), Undef);
15585
15586         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), SrcReg32)
15587           .addReg(Undef)
15588           .addReg(SrcReg)
15589           .addImm(X86::sub_8bit);
15590         BuildMI(mainMBB, DL, TII->get(TargetOpcode::INSERT_SUBREG), AccReg32)
15591           .addReg(Undef)
15592           .addReg(t4)
15593           .addImm(X86::sub_8bit);
15594
15595         BuildMI(mainMBB, DL, TII->get(CMOVOpc), Tmp)
15596           .addReg(SrcReg32)
15597           .addReg(AccReg32);
15598
15599         BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t2)
15600           .addReg(Tmp, 0, X86::sub_8bit);
15601       }
15602     } else {
15603       // Use pseudo select and lower them.
15604       assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
15605              "Invalid atomic-load-op transformation!");
15606       unsigned SelOpc = getPseudoCMOVOpc(VT);
15607       X86::CondCode CC = X86::getCondFromCMovOpc(CMOVOpc);
15608       assert(CC != X86::COND_INVALID && "Invalid atomic-load-op transformation!");
15609       MIB = BuildMI(mainMBB, DL, TII->get(SelOpc), t2)
15610               .addReg(SrcReg).addReg(t4)
15611               .addImm(CC);
15612       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15613       // Replace the original PHI node as mainMBB is changed after CMOV
15614       // lowering.
15615       BuildMI(*origMainMBB, Phi, DL, TII->get(X86::PHI), t4)
15616         .addReg(t1).addMBB(thisMBB).addReg(t3).addMBB(mainMBB);
15617       Phi->eraseFromParent();
15618     }
15619     break;
15620   }
15621   }
15622
15623   // Copy PhyReg back from virtual register.
15624   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), PhyReg)
15625     .addReg(t4);
15626
15627   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15628   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15629     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15630     if (NewMO.isReg())
15631       NewMO.setIsKill(false);
15632     MIB.addOperand(NewMO);
15633   }
15634   MIB.addReg(t2);
15635   MIB.setMemRefs(MMOBegin, MMOEnd);
15636
15637   // Copy PhyReg back to virtual register.
15638   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3)
15639     .addReg(PhyReg);
15640
15641   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15642
15643   mainMBB->addSuccessor(origMainMBB);
15644   mainMBB->addSuccessor(sinkMBB);
15645
15646   // sinkMBB:
15647   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15648           TII->get(TargetOpcode::COPY), DstReg)
15649     .addReg(t3);
15650
15651   MI->eraseFromParent();
15652   return sinkMBB;
15653 }
15654
15655 // EmitAtomicLoadArith6432 - emit the code sequence for pseudo atomic
15656 // instructions. They will be translated into a spin-loop or compare-exchange
15657 // loop from
15658 //
15659 //    ...
15660 //    dst = atomic-fetch-op MI.addr, MI.val
15661 //    ...
15662 //
15663 // to
15664 //
15665 //    ...
15666 //    t1L = LOAD [MI.addr + 0]
15667 //    t1H = LOAD [MI.addr + 4]
15668 // loop:
15669 //    t4L = phi(t1L, t3L / loop)
15670 //    t4H = phi(t1H, t3H / loop)
15671 //    t2L = OP MI.val.lo, t4L
15672 //    t2H = OP MI.val.hi, t4H
15673 //    EAX = t4L
15674 //    EDX = t4H
15675 //    EBX = t2L
15676 //    ECX = t2H
15677 //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15678 //    t3L = EAX
15679 //    t3H = EDX
15680 //    JNE loop
15681 // sink:
15682 //    dstL = t3L
15683 //    dstH = t3H
15684 //    ...
15685 MachineBasicBlock *
15686 X86TargetLowering::EmitAtomicLoadArith6432(MachineInstr *MI,
15687                                            MachineBasicBlock *MBB) const {
15688   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
15689   DebugLoc DL = MI->getDebugLoc();
15690
15691   MachineFunction *MF = MBB->getParent();
15692   MachineRegisterInfo &MRI = MF->getRegInfo();
15693
15694   const BasicBlock *BB = MBB->getBasicBlock();
15695   MachineFunction::iterator I = MBB;
15696   ++I;
15697
15698   assert(MI->getNumOperands() <= X86::AddrNumOperands + 7 &&
15699          "Unexpected number of operands");
15700
15701   assert(MI->hasOneMemOperand() &&
15702          "Expected atomic-load-op32 to have one memoperand");
15703
15704   // Memory Reference
15705   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
15706   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
15707
15708   unsigned DstLoReg, DstHiReg;
15709   unsigned SrcLoReg, SrcHiReg;
15710   unsigned MemOpndSlot;
15711
15712   unsigned CurOp = 0;
15713
15714   DstLoReg = MI->getOperand(CurOp++).getReg();
15715   DstHiReg = MI->getOperand(CurOp++).getReg();
15716   MemOpndSlot = CurOp;
15717   CurOp += X86::AddrNumOperands;
15718   SrcLoReg = MI->getOperand(CurOp++).getReg();
15719   SrcHiReg = MI->getOperand(CurOp++).getReg();
15720
15721   const TargetRegisterClass *RC = &X86::GR32RegClass;
15722   const TargetRegisterClass *RC8 = &X86::GR8RegClass;
15723
15724   unsigned t1L = MRI.createVirtualRegister(RC);
15725   unsigned t1H = MRI.createVirtualRegister(RC);
15726   unsigned t2L = MRI.createVirtualRegister(RC);
15727   unsigned t2H = MRI.createVirtualRegister(RC);
15728   unsigned t3L = MRI.createVirtualRegister(RC);
15729   unsigned t3H = MRI.createVirtualRegister(RC);
15730   unsigned t4L = MRI.createVirtualRegister(RC);
15731   unsigned t4H = MRI.createVirtualRegister(RC);
15732
15733   unsigned LCMPXCHGOpc = X86::LCMPXCHG8B;
15734   unsigned LOADOpc = X86::MOV32rm;
15735
15736   // For the atomic load-arith operator, we generate
15737   //
15738   //  thisMBB:
15739   //    t1L = LOAD [MI.addr + 0]
15740   //    t1H = LOAD [MI.addr + 4]
15741   //  mainMBB:
15742   //    t4L = phi(t1L / thisMBB, t3L / mainMBB)
15743   //    t4H = phi(t1H / thisMBB, t3H / mainMBB)
15744   //    t2L = OP MI.val.lo, t4L
15745   //    t2H = OP MI.val.hi, t4H
15746   //    EBX = t2L
15747   //    ECX = t2H
15748   //    LCMPXCHG8B [MI.addr], [ECX:EBX & EDX:EAX are implicitly used and EDX:EAX is implicitly defined]
15749   //    t3L = EAX
15750   //    t3H = EDX
15751   //    JNE loop
15752   //  sinkMBB:
15753   //    dstL = t3L
15754   //    dstH = t3H
15755
15756   MachineBasicBlock *thisMBB = MBB;
15757   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
15758   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
15759   MF->insert(I, mainMBB);
15760   MF->insert(I, sinkMBB);
15761
15762   MachineInstrBuilder MIB;
15763
15764   // Transfer the remainder of BB and its successor edges to sinkMBB.
15765   sinkMBB->splice(sinkMBB->begin(), MBB,
15766                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
15767   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
15768
15769   // thisMBB:
15770   // Lo
15771   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1L);
15772   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15773     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15774     if (NewMO.isReg())
15775       NewMO.setIsKill(false);
15776     MIB.addOperand(NewMO);
15777   }
15778   for (MachineInstr::mmo_iterator MMOI = MMOBegin; MMOI != MMOEnd; ++MMOI) {
15779     unsigned flags = (*MMOI)->getFlags();
15780     flags = (flags & ~MachineMemOperand::MOStore) | MachineMemOperand::MOLoad;
15781     MachineMemOperand *MMO =
15782       MF->getMachineMemOperand((*MMOI)->getPointerInfo(), flags,
15783                                (*MMOI)->getSize(),
15784                                (*MMOI)->getBaseAlignment(),
15785                                (*MMOI)->getTBAAInfo(),
15786                                (*MMOI)->getRanges());
15787     MIB.addMemOperand(MMO);
15788   };
15789   MachineInstr *LowMI = MIB;
15790
15791   // Hi
15792   MIB = BuildMI(thisMBB, DL, TII->get(LOADOpc), t1H);
15793   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15794     if (i == X86::AddrDisp) {
15795       MIB.addDisp(MI->getOperand(MemOpndSlot + i), 4); // 4 == sizeof(i32)
15796     } else {
15797       MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15798       if (NewMO.isReg())
15799         NewMO.setIsKill(false);
15800       MIB.addOperand(NewMO);
15801     }
15802   }
15803   MIB.setMemRefs(LowMI->memoperands_begin(), LowMI->memoperands_end());
15804
15805   thisMBB->addSuccessor(mainMBB);
15806
15807   // mainMBB:
15808   MachineBasicBlock *origMainMBB = mainMBB;
15809
15810   // Add PHIs.
15811   MachineInstr *PhiL = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4L)
15812                         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15813   MachineInstr *PhiH = BuildMI(mainMBB, DL, TII->get(X86::PHI), t4H)
15814                         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15815
15816   unsigned Opc = MI->getOpcode();
15817   switch (Opc) {
15818   default:
15819     llvm_unreachable("Unhandled atomic-load-op6432 opcode!");
15820   case X86::ATOMAND6432:
15821   case X86::ATOMOR6432:
15822   case X86::ATOMXOR6432:
15823   case X86::ATOMADD6432:
15824   case X86::ATOMSUB6432: {
15825     unsigned HiOpc;
15826     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15827     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(t4L)
15828       .addReg(SrcLoReg);
15829     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(t4H)
15830       .addReg(SrcHiReg);
15831     break;
15832   }
15833   case X86::ATOMNAND6432: {
15834     unsigned HiOpc, NOTOpc;
15835     unsigned LoOpc = getNonAtomic6432OpcodeWithExtraOpc(Opc, HiOpc, NOTOpc);
15836     unsigned TmpL = MRI.createVirtualRegister(RC);
15837     unsigned TmpH = MRI.createVirtualRegister(RC);
15838     BuildMI(mainMBB, DL, TII->get(LoOpc), TmpL).addReg(SrcLoReg)
15839       .addReg(t4L);
15840     BuildMI(mainMBB, DL, TII->get(HiOpc), TmpH).addReg(SrcHiReg)
15841       .addReg(t4H);
15842     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2L).addReg(TmpL);
15843     BuildMI(mainMBB, DL, TII->get(NOTOpc), t2H).addReg(TmpH);
15844     break;
15845   }
15846   case X86::ATOMMAX6432:
15847   case X86::ATOMMIN6432:
15848   case X86::ATOMUMAX6432:
15849   case X86::ATOMUMIN6432: {
15850     unsigned HiOpc;
15851     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15852     unsigned cL = MRI.createVirtualRegister(RC8);
15853     unsigned cH = MRI.createVirtualRegister(RC8);
15854     unsigned cL32 = MRI.createVirtualRegister(RC);
15855     unsigned cH32 = MRI.createVirtualRegister(RC);
15856     unsigned cc = MRI.createVirtualRegister(RC);
15857     // cl := cmp src_lo, lo
15858     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15859       .addReg(SrcLoReg).addReg(t4L);
15860     BuildMI(mainMBB, DL, TII->get(LoOpc), cL);
15861     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cL32).addReg(cL);
15862     // ch := cmp src_hi, hi
15863     BuildMI(mainMBB, DL, TII->get(X86::CMP32rr))
15864       .addReg(SrcHiReg).addReg(t4H);
15865     BuildMI(mainMBB, DL, TII->get(HiOpc), cH);
15866     BuildMI(mainMBB, DL, TII->get(X86::MOVZX32rr8), cH32).addReg(cH);
15867     // cc := if (src_hi == hi) ? cl : ch;
15868     if (Subtarget->hasCMov()) {
15869       BuildMI(mainMBB, DL, TII->get(X86::CMOVE32rr), cc)
15870         .addReg(cH32).addReg(cL32);
15871     } else {
15872       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), cc)
15873               .addReg(cH32).addReg(cL32)
15874               .addImm(X86::COND_E);
15875       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15876     }
15877     BuildMI(mainMBB, DL, TII->get(X86::TEST32rr)).addReg(cc).addReg(cc);
15878     if (Subtarget->hasCMov()) {
15879       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2L)
15880         .addReg(SrcLoReg).addReg(t4L);
15881       BuildMI(mainMBB, DL, TII->get(X86::CMOVNE32rr), t2H)
15882         .addReg(SrcHiReg).addReg(t4H);
15883     } else {
15884       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2L)
15885               .addReg(SrcLoReg).addReg(t4L)
15886               .addImm(X86::COND_NE);
15887       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15888       // As the lowered CMOV won't clobber EFLAGS, we could reuse it for the
15889       // 2nd CMOV lowering.
15890       mainMBB->addLiveIn(X86::EFLAGS);
15891       MIB = BuildMI(mainMBB, DL, TII->get(X86::CMOV_GR32), t2H)
15892               .addReg(SrcHiReg).addReg(t4H)
15893               .addImm(X86::COND_NE);
15894       mainMBB = EmitLoweredSelect(MIB, mainMBB);
15895       // Replace the original PHI node as mainMBB is changed after CMOV
15896       // lowering.
15897       BuildMI(*origMainMBB, PhiL, DL, TII->get(X86::PHI), t4L)
15898         .addReg(t1L).addMBB(thisMBB).addReg(t3L).addMBB(mainMBB);
15899       BuildMI(*origMainMBB, PhiH, DL, TII->get(X86::PHI), t4H)
15900         .addReg(t1H).addMBB(thisMBB).addReg(t3H).addMBB(mainMBB);
15901       PhiL->eraseFromParent();
15902       PhiH->eraseFromParent();
15903     }
15904     break;
15905   }
15906   case X86::ATOMSWAP6432: {
15907     unsigned HiOpc;
15908     unsigned LoOpc = getNonAtomic6432Opcode(Opc, HiOpc);
15909     BuildMI(mainMBB, DL, TII->get(LoOpc), t2L).addReg(SrcLoReg);
15910     BuildMI(mainMBB, DL, TII->get(HiOpc), t2H).addReg(SrcHiReg);
15911     break;
15912   }
15913   }
15914
15915   // Copy EDX:EAX back from HiReg:LoReg
15916   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EAX).addReg(t4L);
15917   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EDX).addReg(t4H);
15918   // Copy ECX:EBX from t1H:t1L
15919   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::EBX).addReg(t2L);
15920   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), X86::ECX).addReg(t2H);
15921
15922   MIB = BuildMI(mainMBB, DL, TII->get(LCMPXCHGOpc));
15923   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
15924     MachineOperand NewMO = MI->getOperand(MemOpndSlot + i);
15925     if (NewMO.isReg())
15926       NewMO.setIsKill(false);
15927     MIB.addOperand(NewMO);
15928   }
15929   MIB.setMemRefs(MMOBegin, MMOEnd);
15930
15931   // Copy EDX:EAX back to t3H:t3L
15932   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3L).addReg(X86::EAX);
15933   BuildMI(mainMBB, DL, TII->get(TargetOpcode::COPY), t3H).addReg(X86::EDX);
15934
15935   BuildMI(mainMBB, DL, TII->get(X86::JNE_4)).addMBB(origMainMBB);
15936
15937   mainMBB->addSuccessor(origMainMBB);
15938   mainMBB->addSuccessor(sinkMBB);
15939
15940   // sinkMBB:
15941   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15942           TII->get(TargetOpcode::COPY), DstLoReg)
15943     .addReg(t3L);
15944   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
15945           TII->get(TargetOpcode::COPY), DstHiReg)
15946     .addReg(t3H);
15947
15948   MI->eraseFromParent();
15949   return sinkMBB;
15950 }
15951
15952 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
15953 // or XMM0_V32I8 in AVX all of this code can be replaced with that
15954 // in the .td file.
15955 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
15956                                        const TargetInstrInfo *TII) {
15957   unsigned Opc;
15958   switch (MI->getOpcode()) {
15959   default: llvm_unreachable("illegal opcode!");
15960   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
15961   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
15962   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
15963   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
15964   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
15965   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
15966   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
15967   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
15968   }
15969
15970   DebugLoc dl = MI->getDebugLoc();
15971   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
15972
15973   unsigned NumArgs = MI->getNumOperands();
15974   for (unsigned i = 1; i < NumArgs; ++i) {
15975     MachineOperand &Op = MI->getOperand(i);
15976     if (!(Op.isReg() && Op.isImplicit()))
15977       MIB.addOperand(Op);
15978   }
15979   if (MI->hasOneMemOperand())
15980     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
15981
15982   BuildMI(*BB, MI, dl,
15983     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
15984     .addReg(X86::XMM0);
15985
15986   MI->eraseFromParent();
15987   return BB;
15988 }
15989
15990 // FIXME: Custom handling because TableGen doesn't support multiple implicit
15991 // defs in an instruction pattern
15992 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
15993                                        const TargetInstrInfo *TII) {
15994   unsigned Opc;
15995   switch (MI->getOpcode()) {
15996   default: llvm_unreachable("illegal opcode!");
15997   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
15998   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
15999   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
16000   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
16001   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
16002   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
16003   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
16004   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
16005   }
16006
16007   DebugLoc dl = MI->getDebugLoc();
16008   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
16009
16010   unsigned NumArgs = MI->getNumOperands(); // remove the results
16011   for (unsigned i = 1; i < NumArgs; ++i) {
16012     MachineOperand &Op = MI->getOperand(i);
16013     if (!(Op.isReg() && Op.isImplicit()))
16014       MIB.addOperand(Op);
16015   }
16016   if (MI->hasOneMemOperand())
16017     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
16018
16019   BuildMI(*BB, MI, dl,
16020     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
16021     .addReg(X86::ECX);
16022
16023   MI->eraseFromParent();
16024   return BB;
16025 }
16026
16027 static MachineBasicBlock * EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
16028                                        const TargetInstrInfo *TII,
16029                                        const X86Subtarget* Subtarget) {
16030   DebugLoc dl = MI->getDebugLoc();
16031
16032   // Address into RAX/EAX, other two args into ECX, EDX.
16033   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
16034   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
16035   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
16036   for (int i = 0; i < X86::AddrNumOperands; ++i)
16037     MIB.addOperand(MI->getOperand(i));
16038
16039   unsigned ValOps = X86::AddrNumOperands;
16040   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
16041     .addReg(MI->getOperand(ValOps).getReg());
16042   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
16043     .addReg(MI->getOperand(ValOps+1).getReg());
16044
16045   // The instruction doesn't actually take any operands though.
16046   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
16047
16048   MI->eraseFromParent(); // The pseudo is gone now.
16049   return BB;
16050 }
16051
16052 MachineBasicBlock *
16053 X86TargetLowering::EmitVAARG64WithCustomInserter(
16054                    MachineInstr *MI,
16055                    MachineBasicBlock *MBB) const {
16056   // Emit va_arg instruction on X86-64.
16057
16058   // Operands to this pseudo-instruction:
16059   // 0  ) Output        : destination address (reg)
16060   // 1-5) Input         : va_list address (addr, i64mem)
16061   // 6  ) ArgSize       : Size (in bytes) of vararg type
16062   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
16063   // 8  ) Align         : Alignment of type
16064   // 9  ) EFLAGS (implicit-def)
16065
16066   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
16067   assert(X86::AddrNumOperands == 5 && "VAARG_64 assumes 5 address operands");
16068
16069   unsigned DestReg = MI->getOperand(0).getReg();
16070   MachineOperand &Base = MI->getOperand(1);
16071   MachineOperand &Scale = MI->getOperand(2);
16072   MachineOperand &Index = MI->getOperand(3);
16073   MachineOperand &Disp = MI->getOperand(4);
16074   MachineOperand &Segment = MI->getOperand(5);
16075   unsigned ArgSize = MI->getOperand(6).getImm();
16076   unsigned ArgMode = MI->getOperand(7).getImm();
16077   unsigned Align = MI->getOperand(8).getImm();
16078
16079   // Memory Reference
16080   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
16081   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16082   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16083
16084   // Machine Information
16085   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16086   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
16087   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
16088   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
16089   DebugLoc DL = MI->getDebugLoc();
16090
16091   // struct va_list {
16092   //   i32   gp_offset
16093   //   i32   fp_offset
16094   //   i64   overflow_area (address)
16095   //   i64   reg_save_area (address)
16096   // }
16097   // sizeof(va_list) = 24
16098   // alignment(va_list) = 8
16099
16100   unsigned TotalNumIntRegs = 6;
16101   unsigned TotalNumXMMRegs = 8;
16102   bool UseGPOffset = (ArgMode == 1);
16103   bool UseFPOffset = (ArgMode == 2);
16104   unsigned MaxOffset = TotalNumIntRegs * 8 +
16105                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
16106
16107   /* Align ArgSize to a multiple of 8 */
16108   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
16109   bool NeedsAlign = (Align > 8);
16110
16111   MachineBasicBlock *thisMBB = MBB;
16112   MachineBasicBlock *overflowMBB;
16113   MachineBasicBlock *offsetMBB;
16114   MachineBasicBlock *endMBB;
16115
16116   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
16117   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
16118   unsigned OffsetReg = 0;
16119
16120   if (!UseGPOffset && !UseFPOffset) {
16121     // If we only pull from the overflow region, we don't create a branch.
16122     // We don't need to alter control flow.
16123     OffsetDestReg = 0; // unused
16124     OverflowDestReg = DestReg;
16125
16126     offsetMBB = nullptr;
16127     overflowMBB = thisMBB;
16128     endMBB = thisMBB;
16129   } else {
16130     // First emit code to check if gp_offset (or fp_offset) is below the bound.
16131     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
16132     // If not, pull from overflow_area. (branch to overflowMBB)
16133     //
16134     //       thisMBB
16135     //         |     .
16136     //         |        .
16137     //     offsetMBB   overflowMBB
16138     //         |        .
16139     //         |     .
16140     //        endMBB
16141
16142     // Registers for the PHI in endMBB
16143     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
16144     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
16145
16146     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16147     MachineFunction *MF = MBB->getParent();
16148     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16149     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16150     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16151
16152     MachineFunction::iterator MBBIter = MBB;
16153     ++MBBIter;
16154
16155     // Insert the new basic blocks
16156     MF->insert(MBBIter, offsetMBB);
16157     MF->insert(MBBIter, overflowMBB);
16158     MF->insert(MBBIter, endMBB);
16159
16160     // Transfer the remainder of MBB and its successor edges to endMBB.
16161     endMBB->splice(endMBB->begin(), thisMBB,
16162                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
16163     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
16164
16165     // Make offsetMBB and overflowMBB successors of thisMBB
16166     thisMBB->addSuccessor(offsetMBB);
16167     thisMBB->addSuccessor(overflowMBB);
16168
16169     // endMBB is a successor of both offsetMBB and overflowMBB
16170     offsetMBB->addSuccessor(endMBB);
16171     overflowMBB->addSuccessor(endMBB);
16172
16173     // Load the offset value into a register
16174     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16175     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
16176       .addOperand(Base)
16177       .addOperand(Scale)
16178       .addOperand(Index)
16179       .addDisp(Disp, UseFPOffset ? 4 : 0)
16180       .addOperand(Segment)
16181       .setMemRefs(MMOBegin, MMOEnd);
16182
16183     // Check if there is enough room left to pull this argument.
16184     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
16185       .addReg(OffsetReg)
16186       .addImm(MaxOffset + 8 - ArgSizeA8);
16187
16188     // Branch to "overflowMBB" if offset >= max
16189     // Fall through to "offsetMBB" otherwise
16190     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
16191       .addMBB(overflowMBB);
16192   }
16193
16194   // In offsetMBB, emit code to use the reg_save_area.
16195   if (offsetMBB) {
16196     assert(OffsetReg != 0);
16197
16198     // Read the reg_save_area address.
16199     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
16200     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
16201       .addOperand(Base)
16202       .addOperand(Scale)
16203       .addOperand(Index)
16204       .addDisp(Disp, 16)
16205       .addOperand(Segment)
16206       .setMemRefs(MMOBegin, MMOEnd);
16207
16208     // Zero-extend the offset
16209     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
16210       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
16211         .addImm(0)
16212         .addReg(OffsetReg)
16213         .addImm(X86::sub_32bit);
16214
16215     // Add the offset to the reg_save_area to get the final address.
16216     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
16217       .addReg(OffsetReg64)
16218       .addReg(RegSaveReg);
16219
16220     // Compute the offset for the next argument
16221     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
16222     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
16223       .addReg(OffsetReg)
16224       .addImm(UseFPOffset ? 16 : 8);
16225
16226     // Store it back into the va_list.
16227     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
16228       .addOperand(Base)
16229       .addOperand(Scale)
16230       .addOperand(Index)
16231       .addDisp(Disp, UseFPOffset ? 4 : 0)
16232       .addOperand(Segment)
16233       .addReg(NextOffsetReg)
16234       .setMemRefs(MMOBegin, MMOEnd);
16235
16236     // Jump to endMBB
16237     BuildMI(offsetMBB, DL, TII->get(X86::JMP_4))
16238       .addMBB(endMBB);
16239   }
16240
16241   //
16242   // Emit code to use overflow area
16243   //
16244
16245   // Load the overflow_area address into a register.
16246   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
16247   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
16248     .addOperand(Base)
16249     .addOperand(Scale)
16250     .addOperand(Index)
16251     .addDisp(Disp, 8)
16252     .addOperand(Segment)
16253     .setMemRefs(MMOBegin, MMOEnd);
16254
16255   // If we need to align it, do so. Otherwise, just copy the address
16256   // to OverflowDestReg.
16257   if (NeedsAlign) {
16258     // Align the overflow address
16259     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
16260     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
16261
16262     // aligned_addr = (addr + (align-1)) & ~(align-1)
16263     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
16264       .addReg(OverflowAddrReg)
16265       .addImm(Align-1);
16266
16267     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
16268       .addReg(TmpReg)
16269       .addImm(~(uint64_t)(Align-1));
16270   } else {
16271     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
16272       .addReg(OverflowAddrReg);
16273   }
16274
16275   // Compute the next overflow address after this argument.
16276   // (the overflow address should be kept 8-byte aligned)
16277   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
16278   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
16279     .addReg(OverflowDestReg)
16280     .addImm(ArgSizeA8);
16281
16282   // Store the new overflow address.
16283   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
16284     .addOperand(Base)
16285     .addOperand(Scale)
16286     .addOperand(Index)
16287     .addDisp(Disp, 8)
16288     .addOperand(Segment)
16289     .addReg(NextAddrReg)
16290     .setMemRefs(MMOBegin, MMOEnd);
16291
16292   // If we branched, emit the PHI to the front of endMBB.
16293   if (offsetMBB) {
16294     BuildMI(*endMBB, endMBB->begin(), DL,
16295             TII->get(X86::PHI), DestReg)
16296       .addReg(OffsetDestReg).addMBB(offsetMBB)
16297       .addReg(OverflowDestReg).addMBB(overflowMBB);
16298   }
16299
16300   // Erase the pseudo instruction
16301   MI->eraseFromParent();
16302
16303   return endMBB;
16304 }
16305
16306 MachineBasicBlock *
16307 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
16308                                                  MachineInstr *MI,
16309                                                  MachineBasicBlock *MBB) const {
16310   // Emit code to save XMM registers to the stack. The ABI says that the
16311   // number of registers to save is given in %al, so it's theoretically
16312   // possible to do an indirect jump trick to avoid saving all of them,
16313   // however this code takes a simpler approach and just executes all
16314   // of the stores if %al is non-zero. It's less code, and it's probably
16315   // easier on the hardware branch predictor, and stores aren't all that
16316   // expensive anyway.
16317
16318   // Create the new basic blocks. One block contains all the XMM stores,
16319   // and one block is the final destination regardless of whether any
16320   // stores were performed.
16321   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
16322   MachineFunction *F = MBB->getParent();
16323   MachineFunction::iterator MBBIter = MBB;
16324   ++MBBIter;
16325   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
16326   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
16327   F->insert(MBBIter, XMMSaveMBB);
16328   F->insert(MBBIter, EndMBB);
16329
16330   // Transfer the remainder of MBB and its successor edges to EndMBB.
16331   EndMBB->splice(EndMBB->begin(), MBB,
16332                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16333   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
16334
16335   // The original block will now fall through to the XMM save block.
16336   MBB->addSuccessor(XMMSaveMBB);
16337   // The XMMSaveMBB will fall through to the end block.
16338   XMMSaveMBB->addSuccessor(EndMBB);
16339
16340   // Now add the instructions.
16341   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16342   DebugLoc DL = MI->getDebugLoc();
16343
16344   unsigned CountReg = MI->getOperand(0).getReg();
16345   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
16346   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
16347
16348   if (!Subtarget->isTargetWin64()) {
16349     // If %al is 0, branch around the XMM save block.
16350     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
16351     BuildMI(MBB, DL, TII->get(X86::JE_4)).addMBB(EndMBB);
16352     MBB->addSuccessor(EndMBB);
16353   }
16354
16355   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
16356   // that was just emitted, but clearly shouldn't be "saved".
16357   assert((MI->getNumOperands() <= 3 ||
16358           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
16359           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
16360          && "Expected last argument to be EFLAGS");
16361   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
16362   // In the XMM save block, save all the XMM argument registers.
16363   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
16364     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
16365     MachineMemOperand *MMO =
16366       F->getMachineMemOperand(
16367           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
16368         MachineMemOperand::MOStore,
16369         /*Size=*/16, /*Align=*/16);
16370     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
16371       .addFrameIndex(RegSaveFrameIndex)
16372       .addImm(/*Scale=*/1)
16373       .addReg(/*IndexReg=*/0)
16374       .addImm(/*Disp=*/Offset)
16375       .addReg(/*Segment=*/0)
16376       .addReg(MI->getOperand(i).getReg())
16377       .addMemOperand(MMO);
16378   }
16379
16380   MI->eraseFromParent();   // The pseudo instruction is gone now.
16381
16382   return EndMBB;
16383 }
16384
16385 // The EFLAGS operand of SelectItr might be missing a kill marker
16386 // because there were multiple uses of EFLAGS, and ISel didn't know
16387 // which to mark. Figure out whether SelectItr should have had a
16388 // kill marker, and set it if it should. Returns the correct kill
16389 // marker value.
16390 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
16391                                      MachineBasicBlock* BB,
16392                                      const TargetRegisterInfo* TRI) {
16393   // Scan forward through BB for a use/def of EFLAGS.
16394   MachineBasicBlock::iterator miI(std::next(SelectItr));
16395   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
16396     const MachineInstr& mi = *miI;
16397     if (mi.readsRegister(X86::EFLAGS))
16398       return false;
16399     if (mi.definesRegister(X86::EFLAGS))
16400       break; // Should have kill-flag - update below.
16401   }
16402
16403   // If we hit the end of the block, check whether EFLAGS is live into a
16404   // successor.
16405   if (miI == BB->end()) {
16406     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
16407                                           sEnd = BB->succ_end();
16408          sItr != sEnd; ++sItr) {
16409       MachineBasicBlock* succ = *sItr;
16410       if (succ->isLiveIn(X86::EFLAGS))
16411         return false;
16412     }
16413   }
16414
16415   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
16416   // out. SelectMI should have a kill flag on EFLAGS.
16417   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
16418   return true;
16419 }
16420
16421 MachineBasicBlock *
16422 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
16423                                      MachineBasicBlock *BB) const {
16424   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16425   DebugLoc DL = MI->getDebugLoc();
16426
16427   // To "insert" a SELECT_CC instruction, we actually have to insert the
16428   // diamond control-flow pattern.  The incoming instruction knows the
16429   // destination vreg to set, the condition code register to branch on, the
16430   // true/false values to select between, and a branch opcode to use.
16431   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16432   MachineFunction::iterator It = BB;
16433   ++It;
16434
16435   //  thisMBB:
16436   //  ...
16437   //   TrueVal = ...
16438   //   cmpTY ccX, r1, r2
16439   //   bCC copy1MBB
16440   //   fallthrough --> copy0MBB
16441   MachineBasicBlock *thisMBB = BB;
16442   MachineFunction *F = BB->getParent();
16443   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
16444   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
16445   F->insert(It, copy0MBB);
16446   F->insert(It, sinkMBB);
16447
16448   // If the EFLAGS register isn't dead in the terminator, then claim that it's
16449   // live into the sink and copy blocks.
16450   const TargetRegisterInfo* TRI = getTargetMachine().getRegisterInfo();
16451   if (!MI->killsRegister(X86::EFLAGS) &&
16452       !checkAndUpdateEFLAGSKill(MI, BB, TRI)) {
16453     copy0MBB->addLiveIn(X86::EFLAGS);
16454     sinkMBB->addLiveIn(X86::EFLAGS);
16455   }
16456
16457   // Transfer the remainder of BB and its successor edges to sinkMBB.
16458   sinkMBB->splice(sinkMBB->begin(), BB,
16459                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
16460   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
16461
16462   // Add the true and fallthrough blocks as its successors.
16463   BB->addSuccessor(copy0MBB);
16464   BB->addSuccessor(sinkMBB);
16465
16466   // Create the conditional branch instruction.
16467   unsigned Opc =
16468     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
16469   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
16470
16471   //  copy0MBB:
16472   //   %FalseValue = ...
16473   //   # fallthrough to sinkMBB
16474   copy0MBB->addSuccessor(sinkMBB);
16475
16476   //  sinkMBB:
16477   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
16478   //  ...
16479   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16480           TII->get(X86::PHI), MI->getOperand(0).getReg())
16481     .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
16482     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
16483
16484   MI->eraseFromParent();   // The pseudo instruction is gone now.
16485   return sinkMBB;
16486 }
16487
16488 MachineBasicBlock *
16489 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI, MachineBasicBlock *BB,
16490                                         bool Is64Bit) const {
16491   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16492   DebugLoc DL = MI->getDebugLoc();
16493   MachineFunction *MF = BB->getParent();
16494   const BasicBlock *LLVM_BB = BB->getBasicBlock();
16495
16496   assert(MF->shouldSplitStack());
16497
16498   unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
16499   unsigned TlsOffset = Is64Bit ? 0x70 : 0x30;
16500
16501   // BB:
16502   //  ... [Till the alloca]
16503   // If stacklet is not large enough, jump to mallocMBB
16504   //
16505   // bumpMBB:
16506   //  Allocate by subtracting from RSP
16507   //  Jump to continueMBB
16508   //
16509   // mallocMBB:
16510   //  Allocate by call to runtime
16511   //
16512   // continueMBB:
16513   //  ...
16514   //  [rest of original BB]
16515   //
16516
16517   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16518   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16519   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
16520
16521   MachineRegisterInfo &MRI = MF->getRegInfo();
16522   const TargetRegisterClass *AddrRegClass =
16523     getRegClassFor(Is64Bit ? MVT::i64:MVT::i32);
16524
16525   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16526     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
16527     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
16528     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
16529     sizeVReg = MI->getOperand(1).getReg(),
16530     physSPReg = Is64Bit ? X86::RSP : X86::ESP;
16531
16532   MachineFunction::iterator MBBIter = BB;
16533   ++MBBIter;
16534
16535   MF->insert(MBBIter, bumpMBB);
16536   MF->insert(MBBIter, mallocMBB);
16537   MF->insert(MBBIter, continueMBB);
16538
16539   continueMBB->splice(continueMBB->begin(), BB,
16540                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
16541   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
16542
16543   // Add code to the main basic block to check if the stack limit has been hit,
16544   // and if so, jump to mallocMBB otherwise to bumpMBB.
16545   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
16546   BuildMI(BB, DL, TII->get(Is64Bit ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
16547     .addReg(tmpSPVReg).addReg(sizeVReg);
16548   BuildMI(BB, DL, TII->get(Is64Bit ? X86::CMP64mr:X86::CMP32mr))
16549     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
16550     .addReg(SPLimitVReg);
16551   BuildMI(BB, DL, TII->get(X86::JG_4)).addMBB(mallocMBB);
16552
16553   // bumpMBB simply decreases the stack pointer, since we know the current
16554   // stacklet has enough space.
16555   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
16556     .addReg(SPLimitVReg);
16557   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
16558     .addReg(SPLimitVReg);
16559   BuildMI(bumpMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16560
16561   // Calls into a routine in libgcc to allocate more space from the heap.
16562   const uint32_t *RegMask =
16563     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16564   if (Is64Bit) {
16565     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
16566       .addReg(sizeVReg);
16567     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
16568       .addExternalSymbol("__morestack_allocate_stack_space")
16569       .addRegMask(RegMask)
16570       .addReg(X86::RDI, RegState::Implicit)
16571       .addReg(X86::RAX, RegState::ImplicitDefine);
16572   } else {
16573     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
16574       .addImm(12);
16575     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
16576     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
16577       .addExternalSymbol("__morestack_allocate_stack_space")
16578       .addRegMask(RegMask)
16579       .addReg(X86::EAX, RegState::ImplicitDefine);
16580   }
16581
16582   if (!Is64Bit)
16583     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
16584       .addImm(16);
16585
16586   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
16587     .addReg(Is64Bit ? X86::RAX : X86::EAX);
16588   BuildMI(mallocMBB, DL, TII->get(X86::JMP_4)).addMBB(continueMBB);
16589
16590   // Set up the CFG correctly.
16591   BB->addSuccessor(bumpMBB);
16592   BB->addSuccessor(mallocMBB);
16593   mallocMBB->addSuccessor(continueMBB);
16594   bumpMBB->addSuccessor(continueMBB);
16595
16596   // Take care of the PHI nodes.
16597   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
16598           MI->getOperand(0).getReg())
16599     .addReg(mallocPtrVReg).addMBB(mallocMBB)
16600     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
16601
16602   // Delete the original pseudo instruction.
16603   MI->eraseFromParent();
16604
16605   // And we're done.
16606   return continueMBB;
16607 }
16608
16609 MachineBasicBlock *
16610 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
16611                                           MachineBasicBlock *BB) const {
16612   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16613   DebugLoc DL = MI->getDebugLoc();
16614
16615   assert(!Subtarget->isTargetMacho());
16616
16617   // The lowering is pretty easy: we're just emitting the call to _alloca.  The
16618   // non-trivial part is impdef of ESP.
16619
16620   if (Subtarget->isTargetWin64()) {
16621     if (Subtarget->isTargetCygMing()) {
16622       // ___chkstk(Mingw64):
16623       // Clobbers R10, R11, RAX and EFLAGS.
16624       // Updates RSP.
16625       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16626         .addExternalSymbol("___chkstk")
16627         .addReg(X86::RAX, RegState::Implicit)
16628         .addReg(X86::RSP, RegState::Implicit)
16629         .addReg(X86::RAX, RegState::Define | RegState::Implicit)
16630         .addReg(X86::RSP, RegState::Define | RegState::Implicit)
16631         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16632     } else {
16633       // __chkstk(MSVCRT): does not update stack pointer.
16634       // Clobbers R10, R11 and EFLAGS.
16635       BuildMI(*BB, MI, DL, TII->get(X86::W64ALLOCA))
16636         .addExternalSymbol("__chkstk")
16637         .addReg(X86::RAX, RegState::Implicit)
16638         .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16639       // RAX has the offset to be subtracted from RSP.
16640       BuildMI(*BB, MI, DL, TII->get(X86::SUB64rr), X86::RSP)
16641         .addReg(X86::RSP)
16642         .addReg(X86::RAX);
16643     }
16644   } else {
16645     const char *StackProbeSymbol =
16646       Subtarget->isTargetKnownWindowsMSVC() ? "_chkstk" : "_alloca";
16647
16648     BuildMI(*BB, MI, DL, TII->get(X86::CALLpcrel32))
16649       .addExternalSymbol(StackProbeSymbol)
16650       .addReg(X86::EAX, RegState::Implicit)
16651       .addReg(X86::ESP, RegState::Implicit)
16652       .addReg(X86::EAX, RegState::Define | RegState::Implicit)
16653       .addReg(X86::ESP, RegState::Define | RegState::Implicit)
16654       .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
16655   }
16656
16657   MI->eraseFromParent();   // The pseudo instruction is gone now.
16658   return BB;
16659 }
16660
16661 MachineBasicBlock *
16662 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
16663                                       MachineBasicBlock *BB) const {
16664   // This is pretty easy.  We're taking the value that we received from
16665   // our load from the relocation, sticking it in either RDI (x86-64)
16666   // or EAX and doing an indirect call.  The return value will then
16667   // be in the normal return register.
16668   const X86InstrInfo *TII
16669     = static_cast<const X86InstrInfo*>(getTargetMachine().getInstrInfo());
16670   DebugLoc DL = MI->getDebugLoc();
16671   MachineFunction *F = BB->getParent();
16672
16673   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
16674   assert(MI->getOperand(3).isGlobal() && "This should be a global");
16675
16676   // Get a register mask for the lowered call.
16677   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
16678   // proper register mask.
16679   const uint32_t *RegMask =
16680     getTargetMachine().getRegisterInfo()->getCallPreservedMask(CallingConv::C);
16681   if (Subtarget->is64Bit()) {
16682     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16683                                       TII->get(X86::MOV64rm), X86::RDI)
16684     .addReg(X86::RIP)
16685     .addImm(0).addReg(0)
16686     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16687                       MI->getOperand(3).getTargetFlags())
16688     .addReg(0);
16689     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
16690     addDirectMem(MIB, X86::RDI);
16691     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
16692   } else if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
16693     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16694                                       TII->get(X86::MOV32rm), X86::EAX)
16695     .addReg(0)
16696     .addImm(0).addReg(0)
16697     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16698                       MI->getOperand(3).getTargetFlags())
16699     .addReg(0);
16700     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16701     addDirectMem(MIB, X86::EAX);
16702     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16703   } else {
16704     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
16705                                       TII->get(X86::MOV32rm), X86::EAX)
16706     .addReg(TII->getGlobalBaseReg(F))
16707     .addImm(0).addReg(0)
16708     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
16709                       MI->getOperand(3).getTargetFlags())
16710     .addReg(0);
16711     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
16712     addDirectMem(MIB, X86::EAX);
16713     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
16714   }
16715
16716   MI->eraseFromParent(); // The pseudo instruction is gone now.
16717   return BB;
16718 }
16719
16720 MachineBasicBlock *
16721 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
16722                                     MachineBasicBlock *MBB) const {
16723   DebugLoc DL = MI->getDebugLoc();
16724   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16725
16726   MachineFunction *MF = MBB->getParent();
16727   MachineRegisterInfo &MRI = MF->getRegInfo();
16728
16729   const BasicBlock *BB = MBB->getBasicBlock();
16730   MachineFunction::iterator I = MBB;
16731   ++I;
16732
16733   // Memory Reference
16734   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16735   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16736
16737   unsigned DstReg;
16738   unsigned MemOpndSlot = 0;
16739
16740   unsigned CurOp = 0;
16741
16742   DstReg = MI->getOperand(CurOp++).getReg();
16743   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
16744   assert(RC->hasType(MVT::i32) && "Invalid destination!");
16745   unsigned mainDstReg = MRI.createVirtualRegister(RC);
16746   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
16747
16748   MemOpndSlot = CurOp;
16749
16750   MVT PVT = getPointerTy();
16751   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16752          "Invalid Pointer Size!");
16753
16754   // For v = setjmp(buf), we generate
16755   //
16756   // thisMBB:
16757   //  buf[LabelOffset] = restoreMBB
16758   //  SjLjSetup restoreMBB
16759   //
16760   // mainMBB:
16761   //  v_main = 0
16762   //
16763   // sinkMBB:
16764   //  v = phi(main, restore)
16765   //
16766   // restoreMBB:
16767   //  v_restore = 1
16768
16769   MachineBasicBlock *thisMBB = MBB;
16770   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
16771   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
16772   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
16773   MF->insert(I, mainMBB);
16774   MF->insert(I, sinkMBB);
16775   MF->push_back(restoreMBB);
16776
16777   MachineInstrBuilder MIB;
16778
16779   // Transfer the remainder of BB and its successor edges to sinkMBB.
16780   sinkMBB->splice(sinkMBB->begin(), MBB,
16781                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
16782   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
16783
16784   // thisMBB:
16785   unsigned PtrStoreOpc = 0;
16786   unsigned LabelReg = 0;
16787   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16788   Reloc::Model RM = getTargetMachine().getRelocationModel();
16789   bool UseImmLabel = (getTargetMachine().getCodeModel() == CodeModel::Small) &&
16790                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
16791
16792   // Prepare IP either in reg or imm.
16793   if (!UseImmLabel) {
16794     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
16795     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
16796     LabelReg = MRI.createVirtualRegister(PtrRC);
16797     if (Subtarget->is64Bit()) {
16798       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
16799               .addReg(X86::RIP)
16800               .addImm(0)
16801               .addReg(0)
16802               .addMBB(restoreMBB)
16803               .addReg(0);
16804     } else {
16805       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
16806       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
16807               .addReg(XII->getGlobalBaseReg(MF))
16808               .addImm(0)
16809               .addReg(0)
16810               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
16811               .addReg(0);
16812     }
16813   } else
16814     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
16815   // Store IP
16816   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
16817   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16818     if (i == X86::AddrDisp)
16819       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
16820     else
16821       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
16822   }
16823   if (!UseImmLabel)
16824     MIB.addReg(LabelReg);
16825   else
16826     MIB.addMBB(restoreMBB);
16827   MIB.setMemRefs(MMOBegin, MMOEnd);
16828   // Setup
16829   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
16830           .addMBB(restoreMBB);
16831
16832   const X86RegisterInfo *RegInfo =
16833     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16834   MIB.addRegMask(RegInfo->getNoPreservedMask());
16835   thisMBB->addSuccessor(mainMBB);
16836   thisMBB->addSuccessor(restoreMBB);
16837
16838   // mainMBB:
16839   //  EAX = 0
16840   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
16841   mainMBB->addSuccessor(sinkMBB);
16842
16843   // sinkMBB:
16844   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
16845           TII->get(X86::PHI), DstReg)
16846     .addReg(mainDstReg).addMBB(mainMBB)
16847     .addReg(restoreDstReg).addMBB(restoreMBB);
16848
16849   // restoreMBB:
16850   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
16851   BuildMI(restoreMBB, DL, TII->get(X86::JMP_4)).addMBB(sinkMBB);
16852   restoreMBB->addSuccessor(sinkMBB);
16853
16854   MI->eraseFromParent();
16855   return sinkMBB;
16856 }
16857
16858 MachineBasicBlock *
16859 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
16860                                      MachineBasicBlock *MBB) const {
16861   DebugLoc DL = MI->getDebugLoc();
16862   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
16863
16864   MachineFunction *MF = MBB->getParent();
16865   MachineRegisterInfo &MRI = MF->getRegInfo();
16866
16867   // Memory Reference
16868   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
16869   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
16870
16871   MVT PVT = getPointerTy();
16872   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
16873          "Invalid Pointer Size!");
16874
16875   const TargetRegisterClass *RC =
16876     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
16877   unsigned Tmp = MRI.createVirtualRegister(RC);
16878   // Since FP is only updated here but NOT referenced, it's treated as GPR.
16879   const X86RegisterInfo *RegInfo =
16880     static_cast<const X86RegisterInfo*>(getTargetMachine().getRegisterInfo());
16881   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
16882   unsigned SP = RegInfo->getStackRegister();
16883
16884   MachineInstrBuilder MIB;
16885
16886   const int64_t LabelOffset = 1 * PVT.getStoreSize();
16887   const int64_t SPOffset = 2 * PVT.getStoreSize();
16888
16889   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
16890   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
16891
16892   // Reload FP
16893   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
16894   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
16895     MIB.addOperand(MI->getOperand(i));
16896   MIB.setMemRefs(MMOBegin, MMOEnd);
16897   // Reload IP
16898   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
16899   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16900     if (i == X86::AddrDisp)
16901       MIB.addDisp(MI->getOperand(i), LabelOffset);
16902     else
16903       MIB.addOperand(MI->getOperand(i));
16904   }
16905   MIB.setMemRefs(MMOBegin, MMOEnd);
16906   // Reload SP
16907   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
16908   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
16909     if (i == X86::AddrDisp)
16910       MIB.addDisp(MI->getOperand(i), SPOffset);
16911     else
16912       MIB.addOperand(MI->getOperand(i));
16913   }
16914   MIB.setMemRefs(MMOBegin, MMOEnd);
16915   // Jump
16916   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
16917
16918   MI->eraseFromParent();
16919   return MBB;
16920 }
16921
16922 // Replace 213-type (isel default) FMA3 instructions with 231-type for
16923 // accumulator loops. Writing back to the accumulator allows the coalescer
16924 // to remove extra copies in the loop.   
16925 MachineBasicBlock *
16926 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
16927                                  MachineBasicBlock *MBB) const {
16928   MachineOperand &AddendOp = MI->getOperand(3);
16929
16930   // Bail out early if the addend isn't a register - we can't switch these.
16931   if (!AddendOp.isReg())
16932     return MBB;
16933
16934   MachineFunction &MF = *MBB->getParent();
16935   MachineRegisterInfo &MRI = MF.getRegInfo();
16936
16937   // Check whether the addend is defined by a PHI:
16938   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
16939   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
16940   if (!AddendDef.isPHI())
16941     return MBB;
16942
16943   // Look for the following pattern:
16944   // loop:
16945   //   %addend = phi [%entry, 0], [%loop, %result]
16946   //   ...
16947   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
16948
16949   // Replace with:
16950   //   loop:
16951   //   %addend = phi [%entry, 0], [%loop, %result]
16952   //   ...
16953   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
16954
16955   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
16956     assert(AddendDef.getOperand(i).isReg());
16957     MachineOperand PHISrcOp = AddendDef.getOperand(i);
16958     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
16959     if (&PHISrcInst == MI) {
16960       // Found a matching instruction.
16961       unsigned NewFMAOpc = 0;
16962       switch (MI->getOpcode()) {
16963         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
16964         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
16965         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
16966         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
16967         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
16968         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
16969         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
16970         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
16971         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
16972         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
16973         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
16974         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
16975         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
16976         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
16977         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
16978         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
16979         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
16980         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
16981         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
16982         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
16983         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
16984         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
16985         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
16986         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
16987         default: llvm_unreachable("Unrecognized FMA variant.");
16988       }
16989
16990       const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
16991       MachineInstrBuilder MIB =
16992         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
16993         .addOperand(MI->getOperand(0))
16994         .addOperand(MI->getOperand(3))
16995         .addOperand(MI->getOperand(2))
16996         .addOperand(MI->getOperand(1));
16997       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
16998       MI->eraseFromParent();
16999     }
17000   }
17001
17002   return MBB;
17003 }
17004
17005 MachineBasicBlock *
17006 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
17007                                                MachineBasicBlock *BB) const {
17008   switch (MI->getOpcode()) {
17009   default: llvm_unreachable("Unexpected instr type to insert");
17010   case X86::TAILJMPd64:
17011   case X86::TAILJMPr64:
17012   case X86::TAILJMPm64:
17013     llvm_unreachable("TAILJMP64 would not be touched here.");
17014   case X86::TCRETURNdi64:
17015   case X86::TCRETURNri64:
17016   case X86::TCRETURNmi64:
17017     return BB;
17018   case X86::WIN_ALLOCA:
17019     return EmitLoweredWinAlloca(MI, BB);
17020   case X86::SEG_ALLOCA_32:
17021     return EmitLoweredSegAlloca(MI, BB, false);
17022   case X86::SEG_ALLOCA_64:
17023     return EmitLoweredSegAlloca(MI, BB, true);
17024   case X86::TLSCall_32:
17025   case X86::TLSCall_64:
17026     return EmitLoweredTLSCall(MI, BB);
17027   case X86::CMOV_GR8:
17028   case X86::CMOV_FR32:
17029   case X86::CMOV_FR64:
17030   case X86::CMOV_V4F32:
17031   case X86::CMOV_V2F64:
17032   case X86::CMOV_V2I64:
17033   case X86::CMOV_V8F32:
17034   case X86::CMOV_V4F64:
17035   case X86::CMOV_V4I64:
17036   case X86::CMOV_V16F32:
17037   case X86::CMOV_V8F64:
17038   case X86::CMOV_V8I64:
17039   case X86::CMOV_GR16:
17040   case X86::CMOV_GR32:
17041   case X86::CMOV_RFP32:
17042   case X86::CMOV_RFP64:
17043   case X86::CMOV_RFP80:
17044     return EmitLoweredSelect(MI, BB);
17045
17046   case X86::FP32_TO_INT16_IN_MEM:
17047   case X86::FP32_TO_INT32_IN_MEM:
17048   case X86::FP32_TO_INT64_IN_MEM:
17049   case X86::FP64_TO_INT16_IN_MEM:
17050   case X86::FP64_TO_INT32_IN_MEM:
17051   case X86::FP64_TO_INT64_IN_MEM:
17052   case X86::FP80_TO_INT16_IN_MEM:
17053   case X86::FP80_TO_INT32_IN_MEM:
17054   case X86::FP80_TO_INT64_IN_MEM: {
17055     const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
17056     DebugLoc DL = MI->getDebugLoc();
17057
17058     // Change the floating point control register to use "round towards zero"
17059     // mode when truncating to an integer value.
17060     MachineFunction *F = BB->getParent();
17061     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
17062     addFrameReference(BuildMI(*BB, MI, DL,
17063                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
17064
17065     // Load the old value of the high byte of the control word...
17066     unsigned OldCW =
17067       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
17068     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
17069                       CWFrameIdx);
17070
17071     // Set the high part to be round to zero...
17072     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
17073       .addImm(0xC7F);
17074
17075     // Reload the modified control word now...
17076     addFrameReference(BuildMI(*BB, MI, DL,
17077                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17078
17079     // Restore the memory image of control word to original value
17080     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
17081       .addReg(OldCW);
17082
17083     // Get the X86 opcode to use.
17084     unsigned Opc;
17085     switch (MI->getOpcode()) {
17086     default: llvm_unreachable("illegal opcode!");
17087     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
17088     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
17089     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
17090     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
17091     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
17092     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
17093     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
17094     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
17095     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
17096     }
17097
17098     X86AddressMode AM;
17099     MachineOperand &Op = MI->getOperand(0);
17100     if (Op.isReg()) {
17101       AM.BaseType = X86AddressMode::RegBase;
17102       AM.Base.Reg = Op.getReg();
17103     } else {
17104       AM.BaseType = X86AddressMode::FrameIndexBase;
17105       AM.Base.FrameIndex = Op.getIndex();
17106     }
17107     Op = MI->getOperand(1);
17108     if (Op.isImm())
17109       AM.Scale = Op.getImm();
17110     Op = MI->getOperand(2);
17111     if (Op.isImm())
17112       AM.IndexReg = Op.getImm();
17113     Op = MI->getOperand(3);
17114     if (Op.isGlobal()) {
17115       AM.GV = Op.getGlobal();
17116     } else {
17117       AM.Disp = Op.getImm();
17118     }
17119     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
17120                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
17121
17122     // Reload the original control word now.
17123     addFrameReference(BuildMI(*BB, MI, DL,
17124                               TII->get(X86::FLDCW16m)), CWFrameIdx);
17125
17126     MI->eraseFromParent();   // The pseudo instruction is gone now.
17127     return BB;
17128   }
17129     // String/text processing lowering.
17130   case X86::PCMPISTRM128REG:
17131   case X86::VPCMPISTRM128REG:
17132   case X86::PCMPISTRM128MEM:
17133   case X86::VPCMPISTRM128MEM:
17134   case X86::PCMPESTRM128REG:
17135   case X86::VPCMPESTRM128REG:
17136   case X86::PCMPESTRM128MEM:
17137   case X86::VPCMPESTRM128MEM:
17138     assert(Subtarget->hasSSE42() &&
17139            "Target must have SSE4.2 or AVX features enabled");
17140     return EmitPCMPSTRM(MI, BB, getTargetMachine().getInstrInfo());
17141
17142   // String/text processing lowering.
17143   case X86::PCMPISTRIREG:
17144   case X86::VPCMPISTRIREG:
17145   case X86::PCMPISTRIMEM:
17146   case X86::VPCMPISTRIMEM:
17147   case X86::PCMPESTRIREG:
17148   case X86::VPCMPESTRIREG:
17149   case X86::PCMPESTRIMEM:
17150   case X86::VPCMPESTRIMEM:
17151     assert(Subtarget->hasSSE42() &&
17152            "Target must have SSE4.2 or AVX features enabled");
17153     return EmitPCMPSTRI(MI, BB, getTargetMachine().getInstrInfo());
17154
17155   // Thread synchronization.
17156   case X86::MONITOR:
17157     return EmitMonitor(MI, BB, getTargetMachine().getInstrInfo(), Subtarget);
17158
17159   // xbegin
17160   case X86::XBEGIN:
17161     return EmitXBegin(MI, BB, getTargetMachine().getInstrInfo());
17162
17163   // Atomic Lowering.
17164   case X86::ATOMAND8:
17165   case X86::ATOMAND16:
17166   case X86::ATOMAND32:
17167   case X86::ATOMAND64:
17168     // Fall through
17169   case X86::ATOMOR8:
17170   case X86::ATOMOR16:
17171   case X86::ATOMOR32:
17172   case X86::ATOMOR64:
17173     // Fall through
17174   case X86::ATOMXOR16:
17175   case X86::ATOMXOR8:
17176   case X86::ATOMXOR32:
17177   case X86::ATOMXOR64:
17178     // Fall through
17179   case X86::ATOMNAND8:
17180   case X86::ATOMNAND16:
17181   case X86::ATOMNAND32:
17182   case X86::ATOMNAND64:
17183     // Fall through
17184   case X86::ATOMMAX8:
17185   case X86::ATOMMAX16:
17186   case X86::ATOMMAX32:
17187   case X86::ATOMMAX64:
17188     // Fall through
17189   case X86::ATOMMIN8:
17190   case X86::ATOMMIN16:
17191   case X86::ATOMMIN32:
17192   case X86::ATOMMIN64:
17193     // Fall through
17194   case X86::ATOMUMAX8:
17195   case X86::ATOMUMAX16:
17196   case X86::ATOMUMAX32:
17197   case X86::ATOMUMAX64:
17198     // Fall through
17199   case X86::ATOMUMIN8:
17200   case X86::ATOMUMIN16:
17201   case X86::ATOMUMIN32:
17202   case X86::ATOMUMIN64:
17203     return EmitAtomicLoadArith(MI, BB);
17204
17205   // This group does 64-bit operations on a 32-bit host.
17206   case X86::ATOMAND6432:
17207   case X86::ATOMOR6432:
17208   case X86::ATOMXOR6432:
17209   case X86::ATOMNAND6432:
17210   case X86::ATOMADD6432:
17211   case X86::ATOMSUB6432:
17212   case X86::ATOMMAX6432:
17213   case X86::ATOMMIN6432:
17214   case X86::ATOMUMAX6432:
17215   case X86::ATOMUMIN6432:
17216   case X86::ATOMSWAP6432:
17217     return EmitAtomicLoadArith6432(MI, BB);
17218
17219   case X86::VASTART_SAVE_XMM_REGS:
17220     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
17221
17222   case X86::VAARG_64:
17223     return EmitVAARG64WithCustomInserter(MI, BB);
17224
17225   case X86::EH_SjLj_SetJmp32:
17226   case X86::EH_SjLj_SetJmp64:
17227     return emitEHSjLjSetJmp(MI, BB);
17228
17229   case X86::EH_SjLj_LongJmp32:
17230   case X86::EH_SjLj_LongJmp64:
17231     return emitEHSjLjLongJmp(MI, BB);
17232
17233   case TargetOpcode::STACKMAP:
17234   case TargetOpcode::PATCHPOINT:
17235     return emitPatchPoint(MI, BB);
17236
17237   case X86::VFMADDPDr213r:
17238   case X86::VFMADDPSr213r:
17239   case X86::VFMADDSDr213r:
17240   case X86::VFMADDSSr213r:
17241   case X86::VFMSUBPDr213r:
17242   case X86::VFMSUBPSr213r:
17243   case X86::VFMSUBSDr213r:
17244   case X86::VFMSUBSSr213r:
17245   case X86::VFNMADDPDr213r:
17246   case X86::VFNMADDPSr213r:
17247   case X86::VFNMADDSDr213r:
17248   case X86::VFNMADDSSr213r:
17249   case X86::VFNMSUBPDr213r:
17250   case X86::VFNMSUBPSr213r:
17251   case X86::VFNMSUBSDr213r:
17252   case X86::VFNMSUBSSr213r:
17253   case X86::VFMADDPDr213rY:
17254   case X86::VFMADDPSr213rY:
17255   case X86::VFMSUBPDr213rY:
17256   case X86::VFMSUBPSr213rY:
17257   case X86::VFNMADDPDr213rY:
17258   case X86::VFNMADDPSr213rY:
17259   case X86::VFNMSUBPDr213rY:
17260   case X86::VFNMSUBPSr213rY:
17261     return emitFMA3Instr(MI, BB);
17262   }
17263 }
17264
17265 //===----------------------------------------------------------------------===//
17266 //                           X86 Optimization Hooks
17267 //===----------------------------------------------------------------------===//
17268
17269 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
17270                                                       APInt &KnownZero,
17271                                                       APInt &KnownOne,
17272                                                       const SelectionDAG &DAG,
17273                                                       unsigned Depth) const {
17274   unsigned BitWidth = KnownZero.getBitWidth();
17275   unsigned Opc = Op.getOpcode();
17276   assert((Opc >= ISD::BUILTIN_OP_END ||
17277           Opc == ISD::INTRINSIC_WO_CHAIN ||
17278           Opc == ISD::INTRINSIC_W_CHAIN ||
17279           Opc == ISD::INTRINSIC_VOID) &&
17280          "Should use MaskedValueIsZero if you don't know whether Op"
17281          " is a target node!");
17282
17283   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
17284   switch (Opc) {
17285   default: break;
17286   case X86ISD::ADD:
17287   case X86ISD::SUB:
17288   case X86ISD::ADC:
17289   case X86ISD::SBB:
17290   case X86ISD::SMUL:
17291   case X86ISD::UMUL:
17292   case X86ISD::INC:
17293   case X86ISD::DEC:
17294   case X86ISD::OR:
17295   case X86ISD::XOR:
17296   case X86ISD::AND:
17297     // These nodes' second result is a boolean.
17298     if (Op.getResNo() == 0)
17299       break;
17300     // Fallthrough
17301   case X86ISD::SETCC:
17302     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
17303     break;
17304   case ISD::INTRINSIC_WO_CHAIN: {
17305     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
17306     unsigned NumLoBits = 0;
17307     switch (IntId) {
17308     default: break;
17309     case Intrinsic::x86_sse_movmsk_ps:
17310     case Intrinsic::x86_avx_movmsk_ps_256:
17311     case Intrinsic::x86_sse2_movmsk_pd:
17312     case Intrinsic::x86_avx_movmsk_pd_256:
17313     case Intrinsic::x86_mmx_pmovmskb:
17314     case Intrinsic::x86_sse2_pmovmskb_128:
17315     case Intrinsic::x86_avx2_pmovmskb: {
17316       // High bits of movmskp{s|d}, pmovmskb are known zero.
17317       switch (IntId) {
17318         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
17319         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
17320         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
17321         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
17322         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
17323         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
17324         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
17325         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
17326       }
17327       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
17328       break;
17329     }
17330     }
17331     break;
17332   }
17333   }
17334 }
17335
17336 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
17337   SDValue Op,
17338   const SelectionDAG &,
17339   unsigned Depth) const {
17340   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
17341   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
17342     return Op.getValueType().getScalarType().getSizeInBits();
17343
17344   // Fallback case.
17345   return 1;
17346 }
17347
17348 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
17349 /// node is a GlobalAddress + offset.
17350 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
17351                                        const GlobalValue* &GA,
17352                                        int64_t &Offset) const {
17353   if (N->getOpcode() == X86ISD::Wrapper) {
17354     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
17355       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
17356       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
17357       return true;
17358     }
17359   }
17360   return TargetLowering::isGAPlusOffset(N, GA, Offset);
17361 }
17362
17363 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
17364 /// same as extracting the high 128-bit part of 256-bit vector and then
17365 /// inserting the result into the low part of a new 256-bit vector
17366 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
17367   EVT VT = SVOp->getValueType(0);
17368   unsigned NumElems = VT.getVectorNumElements();
17369
17370   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17371   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
17372     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17373         SVOp->getMaskElt(j) >= 0)
17374       return false;
17375
17376   return true;
17377 }
17378
17379 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
17380 /// same as extracting the low 128-bit part of 256-bit vector and then
17381 /// inserting the result into the high part of a new 256-bit vector
17382 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
17383   EVT VT = SVOp->getValueType(0);
17384   unsigned NumElems = VT.getVectorNumElements();
17385
17386   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17387   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
17388     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
17389         SVOp->getMaskElt(j) >= 0)
17390       return false;
17391
17392   return true;
17393 }
17394
17395 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
17396 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
17397                                         TargetLowering::DAGCombinerInfo &DCI,
17398                                         const X86Subtarget* Subtarget) {
17399   SDLoc dl(N);
17400   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17401   SDValue V1 = SVOp->getOperand(0);
17402   SDValue V2 = SVOp->getOperand(1);
17403   EVT VT = SVOp->getValueType(0);
17404   unsigned NumElems = VT.getVectorNumElements();
17405
17406   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
17407       V2.getOpcode() == ISD::CONCAT_VECTORS) {
17408     //
17409     //                   0,0,0,...
17410     //                      |
17411     //    V      UNDEF    BUILD_VECTOR    UNDEF
17412     //     \      /           \           /
17413     //  CONCAT_VECTOR         CONCAT_VECTOR
17414     //         \                  /
17415     //          \                /
17416     //          RESULT: V + zero extended
17417     //
17418     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
17419         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
17420         V1.getOperand(1).getOpcode() != ISD::UNDEF)
17421       return SDValue();
17422
17423     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
17424       return SDValue();
17425
17426     // To match the shuffle mask, the first half of the mask should
17427     // be exactly the first vector, and all the rest a splat with the
17428     // first element of the second one.
17429     for (unsigned i = 0; i != NumElems/2; ++i)
17430       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
17431           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
17432         return SDValue();
17433
17434     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
17435     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
17436       if (Ld->hasNUsesOfValue(1, 0)) {
17437         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
17438         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
17439         SDValue ResNode =
17440           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
17441                                   Ld->getMemoryVT(),
17442                                   Ld->getPointerInfo(),
17443                                   Ld->getAlignment(),
17444                                   false/*isVolatile*/, true/*ReadMem*/,
17445                                   false/*WriteMem*/);
17446
17447         // Make sure the newly-created LOAD is in the same position as Ld in
17448         // terms of dependency. We create a TokenFactor for Ld and ResNode,
17449         // and update uses of Ld's output chain to use the TokenFactor.
17450         if (Ld->hasAnyUseOfValue(1)) {
17451           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
17452                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
17453           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
17454           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
17455                                  SDValue(ResNode.getNode(), 1));
17456         }
17457
17458         return DAG.getNode(ISD::BITCAST, dl, VT, ResNode);
17459       }
17460     }
17461
17462     // Emit a zeroed vector and insert the desired subvector on its
17463     // first half.
17464     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17465     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
17466     return DCI.CombineTo(N, InsV);
17467   }
17468
17469   //===--------------------------------------------------------------------===//
17470   // Combine some shuffles into subvector extracts and inserts:
17471   //
17472
17473   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
17474   if (isShuffleHigh128VectorInsertLow(SVOp)) {
17475     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
17476     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
17477     return DCI.CombineTo(N, InsV);
17478   }
17479
17480   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
17481   if (isShuffleLow128VectorInsertHigh(SVOp)) {
17482     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
17483     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
17484     return DCI.CombineTo(N, InsV);
17485   }
17486
17487   return SDValue();
17488 }
17489
17490 /// PerformShuffleCombine - Performs several different shuffle combines.
17491 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
17492                                      TargetLowering::DAGCombinerInfo &DCI,
17493                                      const X86Subtarget *Subtarget) {
17494   SDLoc dl(N);
17495   SDValue N0 = N->getOperand(0);
17496   SDValue N1 = N->getOperand(1);
17497   EVT VT = N->getValueType(0);
17498
17499   // Don't create instructions with illegal types after legalize types has run.
17500   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17501   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
17502     return SDValue();
17503
17504   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
17505   if (Subtarget->hasFp256() && VT.is256BitVector() &&
17506       N->getOpcode() == ISD::VECTOR_SHUFFLE)
17507     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
17508
17509   // During Type Legalization, when promoting illegal vector types,
17510   // the backend might introduce new shuffle dag nodes and bitcasts.
17511   //
17512   // This code performs the following transformation:
17513   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
17514   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
17515   //
17516   // We do this only if both the bitcast and the BINOP dag nodes have
17517   // one use. Also, perform this transformation only if the new binary
17518   // operation is legal. This is to avoid introducing dag nodes that
17519   // potentially need to be further expanded (or custom lowered) into a
17520   // less optimal sequence of dag nodes.
17521   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
17522       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
17523       N0.getOpcode() == ISD::BITCAST) {
17524     SDValue BC0 = N0.getOperand(0);
17525     EVT SVT = BC0.getValueType();
17526     unsigned Opcode = BC0.getOpcode();
17527     unsigned NumElts = VT.getVectorNumElements();
17528     
17529     if (BC0.hasOneUse() && SVT.isVector() &&
17530         SVT.getVectorNumElements() * 2 == NumElts &&
17531         TLI.isOperationLegal(Opcode, VT)) {
17532       bool CanFold = false;
17533       switch (Opcode) {
17534       default : break;
17535       case ISD::ADD :
17536       case ISD::FADD :
17537       case ISD::SUB :
17538       case ISD::FSUB :
17539       case ISD::MUL :
17540       case ISD::FMUL :
17541         CanFold = true;
17542       }
17543
17544       unsigned SVTNumElts = SVT.getVectorNumElements();
17545       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
17546       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
17547         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
17548       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
17549         CanFold = SVOp->getMaskElt(i) < 0;
17550
17551       if (CanFold) {
17552         SDValue BC00 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(0));
17553         SDValue BC01 = DAG.getNode(ISD::BITCAST, dl, VT, BC0.getOperand(1));
17554         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
17555         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
17556       }
17557     }
17558   }
17559
17560   // Only handle 128 wide vector from here on.
17561   if (!VT.is128BitVector())
17562     return SDValue();
17563
17564   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
17565   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
17566   // consecutive, non-overlapping, and in the right order.
17567   SmallVector<SDValue, 16> Elts;
17568   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
17569     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
17570
17571   return EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true);
17572 }
17573
17574 /// PerformTruncateCombine - Converts truncate operation to
17575 /// a sequence of vector shuffle operations.
17576 /// It is possible when we truncate 256-bit vector to 128-bit vector
17577 static SDValue PerformTruncateCombine(SDNode *N, SelectionDAG &DAG,
17578                                       TargetLowering::DAGCombinerInfo &DCI,
17579                                       const X86Subtarget *Subtarget)  {
17580   return SDValue();
17581 }
17582
17583 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
17584 /// specific shuffle of a load can be folded into a single element load.
17585 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
17586 /// shuffles have been customed lowered so we need to handle those here.
17587 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
17588                                          TargetLowering::DAGCombinerInfo &DCI) {
17589   if (DCI.isBeforeLegalizeOps())
17590     return SDValue();
17591
17592   SDValue InVec = N->getOperand(0);
17593   SDValue EltNo = N->getOperand(1);
17594
17595   if (!isa<ConstantSDNode>(EltNo))
17596     return SDValue();
17597
17598   EVT VT = InVec.getValueType();
17599
17600   bool HasShuffleIntoBitcast = false;
17601   if (InVec.getOpcode() == ISD::BITCAST) {
17602     // Don't duplicate a load with other uses.
17603     if (!InVec.hasOneUse())
17604       return SDValue();
17605     EVT BCVT = InVec.getOperand(0).getValueType();
17606     if (BCVT.getVectorNumElements() != VT.getVectorNumElements())
17607       return SDValue();
17608     InVec = InVec.getOperand(0);
17609     HasShuffleIntoBitcast = true;
17610   }
17611
17612   if (!isTargetShuffle(InVec.getOpcode()))
17613     return SDValue();
17614
17615   // Don't duplicate a load with other uses.
17616   if (!InVec.hasOneUse())
17617     return SDValue();
17618
17619   SmallVector<int, 16> ShuffleMask;
17620   bool UnaryShuffle;
17621   if (!getTargetShuffleMask(InVec.getNode(), VT.getSimpleVT(), ShuffleMask,
17622                             UnaryShuffle))
17623     return SDValue();
17624
17625   // Select the input vector, guarding against out of range extract vector.
17626   unsigned NumElems = VT.getVectorNumElements();
17627   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
17628   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
17629   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
17630                                          : InVec.getOperand(1);
17631
17632   // If inputs to shuffle are the same for both ops, then allow 2 uses
17633   unsigned AllowedUses = InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
17634
17635   if (LdNode.getOpcode() == ISD::BITCAST) {
17636     // Don't duplicate a load with other uses.
17637     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
17638       return SDValue();
17639
17640     AllowedUses = 1; // only allow 1 load use if we have a bitcast
17641     LdNode = LdNode.getOperand(0);
17642   }
17643
17644   if (!ISD::isNormalLoad(LdNode.getNode()))
17645     return SDValue();
17646
17647   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
17648
17649   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
17650     return SDValue();
17651
17652   if (HasShuffleIntoBitcast) {
17653     // If there's a bitcast before the shuffle, check if the load type and
17654     // alignment is valid.
17655     unsigned Align = LN0->getAlignment();
17656     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17657     unsigned NewAlign = TLI.getDataLayout()->
17658       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
17659
17660     if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VT))
17661       return SDValue();
17662   }
17663
17664   // All checks match so transform back to vector_shuffle so that DAG combiner
17665   // can finish the job
17666   SDLoc dl(N);
17667
17668   // Create shuffle node taking into account the case that its a unary shuffle
17669   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(VT) : InVec.getOperand(1);
17670   Shuffle = DAG.getVectorShuffle(InVec.getValueType(), dl,
17671                                  InVec.getOperand(0), Shuffle,
17672                                  &ShuffleMask[0]);
17673   Shuffle = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
17674   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
17675                      EltNo);
17676 }
17677
17678 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
17679 /// generation and convert it from being a bunch of shuffles and extracts
17680 /// to a simple store and scalar loads to extract the elements.
17681 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
17682                                          TargetLowering::DAGCombinerInfo &DCI) {
17683   SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI);
17684   if (NewOp.getNode())
17685     return NewOp;
17686
17687   SDValue InputVector = N->getOperand(0);
17688
17689   // Detect whether we are trying to convert from mmx to i32 and the bitcast
17690   // from mmx to v2i32 has a single usage.
17691   if (InputVector.getNode()->getOpcode() == llvm::ISD::BITCAST &&
17692       InputVector.getNode()->getOperand(0).getValueType() == MVT::x86mmx &&
17693       InputVector.hasOneUse() && N->getValueType(0) == MVT::i32)
17694     return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
17695                        N->getValueType(0),
17696                        InputVector.getNode()->getOperand(0));
17697
17698   // Only operate on vectors of 4 elements, where the alternative shuffling
17699   // gets to be more expensive.
17700   if (InputVector.getValueType() != MVT::v4i32)
17701     return SDValue();
17702
17703   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
17704   // single use which is a sign-extend or zero-extend, and all elements are
17705   // used.
17706   SmallVector<SDNode *, 4> Uses;
17707   unsigned ExtractedElements = 0;
17708   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
17709        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
17710     if (UI.getUse().getResNo() != InputVector.getResNo())
17711       return SDValue();
17712
17713     SDNode *Extract = *UI;
17714     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
17715       return SDValue();
17716
17717     if (Extract->getValueType(0) != MVT::i32)
17718       return SDValue();
17719     if (!Extract->hasOneUse())
17720       return SDValue();
17721     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
17722         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
17723       return SDValue();
17724     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
17725       return SDValue();
17726
17727     // Record which element was extracted.
17728     ExtractedElements |=
17729       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
17730
17731     Uses.push_back(Extract);
17732   }
17733
17734   // If not all the elements were used, this may not be worthwhile.
17735   if (ExtractedElements != 15)
17736     return SDValue();
17737
17738   // Ok, we've now decided to do the transformation.
17739   SDLoc dl(InputVector);
17740
17741   // Store the value to a temporary stack slot.
17742   SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
17743   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
17744                             MachinePointerInfo(), false, false, 0);
17745
17746   // Replace each use (extract) with a load of the appropriate element.
17747   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
17748        UE = Uses.end(); UI != UE; ++UI) {
17749     SDNode *Extract = *UI;
17750
17751     // cOMpute the element's address.
17752     SDValue Idx = Extract->getOperand(1);
17753     unsigned EltSize =
17754         InputVector.getValueType().getVectorElementType().getSizeInBits()/8;
17755     uint64_t Offset = EltSize * cast<ConstantSDNode>(Idx)->getZExtValue();
17756     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17757     SDValue OffsetVal = DAG.getConstant(Offset, TLI.getPointerTy());
17758
17759     SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
17760                                      StackPtr, OffsetVal);
17761
17762     // Load the scalar.
17763     SDValue LoadScalar = DAG.getLoad(Extract->getValueType(0), dl, Ch,
17764                                      ScalarAddr, MachinePointerInfo(),
17765                                      false, false, false, 0);
17766
17767     // Replace the exact with the load.
17768     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), LoadScalar);
17769   }
17770
17771   // The replacement was made in place; don't return anything.
17772   return SDValue();
17773 }
17774
17775 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
17776 static std::pair<unsigned, bool>
17777 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
17778                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
17779   if (!VT.isVector())
17780     return std::make_pair(0, false);
17781
17782   bool NeedSplit = false;
17783   switch (VT.getSimpleVT().SimpleTy) {
17784   default: return std::make_pair(0, false);
17785   case MVT::v32i8:
17786   case MVT::v16i16:
17787   case MVT::v8i32:
17788     if (!Subtarget->hasAVX2())
17789       NeedSplit = true;
17790     if (!Subtarget->hasAVX())
17791       return std::make_pair(0, false);
17792     break;
17793   case MVT::v16i8:
17794   case MVT::v8i16:
17795   case MVT::v4i32:
17796     if (!Subtarget->hasSSE2())
17797       return std::make_pair(0, false);
17798   }
17799
17800   // SSE2 has only a small subset of the operations.
17801   bool hasUnsigned = Subtarget->hasSSE41() ||
17802                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
17803   bool hasSigned = Subtarget->hasSSE41() ||
17804                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
17805
17806   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17807
17808   unsigned Opc = 0;
17809   // Check for x CC y ? x : y.
17810   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17811       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17812     switch (CC) {
17813     default: break;
17814     case ISD::SETULT:
17815     case ISD::SETULE:
17816       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17817     case ISD::SETUGT:
17818     case ISD::SETUGE:
17819       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17820     case ISD::SETLT:
17821     case ISD::SETLE:
17822       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17823     case ISD::SETGT:
17824     case ISD::SETGE:
17825       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17826     }
17827   // Check for x CC y ? y : x -- a min/max with reversed arms.
17828   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17829              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17830     switch (CC) {
17831     default: break;
17832     case ISD::SETULT:
17833     case ISD::SETULE:
17834       Opc = hasUnsigned ? X86ISD::UMAX : 0; break;
17835     case ISD::SETUGT:
17836     case ISD::SETUGE:
17837       Opc = hasUnsigned ? X86ISD::UMIN : 0; break;
17838     case ISD::SETLT:
17839     case ISD::SETLE:
17840       Opc = hasSigned ? X86ISD::SMAX : 0; break;
17841     case ISD::SETGT:
17842     case ISD::SETGE:
17843       Opc = hasSigned ? X86ISD::SMIN : 0; break;
17844     }
17845   }
17846
17847   return std::make_pair(Opc, NeedSplit);
17848 }
17849
17850 static SDValue
17851 TransformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
17852                                       const X86Subtarget *Subtarget) {
17853   SDLoc dl(N);
17854   SDValue Cond = N->getOperand(0);
17855   SDValue LHS = N->getOperand(1);
17856   SDValue RHS = N->getOperand(2);
17857
17858   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
17859     SDValue CondSrc = Cond->getOperand(0);
17860     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
17861       Cond = CondSrc->getOperand(0);
17862   }
17863
17864   MVT VT = N->getSimpleValueType(0);
17865   MVT EltVT = VT.getVectorElementType();
17866   unsigned NumElems = VT.getVectorNumElements();
17867   // There is no blend with immediate in AVX-512.
17868   if (VT.is512BitVector())
17869     return SDValue();
17870
17871   if (!Subtarget->hasSSE41() || EltVT == MVT::i8)
17872     return SDValue();
17873   if (!Subtarget->hasInt256() && VT == MVT::v16i16)
17874     return SDValue();
17875
17876   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
17877     return SDValue();
17878
17879   unsigned MaskValue = 0;
17880   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
17881     return SDValue();
17882
17883   SmallVector<int, 8> ShuffleMask(NumElems, -1);
17884   for (unsigned i = 0; i < NumElems; ++i) {
17885     // Be sure we emit undef where we can.
17886     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
17887       ShuffleMask[i] = -1;
17888     else
17889       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
17890   }
17891
17892   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
17893 }
17894
17895 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
17896 /// nodes.
17897 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
17898                                     TargetLowering::DAGCombinerInfo &DCI,
17899                                     const X86Subtarget *Subtarget) {
17900   SDLoc DL(N);
17901   SDValue Cond = N->getOperand(0);
17902   // Get the LHS/RHS of the select.
17903   SDValue LHS = N->getOperand(1);
17904   SDValue RHS = N->getOperand(2);
17905   EVT VT = LHS.getValueType();
17906   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
17907
17908   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
17909   // instructions match the semantics of the common C idiom x<y?x:y but not
17910   // x<=y?x:y, because of how they handle negative zero (which can be
17911   // ignored in unsafe-math mode).
17912   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
17913       VT != MVT::f80 && TLI.isTypeLegal(VT) &&
17914       (Subtarget->hasSSE2() ||
17915        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
17916     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
17917
17918     unsigned Opcode = 0;
17919     // Check for x CC y ? x : y.
17920     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
17921         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
17922       switch (CC) {
17923       default: break;
17924       case ISD::SETULT:
17925         // Converting this to a min would handle NaNs incorrectly, and swapping
17926         // the operands would cause it to handle comparisons between positive
17927         // and negative zero incorrectly.
17928         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17929           if (!DAG.getTarget().Options.UnsafeFPMath &&
17930               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17931             break;
17932           std::swap(LHS, RHS);
17933         }
17934         Opcode = X86ISD::FMIN;
17935         break;
17936       case ISD::SETOLE:
17937         // Converting this to a min would handle comparisons between positive
17938         // and negative zero incorrectly.
17939         if (!DAG.getTarget().Options.UnsafeFPMath &&
17940             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17941           break;
17942         Opcode = X86ISD::FMIN;
17943         break;
17944       case ISD::SETULE:
17945         // Converting this to a min would handle both negative zeros and NaNs
17946         // incorrectly, but we can swap the operands to fix both.
17947         std::swap(LHS, RHS);
17948       case ISD::SETOLT:
17949       case ISD::SETLT:
17950       case ISD::SETLE:
17951         Opcode = X86ISD::FMIN;
17952         break;
17953
17954       case ISD::SETOGE:
17955         // Converting this to a max would handle comparisons between positive
17956         // and negative zero incorrectly.
17957         if (!DAG.getTarget().Options.UnsafeFPMath &&
17958             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
17959           break;
17960         Opcode = X86ISD::FMAX;
17961         break;
17962       case ISD::SETUGT:
17963         // Converting this to a max would handle NaNs incorrectly, and swapping
17964         // the operands would cause it to handle comparisons between positive
17965         // and negative zero incorrectly.
17966         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
17967           if (!DAG.getTarget().Options.UnsafeFPMath &&
17968               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
17969             break;
17970           std::swap(LHS, RHS);
17971         }
17972         Opcode = X86ISD::FMAX;
17973         break;
17974       case ISD::SETUGE:
17975         // Converting this to a max would handle both negative zeros and NaNs
17976         // incorrectly, but we can swap the operands to fix both.
17977         std::swap(LHS, RHS);
17978       case ISD::SETOGT:
17979       case ISD::SETGT:
17980       case ISD::SETGE:
17981         Opcode = X86ISD::FMAX;
17982         break;
17983       }
17984     // Check for x CC y ? y : x -- a min/max with reversed arms.
17985     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
17986                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
17987       switch (CC) {
17988       default: break;
17989       case ISD::SETOGE:
17990         // Converting this to a min would handle comparisons between positive
17991         // and negative zero incorrectly, and swapping the operands would
17992         // cause it to handle NaNs incorrectly.
17993         if (!DAG.getTarget().Options.UnsafeFPMath &&
17994             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
17995           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
17996             break;
17997           std::swap(LHS, RHS);
17998         }
17999         Opcode = X86ISD::FMIN;
18000         break;
18001       case ISD::SETUGT:
18002         // Converting this to a min would handle NaNs incorrectly.
18003         if (!DAG.getTarget().Options.UnsafeFPMath &&
18004             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
18005           break;
18006         Opcode = X86ISD::FMIN;
18007         break;
18008       case ISD::SETUGE:
18009         // Converting this to a min would handle both negative zeros and NaNs
18010         // incorrectly, but we can swap the operands to fix both.
18011         std::swap(LHS, RHS);
18012       case ISD::SETOGT:
18013       case ISD::SETGT:
18014       case ISD::SETGE:
18015         Opcode = X86ISD::FMIN;
18016         break;
18017
18018       case ISD::SETULT:
18019         // Converting this to a max would handle NaNs incorrectly.
18020         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18021           break;
18022         Opcode = X86ISD::FMAX;
18023         break;
18024       case ISD::SETOLE:
18025         // Converting this to a max would handle comparisons between positive
18026         // and negative zero incorrectly, and swapping the operands would
18027         // cause it to handle NaNs incorrectly.
18028         if (!DAG.getTarget().Options.UnsafeFPMath &&
18029             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
18030           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
18031             break;
18032           std::swap(LHS, RHS);
18033         }
18034         Opcode = X86ISD::FMAX;
18035         break;
18036       case ISD::SETULE:
18037         // Converting this to a max would handle both negative zeros and NaNs
18038         // incorrectly, but we can swap the operands to fix both.
18039         std::swap(LHS, RHS);
18040       case ISD::SETOLT:
18041       case ISD::SETLT:
18042       case ISD::SETLE:
18043         Opcode = X86ISD::FMAX;
18044         break;
18045       }
18046     }
18047
18048     if (Opcode)
18049       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
18050   }
18051
18052   EVT CondVT = Cond.getValueType();
18053   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
18054       CondVT.getVectorElementType() == MVT::i1) {
18055     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
18056     // lowering on AVX-512. In this case we convert it to
18057     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
18058     // The same situation for all 128 and 256-bit vectors of i8 and i16
18059     EVT OpVT = LHS.getValueType();
18060     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
18061         (OpVT.getVectorElementType() == MVT::i8 ||
18062          OpVT.getVectorElementType() == MVT::i16)) {
18063       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
18064       DCI.AddToWorklist(Cond.getNode());
18065       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
18066     }
18067   }
18068   // If this is a select between two integer constants, try to do some
18069   // optimizations.
18070   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
18071     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
18072       // Don't do this for crazy integer types.
18073       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
18074         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
18075         // so that TrueC (the true value) is larger than FalseC.
18076         bool NeedsCondInvert = false;
18077
18078         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
18079             // Efficiently invertible.
18080             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
18081              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
18082               isa<ConstantSDNode>(Cond.getOperand(1))))) {
18083           NeedsCondInvert = true;
18084           std::swap(TrueC, FalseC);
18085         }
18086
18087         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
18088         if (FalseC->getAPIntValue() == 0 &&
18089             TrueC->getAPIntValue().isPowerOf2()) {
18090           if (NeedsCondInvert) // Invert the condition if needed.
18091             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18092                                DAG.getConstant(1, Cond.getValueType()));
18093
18094           // Zero extend the condition if needed.
18095           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
18096
18097           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18098           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
18099                              DAG.getConstant(ShAmt, MVT::i8));
18100         }
18101
18102         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
18103         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18104           if (NeedsCondInvert) // Invert the condition if needed.
18105             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18106                                DAG.getConstant(1, Cond.getValueType()));
18107
18108           // Zero extend the condition if needed.
18109           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18110                              FalseC->getValueType(0), Cond);
18111           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18112                              SDValue(FalseC, 0));
18113         }
18114
18115         // Optimize cases that will turn into an LEA instruction.  This requires
18116         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18117         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18118           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18119           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18120
18121           bool isFastMultiplier = false;
18122           if (Diff < 10) {
18123             switch ((unsigned char)Diff) {
18124               default: break;
18125               case 1:  // result = add base, cond
18126               case 2:  // result = lea base(    , cond*2)
18127               case 3:  // result = lea base(cond, cond*2)
18128               case 4:  // result = lea base(    , cond*4)
18129               case 5:  // result = lea base(cond, cond*4)
18130               case 8:  // result = lea base(    , cond*8)
18131               case 9:  // result = lea base(cond, cond*8)
18132                 isFastMultiplier = true;
18133                 break;
18134             }
18135           }
18136
18137           if (isFastMultiplier) {
18138             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18139             if (NeedsCondInvert) // Invert the condition if needed.
18140               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
18141                                  DAG.getConstant(1, Cond.getValueType()));
18142
18143             // Zero extend the condition if needed.
18144             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18145                                Cond);
18146             // Scale the condition by the difference.
18147             if (Diff != 1)
18148               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18149                                  DAG.getConstant(Diff, Cond.getValueType()));
18150
18151             // Add the base if non-zero.
18152             if (FalseC->getAPIntValue() != 0)
18153               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18154                                  SDValue(FalseC, 0));
18155             return Cond;
18156           }
18157         }
18158       }
18159   }
18160
18161   // Canonicalize max and min:
18162   // (x > y) ? x : y -> (x >= y) ? x : y
18163   // (x < y) ? x : y -> (x <= y) ? x : y
18164   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
18165   // the need for an extra compare
18166   // against zero. e.g.
18167   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
18168   // subl   %esi, %edi
18169   // testl  %edi, %edi
18170   // movl   $0, %eax
18171   // cmovgl %edi, %eax
18172   // =>
18173   // xorl   %eax, %eax
18174   // subl   %esi, $edi
18175   // cmovsl %eax, %edi
18176   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
18177       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
18178       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
18179     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18180     switch (CC) {
18181     default: break;
18182     case ISD::SETLT:
18183     case ISD::SETGT: {
18184       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
18185       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
18186                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
18187       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
18188     }
18189     }
18190   }
18191
18192   // Early exit check
18193   if (!TLI.isTypeLegal(VT))
18194     return SDValue();
18195
18196   // Match VSELECTs into subs with unsigned saturation.
18197   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18198       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
18199       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
18200        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
18201     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
18202
18203     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
18204     // left side invert the predicate to simplify logic below.
18205     SDValue Other;
18206     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
18207       Other = RHS;
18208       CC = ISD::getSetCCInverse(CC, true);
18209     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
18210       Other = LHS;
18211     }
18212
18213     if (Other.getNode() && Other->getNumOperands() == 2 &&
18214         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
18215       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
18216       SDValue CondRHS = Cond->getOperand(1);
18217
18218       // Look for a general sub with unsigned saturation first.
18219       // x >= y ? x-y : 0 --> subus x, y
18220       // x >  y ? x-y : 0 --> subus x, y
18221       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
18222           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
18223         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18224
18225       // If the RHS is a constant we have to reverse the const canonicalization.
18226       // x > C-1 ? x+-C : 0 --> subus x, C
18227       if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
18228           isSplatVector(CondRHS.getNode()) && isSplatVector(OpRHS.getNode())) {
18229         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18230         if (CondRHS.getConstantOperandVal(0) == -A-1)
18231           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS,
18232                              DAG.getConstant(-A, VT));
18233       }
18234
18235       // Another special case: If C was a sign bit, the sub has been
18236       // canonicalized into a xor.
18237       // FIXME: Would it be better to use computeKnownBits to determine whether
18238       //        it's safe to decanonicalize the xor?
18239       // x s< 0 ? x^C : 0 --> subus x, C
18240       if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
18241           ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
18242           isSplatVector(OpRHS.getNode())) {
18243         APInt A = cast<ConstantSDNode>(OpRHS.getOperand(0))->getAPIntValue();
18244         if (A.isSignBit())
18245           return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
18246       }
18247     }
18248   }
18249
18250   // Try to match a min/max vector operation.
18251   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
18252     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
18253     unsigned Opc = ret.first;
18254     bool NeedSplit = ret.second;
18255
18256     if (Opc && NeedSplit) {
18257       unsigned NumElems = VT.getVectorNumElements();
18258       // Extract the LHS vectors
18259       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
18260       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
18261
18262       // Extract the RHS vectors
18263       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
18264       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
18265
18266       // Create min/max for each subvector
18267       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
18268       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
18269
18270       // Merge the result
18271       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
18272     } else if (Opc)
18273       return DAG.getNode(Opc, DL, VT, LHS, RHS);
18274   }
18275
18276   // Simplify vector selection if the selector will be produced by CMPP*/PCMP*.
18277   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
18278       // Check if SETCC has already been promoted
18279       TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT &&
18280       // Check that condition value type matches vselect operand type
18281       CondVT == VT) { 
18282
18283     assert(Cond.getValueType().isVector() &&
18284            "vector select expects a vector selector!");
18285
18286     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
18287     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
18288
18289     if (!TValIsAllOnes && !FValIsAllZeros) {
18290       // Try invert the condition if true value is not all 1s and false value
18291       // is not all 0s.
18292       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
18293       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
18294
18295       if (TValIsAllZeros || FValIsAllOnes) {
18296         SDValue CC = Cond.getOperand(2);
18297         ISD::CondCode NewCC =
18298           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
18299                                Cond.getOperand(0).getValueType().isInteger());
18300         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
18301         std::swap(LHS, RHS);
18302         TValIsAllOnes = FValIsAllOnes;
18303         FValIsAllZeros = TValIsAllZeros;
18304       }
18305     }
18306
18307     if (TValIsAllOnes || FValIsAllZeros) {
18308       SDValue Ret;
18309
18310       if (TValIsAllOnes && FValIsAllZeros)
18311         Ret = Cond;
18312       else if (TValIsAllOnes)
18313         Ret = DAG.getNode(ISD::OR, DL, CondVT, Cond,
18314                           DAG.getNode(ISD::BITCAST, DL, CondVT, RHS));
18315       else if (FValIsAllZeros)
18316         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
18317                           DAG.getNode(ISD::BITCAST, DL, CondVT, LHS));
18318
18319       return DAG.getNode(ISD::BITCAST, DL, VT, Ret);
18320     }
18321   }
18322
18323   // Try to fold this VSELECT into a MOVSS/MOVSD
18324   if (N->getOpcode() == ISD::VSELECT &&
18325       Cond.getOpcode() == ISD::BUILD_VECTOR && !DCI.isBeforeLegalize()) {
18326     if (VT == MVT::v4i32 || VT == MVT::v4f32 ||
18327         (Subtarget->hasSSE2() && (VT == MVT::v2i64 || VT == MVT::v2f64))) {
18328       bool CanFold = false;
18329       unsigned NumElems = Cond.getNumOperands();
18330       SDValue A = LHS;
18331       SDValue B = RHS;
18332       
18333       if (isZero(Cond.getOperand(0))) {
18334         CanFold = true;
18335
18336         // fold (vselect <0,-1,-1,-1>, A, B) -> (movss A, B)
18337         // fold (vselect <0,-1> -> (movsd A, B)
18338         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18339           CanFold = isAllOnes(Cond.getOperand(i));
18340       } else if (isAllOnes(Cond.getOperand(0))) {
18341         CanFold = true;
18342         std::swap(A, B);
18343
18344         // fold (vselect <-1,0,0,0>, A, B) -> (movss B, A)
18345         // fold (vselect <-1,0> -> (movsd B, A)
18346         for (unsigned i = 1, e = NumElems; i != e && CanFold; ++i)
18347           CanFold = isZero(Cond.getOperand(i));
18348       }
18349
18350       if (CanFold) {
18351         if (VT == MVT::v4i32 || VT == MVT::v4f32)
18352           return getTargetShuffleNode(X86ISD::MOVSS, DL, VT, A, B, DAG);
18353         return getTargetShuffleNode(X86ISD::MOVSD, DL, VT, A, B, DAG);
18354       }
18355
18356       if (Subtarget->hasSSE2() && (VT == MVT::v4i32 || VT == MVT::v4f32)) {
18357         // fold (v4i32: vselect <0,0,-1,-1>, A, B) ->
18358         //      (v4i32 (bitcast (movsd (v2i64 (bitcast A)),
18359         //                             (v2i64 (bitcast B)))))
18360         //
18361         // fold (v4f32: vselect <0,0,-1,-1>, A, B) ->
18362         //      (v4f32 (bitcast (movsd (v2f64 (bitcast A)),
18363         //                             (v2f64 (bitcast B)))))
18364         //
18365         // fold (v4i32: vselect <-1,-1,0,0>, A, B) ->
18366         //      (v4i32 (bitcast (movsd (v2i64 (bitcast B)),
18367         //                             (v2i64 (bitcast A)))))
18368         //
18369         // fold (v4f32: vselect <-1,-1,0,0>, A, B) ->
18370         //      (v4f32 (bitcast (movsd (v2f64 (bitcast B)),
18371         //                             (v2f64 (bitcast A)))))
18372
18373         CanFold = (isZero(Cond.getOperand(0)) &&
18374                    isZero(Cond.getOperand(1)) &&
18375                    isAllOnes(Cond.getOperand(2)) &&
18376                    isAllOnes(Cond.getOperand(3)));
18377
18378         if (!CanFold && isAllOnes(Cond.getOperand(0)) &&
18379             isAllOnes(Cond.getOperand(1)) &&
18380             isZero(Cond.getOperand(2)) &&
18381             isZero(Cond.getOperand(3))) {
18382           CanFold = true;
18383           std::swap(LHS, RHS);
18384         }
18385
18386         if (CanFold) {
18387           EVT NVT = (VT == MVT::v4i32) ? MVT::v2i64 : MVT::v2f64;
18388           SDValue NewA = DAG.getNode(ISD::BITCAST, DL, NVT, LHS);
18389           SDValue NewB = DAG.getNode(ISD::BITCAST, DL, NVT, RHS);
18390           SDValue Select = getTargetShuffleNode(X86ISD::MOVSD, DL, NVT, NewA,
18391                                                 NewB, DAG);
18392           return DAG.getNode(ISD::BITCAST, DL, VT, Select);
18393         }
18394       }
18395     }
18396   }
18397
18398   // If we know that this node is legal then we know that it is going to be
18399   // matched by one of the SSE/AVX BLEND instructions. These instructions only
18400   // depend on the highest bit in each word. Try to use SimplifyDemandedBits
18401   // to simplify previous instructions.
18402   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
18403       !DCI.isBeforeLegalize() &&
18404       // We explicitly check against v8i16 and v16i16 because, although
18405       // they're marked as Custom, they might only be legal when Cond is a
18406       // build_vector of constants. This will be taken care in a later
18407       // condition.
18408       (TLI.isOperationLegalOrCustom(ISD::VSELECT, VT) && VT != MVT::v16i16 &&
18409        VT != MVT::v8i16)) {
18410     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
18411
18412     // Don't optimize vector selects that map to mask-registers.
18413     if (BitWidth == 1)
18414       return SDValue();
18415
18416     // Check all uses of that condition operand to check whether it will be
18417     // consumed by non-BLEND instructions, which may depend on all bits are set
18418     // properly.
18419     for (SDNode::use_iterator I = Cond->use_begin(),
18420                               E = Cond->use_end(); I != E; ++I)
18421       if (I->getOpcode() != ISD::VSELECT)
18422         // TODO: Add other opcodes eventually lowered into BLEND.
18423         return SDValue();
18424
18425     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
18426     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
18427
18428     APInt KnownZero, KnownOne;
18429     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
18430                                           DCI.isBeforeLegalizeOps());
18431     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
18432         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne, TLO))
18433       DCI.CommitTargetLoweringOpt(TLO);
18434   }
18435
18436   // We should generate an X86ISD::BLENDI from a vselect if its argument
18437   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
18438   // constants. This specific pattern gets generated when we split a
18439   // selector for a 512 bit vector in a machine without AVX512 (but with
18440   // 256-bit vectors), during legalization:
18441   //
18442   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
18443   //
18444   // Iff we find this pattern and the build_vectors are built from
18445   // constants, we translate the vselect into a shuffle_vector that we
18446   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
18447   if (N->getOpcode() == ISD::VSELECT && !DCI.isBeforeLegalize()) {
18448     SDValue Shuffle = TransformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
18449     if (Shuffle.getNode())
18450       return Shuffle;
18451   }
18452
18453   return SDValue();
18454 }
18455
18456 // Check whether a boolean test is testing a boolean value generated by
18457 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
18458 // code.
18459 //
18460 // Simplify the following patterns:
18461 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
18462 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
18463 // to (Op EFLAGS Cond)
18464 //
18465 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
18466 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
18467 // to (Op EFLAGS !Cond)
18468 //
18469 // where Op could be BRCOND or CMOV.
18470 //
18471 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
18472   // Quit if not CMP and SUB with its value result used.
18473   if (Cmp.getOpcode() != X86ISD::CMP &&
18474       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
18475       return SDValue();
18476
18477   // Quit if not used as a boolean value.
18478   if (CC != X86::COND_E && CC != X86::COND_NE)
18479     return SDValue();
18480
18481   // Check CMP operands. One of them should be 0 or 1 and the other should be
18482   // an SetCC or extended from it.
18483   SDValue Op1 = Cmp.getOperand(0);
18484   SDValue Op2 = Cmp.getOperand(1);
18485
18486   SDValue SetCC;
18487   const ConstantSDNode* C = nullptr;
18488   bool needOppositeCond = (CC == X86::COND_E);
18489   bool checkAgainstTrue = false; // Is it a comparison against 1?
18490
18491   if ((C = dyn_cast<ConstantSDNode>(Op1)))
18492     SetCC = Op2;
18493   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
18494     SetCC = Op1;
18495   else // Quit if all operands are not constants.
18496     return SDValue();
18497
18498   if (C->getZExtValue() == 1) {
18499     needOppositeCond = !needOppositeCond;
18500     checkAgainstTrue = true;
18501   } else if (C->getZExtValue() != 0)
18502     // Quit if the constant is neither 0 or 1.
18503     return SDValue();
18504
18505   bool truncatedToBoolWithAnd = false;
18506   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
18507   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
18508          SetCC.getOpcode() == ISD::TRUNCATE ||
18509          SetCC.getOpcode() == ISD::AND) {
18510     if (SetCC.getOpcode() == ISD::AND) {
18511       int OpIdx = -1;
18512       ConstantSDNode *CS;
18513       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
18514           CS->getZExtValue() == 1)
18515         OpIdx = 1;
18516       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
18517           CS->getZExtValue() == 1)
18518         OpIdx = 0;
18519       if (OpIdx == -1)
18520         break;
18521       SetCC = SetCC.getOperand(OpIdx);
18522       truncatedToBoolWithAnd = true;
18523     } else
18524       SetCC = SetCC.getOperand(0);
18525   }
18526
18527   switch (SetCC.getOpcode()) {
18528   case X86ISD::SETCC_CARRY:
18529     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
18530     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
18531     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
18532     // truncated to i1 using 'and'.
18533     if (checkAgainstTrue && !truncatedToBoolWithAnd)
18534       break;
18535     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
18536            "Invalid use of SETCC_CARRY!");
18537     // FALL THROUGH
18538   case X86ISD::SETCC:
18539     // Set the condition code or opposite one if necessary.
18540     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
18541     if (needOppositeCond)
18542       CC = X86::GetOppositeBranchCondition(CC);
18543     return SetCC.getOperand(1);
18544   case X86ISD::CMOV: {
18545     // Check whether false/true value has canonical one, i.e. 0 or 1.
18546     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
18547     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
18548     // Quit if true value is not a constant.
18549     if (!TVal)
18550       return SDValue();
18551     // Quit if false value is not a constant.
18552     if (!FVal) {
18553       SDValue Op = SetCC.getOperand(0);
18554       // Skip 'zext' or 'trunc' node.
18555       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
18556           Op.getOpcode() == ISD::TRUNCATE)
18557         Op = Op.getOperand(0);
18558       // A special case for rdrand/rdseed, where 0 is set if false cond is
18559       // found.
18560       if ((Op.getOpcode() != X86ISD::RDRAND &&
18561            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
18562         return SDValue();
18563     }
18564     // Quit if false value is not the constant 0 or 1.
18565     bool FValIsFalse = true;
18566     if (FVal && FVal->getZExtValue() != 0) {
18567       if (FVal->getZExtValue() != 1)
18568         return SDValue();
18569       // If FVal is 1, opposite cond is needed.
18570       needOppositeCond = !needOppositeCond;
18571       FValIsFalse = false;
18572     }
18573     // Quit if TVal is not the constant opposite of FVal.
18574     if (FValIsFalse && TVal->getZExtValue() != 1)
18575       return SDValue();
18576     if (!FValIsFalse && TVal->getZExtValue() != 0)
18577       return SDValue();
18578     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
18579     if (needOppositeCond)
18580       CC = X86::GetOppositeBranchCondition(CC);
18581     return SetCC.getOperand(3);
18582   }
18583   }
18584
18585   return SDValue();
18586 }
18587
18588 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
18589 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
18590                                   TargetLowering::DAGCombinerInfo &DCI,
18591                                   const X86Subtarget *Subtarget) {
18592   SDLoc DL(N);
18593
18594   // If the flag operand isn't dead, don't touch this CMOV.
18595   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
18596     return SDValue();
18597
18598   SDValue FalseOp = N->getOperand(0);
18599   SDValue TrueOp = N->getOperand(1);
18600   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
18601   SDValue Cond = N->getOperand(3);
18602
18603   if (CC == X86::COND_E || CC == X86::COND_NE) {
18604     switch (Cond.getOpcode()) {
18605     default: break;
18606     case X86ISD::BSR:
18607     case X86ISD::BSF:
18608       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
18609       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
18610         return (CC == X86::COND_E) ? FalseOp : TrueOp;
18611     }
18612   }
18613
18614   SDValue Flags;
18615
18616   Flags = checkBoolTestSetCCCombine(Cond, CC);
18617   if (Flags.getNode() &&
18618       // Extra check as FCMOV only supports a subset of X86 cond.
18619       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
18620     SDValue Ops[] = { FalseOp, TrueOp,
18621                       DAG.getConstant(CC, MVT::i8), Flags };
18622     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
18623   }
18624
18625   // If this is a select between two integer constants, try to do some
18626   // optimizations.  Note that the operands are ordered the opposite of SELECT
18627   // operands.
18628   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
18629     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
18630       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
18631       // larger than FalseC (the false value).
18632       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
18633         CC = X86::GetOppositeBranchCondition(CC);
18634         std::swap(TrueC, FalseC);
18635         std::swap(TrueOp, FalseOp);
18636       }
18637
18638       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
18639       // This is efficient for any integer data type (including i8/i16) and
18640       // shift amount.
18641       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
18642         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18643                            DAG.getConstant(CC, MVT::i8), Cond);
18644
18645         // Zero extend the condition if needed.
18646         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
18647
18648         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
18649         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
18650                            DAG.getConstant(ShAmt, MVT::i8));
18651         if (N->getNumValues() == 2)  // Dead flag value?
18652           return DCI.CombineTo(N, Cond, SDValue());
18653         return Cond;
18654       }
18655
18656       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
18657       // for any integer data type, including i8/i16.
18658       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
18659         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18660                            DAG.getConstant(CC, MVT::i8), Cond);
18661
18662         // Zero extend the condition if needed.
18663         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
18664                            FalseC->getValueType(0), Cond);
18665         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18666                            SDValue(FalseC, 0));
18667
18668         if (N->getNumValues() == 2)  // Dead flag value?
18669           return DCI.CombineTo(N, Cond, SDValue());
18670         return Cond;
18671       }
18672
18673       // Optimize cases that will turn into an LEA instruction.  This requires
18674       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
18675       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
18676         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
18677         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
18678
18679         bool isFastMultiplier = false;
18680         if (Diff < 10) {
18681           switch ((unsigned char)Diff) {
18682           default: break;
18683           case 1:  // result = add base, cond
18684           case 2:  // result = lea base(    , cond*2)
18685           case 3:  // result = lea base(cond, cond*2)
18686           case 4:  // result = lea base(    , cond*4)
18687           case 5:  // result = lea base(cond, cond*4)
18688           case 8:  // result = lea base(    , cond*8)
18689           case 9:  // result = lea base(cond, cond*8)
18690             isFastMultiplier = true;
18691             break;
18692           }
18693         }
18694
18695         if (isFastMultiplier) {
18696           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
18697           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
18698                              DAG.getConstant(CC, MVT::i8), Cond);
18699           // Zero extend the condition if needed.
18700           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
18701                              Cond);
18702           // Scale the condition by the difference.
18703           if (Diff != 1)
18704             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
18705                                DAG.getConstant(Diff, Cond.getValueType()));
18706
18707           // Add the base if non-zero.
18708           if (FalseC->getAPIntValue() != 0)
18709             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
18710                                SDValue(FalseC, 0));
18711           if (N->getNumValues() == 2)  // Dead flag value?
18712             return DCI.CombineTo(N, Cond, SDValue());
18713           return Cond;
18714         }
18715       }
18716     }
18717   }
18718
18719   // Handle these cases:
18720   //   (select (x != c), e, c) -> select (x != c), e, x),
18721   //   (select (x == c), c, e) -> select (x == c), x, e)
18722   // where the c is an integer constant, and the "select" is the combination
18723   // of CMOV and CMP.
18724   //
18725   // The rationale for this change is that the conditional-move from a constant
18726   // needs two instructions, however, conditional-move from a register needs
18727   // only one instruction.
18728   //
18729   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
18730   //  some instruction-combining opportunities. This opt needs to be
18731   //  postponed as late as possible.
18732   //
18733   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
18734     // the DCI.xxxx conditions are provided to postpone the optimization as
18735     // late as possible.
18736
18737     ConstantSDNode *CmpAgainst = nullptr;
18738     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
18739         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
18740         !isa<ConstantSDNode>(Cond.getOperand(0))) {
18741
18742       if (CC == X86::COND_NE &&
18743           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
18744         CC = X86::GetOppositeBranchCondition(CC);
18745         std::swap(TrueOp, FalseOp);
18746       }
18747
18748       if (CC == X86::COND_E &&
18749           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
18750         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
18751                           DAG.getConstant(CC, MVT::i8), Cond };
18752         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
18753       }
18754     }
18755   }
18756
18757   return SDValue();
18758 }
18759
18760 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
18761                                                 const X86Subtarget *Subtarget) {
18762   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
18763   switch (IntNo) {
18764   default: return SDValue();
18765   // SSE/AVX/AVX2 blend intrinsics.
18766   case Intrinsic::x86_avx2_pblendvb:
18767   case Intrinsic::x86_avx2_pblendw:
18768   case Intrinsic::x86_avx2_pblendd_128:
18769   case Intrinsic::x86_avx2_pblendd_256:
18770     // Don't try to simplify this intrinsic if we don't have AVX2.
18771     if (!Subtarget->hasAVX2())
18772       return SDValue();
18773     // FALL-THROUGH
18774   case Intrinsic::x86_avx_blend_pd_256:
18775   case Intrinsic::x86_avx_blend_ps_256:
18776   case Intrinsic::x86_avx_blendv_pd_256:
18777   case Intrinsic::x86_avx_blendv_ps_256:
18778     // Don't try to simplify this intrinsic if we don't have AVX.
18779     if (!Subtarget->hasAVX())
18780       return SDValue();
18781     // FALL-THROUGH
18782   case Intrinsic::x86_sse41_pblendw:
18783   case Intrinsic::x86_sse41_blendpd:
18784   case Intrinsic::x86_sse41_blendps:
18785   case Intrinsic::x86_sse41_blendvps:
18786   case Intrinsic::x86_sse41_blendvpd:
18787   case Intrinsic::x86_sse41_pblendvb: {
18788     SDValue Op0 = N->getOperand(1);
18789     SDValue Op1 = N->getOperand(2);
18790     SDValue Mask = N->getOperand(3);
18791
18792     // Don't try to simplify this intrinsic if we don't have SSE4.1.
18793     if (!Subtarget->hasSSE41())
18794       return SDValue();
18795
18796     // fold (blend A, A, Mask) -> A
18797     if (Op0 == Op1)
18798       return Op0;
18799     // fold (blend A, B, allZeros) -> A
18800     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
18801       return Op0;
18802     // fold (blend A, B, allOnes) -> B
18803     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
18804       return Op1;
18805     
18806     // Simplify the case where the mask is a constant i32 value.
18807     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
18808       if (C->isNullValue())
18809         return Op0;
18810       if (C->isAllOnesValue())
18811         return Op1;
18812     }
18813   }
18814
18815   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
18816   case Intrinsic::x86_sse2_psrai_w:
18817   case Intrinsic::x86_sse2_psrai_d:
18818   case Intrinsic::x86_avx2_psrai_w:
18819   case Intrinsic::x86_avx2_psrai_d:
18820   case Intrinsic::x86_sse2_psra_w:
18821   case Intrinsic::x86_sse2_psra_d:
18822   case Intrinsic::x86_avx2_psra_w:
18823   case Intrinsic::x86_avx2_psra_d: {
18824     SDValue Op0 = N->getOperand(1);
18825     SDValue Op1 = N->getOperand(2);
18826     EVT VT = Op0.getValueType();
18827     assert(VT.isVector() && "Expected a vector type!");
18828
18829     if (isa<BuildVectorSDNode>(Op1))
18830       Op1 = Op1.getOperand(0);
18831
18832     if (!isa<ConstantSDNode>(Op1))
18833       return SDValue();
18834
18835     EVT SVT = VT.getVectorElementType();
18836     unsigned SVTBits = SVT.getSizeInBits();
18837
18838     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
18839     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
18840     uint64_t ShAmt = C.getZExtValue();
18841
18842     // Don't try to convert this shift into a ISD::SRA if the shift
18843     // count is bigger than or equal to the element size.
18844     if (ShAmt >= SVTBits)
18845       return SDValue();
18846
18847     // Trivial case: if the shift count is zero, then fold this
18848     // into the first operand.
18849     if (ShAmt == 0)
18850       return Op0;
18851
18852     // Replace this packed shift intrinsic with a target independent
18853     // shift dag node.
18854     SDValue Splat = DAG.getConstant(C, VT);
18855     return DAG.getNode(ISD::SRA, SDLoc(N), VT, Op0, Splat);
18856   }
18857   }
18858 }
18859
18860 /// PerformMulCombine - Optimize a single multiply with constant into two
18861 /// in order to implement it with two cheaper instructions, e.g.
18862 /// LEA + SHL, LEA + LEA.
18863 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
18864                                  TargetLowering::DAGCombinerInfo &DCI) {
18865   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
18866     return SDValue();
18867
18868   EVT VT = N->getValueType(0);
18869   if (VT != MVT::i64)
18870     return SDValue();
18871
18872   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
18873   if (!C)
18874     return SDValue();
18875   uint64_t MulAmt = C->getZExtValue();
18876   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
18877     return SDValue();
18878
18879   uint64_t MulAmt1 = 0;
18880   uint64_t MulAmt2 = 0;
18881   if ((MulAmt % 9) == 0) {
18882     MulAmt1 = 9;
18883     MulAmt2 = MulAmt / 9;
18884   } else if ((MulAmt % 5) == 0) {
18885     MulAmt1 = 5;
18886     MulAmt2 = MulAmt / 5;
18887   } else if ((MulAmt % 3) == 0) {
18888     MulAmt1 = 3;
18889     MulAmt2 = MulAmt / 3;
18890   }
18891   if (MulAmt2 &&
18892       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
18893     SDLoc DL(N);
18894
18895     if (isPowerOf2_64(MulAmt2) &&
18896         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
18897       // If second multiplifer is pow2, issue it first. We want the multiply by
18898       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
18899       // is an add.
18900       std::swap(MulAmt1, MulAmt2);
18901
18902     SDValue NewMul;
18903     if (isPowerOf2_64(MulAmt1))
18904       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
18905                            DAG.getConstant(Log2_64(MulAmt1), MVT::i8));
18906     else
18907       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
18908                            DAG.getConstant(MulAmt1, VT));
18909
18910     if (isPowerOf2_64(MulAmt2))
18911       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
18912                            DAG.getConstant(Log2_64(MulAmt2), MVT::i8));
18913     else
18914       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
18915                            DAG.getConstant(MulAmt2, VT));
18916
18917     // Do not add new nodes to DAG combiner worklist.
18918     DCI.CombineTo(N, NewMul, false);
18919   }
18920   return SDValue();
18921 }
18922
18923 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
18924   SDValue N0 = N->getOperand(0);
18925   SDValue N1 = N->getOperand(1);
18926   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
18927   EVT VT = N0.getValueType();
18928
18929   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
18930   // since the result of setcc_c is all zero's or all ones.
18931   if (VT.isInteger() && !VT.isVector() &&
18932       N1C && N0.getOpcode() == ISD::AND &&
18933       N0.getOperand(1).getOpcode() == ISD::Constant) {
18934     SDValue N00 = N0.getOperand(0);
18935     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
18936         ((N00.getOpcode() == ISD::ANY_EXTEND ||
18937           N00.getOpcode() == ISD::ZERO_EXTEND) &&
18938          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
18939       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
18940       APInt ShAmt = N1C->getAPIntValue();
18941       Mask = Mask.shl(ShAmt);
18942       if (Mask != 0)
18943         return DAG.getNode(ISD::AND, SDLoc(N), VT,
18944                            N00, DAG.getConstant(Mask, VT));
18945     }
18946   }
18947
18948   // Hardware support for vector shifts is sparse which makes us scalarize the
18949   // vector operations in many cases. Also, on sandybridge ADD is faster than
18950   // shl.
18951   // (shl V, 1) -> add V,V
18952   if (isSplatVector(N1.getNode())) {
18953     assert(N0.getValueType().isVector() && "Invalid vector shift type");
18954     ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(0));
18955     // We shift all of the values by one. In many cases we do not have
18956     // hardware support for this operation. This is better expressed as an ADD
18957     // of two values.
18958     if (N1C && (1 == N1C->getZExtValue())) {
18959       return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
18960     }
18961   }
18962
18963   return SDValue();
18964 }
18965
18966 /// \brief Returns a vector of 0s if the node in input is a vector logical
18967 /// shift by a constant amount which is known to be bigger than or equal
18968 /// to the vector element size in bits.
18969 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
18970                                       const X86Subtarget *Subtarget) {
18971   EVT VT = N->getValueType(0);
18972
18973   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
18974       (!Subtarget->hasInt256() ||
18975        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
18976     return SDValue();
18977
18978   SDValue Amt = N->getOperand(1);
18979   SDLoc DL(N);
18980   if (isSplatVector(Amt.getNode())) {
18981     SDValue SclrAmt = Amt->getOperand(0);
18982     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt)) {
18983       APInt ShiftAmt = C->getAPIntValue();
18984       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
18985
18986       // SSE2/AVX2 logical shifts always return a vector of 0s
18987       // if the shift amount is bigger than or equal to
18988       // the element size. The constant shift amount will be
18989       // encoded as a 8-bit immediate.
18990       if (ShiftAmt.trunc(8).uge(MaxAmount))
18991         return getZeroVector(VT, Subtarget, DAG, DL);
18992     }
18993   }
18994
18995   return SDValue();
18996 }
18997
18998 /// PerformShiftCombine - Combine shifts.
18999 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
19000                                    TargetLowering::DAGCombinerInfo &DCI,
19001                                    const X86Subtarget *Subtarget) {
19002   if (N->getOpcode() == ISD::SHL) {
19003     SDValue V = PerformSHLCombine(N, DAG);
19004     if (V.getNode()) return V;
19005   }
19006
19007   if (N->getOpcode() != ISD::SRA) {
19008     // Try to fold this logical shift into a zero vector.
19009     SDValue V = performShiftToAllZeros(N, DAG, Subtarget);
19010     if (V.getNode()) return V;
19011   }
19012
19013   return SDValue();
19014 }
19015
19016 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
19017 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
19018 // and friends.  Likewise for OR -> CMPNEQSS.
19019 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
19020                             TargetLowering::DAGCombinerInfo &DCI,
19021                             const X86Subtarget *Subtarget) {
19022   unsigned opcode;
19023
19024   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
19025   // we're requiring SSE2 for both.
19026   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
19027     SDValue N0 = N->getOperand(0);
19028     SDValue N1 = N->getOperand(1);
19029     SDValue CMP0 = N0->getOperand(1);
19030     SDValue CMP1 = N1->getOperand(1);
19031     SDLoc DL(N);
19032
19033     // The SETCCs should both refer to the same CMP.
19034     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
19035       return SDValue();
19036
19037     SDValue CMP00 = CMP0->getOperand(0);
19038     SDValue CMP01 = CMP0->getOperand(1);
19039     EVT     VT    = CMP00.getValueType();
19040
19041     if (VT == MVT::f32 || VT == MVT::f64) {
19042       bool ExpectingFlags = false;
19043       // Check for any users that want flags:
19044       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
19045            !ExpectingFlags && UI != UE; ++UI)
19046         switch (UI->getOpcode()) {
19047         default:
19048         case ISD::BR_CC:
19049         case ISD::BRCOND:
19050         case ISD::SELECT:
19051           ExpectingFlags = true;
19052           break;
19053         case ISD::CopyToReg:
19054         case ISD::SIGN_EXTEND:
19055         case ISD::ZERO_EXTEND:
19056         case ISD::ANY_EXTEND:
19057           break;
19058         }
19059
19060       if (!ExpectingFlags) {
19061         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
19062         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
19063
19064         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
19065           X86::CondCode tmp = cc0;
19066           cc0 = cc1;
19067           cc1 = tmp;
19068         }
19069
19070         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
19071             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
19072           // FIXME: need symbolic constants for these magic numbers.
19073           // See X86ATTInstPrinter.cpp:printSSECC().
19074           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
19075           if (Subtarget->hasAVX512()) {
19076             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
19077                                          CMP01, DAG.getConstant(x86cc, MVT::i8));
19078             if (N->getValueType(0) != MVT::i1)
19079               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
19080                                  FSetCC);
19081             return FSetCC;
19082           }
19083           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
19084                                               CMP00.getValueType(), CMP00, CMP01,
19085                                               DAG.getConstant(x86cc, MVT::i8));
19086
19087           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
19088           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
19089
19090           if (is64BitFP && !Subtarget->is64Bit()) {
19091             // On a 32-bit target, we cannot bitcast the 64-bit float to a
19092             // 64-bit integer, since that's not a legal type. Since
19093             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
19094             // bits, but can do this little dance to extract the lowest 32 bits
19095             // and work with those going forward.
19096             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
19097                                            OnesOrZeroesF);
19098             SDValue Vector32 = DAG.getNode(ISD::BITCAST, DL, MVT::v4f32,
19099                                            Vector64);
19100             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
19101                                         Vector32, DAG.getIntPtrConstant(0));
19102             IntVT = MVT::i32;
19103           }
19104
19105           SDValue OnesOrZeroesI = DAG.getNode(ISD::BITCAST, DL, IntVT, OnesOrZeroesF);
19106           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
19107                                       DAG.getConstant(1, IntVT));
19108           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8, ANDed);
19109           return OneBitOfTruth;
19110         }
19111       }
19112     }
19113   }
19114   return SDValue();
19115 }
19116
19117 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
19118 /// so it can be folded inside ANDNP.
19119 static bool CanFoldXORWithAllOnes(const SDNode *N) {
19120   EVT VT = N->getValueType(0);
19121
19122   // Match direct AllOnes for 128 and 256-bit vectors
19123   if (ISD::isBuildVectorAllOnes(N))
19124     return true;
19125
19126   // Look through a bit convert.
19127   if (N->getOpcode() == ISD::BITCAST)
19128     N = N->getOperand(0).getNode();
19129
19130   // Sometimes the operand may come from a insert_subvector building a 256-bit
19131   // allones vector
19132   if (VT.is256BitVector() &&
19133       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
19134     SDValue V1 = N->getOperand(0);
19135     SDValue V2 = N->getOperand(1);
19136
19137     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
19138         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
19139         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
19140         ISD::isBuildVectorAllOnes(V2.getNode()))
19141       return true;
19142   }
19143
19144   return false;
19145 }
19146
19147 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
19148 // register. In most cases we actually compare or select YMM-sized registers
19149 // and mixing the two types creates horrible code. This method optimizes
19150 // some of the transition sequences.
19151 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
19152                                  TargetLowering::DAGCombinerInfo &DCI,
19153                                  const X86Subtarget *Subtarget) {
19154   EVT VT = N->getValueType(0);
19155   if (!VT.is256BitVector())
19156     return SDValue();
19157
19158   assert((N->getOpcode() == ISD::ANY_EXTEND ||
19159           N->getOpcode() == ISD::ZERO_EXTEND ||
19160           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
19161
19162   SDValue Narrow = N->getOperand(0);
19163   EVT NarrowVT = Narrow->getValueType(0);
19164   if (!NarrowVT.is128BitVector())
19165     return SDValue();
19166
19167   if (Narrow->getOpcode() != ISD::XOR &&
19168       Narrow->getOpcode() != ISD::AND &&
19169       Narrow->getOpcode() != ISD::OR)
19170     return SDValue();
19171
19172   SDValue N0  = Narrow->getOperand(0);
19173   SDValue N1  = Narrow->getOperand(1);
19174   SDLoc DL(Narrow);
19175
19176   // The Left side has to be a trunc.
19177   if (N0.getOpcode() != ISD::TRUNCATE)
19178     return SDValue();
19179
19180   // The type of the truncated inputs.
19181   EVT WideVT = N0->getOperand(0)->getValueType(0);
19182   if (WideVT != VT)
19183     return SDValue();
19184
19185   // The right side has to be a 'trunc' or a constant vector.
19186   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
19187   bool RHSConst = (isSplatVector(N1.getNode()) &&
19188                    isa<ConstantSDNode>(N1->getOperand(0)));
19189   if (!RHSTrunc && !RHSConst)
19190     return SDValue();
19191
19192   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19193
19194   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
19195     return SDValue();
19196
19197   // Set N0 and N1 to hold the inputs to the new wide operation.
19198   N0 = N0->getOperand(0);
19199   if (RHSConst) {
19200     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
19201                      N1->getOperand(0));
19202     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
19203     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
19204   } else if (RHSTrunc) {
19205     N1 = N1->getOperand(0);
19206   }
19207
19208   // Generate the wide operation.
19209   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
19210   unsigned Opcode = N->getOpcode();
19211   switch (Opcode) {
19212   case ISD::ANY_EXTEND:
19213     return Op;
19214   case ISD::ZERO_EXTEND: {
19215     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
19216     APInt Mask = APInt::getAllOnesValue(InBits);
19217     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
19218     return DAG.getNode(ISD::AND, DL, VT,
19219                        Op, DAG.getConstant(Mask, VT));
19220   }
19221   case ISD::SIGN_EXTEND:
19222     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
19223                        Op, DAG.getValueType(NarrowVT));
19224   default:
19225     llvm_unreachable("Unexpected opcode");
19226   }
19227 }
19228
19229 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
19230                                  TargetLowering::DAGCombinerInfo &DCI,
19231                                  const X86Subtarget *Subtarget) {
19232   EVT VT = N->getValueType(0);
19233   if (DCI.isBeforeLegalizeOps())
19234     return SDValue();
19235
19236   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19237   if (R.getNode())
19238     return R;
19239
19240   // Create BEXTR instructions
19241   // BEXTR is ((X >> imm) & (2**size-1))
19242   if (VT == MVT::i32 || VT == MVT::i64) {
19243     SDValue N0 = N->getOperand(0);
19244     SDValue N1 = N->getOperand(1);
19245     SDLoc DL(N);
19246
19247     // Check for BEXTR.
19248     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
19249         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
19250       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
19251       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
19252       if (MaskNode && ShiftNode) {
19253         uint64_t Mask = MaskNode->getZExtValue();
19254         uint64_t Shift = ShiftNode->getZExtValue();
19255         if (isMask_64(Mask)) {
19256           uint64_t MaskSize = CountPopulation_64(Mask);
19257           if (Shift + MaskSize <= VT.getSizeInBits())
19258             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
19259                                DAG.getConstant(Shift | (MaskSize << 8), VT));
19260         }
19261       }
19262     } // BEXTR
19263
19264     return SDValue();
19265   }
19266
19267   // Want to form ANDNP nodes:
19268   // 1) In the hopes of then easily combining them with OR and AND nodes
19269   //    to form PBLEND/PSIGN.
19270   // 2) To match ANDN packed intrinsics
19271   if (VT != MVT::v2i64 && VT != MVT::v4i64)
19272     return SDValue();
19273
19274   SDValue N0 = N->getOperand(0);
19275   SDValue N1 = N->getOperand(1);
19276   SDLoc DL(N);
19277
19278   // Check LHS for vnot
19279   if (N0.getOpcode() == ISD::XOR &&
19280       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
19281       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
19282     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
19283
19284   // Check RHS for vnot
19285   if (N1.getOpcode() == ISD::XOR &&
19286       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
19287       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
19288     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
19289
19290   return SDValue();
19291 }
19292
19293 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
19294                                 TargetLowering::DAGCombinerInfo &DCI,
19295                                 const X86Subtarget *Subtarget) {
19296   if (DCI.isBeforeLegalizeOps())
19297     return SDValue();
19298
19299   SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget);
19300   if (R.getNode())
19301     return R;
19302
19303   SDValue N0 = N->getOperand(0);
19304   SDValue N1 = N->getOperand(1);
19305   EVT VT = N->getValueType(0);
19306
19307   // look for psign/blend
19308   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
19309     if (!Subtarget->hasSSSE3() ||
19310         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
19311       return SDValue();
19312
19313     // Canonicalize pandn to RHS
19314     if (N0.getOpcode() == X86ISD::ANDNP)
19315       std::swap(N0, N1);
19316     // or (and (m, y), (pandn m, x))
19317     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
19318       SDValue Mask = N1.getOperand(0);
19319       SDValue X    = N1.getOperand(1);
19320       SDValue Y;
19321       if (N0.getOperand(0) == Mask)
19322         Y = N0.getOperand(1);
19323       if (N0.getOperand(1) == Mask)
19324         Y = N0.getOperand(0);
19325
19326       // Check to see if the mask appeared in both the AND and ANDNP and
19327       if (!Y.getNode())
19328         return SDValue();
19329
19330       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
19331       // Look through mask bitcast.
19332       if (Mask.getOpcode() == ISD::BITCAST)
19333         Mask = Mask.getOperand(0);
19334       if (X.getOpcode() == ISD::BITCAST)
19335         X = X.getOperand(0);
19336       if (Y.getOpcode() == ISD::BITCAST)
19337         Y = Y.getOperand(0);
19338
19339       EVT MaskVT = Mask.getValueType();
19340
19341       // Validate that the Mask operand is a vector sra node.
19342       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
19343       // there is no psrai.b
19344       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
19345       unsigned SraAmt = ~0;
19346       if (Mask.getOpcode() == ISD::SRA) {
19347         SDValue Amt = Mask.getOperand(1);
19348         if (isSplatVector(Amt.getNode())) {
19349           SDValue SclrAmt = Amt->getOperand(0);
19350           if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(SclrAmt))
19351             SraAmt = C->getZExtValue();
19352         }
19353       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
19354         SDValue SraC = Mask.getOperand(1);
19355         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
19356       }
19357       if ((SraAmt + 1) != EltBits)
19358         return SDValue();
19359
19360       SDLoc DL(N);
19361
19362       // Now we know we at least have a plendvb with the mask val.  See if
19363       // we can form a psignb/w/d.
19364       // psign = x.type == y.type == mask.type && y = sub(0, x);
19365       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
19366           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
19367           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
19368         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
19369                "Unsupported VT for PSIGN");
19370         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
19371         return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19372       }
19373       // PBLENDVB only available on SSE 4.1
19374       if (!Subtarget->hasSSE41())
19375         return SDValue();
19376
19377       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
19378
19379       X = DAG.getNode(ISD::BITCAST, DL, BlendVT, X);
19380       Y = DAG.getNode(ISD::BITCAST, DL, BlendVT, Y);
19381       Mask = DAG.getNode(ISD::BITCAST, DL, BlendVT, Mask);
19382       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
19383       return DAG.getNode(ISD::BITCAST, DL, VT, Mask);
19384     }
19385   }
19386
19387   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
19388     return SDValue();
19389
19390   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
19391   MachineFunction &MF = DAG.getMachineFunction();
19392   bool OptForSize = MF.getFunction()->getAttributes().
19393     hasAttribute(AttributeSet::FunctionIndex, Attribute::OptimizeForSize);
19394
19395   // SHLD/SHRD instructions have lower register pressure, but on some
19396   // platforms they have higher latency than the equivalent
19397   // series of shifts/or that would otherwise be generated.
19398   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
19399   // have higher latencies and we are not optimizing for size.
19400   if (!OptForSize && Subtarget->isSHLDSlow())
19401     return SDValue();
19402
19403   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
19404     std::swap(N0, N1);
19405   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
19406     return SDValue();
19407   if (!N0.hasOneUse() || !N1.hasOneUse())
19408     return SDValue();
19409
19410   SDValue ShAmt0 = N0.getOperand(1);
19411   if (ShAmt0.getValueType() != MVT::i8)
19412     return SDValue();
19413   SDValue ShAmt1 = N1.getOperand(1);
19414   if (ShAmt1.getValueType() != MVT::i8)
19415     return SDValue();
19416   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
19417     ShAmt0 = ShAmt0.getOperand(0);
19418   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
19419     ShAmt1 = ShAmt1.getOperand(0);
19420
19421   SDLoc DL(N);
19422   unsigned Opc = X86ISD::SHLD;
19423   SDValue Op0 = N0.getOperand(0);
19424   SDValue Op1 = N1.getOperand(0);
19425   if (ShAmt0.getOpcode() == ISD::SUB) {
19426     Opc = X86ISD::SHRD;
19427     std::swap(Op0, Op1);
19428     std::swap(ShAmt0, ShAmt1);
19429   }
19430
19431   unsigned Bits = VT.getSizeInBits();
19432   if (ShAmt1.getOpcode() == ISD::SUB) {
19433     SDValue Sum = ShAmt1.getOperand(0);
19434     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
19435       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
19436       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
19437         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
19438       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
19439         return DAG.getNode(Opc, DL, VT,
19440                            Op0, Op1,
19441                            DAG.getNode(ISD::TRUNCATE, DL,
19442                                        MVT::i8, ShAmt0));
19443     }
19444   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
19445     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
19446     if (ShAmt0C &&
19447         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
19448       return DAG.getNode(Opc, DL, VT,
19449                          N0.getOperand(0), N1.getOperand(0),
19450                          DAG.getNode(ISD::TRUNCATE, DL,
19451                                        MVT::i8, ShAmt0));
19452   }
19453
19454   return SDValue();
19455 }
19456
19457 // Generate NEG and CMOV for integer abs.
19458 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
19459   EVT VT = N->getValueType(0);
19460
19461   // Since X86 does not have CMOV for 8-bit integer, we don't convert
19462   // 8-bit integer abs to NEG and CMOV.
19463   if (VT.isInteger() && VT.getSizeInBits() == 8)
19464     return SDValue();
19465
19466   SDValue N0 = N->getOperand(0);
19467   SDValue N1 = N->getOperand(1);
19468   SDLoc DL(N);
19469
19470   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
19471   // and change it to SUB and CMOV.
19472   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
19473       N0.getOpcode() == ISD::ADD &&
19474       N0.getOperand(1) == N1 &&
19475       N1.getOpcode() == ISD::SRA &&
19476       N1.getOperand(0) == N0.getOperand(0))
19477     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
19478       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
19479         // Generate SUB & CMOV.
19480         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
19481                                   DAG.getConstant(0, VT), N0.getOperand(0));
19482
19483         SDValue Ops[] = { N0.getOperand(0), Neg,
19484                           DAG.getConstant(X86::COND_GE, MVT::i8),
19485                           SDValue(Neg.getNode(), 1) };
19486         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
19487       }
19488   return SDValue();
19489 }
19490
19491 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
19492 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
19493                                  TargetLowering::DAGCombinerInfo &DCI,
19494                                  const X86Subtarget *Subtarget) {
19495   if (DCI.isBeforeLegalizeOps())
19496     return SDValue();
19497
19498   if (Subtarget->hasCMov()) {
19499     SDValue RV = performIntegerAbsCombine(N, DAG);
19500     if (RV.getNode())
19501       return RV;
19502   }
19503
19504   return SDValue();
19505 }
19506
19507 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
19508 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
19509                                   TargetLowering::DAGCombinerInfo &DCI,
19510                                   const X86Subtarget *Subtarget) {
19511   LoadSDNode *Ld = cast<LoadSDNode>(N);
19512   EVT RegVT = Ld->getValueType(0);
19513   EVT MemVT = Ld->getMemoryVT();
19514   SDLoc dl(Ld);
19515   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19516   unsigned RegSz = RegVT.getSizeInBits();
19517
19518   // On Sandybridge unaligned 256bit loads are inefficient.
19519   ISD::LoadExtType Ext = Ld->getExtensionType();
19520   unsigned Alignment = Ld->getAlignment();
19521   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
19522   if (RegVT.is256BitVector() && !Subtarget->hasInt256() &&
19523       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
19524     unsigned NumElems = RegVT.getVectorNumElements();
19525     if (NumElems < 2)
19526       return SDValue();
19527
19528     SDValue Ptr = Ld->getBasePtr();
19529     SDValue Increment = DAG.getConstant(16, TLI.getPointerTy());
19530
19531     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19532                                   NumElems/2);
19533     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19534                                 Ld->getPointerInfo(), Ld->isVolatile(),
19535                                 Ld->isNonTemporal(), Ld->isInvariant(),
19536                                 Alignment);
19537     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19538     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
19539                                 Ld->getPointerInfo(), Ld->isVolatile(),
19540                                 Ld->isNonTemporal(), Ld->isInvariant(),
19541                                 std::min(16U, Alignment));
19542     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
19543                              Load1.getValue(1),
19544                              Load2.getValue(1));
19545
19546     SDValue NewVec = DAG.getUNDEF(RegVT);
19547     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
19548     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
19549     return DCI.CombineTo(N, NewVec, TF, true);
19550   }
19551
19552   // If this is a vector EXT Load then attempt to optimize it using a
19553   // shuffle. If SSSE3 is not available we may emit an illegal shuffle but the
19554   // expansion is still better than scalar code.
19555   // We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise we'll
19556   // emit a shuffle and a arithmetic shift.
19557   // TODO: It is possible to support ZExt by zeroing the undef values
19558   // during the shuffle phase or after the shuffle.
19559   if (RegVT.isVector() && RegVT.isInteger() && Subtarget->hasSSE2() &&
19560       (Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)) {
19561     assert(MemVT != RegVT && "Cannot extend to the same type");
19562     assert(MemVT.isVector() && "Must load a vector from memory");
19563
19564     unsigned NumElems = RegVT.getVectorNumElements();
19565     unsigned MemSz = MemVT.getSizeInBits();
19566     assert(RegSz > MemSz && "Register size must be greater than the mem size");
19567
19568     if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256())
19569       return SDValue();
19570
19571     // All sizes must be a power of two.
19572     if (!isPowerOf2_32(RegSz * MemSz * NumElems))
19573       return SDValue();
19574
19575     // Attempt to load the original value using scalar loads.
19576     // Find the largest scalar type that divides the total loaded size.
19577     MVT SclrLoadTy = MVT::i8;
19578     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19579          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19580       MVT Tp = (MVT::SimpleValueType)tp;
19581       if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
19582         SclrLoadTy = Tp;
19583       }
19584     }
19585
19586     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19587     if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
19588         (64 <= MemSz))
19589       SclrLoadTy = MVT::f64;
19590
19591     // Calculate the number of scalar loads that we need to perform
19592     // in order to load our vector from memory.
19593     unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
19594     if (Ext == ISD::SEXTLOAD && NumLoads > 1)
19595       return SDValue();
19596
19597     unsigned loadRegZize = RegSz;
19598     if (Ext == ISD::SEXTLOAD && RegSz == 256)
19599       loadRegZize /= 2;
19600
19601     // Represent our vector as a sequence of elements which are the
19602     // largest scalar that we can load.
19603     EVT LoadUnitVecVT = EVT::getVectorVT(*DAG.getContext(), SclrLoadTy,
19604       loadRegZize/SclrLoadTy.getSizeInBits());
19605
19606     // Represent the data using the same element type that is stored in
19607     // memory. In practice, we ''widen'' MemVT.
19608     EVT WideVecVT =
19609           EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
19610                        loadRegZize/MemVT.getScalarType().getSizeInBits());
19611
19612     assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
19613       "Invalid vector type");
19614
19615     // We can't shuffle using an illegal type.
19616     if (!TLI.isTypeLegal(WideVecVT))
19617       return SDValue();
19618
19619     SmallVector<SDValue, 8> Chains;
19620     SDValue Ptr = Ld->getBasePtr();
19621     SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits()/8,
19622                                         TLI.getPointerTy());
19623     SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
19624
19625     for (unsigned i = 0; i < NumLoads; ++i) {
19626       // Perform a single load.
19627       SDValue ScalarLoad = DAG.getLoad(SclrLoadTy, dl, Ld->getChain(),
19628                                        Ptr, Ld->getPointerInfo(),
19629                                        Ld->isVolatile(), Ld->isNonTemporal(),
19630                                        Ld->isInvariant(), Ld->getAlignment());
19631       Chains.push_back(ScalarLoad.getValue(1));
19632       // Create the first element type using SCALAR_TO_VECTOR in order to avoid
19633       // another round of DAGCombining.
19634       if (i == 0)
19635         Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
19636       else
19637         Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
19638                           ScalarLoad, DAG.getIntPtrConstant(i));
19639
19640       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19641     }
19642
19643     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19644
19645     // Bitcast the loaded value to a vector of the original element type, in
19646     // the size of the target vector type.
19647     SDValue SlicedVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, Res);
19648     unsigned SizeRatio = RegSz/MemSz;
19649
19650     if (Ext == ISD::SEXTLOAD) {
19651       // If we have SSE4.1 we can directly emit a VSEXT node.
19652       if (Subtarget->hasSSE41()) {
19653         SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
19654         return DCI.CombineTo(N, Sext, TF, true);
19655       }
19656
19657       // Otherwise we'll shuffle the small elements in the high bits of the
19658       // larger type and perform an arithmetic shift. If the shift is not legal
19659       // it's better to scalarize.
19660       if (!TLI.isOperationLegalOrCustom(ISD::SRA, RegVT))
19661         return SDValue();
19662
19663       // Redistribute the loaded elements into the different locations.
19664       SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19665       for (unsigned i = 0; i != NumElems; ++i)
19666         ShuffleVec[i*SizeRatio + SizeRatio-1] = i;
19667
19668       SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19669                                            DAG.getUNDEF(WideVecVT),
19670                                            &ShuffleVec[0]);
19671
19672       Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19673
19674       // Build the arithmetic shift.
19675       unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
19676                      MemVT.getVectorElementType().getSizeInBits();
19677       Shuff = DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
19678                           DAG.getConstant(Amt, RegVT));
19679
19680       return DCI.CombineTo(N, Shuff, TF, true);
19681     }
19682
19683     // Redistribute the loaded elements into the different locations.
19684     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19685     for (unsigned i = 0; i != NumElems; ++i)
19686       ShuffleVec[i*SizeRatio] = i;
19687
19688     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
19689                                          DAG.getUNDEF(WideVecVT),
19690                                          &ShuffleVec[0]);
19691
19692     // Bitcast to the requested type.
19693     Shuff = DAG.getNode(ISD::BITCAST, dl, RegVT, Shuff);
19694     // Replace the original load with the new sequence
19695     // and return the new chain.
19696     return DCI.CombineTo(N, Shuff, TF, true);
19697   }
19698
19699   return SDValue();
19700 }
19701
19702 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
19703 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
19704                                    const X86Subtarget *Subtarget) {
19705   StoreSDNode *St = cast<StoreSDNode>(N);
19706   EVT VT = St->getValue().getValueType();
19707   EVT StVT = St->getMemoryVT();
19708   SDLoc dl(St);
19709   SDValue StoredVal = St->getOperand(1);
19710   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19711
19712   // If we are saving a concatenation of two XMM registers, perform two stores.
19713   // On Sandy Bridge, 256-bit memory operations are executed by two
19714   // 128-bit ports. However, on Haswell it is better to issue a single 256-bit
19715   // memory  operation.
19716   unsigned Alignment = St->getAlignment();
19717   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
19718   if (VT.is256BitVector() && !Subtarget->hasInt256() &&
19719       StVT == VT && !IsAligned) {
19720     unsigned NumElems = VT.getVectorNumElements();
19721     if (NumElems < 2)
19722       return SDValue();
19723
19724     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
19725     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
19726
19727     SDValue Stride = DAG.getConstant(16, TLI.getPointerTy());
19728     SDValue Ptr0 = St->getBasePtr();
19729     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
19730
19731     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
19732                                 St->getPointerInfo(), St->isVolatile(),
19733                                 St->isNonTemporal(), Alignment);
19734     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
19735                                 St->getPointerInfo(), St->isVolatile(),
19736                                 St->isNonTemporal(),
19737                                 std::min(16U, Alignment));
19738     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
19739   }
19740
19741   // Optimize trunc store (of multiple scalars) to shuffle and store.
19742   // First, pack all of the elements in one place. Next, store to memory
19743   // in fewer chunks.
19744   if (St->isTruncatingStore() && VT.isVector()) {
19745     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
19746     unsigned NumElems = VT.getVectorNumElements();
19747     assert(StVT != VT && "Cannot truncate to the same type");
19748     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
19749     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
19750
19751     // From, To sizes and ElemCount must be pow of two
19752     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
19753     // We are going to use the original vector elt for storing.
19754     // Accumulated smaller vector elements must be a multiple of the store size.
19755     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
19756
19757     unsigned SizeRatio  = FromSz / ToSz;
19758
19759     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
19760
19761     // Create a type on which we perform the shuffle
19762     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
19763             StVT.getScalarType(), NumElems*SizeRatio);
19764
19765     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
19766
19767     SDValue WideVec = DAG.getNode(ISD::BITCAST, dl, WideVecVT, St->getValue());
19768     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
19769     for (unsigned i = 0; i != NumElems; ++i)
19770       ShuffleVec[i] = i * SizeRatio;
19771
19772     // Can't shuffle using an illegal type.
19773     if (!TLI.isTypeLegal(WideVecVT))
19774       return SDValue();
19775
19776     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
19777                                          DAG.getUNDEF(WideVecVT),
19778                                          &ShuffleVec[0]);
19779     // At this point all of the data is stored at the bottom of the
19780     // register. We now need to save it to mem.
19781
19782     // Find the largest store unit
19783     MVT StoreType = MVT::i8;
19784     for (unsigned tp = MVT::FIRST_INTEGER_VALUETYPE;
19785          tp < MVT::LAST_INTEGER_VALUETYPE; ++tp) {
19786       MVT Tp = (MVT::SimpleValueType)tp;
19787       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
19788         StoreType = Tp;
19789     }
19790
19791     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
19792     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
19793         (64 <= NumElems * ToSz))
19794       StoreType = MVT::f64;
19795
19796     // Bitcast the original vector into a vector of store-size units
19797     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
19798             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
19799     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
19800     SDValue ShuffWide = DAG.getNode(ISD::BITCAST, dl, StoreVecVT, Shuff);
19801     SmallVector<SDValue, 8> Chains;
19802     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8,
19803                                         TLI.getPointerTy());
19804     SDValue Ptr = St->getBasePtr();
19805
19806     // Perform one or more big stores into memory.
19807     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
19808       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
19809                                    StoreType, ShuffWide,
19810                                    DAG.getIntPtrConstant(i));
19811       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
19812                                 St->getPointerInfo(), St->isVolatile(),
19813                                 St->isNonTemporal(), St->getAlignment());
19814       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
19815       Chains.push_back(Ch);
19816     }
19817
19818     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
19819   }
19820
19821   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
19822   // the FP state in cases where an emms may be missing.
19823   // A preferable solution to the general problem is to figure out the right
19824   // places to insert EMMS.  This qualifies as a quick hack.
19825
19826   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
19827   if (VT.getSizeInBits() != 64)
19828     return SDValue();
19829
19830   const Function *F = DAG.getMachineFunction().getFunction();
19831   bool NoImplicitFloatOps = F->getAttributes().
19832     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
19833   bool F64IsLegal = !DAG.getTarget().Options.UseSoftFloat && !NoImplicitFloatOps
19834                      && Subtarget->hasSSE2();
19835   if ((VT.isVector() ||
19836        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
19837       isa<LoadSDNode>(St->getValue()) &&
19838       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
19839       St->getChain().hasOneUse() && !St->isVolatile()) {
19840     SDNode* LdVal = St->getValue().getNode();
19841     LoadSDNode *Ld = nullptr;
19842     int TokenFactorIndex = -1;
19843     SmallVector<SDValue, 8> Ops;
19844     SDNode* ChainVal = St->getChain().getNode();
19845     // Must be a store of a load.  We currently handle two cases:  the load
19846     // is a direct child, and it's under an intervening TokenFactor.  It is
19847     // possible to dig deeper under nested TokenFactors.
19848     if (ChainVal == LdVal)
19849       Ld = cast<LoadSDNode>(St->getChain());
19850     else if (St->getValue().hasOneUse() &&
19851              ChainVal->getOpcode() == ISD::TokenFactor) {
19852       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
19853         if (ChainVal->getOperand(i).getNode() == LdVal) {
19854           TokenFactorIndex = i;
19855           Ld = cast<LoadSDNode>(St->getValue());
19856         } else
19857           Ops.push_back(ChainVal->getOperand(i));
19858       }
19859     }
19860
19861     if (!Ld || !ISD::isNormalLoad(Ld))
19862       return SDValue();
19863
19864     // If this is not the MMX case, i.e. we are just turning i64 load/store
19865     // into f64 load/store, avoid the transformation if there are multiple
19866     // uses of the loaded value.
19867     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
19868       return SDValue();
19869
19870     SDLoc LdDL(Ld);
19871     SDLoc StDL(N);
19872     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
19873     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
19874     // pair instead.
19875     if (Subtarget->is64Bit() || F64IsLegal) {
19876       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
19877       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
19878                                   Ld->getPointerInfo(), Ld->isVolatile(),
19879                                   Ld->isNonTemporal(), Ld->isInvariant(),
19880                                   Ld->getAlignment());
19881       SDValue NewChain = NewLd.getValue(1);
19882       if (TokenFactorIndex != -1) {
19883         Ops.push_back(NewChain);
19884         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19885       }
19886       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
19887                           St->getPointerInfo(),
19888                           St->isVolatile(), St->isNonTemporal(),
19889                           St->getAlignment());
19890     }
19891
19892     // Otherwise, lower to two pairs of 32-bit loads / stores.
19893     SDValue LoAddr = Ld->getBasePtr();
19894     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
19895                                  DAG.getConstant(4, MVT::i32));
19896
19897     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
19898                                Ld->getPointerInfo(),
19899                                Ld->isVolatile(), Ld->isNonTemporal(),
19900                                Ld->isInvariant(), Ld->getAlignment());
19901     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
19902                                Ld->getPointerInfo().getWithOffset(4),
19903                                Ld->isVolatile(), Ld->isNonTemporal(),
19904                                Ld->isInvariant(),
19905                                MinAlign(Ld->getAlignment(), 4));
19906
19907     SDValue NewChain = LoLd.getValue(1);
19908     if (TokenFactorIndex != -1) {
19909       Ops.push_back(LoLd);
19910       Ops.push_back(HiLd);
19911       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
19912     }
19913
19914     LoAddr = St->getBasePtr();
19915     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
19916                          DAG.getConstant(4, MVT::i32));
19917
19918     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
19919                                 St->getPointerInfo(),
19920                                 St->isVolatile(), St->isNonTemporal(),
19921                                 St->getAlignment());
19922     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
19923                                 St->getPointerInfo().getWithOffset(4),
19924                                 St->isVolatile(),
19925                                 St->isNonTemporal(),
19926                                 MinAlign(St->getAlignment(), 4));
19927     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
19928   }
19929   return SDValue();
19930 }
19931
19932 /// isHorizontalBinOp - Return 'true' if this vector operation is "horizontal"
19933 /// and return the operands for the horizontal operation in LHS and RHS.  A
19934 /// horizontal operation performs the binary operation on successive elements
19935 /// of its first operand, then on successive elements of its second operand,
19936 /// returning the resulting values in a vector.  For example, if
19937 ///   A = < float a0, float a1, float a2, float a3 >
19938 /// and
19939 ///   B = < float b0, float b1, float b2, float b3 >
19940 /// then the result of doing a horizontal operation on A and B is
19941 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
19942 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
19943 /// A horizontal-op B, for some already available A and B, and if so then LHS is
19944 /// set to A, RHS to B, and the routine returns 'true'.
19945 /// Note that the binary operation should have the property that if one of the
19946 /// operands is UNDEF then the result is UNDEF.
19947 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
19948   // Look for the following pattern: if
19949   //   A = < float a0, float a1, float a2, float a3 >
19950   //   B = < float b0, float b1, float b2, float b3 >
19951   // and
19952   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
19953   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
19954   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
19955   // which is A horizontal-op B.
19956
19957   // At least one of the operands should be a vector shuffle.
19958   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
19959       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
19960     return false;
19961
19962   MVT VT = LHS.getSimpleValueType();
19963
19964   assert((VT.is128BitVector() || VT.is256BitVector()) &&
19965          "Unsupported vector type for horizontal add/sub");
19966
19967   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
19968   // operate independently on 128-bit lanes.
19969   unsigned NumElts = VT.getVectorNumElements();
19970   unsigned NumLanes = VT.getSizeInBits()/128;
19971   unsigned NumLaneElts = NumElts / NumLanes;
19972   assert((NumLaneElts % 2 == 0) &&
19973          "Vector type should have an even number of elements in each lane");
19974   unsigned HalfLaneElts = NumLaneElts/2;
19975
19976   // View LHS in the form
19977   //   LHS = VECTOR_SHUFFLE A, B, LMask
19978   // If LHS is not a shuffle then pretend it is the shuffle
19979   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
19980   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
19981   // type VT.
19982   SDValue A, B;
19983   SmallVector<int, 16> LMask(NumElts);
19984   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
19985     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
19986       A = LHS.getOperand(0);
19987     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
19988       B = LHS.getOperand(1);
19989     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
19990     std::copy(Mask.begin(), Mask.end(), LMask.begin());
19991   } else {
19992     if (LHS.getOpcode() != ISD::UNDEF)
19993       A = LHS;
19994     for (unsigned i = 0; i != NumElts; ++i)
19995       LMask[i] = i;
19996   }
19997
19998   // Likewise, view RHS in the form
19999   //   RHS = VECTOR_SHUFFLE C, D, RMask
20000   SDValue C, D;
20001   SmallVector<int, 16> RMask(NumElts);
20002   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
20003     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
20004       C = RHS.getOperand(0);
20005     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
20006       D = RHS.getOperand(1);
20007     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
20008     std::copy(Mask.begin(), Mask.end(), RMask.begin());
20009   } else {
20010     if (RHS.getOpcode() != ISD::UNDEF)
20011       C = RHS;
20012     for (unsigned i = 0; i != NumElts; ++i)
20013       RMask[i] = i;
20014   }
20015
20016   // Check that the shuffles are both shuffling the same vectors.
20017   if (!(A == C && B == D) && !(A == D && B == C))
20018     return false;
20019
20020   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
20021   if (!A.getNode() && !B.getNode())
20022     return false;
20023
20024   // If A and B occur in reverse order in RHS, then "swap" them (which means
20025   // rewriting the mask).
20026   if (A != C)
20027     CommuteVectorShuffleMask(RMask, NumElts);
20028
20029   // At this point LHS and RHS are equivalent to
20030   //   LHS = VECTOR_SHUFFLE A, B, LMask
20031   //   RHS = VECTOR_SHUFFLE A, B, RMask
20032   // Check that the masks correspond to performing a horizontal operation.
20033   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
20034     for (unsigned i = 0; i != NumLaneElts; ++i) {
20035       int LIdx = LMask[i+l], RIdx = RMask[i+l];
20036
20037       // Ignore any UNDEF components.
20038       if (LIdx < 0 || RIdx < 0 ||
20039           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
20040           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
20041         continue;
20042
20043       // Check that successive elements are being operated on.  If not, this is
20044       // not a horizontal operation.
20045       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
20046       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
20047       if (!(LIdx == Index && RIdx == Index + 1) &&
20048           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
20049         return false;
20050     }
20051   }
20052
20053   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
20054   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
20055   return true;
20056 }
20057
20058 /// PerformFADDCombine - Do target-specific dag combines on floating point adds.
20059 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
20060                                   const X86Subtarget *Subtarget) {
20061   EVT VT = N->getValueType(0);
20062   SDValue LHS = N->getOperand(0);
20063   SDValue RHS = N->getOperand(1);
20064
20065   // Try to synthesize horizontal adds from adds of shuffles.
20066   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20067        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20068       isHorizontalBinOp(LHS, RHS, true))
20069     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
20070   return SDValue();
20071 }
20072
20073 /// PerformFSUBCombine - Do target-specific dag combines on floating point subs.
20074 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
20075                                   const X86Subtarget *Subtarget) {
20076   EVT VT = N->getValueType(0);
20077   SDValue LHS = N->getOperand(0);
20078   SDValue RHS = N->getOperand(1);
20079
20080   // Try to synthesize horizontal subs from subs of shuffles.
20081   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
20082        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
20083       isHorizontalBinOp(LHS, RHS, false))
20084     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
20085   return SDValue();
20086 }
20087
20088 /// PerformFORCombine - Do target-specific dag combines on X86ISD::FOR and
20089 /// X86ISD::FXOR nodes.
20090 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
20091   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
20092   // F[X]OR(0.0, x) -> x
20093   // F[X]OR(x, 0.0) -> x
20094   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20095     if (C->getValueAPF().isPosZero())
20096       return N->getOperand(1);
20097   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20098     if (C->getValueAPF().isPosZero())
20099       return N->getOperand(0);
20100   return SDValue();
20101 }
20102
20103 /// PerformFMinFMaxCombine - Do target-specific dag combines on X86ISD::FMIN and
20104 /// X86ISD::FMAX nodes.
20105 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
20106   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
20107
20108   // Only perform optimizations if UnsafeMath is used.
20109   if (!DAG.getTarget().Options.UnsafeFPMath)
20110     return SDValue();
20111
20112   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
20113   // into FMINC and FMAXC, which are Commutative operations.
20114   unsigned NewOp = 0;
20115   switch (N->getOpcode()) {
20116     default: llvm_unreachable("unknown opcode");
20117     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
20118     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
20119   }
20120
20121   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
20122                      N->getOperand(0), N->getOperand(1));
20123 }
20124
20125 /// PerformFANDCombine - Do target-specific dag combines on X86ISD::FAND nodes.
20126 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
20127   // FAND(0.0, x) -> 0.0
20128   // FAND(x, 0.0) -> 0.0
20129   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20130     if (C->getValueAPF().isPosZero())
20131       return N->getOperand(0);
20132   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20133     if (C->getValueAPF().isPosZero())
20134       return N->getOperand(1);
20135   return SDValue();
20136 }
20137
20138 /// PerformFANDNCombine - Do target-specific dag combines on X86ISD::FANDN nodes
20139 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
20140   // FANDN(x, 0.0) -> 0.0
20141   // FANDN(0.0, x) -> x
20142   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
20143     if (C->getValueAPF().isPosZero())
20144       return N->getOperand(1);
20145   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
20146     if (C->getValueAPF().isPosZero())
20147       return N->getOperand(1);
20148   return SDValue();
20149 }
20150
20151 static SDValue PerformBTCombine(SDNode *N,
20152                                 SelectionDAG &DAG,
20153                                 TargetLowering::DAGCombinerInfo &DCI) {
20154   // BT ignores high bits in the bit index operand.
20155   SDValue Op1 = N->getOperand(1);
20156   if (Op1.hasOneUse()) {
20157     unsigned BitWidth = Op1.getValueSizeInBits();
20158     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
20159     APInt KnownZero, KnownOne;
20160     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
20161                                           !DCI.isBeforeLegalizeOps());
20162     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
20163     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
20164         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
20165       DCI.CommitTargetLoweringOpt(TLO);
20166   }
20167   return SDValue();
20168 }
20169
20170 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
20171   SDValue Op = N->getOperand(0);
20172   if (Op.getOpcode() == ISD::BITCAST)
20173     Op = Op.getOperand(0);
20174   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
20175   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
20176       VT.getVectorElementType().getSizeInBits() ==
20177       OpVT.getVectorElementType().getSizeInBits()) {
20178     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
20179   }
20180   return SDValue();
20181 }
20182
20183 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
20184                                                const X86Subtarget *Subtarget) {
20185   EVT VT = N->getValueType(0);
20186   if (!VT.isVector())
20187     return SDValue();
20188
20189   SDValue N0 = N->getOperand(0);
20190   SDValue N1 = N->getOperand(1);
20191   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
20192   SDLoc dl(N);
20193
20194   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
20195   // both SSE and AVX2 since there is no sign-extended shift right
20196   // operation on a vector with 64-bit elements.
20197   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
20198   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
20199   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
20200       N0.getOpcode() == ISD::SIGN_EXTEND)) {
20201     SDValue N00 = N0.getOperand(0);
20202
20203     // EXTLOAD has a better solution on AVX2,
20204     // it may be replaced with X86ISD::VSEXT node.
20205     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
20206       if (!ISD::isNormalLoad(N00.getNode()))
20207         return SDValue();
20208
20209     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
20210         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
20211                                   N00, N1);
20212       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
20213     }
20214   }
20215   return SDValue();
20216 }
20217
20218 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
20219                                   TargetLowering::DAGCombinerInfo &DCI,
20220                                   const X86Subtarget *Subtarget) {
20221   if (!DCI.isBeforeLegalizeOps())
20222     return SDValue();
20223
20224   if (!Subtarget->hasFp256())
20225     return SDValue();
20226
20227   EVT VT = N->getValueType(0);
20228   if (VT.isVector() && VT.getSizeInBits() == 256) {
20229     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20230     if (R.getNode())
20231       return R;
20232   }
20233
20234   return SDValue();
20235 }
20236
20237 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
20238                                  const X86Subtarget* Subtarget) {
20239   SDLoc dl(N);
20240   EVT VT = N->getValueType(0);
20241
20242   // Let legalize expand this if it isn't a legal type yet.
20243   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
20244     return SDValue();
20245
20246   EVT ScalarVT = VT.getScalarType();
20247   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
20248       (!Subtarget->hasFMA() && !Subtarget->hasFMA4()))
20249     return SDValue();
20250
20251   SDValue A = N->getOperand(0);
20252   SDValue B = N->getOperand(1);
20253   SDValue C = N->getOperand(2);
20254
20255   bool NegA = (A.getOpcode() == ISD::FNEG);
20256   bool NegB = (B.getOpcode() == ISD::FNEG);
20257   bool NegC = (C.getOpcode() == ISD::FNEG);
20258
20259   // Negative multiplication when NegA xor NegB
20260   bool NegMul = (NegA != NegB);
20261   if (NegA)
20262     A = A.getOperand(0);
20263   if (NegB)
20264     B = B.getOperand(0);
20265   if (NegC)
20266     C = C.getOperand(0);
20267
20268   unsigned Opcode;
20269   if (!NegMul)
20270     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
20271   else
20272     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
20273
20274   return DAG.getNode(Opcode, dl, VT, A, B, C);
20275 }
20276
20277 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
20278                                   TargetLowering::DAGCombinerInfo &DCI,
20279                                   const X86Subtarget *Subtarget) {
20280   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
20281   //           (and (i32 x86isd::setcc_carry), 1)
20282   // This eliminates the zext. This transformation is necessary because
20283   // ISD::SETCC is always legalized to i8.
20284   SDLoc dl(N);
20285   SDValue N0 = N->getOperand(0);
20286   EVT VT = N->getValueType(0);
20287
20288   if (N0.getOpcode() == ISD::AND &&
20289       N0.hasOneUse() &&
20290       N0.getOperand(0).hasOneUse()) {
20291     SDValue N00 = N0.getOperand(0);
20292     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20293       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
20294       if (!C || C->getZExtValue() != 1)
20295         return SDValue();
20296       return DAG.getNode(ISD::AND, dl, VT,
20297                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20298                                      N00.getOperand(0), N00.getOperand(1)),
20299                          DAG.getConstant(1, VT));
20300     }
20301   }
20302
20303   if (N0.getOpcode() == ISD::TRUNCATE &&
20304       N0.hasOneUse() &&
20305       N0.getOperand(0).hasOneUse()) {
20306     SDValue N00 = N0.getOperand(0);
20307     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
20308       return DAG.getNode(ISD::AND, dl, VT,
20309                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
20310                                      N00.getOperand(0), N00.getOperand(1)),
20311                          DAG.getConstant(1, VT));
20312     }
20313   }
20314   if (VT.is256BitVector()) {
20315     SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget);
20316     if (R.getNode())
20317       return R;
20318   }
20319
20320   return SDValue();
20321 }
20322
20323 // Optimize x == -y --> x+y == 0
20324 //          x != -y --> x+y != 0
20325 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
20326                                       const X86Subtarget* Subtarget) {
20327   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
20328   SDValue LHS = N->getOperand(0);
20329   SDValue RHS = N->getOperand(1);
20330   EVT VT = N->getValueType(0);
20331   SDLoc DL(N);
20332
20333   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
20334     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
20335       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
20336         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20337                                    LHS.getValueType(), RHS, LHS.getOperand(1));
20338         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20339                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20340       }
20341   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
20342     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
20343       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
20344         SDValue addV = DAG.getNode(ISD::ADD, SDLoc(N),
20345                                    RHS.getValueType(), LHS, RHS.getOperand(1));
20346         return DAG.getSetCC(SDLoc(N), N->getValueType(0),
20347                             addV, DAG.getConstant(0, addV.getValueType()), CC);
20348       }
20349
20350   if (VT.getScalarType() == MVT::i1) {
20351     bool IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
20352       (LHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20353     bool IsVZero0 = ISD::isBuildVectorAllZeros(LHS.getNode());
20354     if (!IsSEXT0 && !IsVZero0)
20355       return SDValue();
20356     bool IsSEXT1 = (RHS.getOpcode() == ISD::SIGN_EXTEND) &&
20357       (RHS.getOperand(0).getValueType().getScalarType() ==  MVT::i1);
20358     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
20359
20360     if (!IsSEXT1 && !IsVZero1)
20361       return SDValue();
20362
20363     if (IsSEXT0 && IsVZero1) {
20364       assert(VT == LHS.getOperand(0).getValueType() && "Uexpected operand type");
20365       if (CC == ISD::SETEQ)
20366         return DAG.getNOT(DL, LHS.getOperand(0), VT);
20367       return LHS.getOperand(0);
20368     }
20369     if (IsSEXT1 && IsVZero0) {
20370       assert(VT == RHS.getOperand(0).getValueType() && "Uexpected operand type");
20371       if (CC == ISD::SETEQ)
20372         return DAG.getNOT(DL, RHS.getOperand(0), VT);
20373       return RHS.getOperand(0);
20374     }
20375   }
20376
20377   return SDValue();
20378 }
20379
20380 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
20381                                       const X86Subtarget *Subtarget) {
20382   SDLoc dl(N);
20383   MVT VT = N->getOperand(1)->getSimpleValueType(0);
20384   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
20385          "X86insertps is only defined for v4x32");
20386
20387   SDValue Ld = N->getOperand(1);
20388   if (MayFoldLoad(Ld)) {
20389     // Extract the countS bits from the immediate so we can get the proper
20390     // address when narrowing the vector load to a specific element.
20391     // When the second source op is a memory address, interps doesn't use
20392     // countS and just gets an f32 from that address.
20393     unsigned DestIndex =
20394         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
20395     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
20396   } else
20397     return SDValue();
20398
20399   // Create this as a scalar to vector to match the instruction pattern.
20400   SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
20401   // countS bits are ignored when loading from memory on insertps, which
20402   // means we don't need to explicitly set them to 0.
20403   return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
20404                      LoadScalarToVector, N->getOperand(2));
20405 }
20406
20407 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
20408 // as "sbb reg,reg", since it can be extended without zext and produces
20409 // an all-ones bit which is more useful than 0/1 in some cases.
20410 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
20411                                MVT VT) {
20412   if (VT == MVT::i8)
20413     return DAG.getNode(ISD::AND, DL, VT,
20414                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20415                                    DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS),
20416                        DAG.getConstant(1, VT));
20417   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
20418   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
20419                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
20420                                  DAG.getConstant(X86::COND_B, MVT::i8), EFLAGS));
20421 }
20422
20423 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
20424 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
20425                                    TargetLowering::DAGCombinerInfo &DCI,
20426                                    const X86Subtarget *Subtarget) {
20427   SDLoc DL(N);
20428   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
20429   SDValue EFLAGS = N->getOperand(1);
20430
20431   if (CC == X86::COND_A) {
20432     // Try to convert COND_A into COND_B in an attempt to facilitate
20433     // materializing "setb reg".
20434     //
20435     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
20436     // cannot take an immediate as its first operand.
20437     //
20438     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
20439         EFLAGS.getValueType().isInteger() &&
20440         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
20441       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
20442                                    EFLAGS.getNode()->getVTList(),
20443                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
20444       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
20445       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
20446     }
20447   }
20448
20449   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
20450   // a zext and produces an all-ones bit which is more useful than 0/1 in some
20451   // cases.
20452   if (CC == X86::COND_B)
20453     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
20454
20455   SDValue Flags;
20456
20457   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20458   if (Flags.getNode()) {
20459     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20460     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
20461   }
20462
20463   return SDValue();
20464 }
20465
20466 // Optimize branch condition evaluation.
20467 //
20468 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
20469                                     TargetLowering::DAGCombinerInfo &DCI,
20470                                     const X86Subtarget *Subtarget) {
20471   SDLoc DL(N);
20472   SDValue Chain = N->getOperand(0);
20473   SDValue Dest = N->getOperand(1);
20474   SDValue EFLAGS = N->getOperand(3);
20475   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
20476
20477   SDValue Flags;
20478
20479   Flags = checkBoolTestSetCCCombine(EFLAGS, CC);
20480   if (Flags.getNode()) {
20481     SDValue Cond = DAG.getConstant(CC, MVT::i8);
20482     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
20483                        Flags);
20484   }
20485
20486   return SDValue();
20487 }
20488
20489 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
20490                                         const X86TargetLowering *XTLI) {
20491   SDValue Op0 = N->getOperand(0);
20492   EVT InVT = Op0->getValueType(0);
20493
20494   // SINT_TO_FP(v4i8) -> SINT_TO_FP(SEXT(v4i8 to v4i32))
20495   if (InVT == MVT::v8i8 || InVT == MVT::v4i8) {
20496     SDLoc dl(N);
20497     MVT DstVT = InVT == MVT::v4i8 ? MVT::v4i32 : MVT::v8i32;
20498     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
20499     return DAG.getNode(ISD::SINT_TO_FP, dl, N->getValueType(0), P);
20500   }
20501
20502   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
20503   // a 32-bit target where SSE doesn't support i64->FP operations.
20504   if (Op0.getOpcode() == ISD::LOAD) {
20505     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
20506     EVT VT = Ld->getValueType(0);
20507     if (!Ld->isVolatile() && !N->getValueType(0).isVector() &&
20508         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
20509         !XTLI->getSubtarget()->is64Bit() &&
20510         VT == MVT::i64) {
20511       SDValue FILDChain = XTLI->BuildFILD(SDValue(N, 0), Ld->getValueType(0),
20512                                           Ld->getChain(), Op0, DAG);
20513       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
20514       return FILDChain;
20515     }
20516   }
20517   return SDValue();
20518 }
20519
20520 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
20521 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
20522                                  X86TargetLowering::DAGCombinerInfo &DCI) {
20523   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
20524   // the result is either zero or one (depending on the input carry bit).
20525   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
20526   if (X86::isZeroNode(N->getOperand(0)) &&
20527       X86::isZeroNode(N->getOperand(1)) &&
20528       // We don't have a good way to replace an EFLAGS use, so only do this when
20529       // dead right now.
20530       SDValue(N, 1).use_empty()) {
20531     SDLoc DL(N);
20532     EVT VT = N->getValueType(0);
20533     SDValue CarryOut = DAG.getConstant(0, N->getValueType(1));
20534     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
20535                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
20536                                            DAG.getConstant(X86::COND_B,MVT::i8),
20537                                            N->getOperand(2)),
20538                                DAG.getConstant(1, VT));
20539     return DCI.CombineTo(N, Res1, CarryOut);
20540   }
20541
20542   return SDValue();
20543 }
20544
20545 // fold (add Y, (sete  X, 0)) -> adc  0, Y
20546 //      (add Y, (setne X, 0)) -> sbb -1, Y
20547 //      (sub (sete  X, 0), Y) -> sbb  0, Y
20548 //      (sub (setne X, 0), Y) -> adc -1, Y
20549 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
20550   SDLoc DL(N);
20551
20552   // Look through ZExts.
20553   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
20554   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
20555     return SDValue();
20556
20557   SDValue SetCC = Ext.getOperand(0);
20558   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
20559     return SDValue();
20560
20561   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
20562   if (CC != X86::COND_E && CC != X86::COND_NE)
20563     return SDValue();
20564
20565   SDValue Cmp = SetCC.getOperand(1);
20566   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
20567       !X86::isZeroNode(Cmp.getOperand(1)) ||
20568       !Cmp.getOperand(0).getValueType().isInteger())
20569     return SDValue();
20570
20571   SDValue CmpOp0 = Cmp.getOperand(0);
20572   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
20573                                DAG.getConstant(1, CmpOp0.getValueType()));
20574
20575   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
20576   if (CC == X86::COND_NE)
20577     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
20578                        DL, OtherVal.getValueType(), OtherVal,
20579                        DAG.getConstant(-1ULL, OtherVal.getValueType()), NewCmp);
20580   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
20581                      DL, OtherVal.getValueType(), OtherVal,
20582                      DAG.getConstant(0, OtherVal.getValueType()), NewCmp);
20583 }
20584
20585 /// PerformADDCombine - Do target-specific dag combines on integer adds.
20586 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
20587                                  const X86Subtarget *Subtarget) {
20588   EVT VT = N->getValueType(0);
20589   SDValue Op0 = N->getOperand(0);
20590   SDValue Op1 = N->getOperand(1);
20591
20592   // Try to synthesize horizontal adds from adds of shuffles.
20593   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20594        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20595       isHorizontalBinOp(Op0, Op1, true))
20596     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
20597
20598   return OptimizeConditionalInDecrement(N, DAG);
20599 }
20600
20601 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
20602                                  const X86Subtarget *Subtarget) {
20603   SDValue Op0 = N->getOperand(0);
20604   SDValue Op1 = N->getOperand(1);
20605
20606   // X86 can't encode an immediate LHS of a sub. See if we can push the
20607   // negation into a preceding instruction.
20608   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
20609     // If the RHS of the sub is a XOR with one use and a constant, invert the
20610     // immediate. Then add one to the LHS of the sub so we can turn
20611     // X-Y -> X+~Y+1, saving one register.
20612     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
20613         isa<ConstantSDNode>(Op1.getOperand(1))) {
20614       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
20615       EVT VT = Op0.getValueType();
20616       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
20617                                    Op1.getOperand(0),
20618                                    DAG.getConstant(~XorC, VT));
20619       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
20620                          DAG.getConstant(C->getAPIntValue()+1, VT));
20621     }
20622   }
20623
20624   // Try to synthesize horizontal adds from adds of shuffles.
20625   EVT VT = N->getValueType(0);
20626   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
20627        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
20628       isHorizontalBinOp(Op0, Op1, true))
20629     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
20630
20631   return OptimizeConditionalInDecrement(N, DAG);
20632 }
20633
20634 /// performVZEXTCombine - Performs build vector combines
20635 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
20636                                         TargetLowering::DAGCombinerInfo &DCI,
20637                                         const X86Subtarget *Subtarget) {
20638   // (vzext (bitcast (vzext (x)) -> (vzext x)
20639   SDValue In = N->getOperand(0);
20640   while (In.getOpcode() == ISD::BITCAST)
20641     In = In.getOperand(0);
20642
20643   if (In.getOpcode() != X86ISD::VZEXT)
20644     return SDValue();
20645
20646   return DAG.getNode(X86ISD::VZEXT, SDLoc(N), N->getValueType(0),
20647                      In.getOperand(0));
20648 }
20649
20650 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
20651                                              DAGCombinerInfo &DCI) const {
20652   SelectionDAG &DAG = DCI.DAG;
20653   switch (N->getOpcode()) {
20654   default: break;
20655   case ISD::EXTRACT_VECTOR_ELT:
20656     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
20657   case ISD::VSELECT:
20658   case ISD::SELECT:         return PerformSELECTCombine(N, DAG, DCI, Subtarget);
20659   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
20660   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
20661   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
20662   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
20663   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
20664   case ISD::SHL:
20665   case ISD::SRA:
20666   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
20667   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
20668   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
20669   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
20670   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
20671   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
20672   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, this);
20673   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
20674   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
20675   case X86ISD::FXOR:
20676   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
20677   case X86ISD::FMIN:
20678   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
20679   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
20680   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
20681   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
20682   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
20683   case ISD::ANY_EXTEND:
20684   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
20685   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
20686   case ISD::SIGN_EXTEND_INREG:
20687     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
20688   case ISD::TRUNCATE:       return PerformTruncateCombine(N, DAG,DCI,Subtarget);
20689   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
20690   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
20691   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
20692   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
20693   case X86ISD::SHUFP:       // Handle all target specific shuffles
20694   case X86ISD::PALIGNR:
20695   case X86ISD::UNPCKH:
20696   case X86ISD::UNPCKL:
20697   case X86ISD::MOVHLPS:
20698   case X86ISD::MOVLHPS:
20699   case X86ISD::PSHUFD:
20700   case X86ISD::PSHUFHW:
20701   case X86ISD::PSHUFLW:
20702   case X86ISD::MOVSS:
20703   case X86ISD::MOVSD:
20704   case X86ISD::VPERMILP:
20705   case X86ISD::VPERM2X128:
20706   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
20707   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
20708   case ISD::INTRINSIC_WO_CHAIN:
20709     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
20710   case X86ISD::INSERTPS:
20711     return PerformINSERTPSCombine(N, DAG, Subtarget);
20712   }
20713
20714   return SDValue();
20715 }
20716
20717 /// isTypeDesirableForOp - Return true if the target has native support for
20718 /// the specified value type and it is 'desirable' to use the type for the
20719 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
20720 /// instruction encodings are longer and some i16 instructions are slow.
20721 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
20722   if (!isTypeLegal(VT))
20723     return false;
20724   if (VT != MVT::i16)
20725     return true;
20726
20727   switch (Opc) {
20728   default:
20729     return true;
20730   case ISD::LOAD:
20731   case ISD::SIGN_EXTEND:
20732   case ISD::ZERO_EXTEND:
20733   case ISD::ANY_EXTEND:
20734   case ISD::SHL:
20735   case ISD::SRL:
20736   case ISD::SUB:
20737   case ISD::ADD:
20738   case ISD::MUL:
20739   case ISD::AND:
20740   case ISD::OR:
20741   case ISD::XOR:
20742     return false;
20743   }
20744 }
20745
20746 /// IsDesirableToPromoteOp - This method query the target whether it is
20747 /// beneficial for dag combiner to promote the specified node. If true, it
20748 /// should return the desired promotion type by reference.
20749 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
20750   EVT VT = Op.getValueType();
20751   if (VT != MVT::i16)
20752     return false;
20753
20754   bool Promote = false;
20755   bool Commute = false;
20756   switch (Op.getOpcode()) {
20757   default: break;
20758   case ISD::LOAD: {
20759     LoadSDNode *LD = cast<LoadSDNode>(Op);
20760     // If the non-extending load has a single use and it's not live out, then it
20761     // might be folded.
20762     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
20763                                                      Op.hasOneUse()*/) {
20764       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
20765              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
20766         // The only case where we'd want to promote LOAD (rather then it being
20767         // promoted as an operand is when it's only use is liveout.
20768         if (UI->getOpcode() != ISD::CopyToReg)
20769           return false;
20770       }
20771     }
20772     Promote = true;
20773     break;
20774   }
20775   case ISD::SIGN_EXTEND:
20776   case ISD::ZERO_EXTEND:
20777   case ISD::ANY_EXTEND:
20778     Promote = true;
20779     break;
20780   case ISD::SHL:
20781   case ISD::SRL: {
20782     SDValue N0 = Op.getOperand(0);
20783     // Look out for (store (shl (load), x)).
20784     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
20785       return false;
20786     Promote = true;
20787     break;
20788   }
20789   case ISD::ADD:
20790   case ISD::MUL:
20791   case ISD::AND:
20792   case ISD::OR:
20793   case ISD::XOR:
20794     Commute = true;
20795     // fallthrough
20796   case ISD::SUB: {
20797     SDValue N0 = Op.getOperand(0);
20798     SDValue N1 = Op.getOperand(1);
20799     if (!Commute && MayFoldLoad(N1))
20800       return false;
20801     // Avoid disabling potential load folding opportunities.
20802     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
20803       return false;
20804     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
20805       return false;
20806     Promote = true;
20807   }
20808   }
20809
20810   PVT = MVT::i32;
20811   return Promote;
20812 }
20813
20814 //===----------------------------------------------------------------------===//
20815 //                           X86 Inline Assembly Support
20816 //===----------------------------------------------------------------------===//
20817
20818 namespace {
20819   // Helper to match a string separated by whitespace.
20820   bool matchAsmImpl(StringRef s, ArrayRef<const StringRef *> args) {
20821     s = s.substr(s.find_first_not_of(" \t")); // Skip leading whitespace.
20822
20823     for (unsigned i = 0, e = args.size(); i != e; ++i) {
20824       StringRef piece(*args[i]);
20825       if (!s.startswith(piece)) // Check if the piece matches.
20826         return false;
20827
20828       s = s.substr(piece.size());
20829       StringRef::size_type pos = s.find_first_not_of(" \t");
20830       if (pos == 0) // We matched a prefix.
20831         return false;
20832
20833       s = s.substr(pos);
20834     }
20835
20836     return s.empty();
20837   }
20838   const VariadicFunction1<bool, StringRef, StringRef, matchAsmImpl> matchAsm={};
20839 }
20840
20841 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
20842
20843   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
20844     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
20845         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
20846         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
20847
20848       if (AsmPieces.size() == 3)
20849         return true;
20850       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
20851         return true;
20852     }
20853   }
20854   return false;
20855 }
20856
20857 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
20858   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
20859
20860   std::string AsmStr = IA->getAsmString();
20861
20862   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
20863   if (!Ty || Ty->getBitWidth() % 16 != 0)
20864     return false;
20865
20866   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
20867   SmallVector<StringRef, 4> AsmPieces;
20868   SplitString(AsmStr, AsmPieces, ";\n");
20869
20870   switch (AsmPieces.size()) {
20871   default: return false;
20872   case 1:
20873     // FIXME: this should verify that we are targeting a 486 or better.  If not,
20874     // we will turn this bswap into something that will be lowered to logical
20875     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
20876     // lower so don't worry about this.
20877     // bswap $0
20878     if (matchAsm(AsmPieces[0], "bswap", "$0") ||
20879         matchAsm(AsmPieces[0], "bswapl", "$0") ||
20880         matchAsm(AsmPieces[0], "bswapq", "$0") ||
20881         matchAsm(AsmPieces[0], "bswap", "${0:q}") ||
20882         matchAsm(AsmPieces[0], "bswapl", "${0:q}") ||
20883         matchAsm(AsmPieces[0], "bswapq", "${0:q}")) {
20884       // No need to check constraints, nothing other than the equivalent of
20885       // "=r,0" would be valid here.
20886       return IntrinsicLowering::LowerToByteSwap(CI);
20887     }
20888
20889     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
20890     if (CI->getType()->isIntegerTy(16) &&
20891         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20892         (matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") ||
20893          matchAsm(AsmPieces[0], "rolw", "$$8,", "${0:w}"))) {
20894       AsmPieces.clear();
20895       const std::string &ConstraintsStr = IA->getConstraintString();
20896       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20897       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20898       if (clobbersFlagRegisters(AsmPieces))
20899         return IntrinsicLowering::LowerToByteSwap(CI);
20900     }
20901     break;
20902   case 3:
20903     if (CI->getType()->isIntegerTy(32) &&
20904         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
20905         matchAsm(AsmPieces[0], "rorw", "$$8,", "${0:w}") &&
20906         matchAsm(AsmPieces[1], "rorl", "$$16,", "$0") &&
20907         matchAsm(AsmPieces[2], "rorw", "$$8,", "${0:w}")) {
20908       AsmPieces.clear();
20909       const std::string &ConstraintsStr = IA->getConstraintString();
20910       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
20911       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
20912       if (clobbersFlagRegisters(AsmPieces))
20913         return IntrinsicLowering::LowerToByteSwap(CI);
20914     }
20915
20916     if (CI->getType()->isIntegerTy(64)) {
20917       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
20918       if (Constraints.size() >= 2 &&
20919           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
20920           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
20921         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
20922         if (matchAsm(AsmPieces[0], "bswap", "%eax") &&
20923             matchAsm(AsmPieces[1], "bswap", "%edx") &&
20924             matchAsm(AsmPieces[2], "xchgl", "%eax,", "%edx"))
20925           return IntrinsicLowering::LowerToByteSwap(CI);
20926       }
20927     }
20928     break;
20929   }
20930   return false;
20931 }
20932
20933 /// getConstraintType - Given a constraint letter, return the type of
20934 /// constraint it is for this target.
20935 X86TargetLowering::ConstraintType
20936 X86TargetLowering::getConstraintType(const std::string &Constraint) const {
20937   if (Constraint.size() == 1) {
20938     switch (Constraint[0]) {
20939     case 'R':
20940     case 'q':
20941     case 'Q':
20942     case 'f':
20943     case 't':
20944     case 'u':
20945     case 'y':
20946     case 'x':
20947     case 'Y':
20948     case 'l':
20949       return C_RegisterClass;
20950     case 'a':
20951     case 'b':
20952     case 'c':
20953     case 'd':
20954     case 'S':
20955     case 'D':
20956     case 'A':
20957       return C_Register;
20958     case 'I':
20959     case 'J':
20960     case 'K':
20961     case 'L':
20962     case 'M':
20963     case 'N':
20964     case 'G':
20965     case 'C':
20966     case 'e':
20967     case 'Z':
20968       return C_Other;
20969     default:
20970       break;
20971     }
20972   }
20973   return TargetLowering::getConstraintType(Constraint);
20974 }
20975
20976 /// Examine constraint type and operand type and determine a weight value.
20977 /// This object must already have been set up with the operand type
20978 /// and the current alternative constraint selected.
20979 TargetLowering::ConstraintWeight
20980   X86TargetLowering::getSingleConstraintMatchWeight(
20981     AsmOperandInfo &info, const char *constraint) const {
20982   ConstraintWeight weight = CW_Invalid;
20983   Value *CallOperandVal = info.CallOperandVal;
20984     // If we don't have a value, we can't do a match,
20985     // but allow it at the lowest weight.
20986   if (!CallOperandVal)
20987     return CW_Default;
20988   Type *type = CallOperandVal->getType();
20989   // Look at the constraint type.
20990   switch (*constraint) {
20991   default:
20992     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
20993   case 'R':
20994   case 'q':
20995   case 'Q':
20996   case 'a':
20997   case 'b':
20998   case 'c':
20999   case 'd':
21000   case 'S':
21001   case 'D':
21002   case 'A':
21003     if (CallOperandVal->getType()->isIntegerTy())
21004       weight = CW_SpecificReg;
21005     break;
21006   case 'f':
21007   case 't':
21008   case 'u':
21009     if (type->isFloatingPointTy())
21010       weight = CW_SpecificReg;
21011     break;
21012   case 'y':
21013     if (type->isX86_MMXTy() && Subtarget->hasMMX())
21014       weight = CW_SpecificReg;
21015     break;
21016   case 'x':
21017   case 'Y':
21018     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
21019         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
21020       weight = CW_Register;
21021     break;
21022   case 'I':
21023     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
21024       if (C->getZExtValue() <= 31)
21025         weight = CW_Constant;
21026     }
21027     break;
21028   case 'J':
21029     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21030       if (C->getZExtValue() <= 63)
21031         weight = CW_Constant;
21032     }
21033     break;
21034   case 'K':
21035     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21036       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
21037         weight = CW_Constant;
21038     }
21039     break;
21040   case 'L':
21041     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21042       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
21043         weight = CW_Constant;
21044     }
21045     break;
21046   case 'M':
21047     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21048       if (C->getZExtValue() <= 3)
21049         weight = CW_Constant;
21050     }
21051     break;
21052   case 'N':
21053     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21054       if (C->getZExtValue() <= 0xff)
21055         weight = CW_Constant;
21056     }
21057     break;
21058   case 'G':
21059   case 'C':
21060     if (dyn_cast<ConstantFP>(CallOperandVal)) {
21061       weight = CW_Constant;
21062     }
21063     break;
21064   case 'e':
21065     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21066       if ((C->getSExtValue() >= -0x80000000LL) &&
21067           (C->getSExtValue() <= 0x7fffffffLL))
21068         weight = CW_Constant;
21069     }
21070     break;
21071   case 'Z':
21072     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
21073       if (C->getZExtValue() <= 0xffffffff)
21074         weight = CW_Constant;
21075     }
21076     break;
21077   }
21078   return weight;
21079 }
21080
21081 /// LowerXConstraint - try to replace an X constraint, which matches anything,
21082 /// with another that has more specific requirements based on the type of the
21083 /// corresponding operand.
21084 const char *X86TargetLowering::
21085 LowerXConstraint(EVT ConstraintVT) const {
21086   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
21087   // 'f' like normal targets.
21088   if (ConstraintVT.isFloatingPoint()) {
21089     if (Subtarget->hasSSE2())
21090       return "Y";
21091     if (Subtarget->hasSSE1())
21092       return "x";
21093   }
21094
21095   return TargetLowering::LowerXConstraint(ConstraintVT);
21096 }
21097
21098 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
21099 /// vector.  If it is invalid, don't add anything to Ops.
21100 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
21101                                                      std::string &Constraint,
21102                                                      std::vector<SDValue>&Ops,
21103                                                      SelectionDAG &DAG) const {
21104   SDValue Result;
21105
21106   // Only support length 1 constraints for now.
21107   if (Constraint.length() > 1) return;
21108
21109   char ConstraintLetter = Constraint[0];
21110   switch (ConstraintLetter) {
21111   default: break;
21112   case 'I':
21113     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21114       if (C->getZExtValue() <= 31) {
21115         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21116         break;
21117       }
21118     }
21119     return;
21120   case 'J':
21121     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21122       if (C->getZExtValue() <= 63) {
21123         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21124         break;
21125       }
21126     }
21127     return;
21128   case 'K':
21129     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21130       if (isInt<8>(C->getSExtValue())) {
21131         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21132         break;
21133       }
21134     }
21135     return;
21136   case 'N':
21137     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21138       if (C->getZExtValue() <= 255) {
21139         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21140         break;
21141       }
21142     }
21143     return;
21144   case 'e': {
21145     // 32-bit signed value
21146     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21147       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21148                                            C->getSExtValue())) {
21149         // Widen to 64 bits here to get it sign extended.
21150         Result = DAG.getTargetConstant(C->getSExtValue(), MVT::i64);
21151         break;
21152       }
21153     // FIXME gcc accepts some relocatable values here too, but only in certain
21154     // memory models; it's complicated.
21155     }
21156     return;
21157   }
21158   case 'Z': {
21159     // 32-bit unsigned value
21160     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
21161       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
21162                                            C->getZExtValue())) {
21163         Result = DAG.getTargetConstant(C->getZExtValue(), Op.getValueType());
21164         break;
21165       }
21166     }
21167     // FIXME gcc accepts some relocatable values here too, but only in certain
21168     // memory models; it's complicated.
21169     return;
21170   }
21171   case 'i': {
21172     // Literal immediates are always ok.
21173     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
21174       // Widen to 64 bits here to get it sign extended.
21175       Result = DAG.getTargetConstant(CST->getSExtValue(), MVT::i64);
21176       break;
21177     }
21178
21179     // In any sort of PIC mode addresses need to be computed at runtime by
21180     // adding in a register or some sort of table lookup.  These can't
21181     // be used as immediates.
21182     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
21183       return;
21184
21185     // If we are in non-pic codegen mode, we allow the address of a global (with
21186     // an optional displacement) to be used with 'i'.
21187     GlobalAddressSDNode *GA = nullptr;
21188     int64_t Offset = 0;
21189
21190     // Match either (GA), (GA+C), (GA+C1+C2), etc.
21191     while (1) {
21192       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
21193         Offset += GA->getOffset();
21194         break;
21195       } else if (Op.getOpcode() == ISD::ADD) {
21196         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21197           Offset += C->getZExtValue();
21198           Op = Op.getOperand(0);
21199           continue;
21200         }
21201       } else if (Op.getOpcode() == ISD::SUB) {
21202         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
21203           Offset += -C->getZExtValue();
21204           Op = Op.getOperand(0);
21205           continue;
21206         }
21207       }
21208
21209       // Otherwise, this isn't something we can handle, reject it.
21210       return;
21211     }
21212
21213     const GlobalValue *GV = GA->getGlobal();
21214     // If we require an extra load to get this address, as in PIC mode, we
21215     // can't accept it.
21216     if (isGlobalStubReference(Subtarget->ClassifyGlobalReference(GV,
21217                                                         getTargetMachine())))
21218       return;
21219
21220     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
21221                                         GA->getValueType(0), Offset);
21222     break;
21223   }
21224   }
21225
21226   if (Result.getNode()) {
21227     Ops.push_back(Result);
21228     return;
21229   }
21230   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
21231 }
21232
21233 std::pair<unsigned, const TargetRegisterClass*>
21234 X86TargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
21235                                                 MVT VT) const {
21236   // First, see if this is a constraint that directly corresponds to an LLVM
21237   // register class.
21238   if (Constraint.size() == 1) {
21239     // GCC Constraint Letters
21240     switch (Constraint[0]) {
21241     default: break;
21242       // TODO: Slight differences here in allocation order and leaving
21243       // RIP in the class. Do they matter any more here than they do
21244       // in the normal allocation?
21245     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
21246       if (Subtarget->is64Bit()) {
21247         if (VT == MVT::i32 || VT == MVT::f32)
21248           return std::make_pair(0U, &X86::GR32RegClass);
21249         if (VT == MVT::i16)
21250           return std::make_pair(0U, &X86::GR16RegClass);
21251         if (VT == MVT::i8 || VT == MVT::i1)
21252           return std::make_pair(0U, &X86::GR8RegClass);
21253         if (VT == MVT::i64 || VT == MVT::f64)
21254           return std::make_pair(0U, &X86::GR64RegClass);
21255         break;
21256       }
21257       // 32-bit fallthrough
21258     case 'Q':   // Q_REGS
21259       if (VT == MVT::i32 || VT == MVT::f32)
21260         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
21261       if (VT == MVT::i16)
21262         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
21263       if (VT == MVT::i8 || VT == MVT::i1)
21264         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
21265       if (VT == MVT::i64)
21266         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
21267       break;
21268     case 'r':   // GENERAL_REGS
21269     case 'l':   // INDEX_REGS
21270       if (VT == MVT::i8 || VT == MVT::i1)
21271         return std::make_pair(0U, &X86::GR8RegClass);
21272       if (VT == MVT::i16)
21273         return std::make_pair(0U, &X86::GR16RegClass);
21274       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
21275         return std::make_pair(0U, &X86::GR32RegClass);
21276       return std::make_pair(0U, &X86::GR64RegClass);
21277     case 'R':   // LEGACY_REGS
21278       if (VT == MVT::i8 || VT == MVT::i1)
21279         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
21280       if (VT == MVT::i16)
21281         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
21282       if (VT == MVT::i32 || !Subtarget->is64Bit())
21283         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
21284       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
21285     case 'f':  // FP Stack registers.
21286       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
21287       // value to the correct fpstack register class.
21288       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
21289         return std::make_pair(0U, &X86::RFP32RegClass);
21290       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
21291         return std::make_pair(0U, &X86::RFP64RegClass);
21292       return std::make_pair(0U, &X86::RFP80RegClass);
21293     case 'y':   // MMX_REGS if MMX allowed.
21294       if (!Subtarget->hasMMX()) break;
21295       return std::make_pair(0U, &X86::VR64RegClass);
21296     case 'Y':   // SSE_REGS if SSE2 allowed
21297       if (!Subtarget->hasSSE2()) break;
21298       // FALL THROUGH.
21299     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
21300       if (!Subtarget->hasSSE1()) break;
21301
21302       switch (VT.SimpleTy) {
21303       default: break;
21304       // Scalar SSE types.
21305       case MVT::f32:
21306       case MVT::i32:
21307         return std::make_pair(0U, &X86::FR32RegClass);
21308       case MVT::f64:
21309       case MVT::i64:
21310         return std::make_pair(0U, &X86::FR64RegClass);
21311       // Vector types.
21312       case MVT::v16i8:
21313       case MVT::v8i16:
21314       case MVT::v4i32:
21315       case MVT::v2i64:
21316       case MVT::v4f32:
21317       case MVT::v2f64:
21318         return std::make_pair(0U, &X86::VR128RegClass);
21319       // AVX types.
21320       case MVT::v32i8:
21321       case MVT::v16i16:
21322       case MVT::v8i32:
21323       case MVT::v4i64:
21324       case MVT::v8f32:
21325       case MVT::v4f64:
21326         return std::make_pair(0U, &X86::VR256RegClass);
21327       case MVT::v8f64:
21328       case MVT::v16f32:
21329       case MVT::v16i32:
21330       case MVT::v8i64:
21331         return std::make_pair(0U, &X86::VR512RegClass);
21332       }
21333       break;
21334     }
21335   }
21336
21337   // Use the default implementation in TargetLowering to convert the register
21338   // constraint into a member of a register class.
21339   std::pair<unsigned, const TargetRegisterClass*> Res;
21340   Res = TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
21341
21342   // Not found as a standard register?
21343   if (!Res.second) {
21344     // Map st(0) -> st(7) -> ST0
21345     if (Constraint.size() == 7 && Constraint[0] == '{' &&
21346         tolower(Constraint[1]) == 's' &&
21347         tolower(Constraint[2]) == 't' &&
21348         Constraint[3] == '(' &&
21349         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
21350         Constraint[5] == ')' &&
21351         Constraint[6] == '}') {
21352
21353       Res.first = X86::ST0+Constraint[4]-'0';
21354       Res.second = &X86::RFP80RegClass;
21355       return Res;
21356     }
21357
21358     // GCC allows "st(0)" to be called just plain "st".
21359     if (StringRef("{st}").equals_lower(Constraint)) {
21360       Res.first = X86::ST0;
21361       Res.second = &X86::RFP80RegClass;
21362       return Res;
21363     }
21364
21365     // flags -> EFLAGS
21366     if (StringRef("{flags}").equals_lower(Constraint)) {
21367       Res.first = X86::EFLAGS;
21368       Res.second = &X86::CCRRegClass;
21369       return Res;
21370     }
21371
21372     // 'A' means EAX + EDX.
21373     if (Constraint == "A") {
21374       Res.first = X86::EAX;
21375       Res.second = &X86::GR32_ADRegClass;
21376       return Res;
21377     }
21378     return Res;
21379   }
21380
21381   // Otherwise, check to see if this is a register class of the wrong value
21382   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
21383   // turn into {ax},{dx}.
21384   if (Res.second->hasType(VT))
21385     return Res;   // Correct type already, nothing to do.
21386
21387   // All of the single-register GCC register classes map their values onto
21388   // 16-bit register pieces "ax","dx","cx","bx","si","di","bp","sp".  If we
21389   // really want an 8-bit or 32-bit register, map to the appropriate register
21390   // class and return the appropriate register.
21391   if (Res.second == &X86::GR16RegClass) {
21392     if (VT == MVT::i8 || VT == MVT::i1) {
21393       unsigned DestReg = 0;
21394       switch (Res.first) {
21395       default: break;
21396       case X86::AX: DestReg = X86::AL; break;
21397       case X86::DX: DestReg = X86::DL; break;
21398       case X86::CX: DestReg = X86::CL; break;
21399       case X86::BX: DestReg = X86::BL; break;
21400       }
21401       if (DestReg) {
21402         Res.first = DestReg;
21403         Res.second = &X86::GR8RegClass;
21404       }
21405     } else if (VT == MVT::i32 || VT == MVT::f32) {
21406       unsigned DestReg = 0;
21407       switch (Res.first) {
21408       default: break;
21409       case X86::AX: DestReg = X86::EAX; break;
21410       case X86::DX: DestReg = X86::EDX; break;
21411       case X86::CX: DestReg = X86::ECX; break;
21412       case X86::BX: DestReg = X86::EBX; break;
21413       case X86::SI: DestReg = X86::ESI; break;
21414       case X86::DI: DestReg = X86::EDI; break;
21415       case X86::BP: DestReg = X86::EBP; break;
21416       case X86::SP: DestReg = X86::ESP; break;
21417       }
21418       if (DestReg) {
21419         Res.first = DestReg;
21420         Res.second = &X86::GR32RegClass;
21421       }
21422     } else if (VT == MVT::i64 || VT == MVT::f64) {
21423       unsigned DestReg = 0;
21424       switch (Res.first) {
21425       default: break;
21426       case X86::AX: DestReg = X86::RAX; break;
21427       case X86::DX: DestReg = X86::RDX; break;
21428       case X86::CX: DestReg = X86::RCX; break;
21429       case X86::BX: DestReg = X86::RBX; break;
21430       case X86::SI: DestReg = X86::RSI; break;
21431       case X86::DI: DestReg = X86::RDI; break;
21432       case X86::BP: DestReg = X86::RBP; break;
21433       case X86::SP: DestReg = X86::RSP; break;
21434       }
21435       if (DestReg) {
21436         Res.first = DestReg;
21437         Res.second = &X86::GR64RegClass;
21438       }
21439     }
21440   } else if (Res.second == &X86::FR32RegClass ||
21441              Res.second == &X86::FR64RegClass ||
21442              Res.second == &X86::VR128RegClass ||
21443              Res.second == &X86::VR256RegClass ||
21444              Res.second == &X86::FR32XRegClass ||
21445              Res.second == &X86::FR64XRegClass ||
21446              Res.second == &X86::VR128XRegClass ||
21447              Res.second == &X86::VR256XRegClass ||
21448              Res.second == &X86::VR512RegClass) {
21449     // Handle references to XMM physical registers that got mapped into the
21450     // wrong class.  This can happen with constraints like {xmm0} where the
21451     // target independent register mapper will just pick the first match it can
21452     // find, ignoring the required type.
21453
21454     if (VT == MVT::f32 || VT == MVT::i32)
21455       Res.second = &X86::FR32RegClass;
21456     else if (VT == MVT::f64 || VT == MVT::i64)
21457       Res.second = &X86::FR64RegClass;
21458     else if (X86::VR128RegClass.hasType(VT))
21459       Res.second = &X86::VR128RegClass;
21460     else if (X86::VR256RegClass.hasType(VT))
21461       Res.second = &X86::VR256RegClass;
21462     else if (X86::VR512RegClass.hasType(VT))
21463       Res.second = &X86::VR512RegClass;
21464   }
21465
21466   return Res;
21467 }
21468
21469 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
21470                                             Type *Ty) const {
21471   // Scaling factors are not free at all.
21472   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
21473   // will take 2 allocations in the out of order engine instead of 1
21474   // for plain addressing mode, i.e. inst (reg1).
21475   // E.g.,
21476   // vaddps (%rsi,%drx), %ymm0, %ymm1
21477   // Requires two allocations (one for the load, one for the computation)
21478   // whereas:
21479   // vaddps (%rsi), %ymm0, %ymm1
21480   // Requires just 1 allocation, i.e., freeing allocations for other operations
21481   // and having less micro operations to execute.
21482   //
21483   // For some X86 architectures, this is even worse because for instance for
21484   // stores, the complex addressing mode forces the instruction to use the
21485   // "load" ports instead of the dedicated "store" port.
21486   // E.g., on Haswell:
21487   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
21488   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.   
21489   if (isLegalAddressingMode(AM, Ty))
21490     // Scale represents reg2 * scale, thus account for 1
21491     // as soon as we use a second register.
21492     return AM.Scale != 0;
21493   return -1;
21494 }